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 #define BPF_GLOBAL_PERCPU_MA_MAX_SIZE 512 199 200 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 201 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 202 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 203 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 204 static int ref_set_non_owning(struct bpf_verifier_env *env, 205 struct bpf_reg_state *reg); 206 static void specialize_kfunc(struct bpf_verifier_env *env, 207 u32 func_id, u16 offset, unsigned long *addr); 208 static bool is_trusted_reg(const struct bpf_reg_state *reg); 209 210 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 211 { 212 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 213 } 214 215 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 216 { 217 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 218 } 219 220 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 221 const struct bpf_map *map, bool unpriv) 222 { 223 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 224 unpriv |= bpf_map_ptr_unpriv(aux); 225 aux->map_ptr_state = (unsigned long)map | 226 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 227 } 228 229 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 230 { 231 return aux->map_key_state & BPF_MAP_KEY_POISON; 232 } 233 234 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 235 { 236 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 237 } 238 239 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 240 { 241 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 242 } 243 244 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 245 { 246 bool poisoned = bpf_map_key_poisoned(aux); 247 248 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 249 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 250 } 251 252 static bool bpf_helper_call(const struct bpf_insn *insn) 253 { 254 return insn->code == (BPF_JMP | BPF_CALL) && 255 insn->src_reg == 0; 256 } 257 258 static bool bpf_pseudo_call(const struct bpf_insn *insn) 259 { 260 return insn->code == (BPF_JMP | BPF_CALL) && 261 insn->src_reg == BPF_PSEUDO_CALL; 262 } 263 264 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 265 { 266 return insn->code == (BPF_JMP | BPF_CALL) && 267 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 268 } 269 270 struct bpf_call_arg_meta { 271 struct bpf_map *map_ptr; 272 bool raw_mode; 273 bool pkt_access; 274 u8 release_regno; 275 int regno; 276 int access_size; 277 int mem_size; 278 u64 msize_max_value; 279 int ref_obj_id; 280 int dynptr_id; 281 int map_uid; 282 int func_id; 283 struct btf *btf; 284 u32 btf_id; 285 struct btf *ret_btf; 286 u32 ret_btf_id; 287 u32 subprogno; 288 struct btf_field *kptr_field; 289 }; 290 291 struct bpf_kfunc_call_arg_meta { 292 /* In parameters */ 293 struct btf *btf; 294 u32 func_id; 295 u32 kfunc_flags; 296 const struct btf_type *func_proto; 297 const char *func_name; 298 /* Out parameters */ 299 u32 ref_obj_id; 300 u8 release_regno; 301 bool r0_rdonly; 302 u32 ret_btf_id; 303 u64 r0_size; 304 u32 subprogno; 305 struct { 306 u64 value; 307 bool found; 308 } arg_constant; 309 310 /* arg_{btf,btf_id,owning_ref} are used by kfunc-specific handling, 311 * generally to pass info about user-defined local kptr types to later 312 * verification logic 313 * bpf_obj_drop/bpf_percpu_obj_drop 314 * Record the local kptr type to be drop'd 315 * bpf_refcount_acquire (via KF_ARG_PTR_TO_REFCOUNTED_KPTR arg type) 316 * Record the local kptr type to be refcount_incr'd and use 317 * arg_owning_ref to determine whether refcount_acquire should be 318 * fallible 319 */ 320 struct btf *arg_btf; 321 u32 arg_btf_id; 322 bool arg_owning_ref; 323 324 struct { 325 struct btf_field *field; 326 } arg_list_head; 327 struct { 328 struct btf_field *field; 329 } arg_rbtree_root; 330 struct { 331 enum bpf_dynptr_type type; 332 u32 id; 333 u32 ref_obj_id; 334 } initialized_dynptr; 335 struct { 336 u8 spi; 337 u8 frameno; 338 } iter; 339 u64 mem_size; 340 }; 341 342 struct btf *btf_vmlinux; 343 344 static const char *btf_type_name(const struct btf *btf, u32 id) 345 { 346 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 347 } 348 349 static DEFINE_MUTEX(bpf_verifier_lock); 350 static DEFINE_MUTEX(bpf_percpu_ma_lock); 351 352 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 353 { 354 struct bpf_verifier_env *env = private_data; 355 va_list args; 356 357 if (!bpf_verifier_log_needed(&env->log)) 358 return; 359 360 va_start(args, fmt); 361 bpf_verifier_vlog(&env->log, fmt, args); 362 va_end(args); 363 } 364 365 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 366 struct bpf_reg_state *reg, 367 struct bpf_retval_range range, const char *ctx, 368 const char *reg_name) 369 { 370 bool unknown = true; 371 372 verbose(env, "%s the register %s has", ctx, reg_name); 373 if (reg->smin_value > S64_MIN) { 374 verbose(env, " smin=%lld", reg->smin_value); 375 unknown = false; 376 } 377 if (reg->smax_value < S64_MAX) { 378 verbose(env, " smax=%lld", reg->smax_value); 379 unknown = false; 380 } 381 if (unknown) 382 verbose(env, " unknown scalar value"); 383 verbose(env, " should have been in [%d, %d]\n", range.minval, range.maxval); 384 } 385 386 static bool type_may_be_null(u32 type) 387 { 388 return type & PTR_MAYBE_NULL; 389 } 390 391 static bool reg_not_null(const struct bpf_reg_state *reg) 392 { 393 enum bpf_reg_type type; 394 395 type = reg->type; 396 if (type_may_be_null(type)) 397 return false; 398 399 type = base_type(type); 400 return type == PTR_TO_SOCKET || 401 type == PTR_TO_TCP_SOCK || 402 type == PTR_TO_MAP_VALUE || 403 type == PTR_TO_MAP_KEY || 404 type == PTR_TO_SOCK_COMMON || 405 (type == PTR_TO_BTF_ID && is_trusted_reg(reg)) || 406 type == PTR_TO_MEM; 407 } 408 409 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 410 { 411 struct btf_record *rec = NULL; 412 struct btf_struct_meta *meta; 413 414 if (reg->type == PTR_TO_MAP_VALUE) { 415 rec = reg->map_ptr->record; 416 } else if (type_is_ptr_alloc_obj(reg->type)) { 417 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 418 if (meta) 419 rec = meta->record; 420 } 421 return rec; 422 } 423 424 static bool subprog_is_global(const struct bpf_verifier_env *env, int subprog) 425 { 426 struct bpf_func_info_aux *aux = env->prog->aux->func_info_aux; 427 428 return aux && aux[subprog].linkage == BTF_FUNC_GLOBAL; 429 } 430 431 static const char *subprog_name(const struct bpf_verifier_env *env, int subprog) 432 { 433 struct bpf_func_info *info; 434 435 if (!env->prog->aux->func_info) 436 return ""; 437 438 info = &env->prog->aux->func_info[subprog]; 439 return btf_type_name(env->prog->aux->btf, info->type_id); 440 } 441 442 static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog) 443 { 444 struct bpf_subprog_info *info = subprog_info(env, subprog); 445 446 info->is_cb = true; 447 info->is_async_cb = true; 448 info->is_exception_cb = true; 449 } 450 451 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog) 452 { 453 return subprog_info(env, subprog)->is_exception_cb; 454 } 455 456 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 457 { 458 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 459 } 460 461 static bool type_is_rdonly_mem(u32 type) 462 { 463 return type & MEM_RDONLY; 464 } 465 466 static bool is_acquire_function(enum bpf_func_id func_id, 467 const struct bpf_map *map) 468 { 469 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 470 471 if (func_id == BPF_FUNC_sk_lookup_tcp || 472 func_id == BPF_FUNC_sk_lookup_udp || 473 func_id == BPF_FUNC_skc_lookup_tcp || 474 func_id == BPF_FUNC_ringbuf_reserve || 475 func_id == BPF_FUNC_kptr_xchg) 476 return true; 477 478 if (func_id == BPF_FUNC_map_lookup_elem && 479 (map_type == BPF_MAP_TYPE_SOCKMAP || 480 map_type == BPF_MAP_TYPE_SOCKHASH)) 481 return true; 482 483 return false; 484 } 485 486 static bool is_ptr_cast_function(enum bpf_func_id func_id) 487 { 488 return func_id == BPF_FUNC_tcp_sock || 489 func_id == BPF_FUNC_sk_fullsock || 490 func_id == BPF_FUNC_skc_to_tcp_sock || 491 func_id == BPF_FUNC_skc_to_tcp6_sock || 492 func_id == BPF_FUNC_skc_to_udp6_sock || 493 func_id == BPF_FUNC_skc_to_mptcp_sock || 494 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 495 func_id == BPF_FUNC_skc_to_tcp_request_sock; 496 } 497 498 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 499 { 500 return func_id == BPF_FUNC_dynptr_data; 501 } 502 503 static bool is_sync_callback_calling_kfunc(u32 btf_id); 504 static bool is_bpf_throw_kfunc(struct bpf_insn *insn); 505 506 static bool is_sync_callback_calling_function(enum bpf_func_id func_id) 507 { 508 return func_id == BPF_FUNC_for_each_map_elem || 509 func_id == BPF_FUNC_find_vma || 510 func_id == BPF_FUNC_loop || 511 func_id == BPF_FUNC_user_ringbuf_drain; 512 } 513 514 static bool is_async_callback_calling_function(enum bpf_func_id func_id) 515 { 516 return func_id == BPF_FUNC_timer_set_callback; 517 } 518 519 static bool is_callback_calling_function(enum bpf_func_id func_id) 520 { 521 return is_sync_callback_calling_function(func_id) || 522 is_async_callback_calling_function(func_id); 523 } 524 525 static bool is_sync_callback_calling_insn(struct bpf_insn *insn) 526 { 527 return (bpf_helper_call(insn) && is_sync_callback_calling_function(insn->imm)) || 528 (bpf_pseudo_kfunc_call(insn) && is_sync_callback_calling_kfunc(insn->imm)); 529 } 530 531 static bool is_async_callback_calling_insn(struct bpf_insn *insn) 532 { 533 return bpf_helper_call(insn) && is_async_callback_calling_function(insn->imm); 534 } 535 536 static bool is_may_goto_insn(struct bpf_insn *insn) 537 { 538 return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO; 539 } 540 541 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx) 542 { 543 return is_may_goto_insn(&env->prog->insnsi[insn_idx]); 544 } 545 546 static bool is_storage_get_function(enum bpf_func_id func_id) 547 { 548 return func_id == BPF_FUNC_sk_storage_get || 549 func_id == BPF_FUNC_inode_storage_get || 550 func_id == BPF_FUNC_task_storage_get || 551 func_id == BPF_FUNC_cgrp_storage_get; 552 } 553 554 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 555 const struct bpf_map *map) 556 { 557 int ref_obj_uses = 0; 558 559 if (is_ptr_cast_function(func_id)) 560 ref_obj_uses++; 561 if (is_acquire_function(func_id, map)) 562 ref_obj_uses++; 563 if (is_dynptr_ref_function(func_id)) 564 ref_obj_uses++; 565 566 return ref_obj_uses > 1; 567 } 568 569 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 570 { 571 return BPF_CLASS(insn->code) == BPF_STX && 572 BPF_MODE(insn->code) == BPF_ATOMIC && 573 insn->imm == BPF_CMPXCHG; 574 } 575 576 static int __get_spi(s32 off) 577 { 578 return (-off - 1) / BPF_REG_SIZE; 579 } 580 581 static struct bpf_func_state *func(struct bpf_verifier_env *env, 582 const struct bpf_reg_state *reg) 583 { 584 struct bpf_verifier_state *cur = env->cur_state; 585 586 return cur->frame[reg->frameno]; 587 } 588 589 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 590 { 591 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 592 593 /* We need to check that slots between [spi - nr_slots + 1, spi] are 594 * within [0, allocated_stack). 595 * 596 * Please note that the spi grows downwards. For example, a dynptr 597 * takes the size of two stack slots; the first slot will be at 598 * spi and the second slot will be at spi - 1. 599 */ 600 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 601 } 602 603 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 604 const char *obj_kind, int nr_slots) 605 { 606 int off, spi; 607 608 if (!tnum_is_const(reg->var_off)) { 609 verbose(env, "%s has to be at a constant offset\n", obj_kind); 610 return -EINVAL; 611 } 612 613 off = reg->off + reg->var_off.value; 614 if (off % BPF_REG_SIZE) { 615 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 616 return -EINVAL; 617 } 618 619 spi = __get_spi(off); 620 if (spi + 1 < nr_slots) { 621 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 622 return -EINVAL; 623 } 624 625 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 626 return -ERANGE; 627 return spi; 628 } 629 630 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 631 { 632 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 633 } 634 635 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 636 { 637 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 638 } 639 640 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 641 { 642 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 643 case DYNPTR_TYPE_LOCAL: 644 return BPF_DYNPTR_TYPE_LOCAL; 645 case DYNPTR_TYPE_RINGBUF: 646 return BPF_DYNPTR_TYPE_RINGBUF; 647 case DYNPTR_TYPE_SKB: 648 return BPF_DYNPTR_TYPE_SKB; 649 case DYNPTR_TYPE_XDP: 650 return BPF_DYNPTR_TYPE_XDP; 651 default: 652 return BPF_DYNPTR_TYPE_INVALID; 653 } 654 } 655 656 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 657 { 658 switch (type) { 659 case BPF_DYNPTR_TYPE_LOCAL: 660 return DYNPTR_TYPE_LOCAL; 661 case BPF_DYNPTR_TYPE_RINGBUF: 662 return DYNPTR_TYPE_RINGBUF; 663 case BPF_DYNPTR_TYPE_SKB: 664 return DYNPTR_TYPE_SKB; 665 case BPF_DYNPTR_TYPE_XDP: 666 return DYNPTR_TYPE_XDP; 667 default: 668 return 0; 669 } 670 } 671 672 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 673 { 674 return type == BPF_DYNPTR_TYPE_RINGBUF; 675 } 676 677 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 678 enum bpf_dynptr_type type, 679 bool first_slot, int dynptr_id); 680 681 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 682 struct bpf_reg_state *reg); 683 684 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 685 struct bpf_reg_state *sreg1, 686 struct bpf_reg_state *sreg2, 687 enum bpf_dynptr_type type) 688 { 689 int id = ++env->id_gen; 690 691 __mark_dynptr_reg(sreg1, type, true, id); 692 __mark_dynptr_reg(sreg2, type, false, id); 693 } 694 695 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 696 struct bpf_reg_state *reg, 697 enum bpf_dynptr_type type) 698 { 699 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 700 } 701 702 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 703 struct bpf_func_state *state, int spi); 704 705 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 706 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 707 { 708 struct bpf_func_state *state = func(env, reg); 709 enum bpf_dynptr_type type; 710 int spi, i, err; 711 712 spi = dynptr_get_spi(env, reg); 713 if (spi < 0) 714 return spi; 715 716 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 717 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 718 * to ensure that for the following example: 719 * [d1][d1][d2][d2] 720 * spi 3 2 1 0 721 * So marking spi = 2 should lead to destruction of both d1 and d2. In 722 * case they do belong to same dynptr, second call won't see slot_type 723 * as STACK_DYNPTR and will simply skip destruction. 724 */ 725 err = destroy_if_dynptr_stack_slot(env, state, spi); 726 if (err) 727 return err; 728 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 729 if (err) 730 return err; 731 732 for (i = 0; i < BPF_REG_SIZE; i++) { 733 state->stack[spi].slot_type[i] = STACK_DYNPTR; 734 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 735 } 736 737 type = arg_to_dynptr_type(arg_type); 738 if (type == BPF_DYNPTR_TYPE_INVALID) 739 return -EINVAL; 740 741 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 742 &state->stack[spi - 1].spilled_ptr, type); 743 744 if (dynptr_type_refcounted(type)) { 745 /* The id is used to track proper releasing */ 746 int id; 747 748 if (clone_ref_obj_id) 749 id = clone_ref_obj_id; 750 else 751 id = acquire_reference_state(env, insn_idx); 752 753 if (id < 0) 754 return id; 755 756 state->stack[spi].spilled_ptr.ref_obj_id = id; 757 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 758 } 759 760 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 761 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 762 763 return 0; 764 } 765 766 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 767 { 768 int i; 769 770 for (i = 0; i < BPF_REG_SIZE; i++) { 771 state->stack[spi].slot_type[i] = STACK_INVALID; 772 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 773 } 774 775 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 776 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 777 778 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 779 * 780 * While we don't allow reading STACK_INVALID, it is still possible to 781 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 782 * helpers or insns can do partial read of that part without failing, 783 * but check_stack_range_initialized, check_stack_read_var_off, and 784 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 785 * the slot conservatively. Hence we need to prevent those liveness 786 * marking walks. 787 * 788 * This was not a problem before because STACK_INVALID is only set by 789 * default (where the default reg state has its reg->parent as NULL), or 790 * in clean_live_states after REG_LIVE_DONE (at which point 791 * mark_reg_read won't walk reg->parent chain), but not randomly during 792 * verifier state exploration (like we did above). Hence, for our case 793 * parentage chain will still be live (i.e. reg->parent may be 794 * non-NULL), while earlier reg->parent was NULL, so we need 795 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 796 * done later on reads or by mark_dynptr_read as well to unnecessary 797 * mark registers in verifier state. 798 */ 799 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 800 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 801 } 802 803 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 804 { 805 struct bpf_func_state *state = func(env, reg); 806 int spi, ref_obj_id, i; 807 808 spi = dynptr_get_spi(env, reg); 809 if (spi < 0) 810 return spi; 811 812 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 813 invalidate_dynptr(env, state, spi); 814 return 0; 815 } 816 817 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 818 819 /* If the dynptr has a ref_obj_id, then we need to invalidate 820 * two things: 821 * 822 * 1) Any dynptrs with a matching ref_obj_id (clones) 823 * 2) Any slices derived from this dynptr. 824 */ 825 826 /* Invalidate any slices associated with this dynptr */ 827 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 828 829 /* Invalidate any dynptr clones */ 830 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 831 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 832 continue; 833 834 /* it should always be the case that if the ref obj id 835 * matches then the stack slot also belongs to a 836 * dynptr 837 */ 838 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 839 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 840 return -EFAULT; 841 } 842 if (state->stack[i].spilled_ptr.dynptr.first_slot) 843 invalidate_dynptr(env, state, i); 844 } 845 846 return 0; 847 } 848 849 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 850 struct bpf_reg_state *reg); 851 852 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 853 { 854 if (!env->allow_ptr_leaks) 855 __mark_reg_not_init(env, reg); 856 else 857 __mark_reg_unknown(env, reg); 858 } 859 860 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 861 struct bpf_func_state *state, int spi) 862 { 863 struct bpf_func_state *fstate; 864 struct bpf_reg_state *dreg; 865 int i, dynptr_id; 866 867 /* We always ensure that STACK_DYNPTR is never set partially, 868 * hence just checking for slot_type[0] is enough. This is 869 * different for STACK_SPILL, where it may be only set for 870 * 1 byte, so code has to use is_spilled_reg. 871 */ 872 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 873 return 0; 874 875 /* Reposition spi to first slot */ 876 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 877 spi = spi + 1; 878 879 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 880 verbose(env, "cannot overwrite referenced dynptr\n"); 881 return -EINVAL; 882 } 883 884 mark_stack_slot_scratched(env, spi); 885 mark_stack_slot_scratched(env, spi - 1); 886 887 /* Writing partially to one dynptr stack slot destroys both. */ 888 for (i = 0; i < BPF_REG_SIZE; i++) { 889 state->stack[spi].slot_type[i] = STACK_INVALID; 890 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 891 } 892 893 dynptr_id = state->stack[spi].spilled_ptr.id; 894 /* Invalidate any slices associated with this dynptr */ 895 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 896 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 897 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 898 continue; 899 if (dreg->dynptr_id == dynptr_id) 900 mark_reg_invalid(env, dreg); 901 })); 902 903 /* Do not release reference state, we are destroying dynptr on stack, 904 * not using some helper to release it. Just reset register. 905 */ 906 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 907 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 908 909 /* Same reason as unmark_stack_slots_dynptr above */ 910 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 911 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 912 913 return 0; 914 } 915 916 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 917 { 918 int spi; 919 920 if (reg->type == CONST_PTR_TO_DYNPTR) 921 return false; 922 923 spi = dynptr_get_spi(env, reg); 924 925 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 926 * error because this just means the stack state hasn't been updated yet. 927 * We will do check_mem_access to check and update stack bounds later. 928 */ 929 if (spi < 0 && spi != -ERANGE) 930 return false; 931 932 /* We don't need to check if the stack slots are marked by previous 933 * dynptr initializations because we allow overwriting existing unreferenced 934 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 935 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 936 * touching are completely destructed before we reinitialize them for a new 937 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 938 * instead of delaying it until the end where the user will get "Unreleased 939 * reference" error. 940 */ 941 return true; 942 } 943 944 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 945 { 946 struct bpf_func_state *state = func(env, reg); 947 int i, spi; 948 949 /* This already represents first slot of initialized bpf_dynptr. 950 * 951 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 952 * check_func_arg_reg_off's logic, so we don't need to check its 953 * offset and alignment. 954 */ 955 if (reg->type == CONST_PTR_TO_DYNPTR) 956 return true; 957 958 spi = dynptr_get_spi(env, reg); 959 if (spi < 0) 960 return false; 961 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 962 return false; 963 964 for (i = 0; i < BPF_REG_SIZE; i++) { 965 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 966 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 967 return false; 968 } 969 970 return true; 971 } 972 973 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 974 enum bpf_arg_type arg_type) 975 { 976 struct bpf_func_state *state = func(env, reg); 977 enum bpf_dynptr_type dynptr_type; 978 int spi; 979 980 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 981 if (arg_type == ARG_PTR_TO_DYNPTR) 982 return true; 983 984 dynptr_type = arg_to_dynptr_type(arg_type); 985 if (reg->type == CONST_PTR_TO_DYNPTR) { 986 return reg->dynptr.type == dynptr_type; 987 } else { 988 spi = dynptr_get_spi(env, reg); 989 if (spi < 0) 990 return false; 991 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 992 } 993 } 994 995 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 996 997 static bool in_rcu_cs(struct bpf_verifier_env *env); 998 999 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta); 1000 1001 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1002 struct bpf_kfunc_call_arg_meta *meta, 1003 struct bpf_reg_state *reg, int insn_idx, 1004 struct btf *btf, u32 btf_id, int nr_slots) 1005 { 1006 struct bpf_func_state *state = func(env, reg); 1007 int spi, i, j, id; 1008 1009 spi = iter_get_spi(env, reg, nr_slots); 1010 if (spi < 0) 1011 return spi; 1012 1013 id = acquire_reference_state(env, insn_idx); 1014 if (id < 0) 1015 return id; 1016 1017 for (i = 0; i < nr_slots; i++) { 1018 struct bpf_stack_state *slot = &state->stack[spi - i]; 1019 struct bpf_reg_state *st = &slot->spilled_ptr; 1020 1021 __mark_reg_known_zero(st); 1022 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1023 if (is_kfunc_rcu_protected(meta)) { 1024 if (in_rcu_cs(env)) 1025 st->type |= MEM_RCU; 1026 else 1027 st->type |= PTR_UNTRUSTED; 1028 } 1029 st->live |= REG_LIVE_WRITTEN; 1030 st->ref_obj_id = i == 0 ? id : 0; 1031 st->iter.btf = btf; 1032 st->iter.btf_id = btf_id; 1033 st->iter.state = BPF_ITER_STATE_ACTIVE; 1034 st->iter.depth = 0; 1035 1036 for (j = 0; j < BPF_REG_SIZE; j++) 1037 slot->slot_type[j] = STACK_ITER; 1038 1039 mark_stack_slot_scratched(env, spi - i); 1040 } 1041 1042 return 0; 1043 } 1044 1045 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1046 struct bpf_reg_state *reg, int nr_slots) 1047 { 1048 struct bpf_func_state *state = func(env, reg); 1049 int spi, i, j; 1050 1051 spi = iter_get_spi(env, reg, nr_slots); 1052 if (spi < 0) 1053 return spi; 1054 1055 for (i = 0; i < nr_slots; i++) { 1056 struct bpf_stack_state *slot = &state->stack[spi - i]; 1057 struct bpf_reg_state *st = &slot->spilled_ptr; 1058 1059 if (i == 0) 1060 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1061 1062 __mark_reg_not_init(env, st); 1063 1064 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1065 st->live |= REG_LIVE_WRITTEN; 1066 1067 for (j = 0; j < BPF_REG_SIZE; j++) 1068 slot->slot_type[j] = STACK_INVALID; 1069 1070 mark_stack_slot_scratched(env, spi - i); 1071 } 1072 1073 return 0; 1074 } 1075 1076 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1077 struct bpf_reg_state *reg, int nr_slots) 1078 { 1079 struct bpf_func_state *state = func(env, reg); 1080 int spi, i, j; 1081 1082 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1083 * will do check_mem_access to check and update stack bounds later, so 1084 * return true for that case. 1085 */ 1086 spi = iter_get_spi(env, reg, nr_slots); 1087 if (spi == -ERANGE) 1088 return true; 1089 if (spi < 0) 1090 return false; 1091 1092 for (i = 0; i < nr_slots; i++) { 1093 struct bpf_stack_state *slot = &state->stack[spi - i]; 1094 1095 for (j = 0; j < BPF_REG_SIZE; j++) 1096 if (slot->slot_type[j] == STACK_ITER) 1097 return false; 1098 } 1099 1100 return true; 1101 } 1102 1103 static int is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1104 struct btf *btf, u32 btf_id, int nr_slots) 1105 { 1106 struct bpf_func_state *state = func(env, reg); 1107 int spi, i, j; 1108 1109 spi = iter_get_spi(env, reg, nr_slots); 1110 if (spi < 0) 1111 return -EINVAL; 1112 1113 for (i = 0; i < nr_slots; i++) { 1114 struct bpf_stack_state *slot = &state->stack[spi - i]; 1115 struct bpf_reg_state *st = &slot->spilled_ptr; 1116 1117 if (st->type & PTR_UNTRUSTED) 1118 return -EPROTO; 1119 /* only main (first) slot has ref_obj_id set */ 1120 if (i == 0 && !st->ref_obj_id) 1121 return -EINVAL; 1122 if (i != 0 && st->ref_obj_id) 1123 return -EINVAL; 1124 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1125 return -EINVAL; 1126 1127 for (j = 0; j < BPF_REG_SIZE; j++) 1128 if (slot->slot_type[j] != STACK_ITER) 1129 return -EINVAL; 1130 } 1131 1132 return 0; 1133 } 1134 1135 /* Check if given stack slot is "special": 1136 * - spilled register state (STACK_SPILL); 1137 * - dynptr state (STACK_DYNPTR); 1138 * - iter state (STACK_ITER). 1139 */ 1140 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1141 { 1142 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1143 1144 switch (type) { 1145 case STACK_SPILL: 1146 case STACK_DYNPTR: 1147 case STACK_ITER: 1148 return true; 1149 case STACK_INVALID: 1150 case STACK_MISC: 1151 case STACK_ZERO: 1152 return false; 1153 default: 1154 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1155 return true; 1156 } 1157 } 1158 1159 /* The reg state of a pointer or a bounded scalar was saved when 1160 * it was spilled to the stack. 1161 */ 1162 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1163 { 1164 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1165 } 1166 1167 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1168 { 1169 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1170 stack->spilled_ptr.type == SCALAR_VALUE; 1171 } 1172 1173 static bool is_spilled_scalar_reg64(const struct bpf_stack_state *stack) 1174 { 1175 return stack->slot_type[0] == STACK_SPILL && 1176 stack->spilled_ptr.type == SCALAR_VALUE; 1177 } 1178 1179 /* Mark stack slot as STACK_MISC, unless it is already STACK_INVALID, in which 1180 * case they are equivalent, or it's STACK_ZERO, in which case we preserve 1181 * more precise STACK_ZERO. 1182 * Note, in uprivileged mode leaving STACK_INVALID is wrong, so we take 1183 * env->allow_ptr_leaks into account and force STACK_MISC, if necessary. 1184 */ 1185 static void mark_stack_slot_misc(struct bpf_verifier_env *env, u8 *stype) 1186 { 1187 if (*stype == STACK_ZERO) 1188 return; 1189 if (env->allow_ptr_leaks && *stype == STACK_INVALID) 1190 return; 1191 *stype = STACK_MISC; 1192 } 1193 1194 static void scrub_spilled_slot(u8 *stype) 1195 { 1196 if (*stype != STACK_INVALID) 1197 *stype = STACK_MISC; 1198 } 1199 1200 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1201 * small to hold src. This is different from krealloc since we don't want to preserve 1202 * the contents of dst. 1203 * 1204 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1205 * not be allocated. 1206 */ 1207 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1208 { 1209 size_t alloc_bytes; 1210 void *orig = dst; 1211 size_t bytes; 1212 1213 if (ZERO_OR_NULL_PTR(src)) 1214 goto out; 1215 1216 if (unlikely(check_mul_overflow(n, size, &bytes))) 1217 return NULL; 1218 1219 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1220 dst = krealloc(orig, alloc_bytes, flags); 1221 if (!dst) { 1222 kfree(orig); 1223 return NULL; 1224 } 1225 1226 memcpy(dst, src, bytes); 1227 out: 1228 return dst ? dst : ZERO_SIZE_PTR; 1229 } 1230 1231 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1232 * small to hold new_n items. new items are zeroed out if the array grows. 1233 * 1234 * Contrary to krealloc_array, does not free arr if new_n is zero. 1235 */ 1236 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1237 { 1238 size_t alloc_size; 1239 void *new_arr; 1240 1241 if (!new_n || old_n == new_n) 1242 goto out; 1243 1244 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1245 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1246 if (!new_arr) { 1247 kfree(arr); 1248 return NULL; 1249 } 1250 arr = new_arr; 1251 1252 if (new_n > old_n) 1253 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1254 1255 out: 1256 return arr ? arr : ZERO_SIZE_PTR; 1257 } 1258 1259 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1260 { 1261 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1262 sizeof(struct bpf_reference_state), GFP_KERNEL); 1263 if (!dst->refs) 1264 return -ENOMEM; 1265 1266 dst->acquired_refs = src->acquired_refs; 1267 return 0; 1268 } 1269 1270 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1271 { 1272 size_t n = src->allocated_stack / BPF_REG_SIZE; 1273 1274 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1275 GFP_KERNEL); 1276 if (!dst->stack) 1277 return -ENOMEM; 1278 1279 dst->allocated_stack = src->allocated_stack; 1280 return 0; 1281 } 1282 1283 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1284 { 1285 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1286 sizeof(struct bpf_reference_state)); 1287 if (!state->refs) 1288 return -ENOMEM; 1289 1290 state->acquired_refs = n; 1291 return 0; 1292 } 1293 1294 /* Possibly update state->allocated_stack to be at least size bytes. Also 1295 * possibly update the function's high-water mark in its bpf_subprog_info. 1296 */ 1297 static int grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size) 1298 { 1299 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n; 1300 1301 /* The stack size is always a multiple of BPF_REG_SIZE. */ 1302 size = round_up(size, BPF_REG_SIZE); 1303 n = size / BPF_REG_SIZE; 1304 1305 if (old_n >= n) 1306 return 0; 1307 1308 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1309 if (!state->stack) 1310 return -ENOMEM; 1311 1312 state->allocated_stack = size; 1313 1314 /* update known max for given subprogram */ 1315 if (env->subprog_info[state->subprogno].stack_depth < size) 1316 env->subprog_info[state->subprogno].stack_depth = size; 1317 1318 return 0; 1319 } 1320 1321 /* Acquire a pointer id from the env and update the state->refs to include 1322 * this new pointer reference. 1323 * On success, returns a valid pointer id to associate with the register 1324 * On failure, returns a negative errno. 1325 */ 1326 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1327 { 1328 struct bpf_func_state *state = cur_func(env); 1329 int new_ofs = state->acquired_refs; 1330 int id, err; 1331 1332 err = resize_reference_state(state, state->acquired_refs + 1); 1333 if (err) 1334 return err; 1335 id = ++env->id_gen; 1336 state->refs[new_ofs].id = id; 1337 state->refs[new_ofs].insn_idx = insn_idx; 1338 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1339 1340 return id; 1341 } 1342 1343 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1344 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1345 { 1346 int i, last_idx; 1347 1348 last_idx = state->acquired_refs - 1; 1349 for (i = 0; i < state->acquired_refs; i++) { 1350 if (state->refs[i].id == ptr_id) { 1351 /* Cannot release caller references in callbacks */ 1352 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1353 return -EINVAL; 1354 if (last_idx && i != last_idx) 1355 memcpy(&state->refs[i], &state->refs[last_idx], 1356 sizeof(*state->refs)); 1357 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1358 state->acquired_refs--; 1359 return 0; 1360 } 1361 } 1362 return -EINVAL; 1363 } 1364 1365 static void free_func_state(struct bpf_func_state *state) 1366 { 1367 if (!state) 1368 return; 1369 kfree(state->refs); 1370 kfree(state->stack); 1371 kfree(state); 1372 } 1373 1374 static void clear_jmp_history(struct bpf_verifier_state *state) 1375 { 1376 kfree(state->jmp_history); 1377 state->jmp_history = NULL; 1378 state->jmp_history_cnt = 0; 1379 } 1380 1381 static void free_verifier_state(struct bpf_verifier_state *state, 1382 bool free_self) 1383 { 1384 int i; 1385 1386 for (i = 0; i <= state->curframe; i++) { 1387 free_func_state(state->frame[i]); 1388 state->frame[i] = NULL; 1389 } 1390 clear_jmp_history(state); 1391 if (free_self) 1392 kfree(state); 1393 } 1394 1395 /* copy verifier state from src to dst growing dst stack space 1396 * when necessary to accommodate larger src stack 1397 */ 1398 static int copy_func_state(struct bpf_func_state *dst, 1399 const struct bpf_func_state *src) 1400 { 1401 int err; 1402 1403 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1404 err = copy_reference_state(dst, src); 1405 if (err) 1406 return err; 1407 return copy_stack_state(dst, src); 1408 } 1409 1410 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1411 const struct bpf_verifier_state *src) 1412 { 1413 struct bpf_func_state *dst; 1414 int i, err; 1415 1416 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1417 src->jmp_history_cnt, sizeof(*dst_state->jmp_history), 1418 GFP_USER); 1419 if (!dst_state->jmp_history) 1420 return -ENOMEM; 1421 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1422 1423 /* if dst has more stack frames then src frame, free them, this is also 1424 * necessary in case of exceptional exits using bpf_throw. 1425 */ 1426 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1427 free_func_state(dst_state->frame[i]); 1428 dst_state->frame[i] = NULL; 1429 } 1430 dst_state->speculative = src->speculative; 1431 dst_state->active_rcu_lock = src->active_rcu_lock; 1432 dst_state->curframe = src->curframe; 1433 dst_state->active_lock.ptr = src->active_lock.ptr; 1434 dst_state->active_lock.id = src->active_lock.id; 1435 dst_state->branches = src->branches; 1436 dst_state->parent = src->parent; 1437 dst_state->first_insn_idx = src->first_insn_idx; 1438 dst_state->last_insn_idx = src->last_insn_idx; 1439 dst_state->dfs_depth = src->dfs_depth; 1440 dst_state->callback_unroll_depth = src->callback_unroll_depth; 1441 dst_state->used_as_loop_entry = src->used_as_loop_entry; 1442 dst_state->may_goto_depth = src->may_goto_depth; 1443 for (i = 0; i <= src->curframe; i++) { 1444 dst = dst_state->frame[i]; 1445 if (!dst) { 1446 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1447 if (!dst) 1448 return -ENOMEM; 1449 dst_state->frame[i] = dst; 1450 } 1451 err = copy_func_state(dst, src->frame[i]); 1452 if (err) 1453 return err; 1454 } 1455 return 0; 1456 } 1457 1458 static u32 state_htab_size(struct bpf_verifier_env *env) 1459 { 1460 return env->prog->len; 1461 } 1462 1463 static struct bpf_verifier_state_list **explored_state(struct bpf_verifier_env *env, int idx) 1464 { 1465 struct bpf_verifier_state *cur = env->cur_state; 1466 struct bpf_func_state *state = cur->frame[cur->curframe]; 1467 1468 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 1469 } 1470 1471 static bool same_callsites(struct bpf_verifier_state *a, struct bpf_verifier_state *b) 1472 { 1473 int fr; 1474 1475 if (a->curframe != b->curframe) 1476 return false; 1477 1478 for (fr = a->curframe; fr >= 0; fr--) 1479 if (a->frame[fr]->callsite != b->frame[fr]->callsite) 1480 return false; 1481 1482 return true; 1483 } 1484 1485 /* Open coded iterators allow back-edges in the state graph in order to 1486 * check unbounded loops that iterators. 1487 * 1488 * In is_state_visited() it is necessary to know if explored states are 1489 * part of some loops in order to decide whether non-exact states 1490 * comparison could be used: 1491 * - non-exact states comparison establishes sub-state relation and uses 1492 * read and precision marks to do so, these marks are propagated from 1493 * children states and thus are not guaranteed to be final in a loop; 1494 * - exact states comparison just checks if current and explored states 1495 * are identical (and thus form a back-edge). 1496 * 1497 * Paper "A New Algorithm for Identifying Loops in Decompilation" 1498 * by Tao Wei, Jian Mao, Wei Zou and Yu Chen [1] presents a convenient 1499 * algorithm for loop structure detection and gives an overview of 1500 * relevant terminology. It also has helpful illustrations. 1501 * 1502 * [1] https://api.semanticscholar.org/CorpusID:15784067 1503 * 1504 * We use a similar algorithm but because loop nested structure is 1505 * irrelevant for verifier ours is significantly simpler and resembles 1506 * strongly connected components algorithm from Sedgewick's textbook. 1507 * 1508 * Define topmost loop entry as a first node of the loop traversed in a 1509 * depth first search starting from initial state. The goal of the loop 1510 * tracking algorithm is to associate topmost loop entries with states 1511 * derived from these entries. 1512 * 1513 * For each step in the DFS states traversal algorithm needs to identify 1514 * the following situations: 1515 * 1516 * initial initial initial 1517 * | | | 1518 * V V V 1519 * ... ... .---------> hdr 1520 * | | | | 1521 * V V | V 1522 * cur .-> succ | .------... 1523 * | | | | | | 1524 * V | V | V V 1525 * succ '-- cur | ... ... 1526 * | | | 1527 * | V V 1528 * | succ <- cur 1529 * | | 1530 * | V 1531 * | ... 1532 * | | 1533 * '----' 1534 * 1535 * (A) successor state of cur (B) successor state of cur or it's entry 1536 * not yet traversed are in current DFS path, thus cur and succ 1537 * are members of the same outermost loop 1538 * 1539 * initial initial 1540 * | | 1541 * V V 1542 * ... ... 1543 * | | 1544 * V V 1545 * .------... .------... 1546 * | | | | 1547 * V V V V 1548 * .-> hdr ... ... ... 1549 * | | | | | 1550 * | V V V V 1551 * | succ <- cur succ <- cur 1552 * | | | 1553 * | V V 1554 * | ... ... 1555 * | | | 1556 * '----' exit 1557 * 1558 * (C) successor state of cur is a part of some loop but this loop 1559 * does not include cur or successor state is not in a loop at all. 1560 * 1561 * Algorithm could be described as the following python code: 1562 * 1563 * traversed = set() # Set of traversed nodes 1564 * entries = {} # Mapping from node to loop entry 1565 * depths = {} # Depth level assigned to graph node 1566 * path = set() # Current DFS path 1567 * 1568 * # Find outermost loop entry known for n 1569 * def get_loop_entry(n): 1570 * h = entries.get(n, None) 1571 * while h in entries and entries[h] != h: 1572 * h = entries[h] 1573 * return h 1574 * 1575 * # Update n's loop entry if h's outermost entry comes 1576 * # before n's outermost entry in current DFS path. 1577 * def update_loop_entry(n, h): 1578 * n1 = get_loop_entry(n) or n 1579 * h1 = get_loop_entry(h) or h 1580 * if h1 in path and depths[h1] <= depths[n1]: 1581 * entries[n] = h1 1582 * 1583 * def dfs(n, depth): 1584 * traversed.add(n) 1585 * path.add(n) 1586 * depths[n] = depth 1587 * for succ in G.successors(n): 1588 * if succ not in traversed: 1589 * # Case A: explore succ and update cur's loop entry 1590 * # only if succ's entry is in current DFS path. 1591 * dfs(succ, depth + 1) 1592 * h = get_loop_entry(succ) 1593 * update_loop_entry(n, h) 1594 * else: 1595 * # Case B or C depending on `h1 in path` check in update_loop_entry(). 1596 * update_loop_entry(n, succ) 1597 * path.remove(n) 1598 * 1599 * To adapt this algorithm for use with verifier: 1600 * - use st->branch == 0 as a signal that DFS of succ had been finished 1601 * and cur's loop entry has to be updated (case A), handle this in 1602 * update_branch_counts(); 1603 * - use st->branch > 0 as a signal that st is in the current DFS path; 1604 * - handle cases B and C in is_state_visited(); 1605 * - update topmost loop entry for intermediate states in get_loop_entry(). 1606 */ 1607 static struct bpf_verifier_state *get_loop_entry(struct bpf_verifier_state *st) 1608 { 1609 struct bpf_verifier_state *topmost = st->loop_entry, *old; 1610 1611 while (topmost && topmost->loop_entry && topmost != topmost->loop_entry) 1612 topmost = topmost->loop_entry; 1613 /* Update loop entries for intermediate states to avoid this 1614 * traversal in future get_loop_entry() calls. 1615 */ 1616 while (st && st->loop_entry != topmost) { 1617 old = st->loop_entry; 1618 st->loop_entry = topmost; 1619 st = old; 1620 } 1621 return topmost; 1622 } 1623 1624 static void update_loop_entry(struct bpf_verifier_state *cur, struct bpf_verifier_state *hdr) 1625 { 1626 struct bpf_verifier_state *cur1, *hdr1; 1627 1628 cur1 = get_loop_entry(cur) ?: cur; 1629 hdr1 = get_loop_entry(hdr) ?: hdr; 1630 /* The head1->branches check decides between cases B and C in 1631 * comment for get_loop_entry(). If hdr1->branches == 0 then 1632 * head's topmost loop entry is not in current DFS path, 1633 * hence 'cur' and 'hdr' are not in the same loop and there is 1634 * no need to update cur->loop_entry. 1635 */ 1636 if (hdr1->branches && hdr1->dfs_depth <= cur1->dfs_depth) { 1637 cur->loop_entry = hdr; 1638 hdr->used_as_loop_entry = true; 1639 } 1640 } 1641 1642 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1643 { 1644 while (st) { 1645 u32 br = --st->branches; 1646 1647 /* br == 0 signals that DFS exploration for 'st' is finished, 1648 * thus it is necessary to update parent's loop entry if it 1649 * turned out that st is a part of some loop. 1650 * This is a part of 'case A' in get_loop_entry() comment. 1651 */ 1652 if (br == 0 && st->parent && st->loop_entry) 1653 update_loop_entry(st->parent, st->loop_entry); 1654 1655 /* WARN_ON(br > 1) technically makes sense here, 1656 * but see comment in push_stack(), hence: 1657 */ 1658 WARN_ONCE((int)br < 0, 1659 "BUG update_branch_counts:branches_to_explore=%d\n", 1660 br); 1661 if (br) 1662 break; 1663 st = st->parent; 1664 } 1665 } 1666 1667 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1668 int *insn_idx, bool pop_log) 1669 { 1670 struct bpf_verifier_state *cur = env->cur_state; 1671 struct bpf_verifier_stack_elem *elem, *head = env->head; 1672 int err; 1673 1674 if (env->head == NULL) 1675 return -ENOENT; 1676 1677 if (cur) { 1678 err = copy_verifier_state(cur, &head->st); 1679 if (err) 1680 return err; 1681 } 1682 if (pop_log) 1683 bpf_vlog_reset(&env->log, head->log_pos); 1684 if (insn_idx) 1685 *insn_idx = head->insn_idx; 1686 if (prev_insn_idx) 1687 *prev_insn_idx = head->prev_insn_idx; 1688 elem = head->next; 1689 free_verifier_state(&head->st, false); 1690 kfree(head); 1691 env->head = elem; 1692 env->stack_size--; 1693 return 0; 1694 } 1695 1696 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1697 int insn_idx, int prev_insn_idx, 1698 bool speculative) 1699 { 1700 struct bpf_verifier_state *cur = env->cur_state; 1701 struct bpf_verifier_stack_elem *elem; 1702 int err; 1703 1704 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1705 if (!elem) 1706 goto err; 1707 1708 elem->insn_idx = insn_idx; 1709 elem->prev_insn_idx = prev_insn_idx; 1710 elem->next = env->head; 1711 elem->log_pos = env->log.end_pos; 1712 env->head = elem; 1713 env->stack_size++; 1714 err = copy_verifier_state(&elem->st, cur); 1715 if (err) 1716 goto err; 1717 elem->st.speculative |= speculative; 1718 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1719 verbose(env, "The sequence of %d jumps is too complex.\n", 1720 env->stack_size); 1721 goto err; 1722 } 1723 if (elem->st.parent) { 1724 ++elem->st.parent->branches; 1725 /* WARN_ON(branches > 2) technically makes sense here, 1726 * but 1727 * 1. speculative states will bump 'branches' for non-branch 1728 * instructions 1729 * 2. is_state_visited() heuristics may decide not to create 1730 * a new state for a sequence of branches and all such current 1731 * and cloned states will be pointing to a single parent state 1732 * which might have large 'branches' count. 1733 */ 1734 } 1735 return &elem->st; 1736 err: 1737 free_verifier_state(env->cur_state, true); 1738 env->cur_state = NULL; 1739 /* pop all elements and return */ 1740 while (!pop_stack(env, NULL, NULL, false)); 1741 return NULL; 1742 } 1743 1744 #define CALLER_SAVED_REGS 6 1745 static const int caller_saved[CALLER_SAVED_REGS] = { 1746 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1747 }; 1748 1749 /* This helper doesn't clear reg->id */ 1750 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1751 { 1752 reg->var_off = tnum_const(imm); 1753 reg->smin_value = (s64)imm; 1754 reg->smax_value = (s64)imm; 1755 reg->umin_value = imm; 1756 reg->umax_value = imm; 1757 1758 reg->s32_min_value = (s32)imm; 1759 reg->s32_max_value = (s32)imm; 1760 reg->u32_min_value = (u32)imm; 1761 reg->u32_max_value = (u32)imm; 1762 } 1763 1764 /* Mark the unknown part of a register (variable offset or scalar value) as 1765 * known to have the value @imm. 1766 */ 1767 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1768 { 1769 /* Clear off and union(map_ptr, range) */ 1770 memset(((u8 *)reg) + sizeof(reg->type), 0, 1771 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1772 reg->id = 0; 1773 reg->ref_obj_id = 0; 1774 ___mark_reg_known(reg, imm); 1775 } 1776 1777 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1778 { 1779 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1780 reg->s32_min_value = (s32)imm; 1781 reg->s32_max_value = (s32)imm; 1782 reg->u32_min_value = (u32)imm; 1783 reg->u32_max_value = (u32)imm; 1784 } 1785 1786 /* Mark the 'variable offset' part of a register as zero. This should be 1787 * used only on registers holding a pointer type. 1788 */ 1789 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1790 { 1791 __mark_reg_known(reg, 0); 1792 } 1793 1794 static void __mark_reg_const_zero(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1795 { 1796 __mark_reg_known(reg, 0); 1797 reg->type = SCALAR_VALUE; 1798 /* all scalars are assumed imprecise initially (unless unprivileged, 1799 * in which case everything is forced to be precise) 1800 */ 1801 reg->precise = !env->bpf_capable; 1802 } 1803 1804 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1805 struct bpf_reg_state *regs, u32 regno) 1806 { 1807 if (WARN_ON(regno >= MAX_BPF_REG)) { 1808 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1809 /* Something bad happened, let's kill all regs */ 1810 for (regno = 0; regno < MAX_BPF_REG; regno++) 1811 __mark_reg_not_init(env, regs + regno); 1812 return; 1813 } 1814 __mark_reg_known_zero(regs + regno); 1815 } 1816 1817 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1818 bool first_slot, int dynptr_id) 1819 { 1820 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1821 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1822 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1823 */ 1824 __mark_reg_known_zero(reg); 1825 reg->type = CONST_PTR_TO_DYNPTR; 1826 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1827 reg->id = dynptr_id; 1828 reg->dynptr.type = type; 1829 reg->dynptr.first_slot = first_slot; 1830 } 1831 1832 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1833 { 1834 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1835 const struct bpf_map *map = reg->map_ptr; 1836 1837 if (map->inner_map_meta) { 1838 reg->type = CONST_PTR_TO_MAP; 1839 reg->map_ptr = map->inner_map_meta; 1840 /* transfer reg's id which is unique for every map_lookup_elem 1841 * as UID of the inner map. 1842 */ 1843 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1844 reg->map_uid = reg->id; 1845 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1846 reg->type = PTR_TO_XDP_SOCK; 1847 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1848 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1849 reg->type = PTR_TO_SOCKET; 1850 } else { 1851 reg->type = PTR_TO_MAP_VALUE; 1852 } 1853 return; 1854 } 1855 1856 reg->type &= ~PTR_MAYBE_NULL; 1857 } 1858 1859 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1860 struct btf_field_graph_root *ds_head) 1861 { 1862 __mark_reg_known_zero(®s[regno]); 1863 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1864 regs[regno].btf = ds_head->btf; 1865 regs[regno].btf_id = ds_head->value_btf_id; 1866 regs[regno].off = ds_head->node_offset; 1867 } 1868 1869 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1870 { 1871 return type_is_pkt_pointer(reg->type); 1872 } 1873 1874 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1875 { 1876 return reg_is_pkt_pointer(reg) || 1877 reg->type == PTR_TO_PACKET_END; 1878 } 1879 1880 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1881 { 1882 return base_type(reg->type) == PTR_TO_MEM && 1883 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1884 } 1885 1886 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1887 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1888 enum bpf_reg_type which) 1889 { 1890 /* The register can already have a range from prior markings. 1891 * This is fine as long as it hasn't been advanced from its 1892 * origin. 1893 */ 1894 return reg->type == which && 1895 reg->id == 0 && 1896 reg->off == 0 && 1897 tnum_equals_const(reg->var_off, 0); 1898 } 1899 1900 /* Reset the min/max bounds of a register */ 1901 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1902 { 1903 reg->smin_value = S64_MIN; 1904 reg->smax_value = S64_MAX; 1905 reg->umin_value = 0; 1906 reg->umax_value = U64_MAX; 1907 1908 reg->s32_min_value = S32_MIN; 1909 reg->s32_max_value = S32_MAX; 1910 reg->u32_min_value = 0; 1911 reg->u32_max_value = U32_MAX; 1912 } 1913 1914 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1915 { 1916 reg->smin_value = S64_MIN; 1917 reg->smax_value = S64_MAX; 1918 reg->umin_value = 0; 1919 reg->umax_value = U64_MAX; 1920 } 1921 1922 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1923 { 1924 reg->s32_min_value = S32_MIN; 1925 reg->s32_max_value = S32_MAX; 1926 reg->u32_min_value = 0; 1927 reg->u32_max_value = U32_MAX; 1928 } 1929 1930 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1931 { 1932 struct tnum var32_off = tnum_subreg(reg->var_off); 1933 1934 /* min signed is max(sign bit) | min(other bits) */ 1935 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1936 var32_off.value | (var32_off.mask & S32_MIN)); 1937 /* max signed is min(sign bit) | max(other bits) */ 1938 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1939 var32_off.value | (var32_off.mask & S32_MAX)); 1940 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1941 reg->u32_max_value = min(reg->u32_max_value, 1942 (u32)(var32_off.value | var32_off.mask)); 1943 } 1944 1945 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1946 { 1947 /* min signed is max(sign bit) | min(other bits) */ 1948 reg->smin_value = max_t(s64, reg->smin_value, 1949 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1950 /* max signed is min(sign bit) | max(other bits) */ 1951 reg->smax_value = min_t(s64, reg->smax_value, 1952 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1953 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1954 reg->umax_value = min(reg->umax_value, 1955 reg->var_off.value | reg->var_off.mask); 1956 } 1957 1958 static void __update_reg_bounds(struct bpf_reg_state *reg) 1959 { 1960 __update_reg32_bounds(reg); 1961 __update_reg64_bounds(reg); 1962 } 1963 1964 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1965 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1966 { 1967 /* If upper 32 bits of u64/s64 range don't change, we can use lower 32 1968 * bits to improve our u32/s32 boundaries. 1969 * 1970 * E.g., the case where we have upper 32 bits as zero ([10, 20] in 1971 * u64) is pretty trivial, it's obvious that in u32 we'll also have 1972 * [10, 20] range. But this property holds for any 64-bit range as 1973 * long as upper 32 bits in that entire range of values stay the same. 1974 * 1975 * E.g., u64 range [0x10000000A, 0x10000000F] ([4294967306, 4294967311] 1976 * in decimal) has the same upper 32 bits throughout all the values in 1977 * that range. As such, lower 32 bits form a valid [0xA, 0xF] ([10, 15]) 1978 * range. 1979 * 1980 * Note also, that [0xA, 0xF] is a valid range both in u32 and in s32, 1981 * following the rules outlined below about u64/s64 correspondence 1982 * (which equally applies to u32 vs s32 correspondence). In general it 1983 * depends on actual hexadecimal values of 32-bit range. They can form 1984 * only valid u32, or only valid s32 ranges in some cases. 1985 * 1986 * So we use all these insights to derive bounds for subregisters here. 1987 */ 1988 if ((reg->umin_value >> 32) == (reg->umax_value >> 32)) { 1989 /* u64 to u32 casting preserves validity of low 32 bits as 1990 * a range, if upper 32 bits are the same 1991 */ 1992 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->umin_value); 1993 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->umax_value); 1994 1995 if ((s32)reg->umin_value <= (s32)reg->umax_value) { 1996 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 1997 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 1998 } 1999 } 2000 if ((reg->smin_value >> 32) == (reg->smax_value >> 32)) { 2001 /* low 32 bits should form a proper u32 range */ 2002 if ((u32)reg->smin_value <= (u32)reg->smax_value) { 2003 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)reg->smin_value); 2004 reg->u32_max_value = min_t(u32, reg->u32_max_value, (u32)reg->smax_value); 2005 } 2006 /* low 32 bits should form a proper s32 range */ 2007 if ((s32)reg->smin_value <= (s32)reg->smax_value) { 2008 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2009 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2010 } 2011 } 2012 /* Special case where upper bits form a small sequence of two 2013 * sequential numbers (in 32-bit unsigned space, so 0xffffffff to 2014 * 0x00000000 is also valid), while lower bits form a proper s32 range 2015 * going from negative numbers to positive numbers. E.g., let's say we 2016 * have s64 range [-1, 1] ([0xffffffffffffffff, 0x0000000000000001]). 2017 * Possible s64 values are {-1, 0, 1} ({0xffffffffffffffff, 2018 * 0x0000000000000000, 0x00000000000001}). Ignoring upper 32 bits, 2019 * we still get a valid s32 range [-1, 1] ([0xffffffff, 0x00000001]). 2020 * Note that it doesn't have to be 0xffffffff going to 0x00000000 in 2021 * upper 32 bits. As a random example, s64 range 2022 * [0xfffffff0fffffff0; 0xfffffff100000010], forms a valid s32 range 2023 * [-16, 16] ([0xfffffff0; 0x00000010]) in its 32 bit subregister. 2024 */ 2025 if ((u32)(reg->umin_value >> 32) + 1 == (u32)(reg->umax_value >> 32) && 2026 (s32)reg->umin_value < 0 && (s32)reg->umax_value >= 0) { 2027 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->umin_value); 2028 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->umax_value); 2029 } 2030 if ((u32)(reg->smin_value >> 32) + 1 == (u32)(reg->smax_value >> 32) && 2031 (s32)reg->smin_value < 0 && (s32)reg->smax_value >= 0) { 2032 reg->s32_min_value = max_t(s32, reg->s32_min_value, (s32)reg->smin_value); 2033 reg->s32_max_value = min_t(s32, reg->s32_max_value, (s32)reg->smax_value); 2034 } 2035 /* if u32 range forms a valid s32 range (due to matching sign bit), 2036 * try to learn from that 2037 */ 2038 if ((s32)reg->u32_min_value <= (s32)reg->u32_max_value) { 2039 reg->s32_min_value = max_t(s32, reg->s32_min_value, reg->u32_min_value); 2040 reg->s32_max_value = min_t(s32, reg->s32_max_value, reg->u32_max_value); 2041 } 2042 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2043 * are the same, so combine. This works even in the negative case, e.g. 2044 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2045 */ 2046 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2047 reg->u32_min_value = max_t(u32, reg->s32_min_value, reg->u32_min_value); 2048 reg->u32_max_value = min_t(u32, reg->s32_max_value, reg->u32_max_value); 2049 } 2050 } 2051 2052 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2053 { 2054 /* If u64 range forms a valid s64 range (due to matching sign bit), 2055 * try to learn from that. Let's do a bit of ASCII art to see when 2056 * this is happening. Let's take u64 range first: 2057 * 2058 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2059 * |-------------------------------|--------------------------------| 2060 * 2061 * Valid u64 range is formed when umin and umax are anywhere in the 2062 * range [0, U64_MAX], and umin <= umax. u64 case is simple and 2063 * straightforward. Let's see how s64 range maps onto the same range 2064 * of values, annotated below the line for comparison: 2065 * 2066 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2067 * |-------------------------------|--------------------------------| 2068 * 0 S64_MAX S64_MIN -1 2069 * 2070 * So s64 values basically start in the middle and they are logically 2071 * contiguous to the right of it, wrapping around from -1 to 0, and 2072 * then finishing as S64_MAX (0x7fffffffffffffff) right before 2073 * S64_MIN. We can try drawing the continuity of u64 vs s64 values 2074 * more visually as mapped to sign-agnostic range of hex values. 2075 * 2076 * u64 start u64 end 2077 * _______________________________________________________________ 2078 * / \ 2079 * 0 0x7fffffffffffffff 0x8000000000000000 U64_MAX 2080 * |-------------------------------|--------------------------------| 2081 * 0 S64_MAX S64_MIN -1 2082 * / \ 2083 * >------------------------------ -------------------------------> 2084 * s64 continues... s64 end s64 start s64 "midpoint" 2085 * 2086 * What this means is that, in general, we can't always derive 2087 * something new about u64 from any random s64 range, and vice versa. 2088 * 2089 * But we can do that in two particular cases. One is when entire 2090 * u64/s64 range is *entirely* contained within left half of the above 2091 * diagram or when it is *entirely* contained in the right half. I.e.: 2092 * 2093 * |-------------------------------|--------------------------------| 2094 * ^ ^ ^ ^ 2095 * A B C D 2096 * 2097 * [A, B] and [C, D] are contained entirely in their respective halves 2098 * and form valid contiguous ranges as both u64 and s64 values. [A, B] 2099 * will be non-negative both as u64 and s64 (and in fact it will be 2100 * identical ranges no matter the signedness). [C, D] treated as s64 2101 * will be a range of negative values, while in u64 it will be 2102 * non-negative range of values larger than 0x8000000000000000. 2103 * 2104 * Now, any other range here can't be represented in both u64 and s64 2105 * simultaneously. E.g., [A, C], [A, D], [B, C], [B, D] are valid 2106 * contiguous u64 ranges, but they are discontinuous in s64. [B, C] 2107 * in s64 would be properly presented as [S64_MIN, C] and [B, S64_MAX], 2108 * for example. Similarly, valid s64 range [D, A] (going from negative 2109 * to positive values), would be two separate [D, U64_MAX] and [0, A] 2110 * ranges as u64. Currently reg_state can't represent two segments per 2111 * numeric domain, so in such situations we can only derive maximal 2112 * possible range ([0, U64_MAX] for u64, and [S64_MIN, S64_MAX] for s64). 2113 * 2114 * So we use these facts to derive umin/umax from smin/smax and vice 2115 * versa only if they stay within the same "half". This is equivalent 2116 * to checking sign bit: lower half will have sign bit as zero, upper 2117 * half have sign bit 1. Below in code we simplify this by just 2118 * casting umin/umax as smin/smax and checking if they form valid 2119 * range, and vice versa. Those are equivalent checks. 2120 */ 2121 if ((s64)reg->umin_value <= (s64)reg->umax_value) { 2122 reg->smin_value = max_t(s64, reg->smin_value, reg->umin_value); 2123 reg->smax_value = min_t(s64, reg->smax_value, reg->umax_value); 2124 } 2125 /* If we cannot cross the sign boundary, then signed and unsigned bounds 2126 * are the same, so combine. This works even in the negative case, e.g. 2127 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2128 */ 2129 if ((u64)reg->smin_value <= (u64)reg->smax_value) { 2130 reg->umin_value = max_t(u64, reg->smin_value, reg->umin_value); 2131 reg->umax_value = min_t(u64, reg->smax_value, reg->umax_value); 2132 } 2133 } 2134 2135 static void __reg_deduce_mixed_bounds(struct bpf_reg_state *reg) 2136 { 2137 /* Try to tighten 64-bit bounds from 32-bit knowledge, using 32-bit 2138 * values on both sides of 64-bit range in hope to have tigher range. 2139 * E.g., if r1 is [0x1'00000000, 0x3'80000000], and we learn from 2140 * 32-bit signed > 0 operation that s32 bounds are now [1; 0x7fffffff]. 2141 * With this, we can substitute 1 as low 32-bits of _low_ 64-bit bound 2142 * (0x100000000 -> 0x100000001) and 0x7fffffff as low 32-bits of 2143 * _high_ 64-bit bound (0x380000000 -> 0x37fffffff) and arrive at a 2144 * better overall bounds for r1 as [0x1'000000001; 0x3'7fffffff]. 2145 * We just need to make sure that derived bounds we are intersecting 2146 * with are well-formed ranges in respecitve s64 or u64 domain, just 2147 * like we do with similar kinds of 32-to-64 or 64-to-32 adjustments. 2148 */ 2149 __u64 new_umin, new_umax; 2150 __s64 new_smin, new_smax; 2151 2152 /* u32 -> u64 tightening, it's always well-formed */ 2153 new_umin = (reg->umin_value & ~0xffffffffULL) | reg->u32_min_value; 2154 new_umax = (reg->umax_value & ~0xffffffffULL) | reg->u32_max_value; 2155 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2156 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2157 /* u32 -> s64 tightening, u32 range embedded into s64 preserves range validity */ 2158 new_smin = (reg->smin_value & ~0xffffffffULL) | reg->u32_min_value; 2159 new_smax = (reg->smax_value & ~0xffffffffULL) | reg->u32_max_value; 2160 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2161 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2162 2163 /* if s32 can be treated as valid u32 range, we can use it as well */ 2164 if ((u32)reg->s32_min_value <= (u32)reg->s32_max_value) { 2165 /* s32 -> u64 tightening */ 2166 new_umin = (reg->umin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2167 new_umax = (reg->umax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2168 reg->umin_value = max_t(u64, reg->umin_value, new_umin); 2169 reg->umax_value = min_t(u64, reg->umax_value, new_umax); 2170 /* s32 -> s64 tightening */ 2171 new_smin = (reg->smin_value & ~0xffffffffULL) | (u32)reg->s32_min_value; 2172 new_smax = (reg->smax_value & ~0xffffffffULL) | (u32)reg->s32_max_value; 2173 reg->smin_value = max_t(s64, reg->smin_value, new_smin); 2174 reg->smax_value = min_t(s64, reg->smax_value, new_smax); 2175 } 2176 } 2177 2178 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2179 { 2180 __reg32_deduce_bounds(reg); 2181 __reg64_deduce_bounds(reg); 2182 __reg_deduce_mixed_bounds(reg); 2183 } 2184 2185 /* Attempts to improve var_off based on unsigned min/max information */ 2186 static void __reg_bound_offset(struct bpf_reg_state *reg) 2187 { 2188 struct tnum var64_off = tnum_intersect(reg->var_off, 2189 tnum_range(reg->umin_value, 2190 reg->umax_value)); 2191 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2192 tnum_range(reg->u32_min_value, 2193 reg->u32_max_value)); 2194 2195 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2196 } 2197 2198 static void reg_bounds_sync(struct bpf_reg_state *reg) 2199 { 2200 /* We might have learned new bounds from the var_off. */ 2201 __update_reg_bounds(reg); 2202 /* We might have learned something about the sign bit. */ 2203 __reg_deduce_bounds(reg); 2204 __reg_deduce_bounds(reg); 2205 /* We might have learned some bits from the bounds. */ 2206 __reg_bound_offset(reg); 2207 /* Intersecting with the old var_off might have improved our bounds 2208 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2209 * then new var_off is (0; 0x7f...fc) which improves our umax. 2210 */ 2211 __update_reg_bounds(reg); 2212 } 2213 2214 static int reg_bounds_sanity_check(struct bpf_verifier_env *env, 2215 struct bpf_reg_state *reg, const char *ctx) 2216 { 2217 const char *msg; 2218 2219 if (reg->umin_value > reg->umax_value || 2220 reg->smin_value > reg->smax_value || 2221 reg->u32_min_value > reg->u32_max_value || 2222 reg->s32_min_value > reg->s32_max_value) { 2223 msg = "range bounds violation"; 2224 goto out; 2225 } 2226 2227 if (tnum_is_const(reg->var_off)) { 2228 u64 uval = reg->var_off.value; 2229 s64 sval = (s64)uval; 2230 2231 if (reg->umin_value != uval || reg->umax_value != uval || 2232 reg->smin_value != sval || reg->smax_value != sval) { 2233 msg = "const tnum out of sync with range bounds"; 2234 goto out; 2235 } 2236 } 2237 2238 if (tnum_subreg_is_const(reg->var_off)) { 2239 u32 uval32 = tnum_subreg(reg->var_off).value; 2240 s32 sval32 = (s32)uval32; 2241 2242 if (reg->u32_min_value != uval32 || reg->u32_max_value != uval32 || 2243 reg->s32_min_value != sval32 || reg->s32_max_value != sval32) { 2244 msg = "const subreg tnum out of sync with range bounds"; 2245 goto out; 2246 } 2247 } 2248 2249 return 0; 2250 out: 2251 verbose(env, "REG INVARIANTS VIOLATION (%s): %s u64=[%#llx, %#llx] " 2252 "s64=[%#llx, %#llx] u32=[%#x, %#x] s32=[%#x, %#x] var_off=(%#llx, %#llx)\n", 2253 ctx, msg, reg->umin_value, reg->umax_value, 2254 reg->smin_value, reg->smax_value, 2255 reg->u32_min_value, reg->u32_max_value, 2256 reg->s32_min_value, reg->s32_max_value, 2257 reg->var_off.value, reg->var_off.mask); 2258 if (env->test_reg_invariants) 2259 return -EFAULT; 2260 __mark_reg_unbounded(reg); 2261 return 0; 2262 } 2263 2264 static bool __reg32_bound_s64(s32 a) 2265 { 2266 return a >= 0 && a <= S32_MAX; 2267 } 2268 2269 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2270 { 2271 reg->umin_value = reg->u32_min_value; 2272 reg->umax_value = reg->u32_max_value; 2273 2274 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2275 * be positive otherwise set to worse case bounds and refine later 2276 * from tnum. 2277 */ 2278 if (__reg32_bound_s64(reg->s32_min_value) && 2279 __reg32_bound_s64(reg->s32_max_value)) { 2280 reg->smin_value = reg->s32_min_value; 2281 reg->smax_value = reg->s32_max_value; 2282 } else { 2283 reg->smin_value = 0; 2284 reg->smax_value = U32_MAX; 2285 } 2286 } 2287 2288 /* Mark a register as having a completely unknown (scalar) value. */ 2289 static void __mark_reg_unknown_imprecise(struct bpf_reg_state *reg) 2290 { 2291 /* 2292 * Clear type, off, and union(map_ptr, range) and 2293 * padding between 'type' and union 2294 */ 2295 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2296 reg->type = SCALAR_VALUE; 2297 reg->id = 0; 2298 reg->ref_obj_id = 0; 2299 reg->var_off = tnum_unknown; 2300 reg->frameno = 0; 2301 reg->precise = false; 2302 __mark_reg_unbounded(reg); 2303 } 2304 2305 /* Mark a register as having a completely unknown (scalar) value, 2306 * initialize .precise as true when not bpf capable. 2307 */ 2308 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2309 struct bpf_reg_state *reg) 2310 { 2311 __mark_reg_unknown_imprecise(reg); 2312 reg->precise = !env->bpf_capable; 2313 } 2314 2315 static void mark_reg_unknown(struct bpf_verifier_env *env, 2316 struct bpf_reg_state *regs, u32 regno) 2317 { 2318 if (WARN_ON(regno >= MAX_BPF_REG)) { 2319 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2320 /* Something bad happened, let's kill all regs except FP */ 2321 for (regno = 0; regno < BPF_REG_FP; regno++) 2322 __mark_reg_not_init(env, regs + regno); 2323 return; 2324 } 2325 __mark_reg_unknown(env, regs + regno); 2326 } 2327 2328 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2329 struct bpf_reg_state *reg) 2330 { 2331 __mark_reg_unknown(env, reg); 2332 reg->type = NOT_INIT; 2333 } 2334 2335 static void mark_reg_not_init(struct bpf_verifier_env *env, 2336 struct bpf_reg_state *regs, u32 regno) 2337 { 2338 if (WARN_ON(regno >= MAX_BPF_REG)) { 2339 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2340 /* Something bad happened, let's kill all regs except FP */ 2341 for (regno = 0; regno < BPF_REG_FP; regno++) 2342 __mark_reg_not_init(env, regs + regno); 2343 return; 2344 } 2345 __mark_reg_not_init(env, regs + regno); 2346 } 2347 2348 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2349 struct bpf_reg_state *regs, u32 regno, 2350 enum bpf_reg_type reg_type, 2351 struct btf *btf, u32 btf_id, 2352 enum bpf_type_flag flag) 2353 { 2354 if (reg_type == SCALAR_VALUE) { 2355 mark_reg_unknown(env, regs, regno); 2356 return; 2357 } 2358 mark_reg_known_zero(env, regs, regno); 2359 regs[regno].type = PTR_TO_BTF_ID | flag; 2360 regs[regno].btf = btf; 2361 regs[regno].btf_id = btf_id; 2362 } 2363 2364 #define DEF_NOT_SUBREG (0) 2365 static void init_reg_state(struct bpf_verifier_env *env, 2366 struct bpf_func_state *state) 2367 { 2368 struct bpf_reg_state *regs = state->regs; 2369 int i; 2370 2371 for (i = 0; i < MAX_BPF_REG; i++) { 2372 mark_reg_not_init(env, regs, i); 2373 regs[i].live = REG_LIVE_NONE; 2374 regs[i].parent = NULL; 2375 regs[i].subreg_def = DEF_NOT_SUBREG; 2376 } 2377 2378 /* frame pointer */ 2379 regs[BPF_REG_FP].type = PTR_TO_STACK; 2380 mark_reg_known_zero(env, regs, BPF_REG_FP); 2381 regs[BPF_REG_FP].frameno = state->frameno; 2382 } 2383 2384 static struct bpf_retval_range retval_range(s32 minval, s32 maxval) 2385 { 2386 return (struct bpf_retval_range){ minval, maxval }; 2387 } 2388 2389 #define BPF_MAIN_FUNC (-1) 2390 static void init_func_state(struct bpf_verifier_env *env, 2391 struct bpf_func_state *state, 2392 int callsite, int frameno, int subprogno) 2393 { 2394 state->callsite = callsite; 2395 state->frameno = frameno; 2396 state->subprogno = subprogno; 2397 state->callback_ret_range = retval_range(0, 0); 2398 init_reg_state(env, state); 2399 mark_verifier_state_scratched(env); 2400 } 2401 2402 /* Similar to push_stack(), but for async callbacks */ 2403 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2404 int insn_idx, int prev_insn_idx, 2405 int subprog) 2406 { 2407 struct bpf_verifier_stack_elem *elem; 2408 struct bpf_func_state *frame; 2409 2410 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2411 if (!elem) 2412 goto err; 2413 2414 elem->insn_idx = insn_idx; 2415 elem->prev_insn_idx = prev_insn_idx; 2416 elem->next = env->head; 2417 elem->log_pos = env->log.end_pos; 2418 env->head = elem; 2419 env->stack_size++; 2420 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2421 verbose(env, 2422 "The sequence of %d jumps is too complex for async cb.\n", 2423 env->stack_size); 2424 goto err; 2425 } 2426 /* Unlike push_stack() do not copy_verifier_state(). 2427 * The caller state doesn't matter. 2428 * This is async callback. It starts in a fresh stack. 2429 * Initialize it similar to do_check_common(). 2430 */ 2431 elem->st.branches = 1; 2432 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2433 if (!frame) 2434 goto err; 2435 init_func_state(env, frame, 2436 BPF_MAIN_FUNC /* callsite */, 2437 0 /* frameno within this callchain */, 2438 subprog /* subprog number within this prog */); 2439 elem->st.frame[0] = frame; 2440 return &elem->st; 2441 err: 2442 free_verifier_state(env->cur_state, true); 2443 env->cur_state = NULL; 2444 /* pop all elements and return */ 2445 while (!pop_stack(env, NULL, NULL, false)); 2446 return NULL; 2447 } 2448 2449 2450 enum reg_arg_type { 2451 SRC_OP, /* register is used as source operand */ 2452 DST_OP, /* register is used as destination operand */ 2453 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2454 }; 2455 2456 static int cmp_subprogs(const void *a, const void *b) 2457 { 2458 return ((struct bpf_subprog_info *)a)->start - 2459 ((struct bpf_subprog_info *)b)->start; 2460 } 2461 2462 static int find_subprog(struct bpf_verifier_env *env, int off) 2463 { 2464 struct bpf_subprog_info *p; 2465 2466 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2467 sizeof(env->subprog_info[0]), cmp_subprogs); 2468 if (!p) 2469 return -ENOENT; 2470 return p - env->subprog_info; 2471 2472 } 2473 2474 static int add_subprog(struct bpf_verifier_env *env, int off) 2475 { 2476 int insn_cnt = env->prog->len; 2477 int ret; 2478 2479 if (off >= insn_cnt || off < 0) { 2480 verbose(env, "call to invalid destination\n"); 2481 return -EINVAL; 2482 } 2483 ret = find_subprog(env, off); 2484 if (ret >= 0) 2485 return ret; 2486 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2487 verbose(env, "too many subprograms\n"); 2488 return -E2BIG; 2489 } 2490 /* determine subprog starts. The end is one before the next starts */ 2491 env->subprog_info[env->subprog_cnt++].start = off; 2492 sort(env->subprog_info, env->subprog_cnt, 2493 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2494 return env->subprog_cnt - 1; 2495 } 2496 2497 static int bpf_find_exception_callback_insn_off(struct bpf_verifier_env *env) 2498 { 2499 struct bpf_prog_aux *aux = env->prog->aux; 2500 struct btf *btf = aux->btf; 2501 const struct btf_type *t; 2502 u32 main_btf_id, id; 2503 const char *name; 2504 int ret, i; 2505 2506 /* Non-zero func_info_cnt implies valid btf */ 2507 if (!aux->func_info_cnt) 2508 return 0; 2509 main_btf_id = aux->func_info[0].type_id; 2510 2511 t = btf_type_by_id(btf, main_btf_id); 2512 if (!t) { 2513 verbose(env, "invalid btf id for main subprog in func_info\n"); 2514 return -EINVAL; 2515 } 2516 2517 name = btf_find_decl_tag_value(btf, t, -1, "exception_callback:"); 2518 if (IS_ERR(name)) { 2519 ret = PTR_ERR(name); 2520 /* If there is no tag present, there is no exception callback */ 2521 if (ret == -ENOENT) 2522 ret = 0; 2523 else if (ret == -EEXIST) 2524 verbose(env, "multiple exception callback tags for main subprog\n"); 2525 return ret; 2526 } 2527 2528 ret = btf_find_by_name_kind(btf, name, BTF_KIND_FUNC); 2529 if (ret < 0) { 2530 verbose(env, "exception callback '%s' could not be found in BTF\n", name); 2531 return ret; 2532 } 2533 id = ret; 2534 t = btf_type_by_id(btf, id); 2535 if (btf_func_linkage(t) != BTF_FUNC_GLOBAL) { 2536 verbose(env, "exception callback '%s' must have global linkage\n", name); 2537 return -EINVAL; 2538 } 2539 ret = 0; 2540 for (i = 0; i < aux->func_info_cnt; i++) { 2541 if (aux->func_info[i].type_id != id) 2542 continue; 2543 ret = aux->func_info[i].insn_off; 2544 /* Further func_info and subprog checks will also happen 2545 * later, so assume this is the right insn_off for now. 2546 */ 2547 if (!ret) { 2548 verbose(env, "invalid exception callback insn_off in func_info: 0\n"); 2549 ret = -EINVAL; 2550 } 2551 } 2552 if (!ret) { 2553 verbose(env, "exception callback type id not found in func_info\n"); 2554 ret = -EINVAL; 2555 } 2556 return ret; 2557 } 2558 2559 #define MAX_KFUNC_DESCS 256 2560 #define MAX_KFUNC_BTFS 256 2561 2562 struct bpf_kfunc_desc { 2563 struct btf_func_model func_model; 2564 u32 func_id; 2565 s32 imm; 2566 u16 offset; 2567 unsigned long addr; 2568 }; 2569 2570 struct bpf_kfunc_btf { 2571 struct btf *btf; 2572 struct module *module; 2573 u16 offset; 2574 }; 2575 2576 struct bpf_kfunc_desc_tab { 2577 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2578 * verification. JITs do lookups by bpf_insn, where func_id may not be 2579 * available, therefore at the end of verification do_misc_fixups() 2580 * sorts this by imm and offset. 2581 */ 2582 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2583 u32 nr_descs; 2584 }; 2585 2586 struct bpf_kfunc_btf_tab { 2587 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2588 u32 nr_descs; 2589 }; 2590 2591 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2592 { 2593 const struct bpf_kfunc_desc *d0 = a; 2594 const struct bpf_kfunc_desc *d1 = b; 2595 2596 /* func_id is not greater than BTF_MAX_TYPE */ 2597 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2598 } 2599 2600 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2601 { 2602 const struct bpf_kfunc_btf *d0 = a; 2603 const struct bpf_kfunc_btf *d1 = b; 2604 2605 return d0->offset - d1->offset; 2606 } 2607 2608 static const struct bpf_kfunc_desc * 2609 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2610 { 2611 struct bpf_kfunc_desc desc = { 2612 .func_id = func_id, 2613 .offset = offset, 2614 }; 2615 struct bpf_kfunc_desc_tab *tab; 2616 2617 tab = prog->aux->kfunc_tab; 2618 return bsearch(&desc, tab->descs, tab->nr_descs, 2619 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2620 } 2621 2622 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2623 u16 btf_fd_idx, u8 **func_addr) 2624 { 2625 const struct bpf_kfunc_desc *desc; 2626 2627 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2628 if (!desc) 2629 return -EFAULT; 2630 2631 *func_addr = (u8 *)desc->addr; 2632 return 0; 2633 } 2634 2635 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2636 s16 offset) 2637 { 2638 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2639 struct bpf_kfunc_btf_tab *tab; 2640 struct bpf_kfunc_btf *b; 2641 struct module *mod; 2642 struct btf *btf; 2643 int btf_fd; 2644 2645 tab = env->prog->aux->kfunc_btf_tab; 2646 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2647 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2648 if (!b) { 2649 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2650 verbose(env, "too many different module BTFs\n"); 2651 return ERR_PTR(-E2BIG); 2652 } 2653 2654 if (bpfptr_is_null(env->fd_array)) { 2655 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2656 return ERR_PTR(-EPROTO); 2657 } 2658 2659 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2660 offset * sizeof(btf_fd), 2661 sizeof(btf_fd))) 2662 return ERR_PTR(-EFAULT); 2663 2664 btf = btf_get_by_fd(btf_fd); 2665 if (IS_ERR(btf)) { 2666 verbose(env, "invalid module BTF fd specified\n"); 2667 return btf; 2668 } 2669 2670 if (!btf_is_module(btf)) { 2671 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2672 btf_put(btf); 2673 return ERR_PTR(-EINVAL); 2674 } 2675 2676 mod = btf_try_get_module(btf); 2677 if (!mod) { 2678 btf_put(btf); 2679 return ERR_PTR(-ENXIO); 2680 } 2681 2682 b = &tab->descs[tab->nr_descs++]; 2683 b->btf = btf; 2684 b->module = mod; 2685 b->offset = offset; 2686 2687 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2688 kfunc_btf_cmp_by_off, NULL); 2689 } 2690 return b->btf; 2691 } 2692 2693 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2694 { 2695 if (!tab) 2696 return; 2697 2698 while (tab->nr_descs--) { 2699 module_put(tab->descs[tab->nr_descs].module); 2700 btf_put(tab->descs[tab->nr_descs].btf); 2701 } 2702 kfree(tab); 2703 } 2704 2705 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2706 { 2707 if (offset) { 2708 if (offset < 0) { 2709 /* In the future, this can be allowed to increase limit 2710 * of fd index into fd_array, interpreted as u16. 2711 */ 2712 verbose(env, "negative offset disallowed for kernel module function call\n"); 2713 return ERR_PTR(-EINVAL); 2714 } 2715 2716 return __find_kfunc_desc_btf(env, offset); 2717 } 2718 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2719 } 2720 2721 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2722 { 2723 const struct btf_type *func, *func_proto; 2724 struct bpf_kfunc_btf_tab *btf_tab; 2725 struct bpf_kfunc_desc_tab *tab; 2726 struct bpf_prog_aux *prog_aux; 2727 struct bpf_kfunc_desc *desc; 2728 const char *func_name; 2729 struct btf *desc_btf; 2730 unsigned long call_imm; 2731 unsigned long addr; 2732 int err; 2733 2734 prog_aux = env->prog->aux; 2735 tab = prog_aux->kfunc_tab; 2736 btf_tab = prog_aux->kfunc_btf_tab; 2737 if (!tab) { 2738 if (!btf_vmlinux) { 2739 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2740 return -ENOTSUPP; 2741 } 2742 2743 if (!env->prog->jit_requested) { 2744 verbose(env, "JIT is required for calling kernel function\n"); 2745 return -ENOTSUPP; 2746 } 2747 2748 if (!bpf_jit_supports_kfunc_call()) { 2749 verbose(env, "JIT does not support calling kernel function\n"); 2750 return -ENOTSUPP; 2751 } 2752 2753 if (!env->prog->gpl_compatible) { 2754 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2755 return -EINVAL; 2756 } 2757 2758 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2759 if (!tab) 2760 return -ENOMEM; 2761 prog_aux->kfunc_tab = tab; 2762 } 2763 2764 /* func_id == 0 is always invalid, but instead of returning an error, be 2765 * conservative and wait until the code elimination pass before returning 2766 * error, so that invalid calls that get pruned out can be in BPF programs 2767 * loaded from userspace. It is also required that offset be untouched 2768 * for such calls. 2769 */ 2770 if (!func_id && !offset) 2771 return 0; 2772 2773 if (!btf_tab && offset) { 2774 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2775 if (!btf_tab) 2776 return -ENOMEM; 2777 prog_aux->kfunc_btf_tab = btf_tab; 2778 } 2779 2780 desc_btf = find_kfunc_desc_btf(env, offset); 2781 if (IS_ERR(desc_btf)) { 2782 verbose(env, "failed to find BTF for kernel function\n"); 2783 return PTR_ERR(desc_btf); 2784 } 2785 2786 if (find_kfunc_desc(env->prog, func_id, offset)) 2787 return 0; 2788 2789 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2790 verbose(env, "too many different kernel function calls\n"); 2791 return -E2BIG; 2792 } 2793 2794 func = btf_type_by_id(desc_btf, func_id); 2795 if (!func || !btf_type_is_func(func)) { 2796 verbose(env, "kernel btf_id %u is not a function\n", 2797 func_id); 2798 return -EINVAL; 2799 } 2800 func_proto = btf_type_by_id(desc_btf, func->type); 2801 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2802 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2803 func_id); 2804 return -EINVAL; 2805 } 2806 2807 func_name = btf_name_by_offset(desc_btf, func->name_off); 2808 addr = kallsyms_lookup_name(func_name); 2809 if (!addr) { 2810 verbose(env, "cannot find address for kernel function %s\n", 2811 func_name); 2812 return -EINVAL; 2813 } 2814 specialize_kfunc(env, func_id, offset, &addr); 2815 2816 if (bpf_jit_supports_far_kfunc_call()) { 2817 call_imm = func_id; 2818 } else { 2819 call_imm = BPF_CALL_IMM(addr); 2820 /* Check whether the relative offset overflows desc->imm */ 2821 if ((unsigned long)(s32)call_imm != call_imm) { 2822 verbose(env, "address of kernel function %s is out of range\n", 2823 func_name); 2824 return -EINVAL; 2825 } 2826 } 2827 2828 if (bpf_dev_bound_kfunc_id(func_id)) { 2829 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2830 if (err) 2831 return err; 2832 } 2833 2834 desc = &tab->descs[tab->nr_descs++]; 2835 desc->func_id = func_id; 2836 desc->imm = call_imm; 2837 desc->offset = offset; 2838 desc->addr = addr; 2839 err = btf_distill_func_proto(&env->log, desc_btf, 2840 func_proto, func_name, 2841 &desc->func_model); 2842 if (!err) 2843 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2844 kfunc_desc_cmp_by_id_off, NULL); 2845 return err; 2846 } 2847 2848 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2849 { 2850 const struct bpf_kfunc_desc *d0 = a; 2851 const struct bpf_kfunc_desc *d1 = b; 2852 2853 if (d0->imm != d1->imm) 2854 return d0->imm < d1->imm ? -1 : 1; 2855 if (d0->offset != d1->offset) 2856 return d0->offset < d1->offset ? -1 : 1; 2857 return 0; 2858 } 2859 2860 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2861 { 2862 struct bpf_kfunc_desc_tab *tab; 2863 2864 tab = prog->aux->kfunc_tab; 2865 if (!tab) 2866 return; 2867 2868 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2869 kfunc_desc_cmp_by_imm_off, NULL); 2870 } 2871 2872 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2873 { 2874 return !!prog->aux->kfunc_tab; 2875 } 2876 2877 const struct btf_func_model * 2878 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2879 const struct bpf_insn *insn) 2880 { 2881 const struct bpf_kfunc_desc desc = { 2882 .imm = insn->imm, 2883 .offset = insn->off, 2884 }; 2885 const struct bpf_kfunc_desc *res; 2886 struct bpf_kfunc_desc_tab *tab; 2887 2888 tab = prog->aux->kfunc_tab; 2889 res = bsearch(&desc, tab->descs, tab->nr_descs, 2890 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2891 2892 return res ? &res->func_model : NULL; 2893 } 2894 2895 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2896 { 2897 struct bpf_subprog_info *subprog = env->subprog_info; 2898 int i, ret, insn_cnt = env->prog->len, ex_cb_insn; 2899 struct bpf_insn *insn = env->prog->insnsi; 2900 2901 /* Add entry function. */ 2902 ret = add_subprog(env, 0); 2903 if (ret) 2904 return ret; 2905 2906 for (i = 0; i < insn_cnt; i++, insn++) { 2907 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2908 !bpf_pseudo_kfunc_call(insn)) 2909 continue; 2910 2911 if (!env->bpf_capable) { 2912 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2913 return -EPERM; 2914 } 2915 2916 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2917 ret = add_subprog(env, i + insn->imm + 1); 2918 else 2919 ret = add_kfunc_call(env, insn->imm, insn->off); 2920 2921 if (ret < 0) 2922 return ret; 2923 } 2924 2925 ret = bpf_find_exception_callback_insn_off(env); 2926 if (ret < 0) 2927 return ret; 2928 ex_cb_insn = ret; 2929 2930 /* If ex_cb_insn > 0, this means that the main program has a subprog 2931 * marked using BTF decl tag to serve as the exception callback. 2932 */ 2933 if (ex_cb_insn) { 2934 ret = add_subprog(env, ex_cb_insn); 2935 if (ret < 0) 2936 return ret; 2937 for (i = 1; i < env->subprog_cnt; i++) { 2938 if (env->subprog_info[i].start != ex_cb_insn) 2939 continue; 2940 env->exception_callback_subprog = i; 2941 mark_subprog_exc_cb(env, i); 2942 break; 2943 } 2944 } 2945 2946 /* Add a fake 'exit' subprog which could simplify subprog iteration 2947 * logic. 'subprog_cnt' should not be increased. 2948 */ 2949 subprog[env->subprog_cnt].start = insn_cnt; 2950 2951 if (env->log.level & BPF_LOG_LEVEL2) 2952 for (i = 0; i < env->subprog_cnt; i++) 2953 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2954 2955 return 0; 2956 } 2957 2958 static int check_subprogs(struct bpf_verifier_env *env) 2959 { 2960 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2961 struct bpf_subprog_info *subprog = env->subprog_info; 2962 struct bpf_insn *insn = env->prog->insnsi; 2963 int insn_cnt = env->prog->len; 2964 2965 /* now check that all jumps are within the same subprog */ 2966 subprog_start = subprog[cur_subprog].start; 2967 subprog_end = subprog[cur_subprog + 1].start; 2968 for (i = 0; i < insn_cnt; i++) { 2969 u8 code = insn[i].code; 2970 2971 if (code == (BPF_JMP | BPF_CALL) && 2972 insn[i].src_reg == 0 && 2973 insn[i].imm == BPF_FUNC_tail_call) 2974 subprog[cur_subprog].has_tail_call = true; 2975 if (BPF_CLASS(code) == BPF_LD && 2976 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2977 subprog[cur_subprog].has_ld_abs = true; 2978 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2979 goto next; 2980 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2981 goto next; 2982 if (code == (BPF_JMP32 | BPF_JA)) 2983 off = i + insn[i].imm + 1; 2984 else 2985 off = i + insn[i].off + 1; 2986 if (off < subprog_start || off >= subprog_end) { 2987 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2988 return -EINVAL; 2989 } 2990 next: 2991 if (i == subprog_end - 1) { 2992 /* to avoid fall-through from one subprog into another 2993 * the last insn of the subprog should be either exit 2994 * or unconditional jump back or bpf_throw call 2995 */ 2996 if (code != (BPF_JMP | BPF_EXIT) && 2997 code != (BPF_JMP32 | BPF_JA) && 2998 code != (BPF_JMP | BPF_JA)) { 2999 verbose(env, "last insn is not an exit or jmp\n"); 3000 return -EINVAL; 3001 } 3002 subprog_start = subprog_end; 3003 cur_subprog++; 3004 if (cur_subprog < env->subprog_cnt) 3005 subprog_end = subprog[cur_subprog + 1].start; 3006 } 3007 } 3008 return 0; 3009 } 3010 3011 /* Parentage chain of this register (or stack slot) should take care of all 3012 * issues like callee-saved registers, stack slot allocation time, etc. 3013 */ 3014 static int mark_reg_read(struct bpf_verifier_env *env, 3015 const struct bpf_reg_state *state, 3016 struct bpf_reg_state *parent, u8 flag) 3017 { 3018 bool writes = parent == state->parent; /* Observe write marks */ 3019 int cnt = 0; 3020 3021 while (parent) { 3022 /* if read wasn't screened by an earlier write ... */ 3023 if (writes && state->live & REG_LIVE_WRITTEN) 3024 break; 3025 if (parent->live & REG_LIVE_DONE) { 3026 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 3027 reg_type_str(env, parent->type), 3028 parent->var_off.value, parent->off); 3029 return -EFAULT; 3030 } 3031 /* The first condition is more likely to be true than the 3032 * second, checked it first. 3033 */ 3034 if ((parent->live & REG_LIVE_READ) == flag || 3035 parent->live & REG_LIVE_READ64) 3036 /* The parentage chain never changes and 3037 * this parent was already marked as LIVE_READ. 3038 * There is no need to keep walking the chain again and 3039 * keep re-marking all parents as LIVE_READ. 3040 * This case happens when the same register is read 3041 * multiple times without writes into it in-between. 3042 * Also, if parent has the stronger REG_LIVE_READ64 set, 3043 * then no need to set the weak REG_LIVE_READ32. 3044 */ 3045 break; 3046 /* ... then we depend on parent's value */ 3047 parent->live |= flag; 3048 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 3049 if (flag == REG_LIVE_READ64) 3050 parent->live &= ~REG_LIVE_READ32; 3051 state = parent; 3052 parent = state->parent; 3053 writes = true; 3054 cnt++; 3055 } 3056 3057 if (env->longest_mark_read_walk < cnt) 3058 env->longest_mark_read_walk = cnt; 3059 return 0; 3060 } 3061 3062 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 3063 { 3064 struct bpf_func_state *state = func(env, reg); 3065 int spi, ret; 3066 3067 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 3068 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 3069 * check_kfunc_call. 3070 */ 3071 if (reg->type == CONST_PTR_TO_DYNPTR) 3072 return 0; 3073 spi = dynptr_get_spi(env, reg); 3074 if (spi < 0) 3075 return spi; 3076 /* Caller ensures dynptr is valid and initialized, which means spi is in 3077 * bounds and spi is the first dynptr slot. Simply mark stack slot as 3078 * read. 3079 */ 3080 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 3081 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 3082 if (ret) 3083 return ret; 3084 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 3085 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 3086 } 3087 3088 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 3089 int spi, int nr_slots) 3090 { 3091 struct bpf_func_state *state = func(env, reg); 3092 int err, i; 3093 3094 for (i = 0; i < nr_slots; i++) { 3095 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 3096 3097 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 3098 if (err) 3099 return err; 3100 3101 mark_stack_slot_scratched(env, spi - i); 3102 } 3103 3104 return 0; 3105 } 3106 3107 /* This function is supposed to be used by the following 32-bit optimization 3108 * code only. It returns TRUE if the source or destination register operates 3109 * on 64-bit, otherwise return FALSE. 3110 */ 3111 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 3112 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 3113 { 3114 u8 code, class, op; 3115 3116 code = insn->code; 3117 class = BPF_CLASS(code); 3118 op = BPF_OP(code); 3119 if (class == BPF_JMP) { 3120 /* BPF_EXIT for "main" will reach here. Return TRUE 3121 * conservatively. 3122 */ 3123 if (op == BPF_EXIT) 3124 return true; 3125 if (op == BPF_CALL) { 3126 /* BPF to BPF call will reach here because of marking 3127 * caller saved clobber with DST_OP_NO_MARK for which we 3128 * don't care the register def because they are anyway 3129 * marked as NOT_INIT already. 3130 */ 3131 if (insn->src_reg == BPF_PSEUDO_CALL) 3132 return false; 3133 /* Helper call will reach here because of arg type 3134 * check, conservatively return TRUE. 3135 */ 3136 if (t == SRC_OP) 3137 return true; 3138 3139 return false; 3140 } 3141 } 3142 3143 if (class == BPF_ALU64 && op == BPF_END && (insn->imm == 16 || insn->imm == 32)) 3144 return false; 3145 3146 if (class == BPF_ALU64 || class == BPF_JMP || 3147 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 3148 return true; 3149 3150 if (class == BPF_ALU || class == BPF_JMP32) 3151 return false; 3152 3153 if (class == BPF_LDX) { 3154 if (t != SRC_OP) 3155 return BPF_SIZE(code) == BPF_DW || BPF_MODE(code) == BPF_MEMSX; 3156 /* LDX source must be ptr. */ 3157 return true; 3158 } 3159 3160 if (class == BPF_STX) { 3161 /* BPF_STX (including atomic variants) has multiple source 3162 * operands, one of which is a ptr. Check whether the caller is 3163 * asking about it. 3164 */ 3165 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3166 return true; 3167 return BPF_SIZE(code) == BPF_DW; 3168 } 3169 3170 if (class == BPF_LD) { 3171 u8 mode = BPF_MODE(code); 3172 3173 /* LD_IMM64 */ 3174 if (mode == BPF_IMM) 3175 return true; 3176 3177 /* Both LD_IND and LD_ABS return 32-bit data. */ 3178 if (t != SRC_OP) 3179 return false; 3180 3181 /* Implicit ctx ptr. */ 3182 if (regno == BPF_REG_6) 3183 return true; 3184 3185 /* Explicit source could be any width. */ 3186 return true; 3187 } 3188 3189 if (class == BPF_ST) 3190 /* The only source register for BPF_ST is a ptr. */ 3191 return true; 3192 3193 /* Conservatively return true at default. */ 3194 return true; 3195 } 3196 3197 /* Return the regno defined by the insn, or -1. */ 3198 static int insn_def_regno(const struct bpf_insn *insn) 3199 { 3200 switch (BPF_CLASS(insn->code)) { 3201 case BPF_JMP: 3202 case BPF_JMP32: 3203 case BPF_ST: 3204 return -1; 3205 case BPF_STX: 3206 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3207 (insn->imm & BPF_FETCH)) { 3208 if (insn->imm == BPF_CMPXCHG) 3209 return BPF_REG_0; 3210 else 3211 return insn->src_reg; 3212 } else { 3213 return -1; 3214 } 3215 default: 3216 return insn->dst_reg; 3217 } 3218 } 3219 3220 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3221 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3222 { 3223 int dst_reg = insn_def_regno(insn); 3224 3225 if (dst_reg == -1) 3226 return false; 3227 3228 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3229 } 3230 3231 static void mark_insn_zext(struct bpf_verifier_env *env, 3232 struct bpf_reg_state *reg) 3233 { 3234 s32 def_idx = reg->subreg_def; 3235 3236 if (def_idx == DEF_NOT_SUBREG) 3237 return; 3238 3239 env->insn_aux_data[def_idx - 1].zext_dst = true; 3240 /* The dst will be zero extended, so won't be sub-register anymore. */ 3241 reg->subreg_def = DEF_NOT_SUBREG; 3242 } 3243 3244 static int __check_reg_arg(struct bpf_verifier_env *env, struct bpf_reg_state *regs, u32 regno, 3245 enum reg_arg_type t) 3246 { 3247 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3248 struct bpf_reg_state *reg; 3249 bool rw64; 3250 3251 if (regno >= MAX_BPF_REG) { 3252 verbose(env, "R%d is invalid\n", regno); 3253 return -EINVAL; 3254 } 3255 3256 mark_reg_scratched(env, regno); 3257 3258 reg = ®s[regno]; 3259 rw64 = is_reg64(env, insn, regno, reg, t); 3260 if (t == SRC_OP) { 3261 /* check whether register used as source operand can be read */ 3262 if (reg->type == NOT_INIT) { 3263 verbose(env, "R%d !read_ok\n", regno); 3264 return -EACCES; 3265 } 3266 /* We don't need to worry about FP liveness because it's read-only */ 3267 if (regno == BPF_REG_FP) 3268 return 0; 3269 3270 if (rw64) 3271 mark_insn_zext(env, reg); 3272 3273 return mark_reg_read(env, reg, reg->parent, 3274 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3275 } else { 3276 /* check whether register used as dest operand can be written to */ 3277 if (regno == BPF_REG_FP) { 3278 verbose(env, "frame pointer is read only\n"); 3279 return -EACCES; 3280 } 3281 reg->live |= REG_LIVE_WRITTEN; 3282 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3283 if (t == DST_OP) 3284 mark_reg_unknown(env, regs, regno); 3285 } 3286 return 0; 3287 } 3288 3289 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3290 enum reg_arg_type t) 3291 { 3292 struct bpf_verifier_state *vstate = env->cur_state; 3293 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3294 3295 return __check_reg_arg(env, state->regs, regno, t); 3296 } 3297 3298 static int insn_stack_access_flags(int frameno, int spi) 3299 { 3300 return INSN_F_STACK_ACCESS | (spi << INSN_F_SPI_SHIFT) | frameno; 3301 } 3302 3303 static int insn_stack_access_spi(int insn_flags) 3304 { 3305 return (insn_flags >> INSN_F_SPI_SHIFT) & INSN_F_SPI_MASK; 3306 } 3307 3308 static int insn_stack_access_frameno(int insn_flags) 3309 { 3310 return insn_flags & INSN_F_FRAMENO_MASK; 3311 } 3312 3313 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3314 { 3315 env->insn_aux_data[idx].jmp_point = true; 3316 } 3317 3318 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3319 { 3320 return env->insn_aux_data[insn_idx].jmp_point; 3321 } 3322 3323 /* for any branch, call, exit record the history of jmps in the given state */ 3324 static int push_jmp_history(struct bpf_verifier_env *env, struct bpf_verifier_state *cur, 3325 int insn_flags) 3326 { 3327 u32 cnt = cur->jmp_history_cnt; 3328 struct bpf_jmp_history_entry *p; 3329 size_t alloc_size; 3330 3331 /* combine instruction flags if we already recorded this instruction */ 3332 if (env->cur_hist_ent) { 3333 /* atomic instructions push insn_flags twice, for READ and 3334 * WRITE sides, but they should agree on stack slot 3335 */ 3336 WARN_ONCE((env->cur_hist_ent->flags & insn_flags) && 3337 (env->cur_hist_ent->flags & insn_flags) != insn_flags, 3338 "verifier insn history bug: insn_idx %d cur flags %x new flags %x\n", 3339 env->insn_idx, env->cur_hist_ent->flags, insn_flags); 3340 env->cur_hist_ent->flags |= insn_flags; 3341 return 0; 3342 } 3343 3344 cnt++; 3345 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3346 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3347 if (!p) 3348 return -ENOMEM; 3349 cur->jmp_history = p; 3350 3351 p = &cur->jmp_history[cnt - 1]; 3352 p->idx = env->insn_idx; 3353 p->prev_idx = env->prev_insn_idx; 3354 p->flags = insn_flags; 3355 cur->jmp_history_cnt = cnt; 3356 env->cur_hist_ent = p; 3357 3358 return 0; 3359 } 3360 3361 static struct bpf_jmp_history_entry *get_jmp_hist_entry(struct bpf_verifier_state *st, 3362 u32 hist_end, int insn_idx) 3363 { 3364 if (hist_end > 0 && st->jmp_history[hist_end - 1].idx == insn_idx) 3365 return &st->jmp_history[hist_end - 1]; 3366 return NULL; 3367 } 3368 3369 /* Backtrack one insn at a time. If idx is not at the top of recorded 3370 * history then previous instruction came from straight line execution. 3371 * Return -ENOENT if we exhausted all instructions within given state. 3372 * 3373 * It's legal to have a bit of a looping with the same starting and ending 3374 * insn index within the same state, e.g.: 3->4->5->3, so just because current 3375 * instruction index is the same as state's first_idx doesn't mean we are 3376 * done. If there is still some jump history left, we should keep going. We 3377 * need to take into account that we might have a jump history between given 3378 * state's parent and itself, due to checkpointing. In this case, we'll have 3379 * history entry recording a jump from last instruction of parent state and 3380 * first instruction of given state. 3381 */ 3382 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3383 u32 *history) 3384 { 3385 u32 cnt = *history; 3386 3387 if (i == st->first_insn_idx) { 3388 if (cnt == 0) 3389 return -ENOENT; 3390 if (cnt == 1 && st->jmp_history[0].idx == i) 3391 return -ENOENT; 3392 } 3393 3394 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3395 i = st->jmp_history[cnt - 1].prev_idx; 3396 (*history)--; 3397 } else { 3398 i--; 3399 } 3400 return i; 3401 } 3402 3403 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3404 { 3405 const struct btf_type *func; 3406 struct btf *desc_btf; 3407 3408 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3409 return NULL; 3410 3411 desc_btf = find_kfunc_desc_btf(data, insn->off); 3412 if (IS_ERR(desc_btf)) 3413 return "<error>"; 3414 3415 func = btf_type_by_id(desc_btf, insn->imm); 3416 return btf_name_by_offset(desc_btf, func->name_off); 3417 } 3418 3419 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3420 { 3421 bt->frame = frame; 3422 } 3423 3424 static inline void bt_reset(struct backtrack_state *bt) 3425 { 3426 struct bpf_verifier_env *env = bt->env; 3427 3428 memset(bt, 0, sizeof(*bt)); 3429 bt->env = env; 3430 } 3431 3432 static inline u32 bt_empty(struct backtrack_state *bt) 3433 { 3434 u64 mask = 0; 3435 int i; 3436 3437 for (i = 0; i <= bt->frame; i++) 3438 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3439 3440 return mask == 0; 3441 } 3442 3443 static inline int bt_subprog_enter(struct backtrack_state *bt) 3444 { 3445 if (bt->frame == MAX_CALL_FRAMES - 1) { 3446 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3447 WARN_ONCE(1, "verifier backtracking bug"); 3448 return -EFAULT; 3449 } 3450 bt->frame++; 3451 return 0; 3452 } 3453 3454 static inline int bt_subprog_exit(struct backtrack_state *bt) 3455 { 3456 if (bt->frame == 0) { 3457 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3458 WARN_ONCE(1, "verifier backtracking bug"); 3459 return -EFAULT; 3460 } 3461 bt->frame--; 3462 return 0; 3463 } 3464 3465 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3466 { 3467 bt->reg_masks[frame] |= 1 << reg; 3468 } 3469 3470 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3471 { 3472 bt->reg_masks[frame] &= ~(1 << reg); 3473 } 3474 3475 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3476 { 3477 bt_set_frame_reg(bt, bt->frame, reg); 3478 } 3479 3480 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3481 { 3482 bt_clear_frame_reg(bt, bt->frame, reg); 3483 } 3484 3485 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3486 { 3487 bt->stack_masks[frame] |= 1ull << slot; 3488 } 3489 3490 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3491 { 3492 bt->stack_masks[frame] &= ~(1ull << slot); 3493 } 3494 3495 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3496 { 3497 return bt->reg_masks[frame]; 3498 } 3499 3500 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3501 { 3502 return bt->reg_masks[bt->frame]; 3503 } 3504 3505 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3506 { 3507 return bt->stack_masks[frame]; 3508 } 3509 3510 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3511 { 3512 return bt->stack_masks[bt->frame]; 3513 } 3514 3515 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3516 { 3517 return bt->reg_masks[bt->frame] & (1 << reg); 3518 } 3519 3520 static inline bool bt_is_frame_slot_set(struct backtrack_state *bt, u32 frame, u32 slot) 3521 { 3522 return bt->stack_masks[frame] & (1ull << slot); 3523 } 3524 3525 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3526 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3527 { 3528 DECLARE_BITMAP(mask, 64); 3529 bool first = true; 3530 int i, n; 3531 3532 buf[0] = '\0'; 3533 3534 bitmap_from_u64(mask, reg_mask); 3535 for_each_set_bit(i, mask, 32) { 3536 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3537 first = false; 3538 buf += n; 3539 buf_sz -= n; 3540 if (buf_sz < 0) 3541 break; 3542 } 3543 } 3544 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3545 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3546 { 3547 DECLARE_BITMAP(mask, 64); 3548 bool first = true; 3549 int i, n; 3550 3551 buf[0] = '\0'; 3552 3553 bitmap_from_u64(mask, stack_mask); 3554 for_each_set_bit(i, mask, 64) { 3555 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3556 first = false; 3557 buf += n; 3558 buf_sz -= n; 3559 if (buf_sz < 0) 3560 break; 3561 } 3562 } 3563 3564 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx); 3565 3566 /* For given verifier state backtrack_insn() is called from the last insn to 3567 * the first insn. Its purpose is to compute a bitmask of registers and 3568 * stack slots that needs precision in the parent verifier state. 3569 * 3570 * @idx is an index of the instruction we are currently processing; 3571 * @subseq_idx is an index of the subsequent instruction that: 3572 * - *would be* executed next, if jump history is viewed in forward order; 3573 * - *was* processed previously during backtracking. 3574 */ 3575 static int backtrack_insn(struct bpf_verifier_env *env, int idx, int subseq_idx, 3576 struct bpf_jmp_history_entry *hist, struct backtrack_state *bt) 3577 { 3578 const struct bpf_insn_cbs cbs = { 3579 .cb_call = disasm_kfunc_name, 3580 .cb_print = verbose, 3581 .private_data = env, 3582 }; 3583 struct bpf_insn *insn = env->prog->insnsi + idx; 3584 u8 class = BPF_CLASS(insn->code); 3585 u8 opcode = BPF_OP(insn->code); 3586 u8 mode = BPF_MODE(insn->code); 3587 u32 dreg = insn->dst_reg; 3588 u32 sreg = insn->src_reg; 3589 u32 spi, i, fr; 3590 3591 if (insn->code == 0) 3592 return 0; 3593 if (env->log.level & BPF_LOG_LEVEL2) { 3594 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3595 verbose(env, "mark_precise: frame%d: regs=%s ", 3596 bt->frame, env->tmp_str_buf); 3597 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3598 verbose(env, "stack=%s before ", env->tmp_str_buf); 3599 verbose(env, "%d: ", idx); 3600 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3601 } 3602 3603 if (class == BPF_ALU || class == BPF_ALU64) { 3604 if (!bt_is_reg_set(bt, dreg)) 3605 return 0; 3606 if (opcode == BPF_END || opcode == BPF_NEG) { 3607 /* sreg is reserved and unused 3608 * dreg still need precision before this insn 3609 */ 3610 return 0; 3611 } else if (opcode == BPF_MOV) { 3612 if (BPF_SRC(insn->code) == BPF_X) { 3613 /* dreg = sreg or dreg = (s8, s16, s32)sreg 3614 * dreg needs precision after this insn 3615 * sreg needs precision before this insn 3616 */ 3617 bt_clear_reg(bt, dreg); 3618 bt_set_reg(bt, sreg); 3619 } else { 3620 /* dreg = K 3621 * dreg needs precision after this insn. 3622 * Corresponding register is already marked 3623 * as precise=true in this verifier state. 3624 * No further markings in parent are necessary 3625 */ 3626 bt_clear_reg(bt, dreg); 3627 } 3628 } else { 3629 if (BPF_SRC(insn->code) == BPF_X) { 3630 /* dreg += sreg 3631 * both dreg and sreg need precision 3632 * before this insn 3633 */ 3634 bt_set_reg(bt, sreg); 3635 } /* else dreg += K 3636 * dreg still needs precision before this insn 3637 */ 3638 } 3639 } else if (class == BPF_LDX) { 3640 if (!bt_is_reg_set(bt, dreg)) 3641 return 0; 3642 bt_clear_reg(bt, dreg); 3643 3644 /* scalars can only be spilled into stack w/o losing precision. 3645 * Load from any other memory can be zero extended. 3646 * The desire to keep that precision is already indicated 3647 * by 'precise' mark in corresponding register of this state. 3648 * No further tracking necessary. 3649 */ 3650 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3651 return 0; 3652 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3653 * that [fp - off] slot contains scalar that needs to be 3654 * tracked with precision 3655 */ 3656 spi = insn_stack_access_spi(hist->flags); 3657 fr = insn_stack_access_frameno(hist->flags); 3658 bt_set_frame_slot(bt, fr, spi); 3659 } else if (class == BPF_STX || class == BPF_ST) { 3660 if (bt_is_reg_set(bt, dreg)) 3661 /* stx & st shouldn't be using _scalar_ dst_reg 3662 * to access memory. It means backtracking 3663 * encountered a case of pointer subtraction. 3664 */ 3665 return -ENOTSUPP; 3666 /* scalars can only be spilled into stack */ 3667 if (!hist || !(hist->flags & INSN_F_STACK_ACCESS)) 3668 return 0; 3669 spi = insn_stack_access_spi(hist->flags); 3670 fr = insn_stack_access_frameno(hist->flags); 3671 if (!bt_is_frame_slot_set(bt, fr, spi)) 3672 return 0; 3673 bt_clear_frame_slot(bt, fr, spi); 3674 if (class == BPF_STX) 3675 bt_set_reg(bt, sreg); 3676 } else if (class == BPF_JMP || class == BPF_JMP32) { 3677 if (bpf_pseudo_call(insn)) { 3678 int subprog_insn_idx, subprog; 3679 3680 subprog_insn_idx = idx + insn->imm + 1; 3681 subprog = find_subprog(env, subprog_insn_idx); 3682 if (subprog < 0) 3683 return -EFAULT; 3684 3685 if (subprog_is_global(env, subprog)) { 3686 /* check that jump history doesn't have any 3687 * extra instructions from subprog; the next 3688 * instruction after call to global subprog 3689 * should be literally next instruction in 3690 * caller program 3691 */ 3692 WARN_ONCE(idx + 1 != subseq_idx, "verifier backtracking bug"); 3693 /* r1-r5 are invalidated after subprog call, 3694 * so for global func call it shouldn't be set 3695 * anymore 3696 */ 3697 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3698 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3699 WARN_ONCE(1, "verifier backtracking bug"); 3700 return -EFAULT; 3701 } 3702 /* global subprog always sets R0 */ 3703 bt_clear_reg(bt, BPF_REG_0); 3704 return 0; 3705 } else { 3706 /* static subprog call instruction, which 3707 * means that we are exiting current subprog, 3708 * so only r1-r5 could be still requested as 3709 * precise, r0 and r6-r10 or any stack slot in 3710 * the current frame should be zero by now 3711 */ 3712 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3713 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3714 WARN_ONCE(1, "verifier backtracking bug"); 3715 return -EFAULT; 3716 } 3717 /* we are now tracking register spills correctly, 3718 * so any instance of leftover slots is a bug 3719 */ 3720 if (bt_stack_mask(bt) != 0) { 3721 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3722 WARN_ONCE(1, "verifier backtracking bug (subprog leftover stack slots)"); 3723 return -EFAULT; 3724 } 3725 /* propagate r1-r5 to the caller */ 3726 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 3727 if (bt_is_reg_set(bt, i)) { 3728 bt_clear_reg(bt, i); 3729 bt_set_frame_reg(bt, bt->frame - 1, i); 3730 } 3731 } 3732 if (bt_subprog_exit(bt)) 3733 return -EFAULT; 3734 return 0; 3735 } 3736 } else if (is_sync_callback_calling_insn(insn) && idx != subseq_idx - 1) { 3737 /* exit from callback subprog to callback-calling helper or 3738 * kfunc call. Use idx/subseq_idx check to discern it from 3739 * straight line code backtracking. 3740 * Unlike the subprog call handling above, we shouldn't 3741 * propagate precision of r1-r5 (if any requested), as they are 3742 * not actually arguments passed directly to callback subprogs 3743 */ 3744 if (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) { 3745 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3746 WARN_ONCE(1, "verifier backtracking bug"); 3747 return -EFAULT; 3748 } 3749 if (bt_stack_mask(bt) != 0) { 3750 verbose(env, "BUG stack slots %llx\n", bt_stack_mask(bt)); 3751 WARN_ONCE(1, "verifier backtracking bug (callback leftover stack slots)"); 3752 return -EFAULT; 3753 } 3754 /* clear r1-r5 in callback subprog's mask */ 3755 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3756 bt_clear_reg(bt, i); 3757 if (bt_subprog_exit(bt)) 3758 return -EFAULT; 3759 return 0; 3760 } else if (opcode == BPF_CALL) { 3761 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3762 * catch this error later. Make backtracking conservative 3763 * with ENOTSUPP. 3764 */ 3765 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3766 return -ENOTSUPP; 3767 /* regular helper call sets R0 */ 3768 bt_clear_reg(bt, BPF_REG_0); 3769 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3770 /* if backtracing was looking for registers R1-R5 3771 * they should have been found already. 3772 */ 3773 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3774 WARN_ONCE(1, "verifier backtracking bug"); 3775 return -EFAULT; 3776 } 3777 } else if (opcode == BPF_EXIT) { 3778 bool r0_precise; 3779 3780 /* Backtracking to a nested function call, 'idx' is a part of 3781 * the inner frame 'subseq_idx' is a part of the outer frame. 3782 * In case of a regular function call, instructions giving 3783 * precision to registers R1-R5 should have been found already. 3784 * In case of a callback, it is ok to have R1-R5 marked for 3785 * backtracking, as these registers are set by the function 3786 * invoking callback. 3787 */ 3788 if (subseq_idx >= 0 && calls_callback(env, subseq_idx)) 3789 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3790 bt_clear_reg(bt, i); 3791 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3792 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3793 WARN_ONCE(1, "verifier backtracking bug"); 3794 return -EFAULT; 3795 } 3796 3797 /* BPF_EXIT in subprog or callback always returns 3798 * right after the call instruction, so by checking 3799 * whether the instruction at subseq_idx-1 is subprog 3800 * call or not we can distinguish actual exit from 3801 * *subprog* from exit from *callback*. In the former 3802 * case, we need to propagate r0 precision, if 3803 * necessary. In the former we never do that. 3804 */ 3805 r0_precise = subseq_idx - 1 >= 0 && 3806 bpf_pseudo_call(&env->prog->insnsi[subseq_idx - 1]) && 3807 bt_is_reg_set(bt, BPF_REG_0); 3808 3809 bt_clear_reg(bt, BPF_REG_0); 3810 if (bt_subprog_enter(bt)) 3811 return -EFAULT; 3812 3813 if (r0_precise) 3814 bt_set_reg(bt, BPF_REG_0); 3815 /* r6-r9 and stack slots will stay set in caller frame 3816 * bitmasks until we return back from callee(s) 3817 */ 3818 return 0; 3819 } else if (BPF_SRC(insn->code) == BPF_X) { 3820 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3821 return 0; 3822 /* dreg <cond> sreg 3823 * Both dreg and sreg need precision before 3824 * this insn. If only sreg was marked precise 3825 * before it would be equally necessary to 3826 * propagate it to dreg. 3827 */ 3828 bt_set_reg(bt, dreg); 3829 bt_set_reg(bt, sreg); 3830 /* else dreg <cond> K 3831 * Only dreg still needs precision before 3832 * this insn, so for the K-based conditional 3833 * there is nothing new to be marked. 3834 */ 3835 } 3836 } else if (class == BPF_LD) { 3837 if (!bt_is_reg_set(bt, dreg)) 3838 return 0; 3839 bt_clear_reg(bt, dreg); 3840 /* It's ld_imm64 or ld_abs or ld_ind. 3841 * For ld_imm64 no further tracking of precision 3842 * into parent is necessary 3843 */ 3844 if (mode == BPF_IND || mode == BPF_ABS) 3845 /* to be analyzed */ 3846 return -ENOTSUPP; 3847 } 3848 return 0; 3849 } 3850 3851 /* the scalar precision tracking algorithm: 3852 * . at the start all registers have precise=false. 3853 * . scalar ranges are tracked as normal through alu and jmp insns. 3854 * . once precise value of the scalar register is used in: 3855 * . ptr + scalar alu 3856 * . if (scalar cond K|scalar) 3857 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3858 * backtrack through the verifier states and mark all registers and 3859 * stack slots with spilled constants that these scalar regisers 3860 * should be precise. 3861 * . during state pruning two registers (or spilled stack slots) 3862 * are equivalent if both are not precise. 3863 * 3864 * Note the verifier cannot simply walk register parentage chain, 3865 * since many different registers and stack slots could have been 3866 * used to compute single precise scalar. 3867 * 3868 * The approach of starting with precise=true for all registers and then 3869 * backtrack to mark a register as not precise when the verifier detects 3870 * that program doesn't care about specific value (e.g., when helper 3871 * takes register as ARG_ANYTHING parameter) is not safe. 3872 * 3873 * It's ok to walk single parentage chain of the verifier states. 3874 * It's possible that this backtracking will go all the way till 1st insn. 3875 * All other branches will be explored for needing precision later. 3876 * 3877 * The backtracking needs to deal with cases like: 3878 * 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) 3879 * r9 -= r8 3880 * r5 = r9 3881 * if r5 > 0x79f goto pc+7 3882 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3883 * r5 += 1 3884 * ... 3885 * call bpf_perf_event_output#25 3886 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3887 * 3888 * and this case: 3889 * r6 = 1 3890 * call foo // uses callee's r6 inside to compute r0 3891 * r0 += r6 3892 * if r0 == 0 goto 3893 * 3894 * to track above reg_mask/stack_mask needs to be independent for each frame. 3895 * 3896 * Also if parent's curframe > frame where backtracking started, 3897 * the verifier need to mark registers in both frames, otherwise callees 3898 * may incorrectly prune callers. This is similar to 3899 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3900 * 3901 * For now backtracking falls back into conservative marking. 3902 */ 3903 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3904 struct bpf_verifier_state *st) 3905 { 3906 struct bpf_func_state *func; 3907 struct bpf_reg_state *reg; 3908 int i, j; 3909 3910 if (env->log.level & BPF_LOG_LEVEL2) { 3911 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3912 st->curframe); 3913 } 3914 3915 /* big hammer: mark all scalars precise in this path. 3916 * pop_stack may still get !precise scalars. 3917 * We also skip current state and go straight to first parent state, 3918 * because precision markings in current non-checkpointed state are 3919 * not needed. See why in the comment in __mark_chain_precision below. 3920 */ 3921 for (st = st->parent; st; st = st->parent) { 3922 for (i = 0; i <= st->curframe; i++) { 3923 func = st->frame[i]; 3924 for (j = 0; j < BPF_REG_FP; j++) { 3925 reg = &func->regs[j]; 3926 if (reg->type != SCALAR_VALUE || reg->precise) 3927 continue; 3928 reg->precise = true; 3929 if (env->log.level & BPF_LOG_LEVEL2) { 3930 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 3931 i, j); 3932 } 3933 } 3934 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3935 if (!is_spilled_reg(&func->stack[j])) 3936 continue; 3937 reg = &func->stack[j].spilled_ptr; 3938 if (reg->type != SCALAR_VALUE || reg->precise) 3939 continue; 3940 reg->precise = true; 3941 if (env->log.level & BPF_LOG_LEVEL2) { 3942 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 3943 i, -(j + 1) * 8); 3944 } 3945 } 3946 } 3947 } 3948 } 3949 3950 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3951 { 3952 struct bpf_func_state *func; 3953 struct bpf_reg_state *reg; 3954 int i, j; 3955 3956 for (i = 0; i <= st->curframe; i++) { 3957 func = st->frame[i]; 3958 for (j = 0; j < BPF_REG_FP; j++) { 3959 reg = &func->regs[j]; 3960 if (reg->type != SCALAR_VALUE) 3961 continue; 3962 reg->precise = false; 3963 } 3964 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3965 if (!is_spilled_reg(&func->stack[j])) 3966 continue; 3967 reg = &func->stack[j].spilled_ptr; 3968 if (reg->type != SCALAR_VALUE) 3969 continue; 3970 reg->precise = false; 3971 } 3972 } 3973 } 3974 3975 static bool idset_contains(struct bpf_idset *s, u32 id) 3976 { 3977 u32 i; 3978 3979 for (i = 0; i < s->count; ++i) 3980 if (s->ids[i] == id) 3981 return true; 3982 3983 return false; 3984 } 3985 3986 static int idset_push(struct bpf_idset *s, u32 id) 3987 { 3988 if (WARN_ON_ONCE(s->count >= ARRAY_SIZE(s->ids))) 3989 return -EFAULT; 3990 s->ids[s->count++] = id; 3991 return 0; 3992 } 3993 3994 static void idset_reset(struct bpf_idset *s) 3995 { 3996 s->count = 0; 3997 } 3998 3999 /* Collect a set of IDs for all registers currently marked as precise in env->bt. 4000 * Mark all registers with these IDs as precise. 4001 */ 4002 static int mark_precise_scalar_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 4003 { 4004 struct bpf_idset *precise_ids = &env->idset_scratch; 4005 struct backtrack_state *bt = &env->bt; 4006 struct bpf_func_state *func; 4007 struct bpf_reg_state *reg; 4008 DECLARE_BITMAP(mask, 64); 4009 int i, fr; 4010 4011 idset_reset(precise_ids); 4012 4013 for (fr = bt->frame; fr >= 0; fr--) { 4014 func = st->frame[fr]; 4015 4016 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4017 for_each_set_bit(i, mask, 32) { 4018 reg = &func->regs[i]; 4019 if (!reg->id || reg->type != SCALAR_VALUE) 4020 continue; 4021 if (idset_push(precise_ids, reg->id)) 4022 return -EFAULT; 4023 } 4024 4025 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4026 for_each_set_bit(i, mask, 64) { 4027 if (i >= func->allocated_stack / BPF_REG_SIZE) 4028 break; 4029 if (!is_spilled_scalar_reg(&func->stack[i])) 4030 continue; 4031 reg = &func->stack[i].spilled_ptr; 4032 if (!reg->id) 4033 continue; 4034 if (idset_push(precise_ids, reg->id)) 4035 return -EFAULT; 4036 } 4037 } 4038 4039 for (fr = 0; fr <= st->curframe; ++fr) { 4040 func = st->frame[fr]; 4041 4042 for (i = BPF_REG_0; i < BPF_REG_10; ++i) { 4043 reg = &func->regs[i]; 4044 if (!reg->id) 4045 continue; 4046 if (!idset_contains(precise_ids, reg->id)) 4047 continue; 4048 bt_set_frame_reg(bt, fr, i); 4049 } 4050 for (i = 0; i < func->allocated_stack / BPF_REG_SIZE; ++i) { 4051 if (!is_spilled_scalar_reg(&func->stack[i])) 4052 continue; 4053 reg = &func->stack[i].spilled_ptr; 4054 if (!reg->id) 4055 continue; 4056 if (!idset_contains(precise_ids, reg->id)) 4057 continue; 4058 bt_set_frame_slot(bt, fr, i); 4059 } 4060 } 4061 4062 return 0; 4063 } 4064 4065 /* 4066 * __mark_chain_precision() backtracks BPF program instruction sequence and 4067 * chain of verifier states making sure that register *regno* (if regno >= 0) 4068 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 4069 * SCALARS, as well as any other registers and slots that contribute to 4070 * a tracked state of given registers/stack slots, depending on specific BPF 4071 * assembly instructions (see backtrack_insns() for exact instruction handling 4072 * logic). This backtracking relies on recorded jmp_history and is able to 4073 * traverse entire chain of parent states. This process ends only when all the 4074 * necessary registers/slots and their transitive dependencies are marked as 4075 * precise. 4076 * 4077 * One important and subtle aspect is that precise marks *do not matter* in 4078 * the currently verified state (current state). It is important to understand 4079 * why this is the case. 4080 * 4081 * First, note that current state is the state that is not yet "checkpointed", 4082 * i.e., it is not yet put into env->explored_states, and it has no children 4083 * states as well. It's ephemeral, and can end up either a) being discarded if 4084 * compatible explored state is found at some point or BPF_EXIT instruction is 4085 * reached or b) checkpointed and put into env->explored_states, branching out 4086 * into one or more children states. 4087 * 4088 * In the former case, precise markings in current state are completely 4089 * ignored by state comparison code (see regsafe() for details). Only 4090 * checkpointed ("old") state precise markings are important, and if old 4091 * state's register/slot is precise, regsafe() assumes current state's 4092 * register/slot as precise and checks value ranges exactly and precisely. If 4093 * states turn out to be compatible, current state's necessary precise 4094 * markings and any required parent states' precise markings are enforced 4095 * after the fact with propagate_precision() logic, after the fact. But it's 4096 * important to realize that in this case, even after marking current state 4097 * registers/slots as precise, we immediately discard current state. So what 4098 * actually matters is any of the precise markings propagated into current 4099 * state's parent states, which are always checkpointed (due to b) case above). 4100 * As such, for scenario a) it doesn't matter if current state has precise 4101 * markings set or not. 4102 * 4103 * Now, for the scenario b), checkpointing and forking into child(ren) 4104 * state(s). Note that before current state gets to checkpointing step, any 4105 * processed instruction always assumes precise SCALAR register/slot 4106 * knowledge: if precise value or range is useful to prune jump branch, BPF 4107 * verifier takes this opportunity enthusiastically. Similarly, when 4108 * register's value is used to calculate offset or memory address, exact 4109 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 4110 * what we mentioned above about state comparison ignoring precise markings 4111 * during state comparison, BPF verifier ignores and also assumes precise 4112 * markings *at will* during instruction verification process. But as verifier 4113 * assumes precision, it also propagates any precision dependencies across 4114 * parent states, which are not yet finalized, so can be further restricted 4115 * based on new knowledge gained from restrictions enforced by their children 4116 * states. This is so that once those parent states are finalized, i.e., when 4117 * they have no more active children state, state comparison logic in 4118 * is_state_visited() would enforce strict and precise SCALAR ranges, if 4119 * required for correctness. 4120 * 4121 * To build a bit more intuition, note also that once a state is checkpointed, 4122 * the path we took to get to that state is not important. This is crucial 4123 * property for state pruning. When state is checkpointed and finalized at 4124 * some instruction index, it can be correctly and safely used to "short 4125 * circuit" any *compatible* state that reaches exactly the same instruction 4126 * index. I.e., if we jumped to that instruction from a completely different 4127 * code path than original finalized state was derived from, it doesn't 4128 * matter, current state can be discarded because from that instruction 4129 * forward having a compatible state will ensure we will safely reach the 4130 * exit. States describe preconditions for further exploration, but completely 4131 * forget the history of how we got here. 4132 * 4133 * This also means that even if we needed precise SCALAR range to get to 4134 * finalized state, but from that point forward *that same* SCALAR register is 4135 * never used in a precise context (i.e., it's precise value is not needed for 4136 * correctness), it's correct and safe to mark such register as "imprecise" 4137 * (i.e., precise marking set to false). This is what we rely on when we do 4138 * not set precise marking in current state. If no child state requires 4139 * precision for any given SCALAR register, it's safe to dictate that it can 4140 * be imprecise. If any child state does require this register to be precise, 4141 * we'll mark it precise later retroactively during precise markings 4142 * propagation from child state to parent states. 4143 * 4144 * Skipping precise marking setting in current state is a mild version of 4145 * relying on the above observation. But we can utilize this property even 4146 * more aggressively by proactively forgetting any precise marking in the 4147 * current state (which we inherited from the parent state), right before we 4148 * checkpoint it and branch off into new child state. This is done by 4149 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 4150 * finalized states which help in short circuiting more future states. 4151 */ 4152 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno) 4153 { 4154 struct backtrack_state *bt = &env->bt; 4155 struct bpf_verifier_state *st = env->cur_state; 4156 int first_idx = st->first_insn_idx; 4157 int last_idx = env->insn_idx; 4158 int subseq_idx = -1; 4159 struct bpf_func_state *func; 4160 struct bpf_reg_state *reg; 4161 bool skip_first = true; 4162 int i, fr, err; 4163 4164 if (!env->bpf_capable) 4165 return 0; 4166 4167 /* set frame number from which we are starting to backtrack */ 4168 bt_init(bt, env->cur_state->curframe); 4169 4170 /* Do sanity checks against current state of register and/or stack 4171 * slot, but don't set precise flag in current state, as precision 4172 * tracking in the current state is unnecessary. 4173 */ 4174 func = st->frame[bt->frame]; 4175 if (regno >= 0) { 4176 reg = &func->regs[regno]; 4177 if (reg->type != SCALAR_VALUE) { 4178 WARN_ONCE(1, "backtracing misuse"); 4179 return -EFAULT; 4180 } 4181 bt_set_reg(bt, regno); 4182 } 4183 4184 if (bt_empty(bt)) 4185 return 0; 4186 4187 for (;;) { 4188 DECLARE_BITMAP(mask, 64); 4189 u32 history = st->jmp_history_cnt; 4190 struct bpf_jmp_history_entry *hist; 4191 4192 if (env->log.level & BPF_LOG_LEVEL2) { 4193 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d subseq_idx %d \n", 4194 bt->frame, last_idx, first_idx, subseq_idx); 4195 } 4196 4197 /* If some register with scalar ID is marked as precise, 4198 * make sure that all registers sharing this ID are also precise. 4199 * This is needed to estimate effect of find_equal_scalars(). 4200 * Do this at the last instruction of each state, 4201 * bpf_reg_state::id fields are valid for these instructions. 4202 * 4203 * Allows to track precision in situation like below: 4204 * 4205 * r2 = unknown value 4206 * ... 4207 * --- state #0 --- 4208 * ... 4209 * r1 = r2 // r1 and r2 now share the same ID 4210 * ... 4211 * --- state #1 {r1.id = A, r2.id = A} --- 4212 * ... 4213 * if (r2 > 10) goto exit; // find_equal_scalars() assigns range to r1 4214 * ... 4215 * --- state #2 {r1.id = A, r2.id = A} --- 4216 * r3 = r10 4217 * r3 += r1 // need to mark both r1 and r2 4218 */ 4219 if (mark_precise_scalar_ids(env, st)) 4220 return -EFAULT; 4221 4222 if (last_idx < 0) { 4223 /* we are at the entry into subprog, which 4224 * is expected for global funcs, but only if 4225 * requested precise registers are R1-R5 4226 * (which are global func's input arguments) 4227 */ 4228 if (st->curframe == 0 && 4229 st->frame[0]->subprogno > 0 && 4230 st->frame[0]->callsite == BPF_MAIN_FUNC && 4231 bt_stack_mask(bt) == 0 && 4232 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 4233 bitmap_from_u64(mask, bt_reg_mask(bt)); 4234 for_each_set_bit(i, mask, 32) { 4235 reg = &st->frame[0]->regs[i]; 4236 bt_clear_reg(bt, i); 4237 if (reg->type == SCALAR_VALUE) 4238 reg->precise = true; 4239 } 4240 return 0; 4241 } 4242 4243 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 4244 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 4245 WARN_ONCE(1, "verifier backtracking bug"); 4246 return -EFAULT; 4247 } 4248 4249 for (i = last_idx;;) { 4250 if (skip_first) { 4251 err = 0; 4252 skip_first = false; 4253 } else { 4254 hist = get_jmp_hist_entry(st, history, i); 4255 err = backtrack_insn(env, i, subseq_idx, hist, bt); 4256 } 4257 if (err == -ENOTSUPP) { 4258 mark_all_scalars_precise(env, env->cur_state); 4259 bt_reset(bt); 4260 return 0; 4261 } else if (err) { 4262 return err; 4263 } 4264 if (bt_empty(bt)) 4265 /* Found assignment(s) into tracked register in this state. 4266 * Since this state is already marked, just return. 4267 * Nothing to be tracked further in the parent state. 4268 */ 4269 return 0; 4270 subseq_idx = i; 4271 i = get_prev_insn_idx(st, i, &history); 4272 if (i == -ENOENT) 4273 break; 4274 if (i >= env->prog->len) { 4275 /* This can happen if backtracking reached insn 0 4276 * and there are still reg_mask or stack_mask 4277 * to backtrack. 4278 * It means the backtracking missed the spot where 4279 * particular register was initialized with a constant. 4280 */ 4281 verbose(env, "BUG backtracking idx %d\n", i); 4282 WARN_ONCE(1, "verifier backtracking bug"); 4283 return -EFAULT; 4284 } 4285 } 4286 st = st->parent; 4287 if (!st) 4288 break; 4289 4290 for (fr = bt->frame; fr >= 0; fr--) { 4291 func = st->frame[fr]; 4292 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 4293 for_each_set_bit(i, mask, 32) { 4294 reg = &func->regs[i]; 4295 if (reg->type != SCALAR_VALUE) { 4296 bt_clear_frame_reg(bt, fr, i); 4297 continue; 4298 } 4299 if (reg->precise) 4300 bt_clear_frame_reg(bt, fr, i); 4301 else 4302 reg->precise = true; 4303 } 4304 4305 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 4306 for_each_set_bit(i, mask, 64) { 4307 if (i >= func->allocated_stack / BPF_REG_SIZE) { 4308 verbose(env, "BUG backtracking (stack slot %d, total slots %d)\n", 4309 i, func->allocated_stack / BPF_REG_SIZE); 4310 WARN_ONCE(1, "verifier backtracking bug (stack slot out of bounds)"); 4311 return -EFAULT; 4312 } 4313 4314 if (!is_spilled_scalar_reg(&func->stack[i])) { 4315 bt_clear_frame_slot(bt, fr, i); 4316 continue; 4317 } 4318 reg = &func->stack[i].spilled_ptr; 4319 if (reg->precise) 4320 bt_clear_frame_slot(bt, fr, i); 4321 else 4322 reg->precise = true; 4323 } 4324 if (env->log.level & BPF_LOG_LEVEL2) { 4325 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4326 bt_frame_reg_mask(bt, fr)); 4327 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 4328 fr, env->tmp_str_buf); 4329 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 4330 bt_frame_stack_mask(bt, fr)); 4331 verbose(env, "stack=%s: ", env->tmp_str_buf); 4332 print_verifier_state(env, func, true); 4333 } 4334 } 4335 4336 if (bt_empty(bt)) 4337 return 0; 4338 4339 subseq_idx = first_idx; 4340 last_idx = st->last_insn_idx; 4341 first_idx = st->first_insn_idx; 4342 } 4343 4344 /* if we still have requested precise regs or slots, we missed 4345 * something (e.g., stack access through non-r10 register), so 4346 * fallback to marking all precise 4347 */ 4348 if (!bt_empty(bt)) { 4349 mark_all_scalars_precise(env, env->cur_state); 4350 bt_reset(bt); 4351 } 4352 4353 return 0; 4354 } 4355 4356 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 4357 { 4358 return __mark_chain_precision(env, regno); 4359 } 4360 4361 /* mark_chain_precision_batch() assumes that env->bt is set in the caller to 4362 * desired reg and stack masks across all relevant frames 4363 */ 4364 static int mark_chain_precision_batch(struct bpf_verifier_env *env) 4365 { 4366 return __mark_chain_precision(env, -1); 4367 } 4368 4369 static bool is_spillable_regtype(enum bpf_reg_type type) 4370 { 4371 switch (base_type(type)) { 4372 case PTR_TO_MAP_VALUE: 4373 case PTR_TO_STACK: 4374 case PTR_TO_CTX: 4375 case PTR_TO_PACKET: 4376 case PTR_TO_PACKET_META: 4377 case PTR_TO_PACKET_END: 4378 case PTR_TO_FLOW_KEYS: 4379 case CONST_PTR_TO_MAP: 4380 case PTR_TO_SOCKET: 4381 case PTR_TO_SOCK_COMMON: 4382 case PTR_TO_TCP_SOCK: 4383 case PTR_TO_XDP_SOCK: 4384 case PTR_TO_BTF_ID: 4385 case PTR_TO_BUF: 4386 case PTR_TO_MEM: 4387 case PTR_TO_FUNC: 4388 case PTR_TO_MAP_KEY: 4389 case PTR_TO_ARENA: 4390 return true; 4391 default: 4392 return false; 4393 } 4394 } 4395 4396 /* Does this register contain a constant zero? */ 4397 static bool register_is_null(struct bpf_reg_state *reg) 4398 { 4399 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 4400 } 4401 4402 /* check if register is a constant scalar value */ 4403 static bool is_reg_const(struct bpf_reg_state *reg, bool subreg32) 4404 { 4405 return reg->type == SCALAR_VALUE && 4406 tnum_is_const(subreg32 ? tnum_subreg(reg->var_off) : reg->var_off); 4407 } 4408 4409 /* assuming is_reg_const() is true, return constant value of a register */ 4410 static u64 reg_const_value(struct bpf_reg_state *reg, bool subreg32) 4411 { 4412 return subreg32 ? tnum_subreg(reg->var_off).value : reg->var_off.value; 4413 } 4414 4415 static bool __is_pointer_value(bool allow_ptr_leaks, 4416 const struct bpf_reg_state *reg) 4417 { 4418 if (allow_ptr_leaks) 4419 return false; 4420 4421 return reg->type != SCALAR_VALUE; 4422 } 4423 4424 static void assign_scalar_id_before_mov(struct bpf_verifier_env *env, 4425 struct bpf_reg_state *src_reg) 4426 { 4427 if (src_reg->type == SCALAR_VALUE && !src_reg->id && 4428 !tnum_is_const(src_reg->var_off)) 4429 /* Ensure that src_reg has a valid ID that will be copied to 4430 * dst_reg and then will be used by find_equal_scalars() to 4431 * propagate min/max range. 4432 */ 4433 src_reg->id = ++env->id_gen; 4434 } 4435 4436 /* Copy src state preserving dst->parent and dst->live fields */ 4437 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 4438 { 4439 struct bpf_reg_state *parent = dst->parent; 4440 enum bpf_reg_liveness live = dst->live; 4441 4442 *dst = *src; 4443 dst->parent = parent; 4444 dst->live = live; 4445 } 4446 4447 static void save_register_state(struct bpf_verifier_env *env, 4448 struct bpf_func_state *state, 4449 int spi, struct bpf_reg_state *reg, 4450 int size) 4451 { 4452 int i; 4453 4454 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4455 if (size == BPF_REG_SIZE) 4456 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4457 4458 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4459 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4460 4461 /* size < 8 bytes spill */ 4462 for (; i; i--) 4463 mark_stack_slot_misc(env, &state->stack[spi].slot_type[i - 1]); 4464 } 4465 4466 static bool is_bpf_st_mem(struct bpf_insn *insn) 4467 { 4468 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4469 } 4470 4471 static int get_reg_width(struct bpf_reg_state *reg) 4472 { 4473 return fls64(reg->umax_value); 4474 } 4475 4476 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4477 * stack boundary and alignment are checked in check_mem_access() 4478 */ 4479 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4480 /* stack frame we're writing to */ 4481 struct bpf_func_state *state, 4482 int off, int size, int value_regno, 4483 int insn_idx) 4484 { 4485 struct bpf_func_state *cur; /* state of the current function */ 4486 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4487 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4488 struct bpf_reg_state *reg = NULL; 4489 int insn_flags = insn_stack_access_flags(state->frameno, spi); 4490 4491 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4492 * so it's aligned access and [off, off + size) are within stack limits 4493 */ 4494 if (!env->allow_ptr_leaks && 4495 is_spilled_reg(&state->stack[spi]) && 4496 size != BPF_REG_SIZE) { 4497 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4498 return -EACCES; 4499 } 4500 4501 cur = env->cur_state->frame[env->cur_state->curframe]; 4502 if (value_regno >= 0) 4503 reg = &cur->regs[value_regno]; 4504 if (!env->bypass_spec_v4) { 4505 bool sanitize = reg && is_spillable_regtype(reg->type); 4506 4507 for (i = 0; i < size; i++) { 4508 u8 type = state->stack[spi].slot_type[i]; 4509 4510 if (type != STACK_MISC && type != STACK_ZERO) { 4511 sanitize = true; 4512 break; 4513 } 4514 } 4515 4516 if (sanitize) 4517 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4518 } 4519 4520 err = destroy_if_dynptr_stack_slot(env, state, spi); 4521 if (err) 4522 return err; 4523 4524 mark_stack_slot_scratched(env, spi); 4525 if (reg && !(off % BPF_REG_SIZE) && reg->type == SCALAR_VALUE && env->bpf_capable) { 4526 bool reg_value_fits; 4527 4528 reg_value_fits = get_reg_width(reg) <= BITS_PER_BYTE * size; 4529 /* Make sure that reg had an ID to build a relation on spill. */ 4530 if (reg_value_fits) 4531 assign_scalar_id_before_mov(env, reg); 4532 save_register_state(env, state, spi, reg, size); 4533 /* Break the relation on a narrowing spill. */ 4534 if (!reg_value_fits) 4535 state->stack[spi].spilled_ptr.id = 0; 4536 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4537 env->bpf_capable) { 4538 struct bpf_reg_state fake_reg = {}; 4539 4540 __mark_reg_known(&fake_reg, insn->imm); 4541 fake_reg.type = SCALAR_VALUE; 4542 save_register_state(env, state, spi, &fake_reg, size); 4543 } else if (reg && is_spillable_regtype(reg->type)) { 4544 /* register containing pointer is being spilled into stack */ 4545 if (size != BPF_REG_SIZE) { 4546 verbose_linfo(env, insn_idx, "; "); 4547 verbose(env, "invalid size of register spill\n"); 4548 return -EACCES; 4549 } 4550 if (state != cur && reg->type == PTR_TO_STACK) { 4551 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4552 return -EINVAL; 4553 } 4554 save_register_state(env, state, spi, reg, size); 4555 } else { 4556 u8 type = STACK_MISC; 4557 4558 /* regular write of data into stack destroys any spilled ptr */ 4559 state->stack[spi].spilled_ptr.type = NOT_INIT; 4560 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4561 if (is_stack_slot_special(&state->stack[spi])) 4562 for (i = 0; i < BPF_REG_SIZE; i++) 4563 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4564 4565 /* only mark the slot as written if all 8 bytes were written 4566 * otherwise read propagation may incorrectly stop too soon 4567 * when stack slots are partially written. 4568 * This heuristic means that read propagation will be 4569 * conservative, since it will add reg_live_read marks 4570 * to stack slots all the way to first state when programs 4571 * writes+reads less than 8 bytes 4572 */ 4573 if (size == BPF_REG_SIZE) 4574 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4575 4576 /* when we zero initialize stack slots mark them as such */ 4577 if ((reg && register_is_null(reg)) || 4578 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4579 /* STACK_ZERO case happened because register spill 4580 * wasn't properly aligned at the stack slot boundary, 4581 * so it's not a register spill anymore; force 4582 * originating register to be precise to make 4583 * STACK_ZERO correct for subsequent states 4584 */ 4585 err = mark_chain_precision(env, value_regno); 4586 if (err) 4587 return err; 4588 type = STACK_ZERO; 4589 } 4590 4591 /* Mark slots affected by this stack write. */ 4592 for (i = 0; i < size; i++) 4593 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = type; 4594 insn_flags = 0; /* not a register spill */ 4595 } 4596 4597 if (insn_flags) 4598 return push_jmp_history(env, env->cur_state, insn_flags); 4599 return 0; 4600 } 4601 4602 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4603 * known to contain a variable offset. 4604 * This function checks whether the write is permitted and conservatively 4605 * tracks the effects of the write, considering that each stack slot in the 4606 * dynamic range is potentially written to. 4607 * 4608 * 'off' includes 'regno->off'. 4609 * 'value_regno' can be -1, meaning that an unknown value is being written to 4610 * the stack. 4611 * 4612 * Spilled pointers in range are not marked as written because we don't know 4613 * what's going to be actually written. This means that read propagation for 4614 * future reads cannot be terminated by this write. 4615 * 4616 * For privileged programs, uninitialized stack slots are considered 4617 * initialized by this write (even though we don't know exactly what offsets 4618 * are going to be written to). The idea is that we don't want the verifier to 4619 * reject future reads that access slots written to through variable offsets. 4620 */ 4621 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4622 /* func where register points to */ 4623 struct bpf_func_state *state, 4624 int ptr_regno, int off, int size, 4625 int value_regno, int insn_idx) 4626 { 4627 struct bpf_func_state *cur; /* state of the current function */ 4628 int min_off, max_off; 4629 int i, err; 4630 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4631 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4632 bool writing_zero = false; 4633 /* set if the fact that we're writing a zero is used to let any 4634 * stack slots remain STACK_ZERO 4635 */ 4636 bool zero_used = false; 4637 4638 cur = env->cur_state->frame[env->cur_state->curframe]; 4639 ptr_reg = &cur->regs[ptr_regno]; 4640 min_off = ptr_reg->smin_value + off; 4641 max_off = ptr_reg->smax_value + off + size; 4642 if (value_regno >= 0) 4643 value_reg = &cur->regs[value_regno]; 4644 if ((value_reg && register_is_null(value_reg)) || 4645 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4646 writing_zero = true; 4647 4648 for (i = min_off; i < max_off; i++) { 4649 int spi; 4650 4651 spi = __get_spi(i); 4652 err = destroy_if_dynptr_stack_slot(env, state, spi); 4653 if (err) 4654 return err; 4655 } 4656 4657 /* Variable offset writes destroy any spilled pointers in range. */ 4658 for (i = min_off; i < max_off; i++) { 4659 u8 new_type, *stype; 4660 int slot, spi; 4661 4662 slot = -i - 1; 4663 spi = slot / BPF_REG_SIZE; 4664 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4665 mark_stack_slot_scratched(env, spi); 4666 4667 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4668 /* Reject the write if range we may write to has not 4669 * been initialized beforehand. If we didn't reject 4670 * here, the ptr status would be erased below (even 4671 * though not all slots are actually overwritten), 4672 * possibly opening the door to leaks. 4673 * 4674 * We do however catch STACK_INVALID case below, and 4675 * only allow reading possibly uninitialized memory 4676 * later for CAP_PERFMON, as the write may not happen to 4677 * that slot. 4678 */ 4679 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4680 insn_idx, i); 4681 return -EINVAL; 4682 } 4683 4684 /* If writing_zero and the spi slot contains a spill of value 0, 4685 * maintain the spill type. 4686 */ 4687 if (writing_zero && *stype == STACK_SPILL && 4688 is_spilled_scalar_reg(&state->stack[spi])) { 4689 struct bpf_reg_state *spill_reg = &state->stack[spi].spilled_ptr; 4690 4691 if (tnum_is_const(spill_reg->var_off) && spill_reg->var_off.value == 0) { 4692 zero_used = true; 4693 continue; 4694 } 4695 } 4696 4697 /* Erase all other spilled pointers. */ 4698 state->stack[spi].spilled_ptr.type = NOT_INIT; 4699 4700 /* Update the slot type. */ 4701 new_type = STACK_MISC; 4702 if (writing_zero && *stype == STACK_ZERO) { 4703 new_type = STACK_ZERO; 4704 zero_used = true; 4705 } 4706 /* If the slot is STACK_INVALID, we check whether it's OK to 4707 * pretend that it will be initialized by this write. The slot 4708 * might not actually be written to, and so if we mark it as 4709 * initialized future reads might leak uninitialized memory. 4710 * For privileged programs, we will accept such reads to slots 4711 * that may or may not be written because, if we're reject 4712 * them, the error would be too confusing. 4713 */ 4714 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4715 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4716 insn_idx, i); 4717 return -EINVAL; 4718 } 4719 *stype = new_type; 4720 } 4721 if (zero_used) { 4722 /* backtracking doesn't work for STACK_ZERO yet. */ 4723 err = mark_chain_precision(env, value_regno); 4724 if (err) 4725 return err; 4726 } 4727 return 0; 4728 } 4729 4730 /* When register 'dst_regno' is assigned some values from stack[min_off, 4731 * max_off), we set the register's type according to the types of the 4732 * respective stack slots. If all the stack values are known to be zeros, then 4733 * so is the destination reg. Otherwise, the register is considered to be 4734 * SCALAR. This function does not deal with register filling; the caller must 4735 * ensure that all spilled registers in the stack range have been marked as 4736 * read. 4737 */ 4738 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4739 /* func where src register points to */ 4740 struct bpf_func_state *ptr_state, 4741 int min_off, int max_off, int dst_regno) 4742 { 4743 struct bpf_verifier_state *vstate = env->cur_state; 4744 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4745 int i, slot, spi; 4746 u8 *stype; 4747 int zeros = 0; 4748 4749 for (i = min_off; i < max_off; i++) { 4750 slot = -i - 1; 4751 spi = slot / BPF_REG_SIZE; 4752 mark_stack_slot_scratched(env, spi); 4753 stype = ptr_state->stack[spi].slot_type; 4754 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4755 break; 4756 zeros++; 4757 } 4758 if (zeros == max_off - min_off) { 4759 /* Any access_size read into register is zero extended, 4760 * so the whole register == const_zero. 4761 */ 4762 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4763 } else { 4764 /* have read misc data from the stack */ 4765 mark_reg_unknown(env, state->regs, dst_regno); 4766 } 4767 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4768 } 4769 4770 /* Read the stack at 'off' and put the results into the register indicated by 4771 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4772 * spilled reg. 4773 * 4774 * 'dst_regno' can be -1, meaning that the read value is not going to a 4775 * register. 4776 * 4777 * The access is assumed to be within the current stack bounds. 4778 */ 4779 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4780 /* func where src register points to */ 4781 struct bpf_func_state *reg_state, 4782 int off, int size, int dst_regno) 4783 { 4784 struct bpf_verifier_state *vstate = env->cur_state; 4785 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4786 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4787 struct bpf_reg_state *reg; 4788 u8 *stype, type; 4789 int insn_flags = insn_stack_access_flags(reg_state->frameno, spi); 4790 4791 stype = reg_state->stack[spi].slot_type; 4792 reg = ®_state->stack[spi].spilled_ptr; 4793 4794 mark_stack_slot_scratched(env, spi); 4795 4796 if (is_spilled_reg(®_state->stack[spi])) { 4797 u8 spill_size = 1; 4798 4799 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4800 spill_size++; 4801 4802 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4803 if (reg->type != SCALAR_VALUE) { 4804 verbose_linfo(env, env->insn_idx, "; "); 4805 verbose(env, "invalid size of register fill\n"); 4806 return -EACCES; 4807 } 4808 4809 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4810 if (dst_regno < 0) 4811 return 0; 4812 4813 if (size <= spill_size && 4814 bpf_stack_narrow_access_ok(off, size, spill_size)) { 4815 /* The earlier check_reg_arg() has decided the 4816 * subreg_def for this insn. Save it first. 4817 */ 4818 s32 subreg_def = state->regs[dst_regno].subreg_def; 4819 4820 copy_register_state(&state->regs[dst_regno], reg); 4821 state->regs[dst_regno].subreg_def = subreg_def; 4822 4823 /* Break the relation on a narrowing fill. 4824 * coerce_reg_to_size will adjust the boundaries. 4825 */ 4826 if (get_reg_width(reg) > size * BITS_PER_BYTE) 4827 state->regs[dst_regno].id = 0; 4828 } else { 4829 int spill_cnt = 0, zero_cnt = 0; 4830 4831 for (i = 0; i < size; i++) { 4832 type = stype[(slot - i) % BPF_REG_SIZE]; 4833 if (type == STACK_SPILL) { 4834 spill_cnt++; 4835 continue; 4836 } 4837 if (type == STACK_MISC) 4838 continue; 4839 if (type == STACK_ZERO) { 4840 zero_cnt++; 4841 continue; 4842 } 4843 if (type == STACK_INVALID && env->allow_uninit_stack) 4844 continue; 4845 verbose(env, "invalid read from stack off %d+%d size %d\n", 4846 off, i, size); 4847 return -EACCES; 4848 } 4849 4850 if (spill_cnt == size && 4851 tnum_is_const(reg->var_off) && reg->var_off.value == 0) { 4852 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4853 /* this IS register fill, so keep insn_flags */ 4854 } else if (zero_cnt == size) { 4855 /* similarly to mark_reg_stack_read(), preserve zeroes */ 4856 __mark_reg_const_zero(env, &state->regs[dst_regno]); 4857 insn_flags = 0; /* not restoring original register state */ 4858 } else { 4859 mark_reg_unknown(env, state->regs, dst_regno); 4860 insn_flags = 0; /* not restoring original register state */ 4861 } 4862 } 4863 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4864 } else if (dst_regno >= 0) { 4865 /* restore register state from stack */ 4866 copy_register_state(&state->regs[dst_regno], reg); 4867 /* mark reg as written since spilled pointer state likely 4868 * has its liveness marks cleared by is_state_visited() 4869 * which resets stack/reg liveness for state transitions 4870 */ 4871 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4872 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4873 /* If dst_regno==-1, the caller is asking us whether 4874 * it is acceptable to use this value as a SCALAR_VALUE 4875 * (e.g. for XADD). 4876 * We must not allow unprivileged callers to do that 4877 * with spilled pointers. 4878 */ 4879 verbose(env, "leaking pointer from stack off %d\n", 4880 off); 4881 return -EACCES; 4882 } 4883 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4884 } else { 4885 for (i = 0; i < size; i++) { 4886 type = stype[(slot - i) % BPF_REG_SIZE]; 4887 if (type == STACK_MISC) 4888 continue; 4889 if (type == STACK_ZERO) 4890 continue; 4891 if (type == STACK_INVALID && env->allow_uninit_stack) 4892 continue; 4893 verbose(env, "invalid read from stack off %d+%d size %d\n", 4894 off, i, size); 4895 return -EACCES; 4896 } 4897 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4898 if (dst_regno >= 0) 4899 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4900 insn_flags = 0; /* we are not restoring spilled register */ 4901 } 4902 if (insn_flags) 4903 return push_jmp_history(env, env->cur_state, insn_flags); 4904 return 0; 4905 } 4906 4907 enum bpf_access_src { 4908 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4909 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4910 }; 4911 4912 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4913 int regno, int off, int access_size, 4914 bool zero_size_allowed, 4915 enum bpf_access_src type, 4916 struct bpf_call_arg_meta *meta); 4917 4918 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4919 { 4920 return cur_regs(env) + regno; 4921 } 4922 4923 /* Read the stack at 'ptr_regno + off' and put the result into the register 4924 * 'dst_regno'. 4925 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4926 * but not its variable offset. 4927 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4928 * 4929 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4930 * filling registers (i.e. reads of spilled register cannot be detected when 4931 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4932 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4933 * offset; for a fixed offset check_stack_read_fixed_off should be used 4934 * instead. 4935 */ 4936 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4937 int ptr_regno, int off, int size, int dst_regno) 4938 { 4939 /* The state of the source register. */ 4940 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4941 struct bpf_func_state *ptr_state = func(env, reg); 4942 int err; 4943 int min_off, max_off; 4944 4945 /* Note that we pass a NULL meta, so raw access will not be permitted. 4946 */ 4947 err = check_stack_range_initialized(env, ptr_regno, off, size, 4948 false, ACCESS_DIRECT, NULL); 4949 if (err) 4950 return err; 4951 4952 min_off = reg->smin_value + off; 4953 max_off = reg->smax_value + off; 4954 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4955 return 0; 4956 } 4957 4958 /* check_stack_read dispatches to check_stack_read_fixed_off or 4959 * check_stack_read_var_off. 4960 * 4961 * The caller must ensure that the offset falls within the allocated stack 4962 * bounds. 4963 * 4964 * 'dst_regno' is a register which will receive the value from the stack. It 4965 * can be -1, meaning that the read value is not going to a register. 4966 */ 4967 static int check_stack_read(struct bpf_verifier_env *env, 4968 int ptr_regno, int off, int size, 4969 int dst_regno) 4970 { 4971 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4972 struct bpf_func_state *state = func(env, reg); 4973 int err; 4974 /* Some accesses are only permitted with a static offset. */ 4975 bool var_off = !tnum_is_const(reg->var_off); 4976 4977 /* The offset is required to be static when reads don't go to a 4978 * register, in order to not leak pointers (see 4979 * check_stack_read_fixed_off). 4980 */ 4981 if (dst_regno < 0 && var_off) { 4982 char tn_buf[48]; 4983 4984 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4985 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4986 tn_buf, off, size); 4987 return -EACCES; 4988 } 4989 /* Variable offset is prohibited for unprivileged mode for simplicity 4990 * since it requires corresponding support in Spectre masking for stack 4991 * ALU. See also retrieve_ptr_limit(). The check in 4992 * check_stack_access_for_ptr_arithmetic() called by 4993 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4994 * with variable offsets, therefore no check is required here. Further, 4995 * just checking it here would be insufficient as speculative stack 4996 * writes could still lead to unsafe speculative behaviour. 4997 */ 4998 if (!var_off) { 4999 off += reg->var_off.value; 5000 err = check_stack_read_fixed_off(env, state, off, size, 5001 dst_regno); 5002 } else { 5003 /* Variable offset stack reads need more conservative handling 5004 * than fixed offset ones. Note that dst_regno >= 0 on this 5005 * branch. 5006 */ 5007 err = check_stack_read_var_off(env, ptr_regno, off, size, 5008 dst_regno); 5009 } 5010 return err; 5011 } 5012 5013 5014 /* check_stack_write dispatches to check_stack_write_fixed_off or 5015 * check_stack_write_var_off. 5016 * 5017 * 'ptr_regno' is the register used as a pointer into the stack. 5018 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 5019 * 'value_regno' is the register whose value we're writing to the stack. It can 5020 * be -1, meaning that we're not writing from a register. 5021 * 5022 * The caller must ensure that the offset falls within the maximum stack size. 5023 */ 5024 static int check_stack_write(struct bpf_verifier_env *env, 5025 int ptr_regno, int off, int size, 5026 int value_regno, int insn_idx) 5027 { 5028 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 5029 struct bpf_func_state *state = func(env, reg); 5030 int err; 5031 5032 if (tnum_is_const(reg->var_off)) { 5033 off += reg->var_off.value; 5034 err = check_stack_write_fixed_off(env, state, off, size, 5035 value_regno, insn_idx); 5036 } else { 5037 /* Variable offset stack reads need more conservative handling 5038 * than fixed offset ones. 5039 */ 5040 err = check_stack_write_var_off(env, state, 5041 ptr_regno, off, size, 5042 value_regno, insn_idx); 5043 } 5044 return err; 5045 } 5046 5047 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 5048 int off, int size, enum bpf_access_type type) 5049 { 5050 struct bpf_reg_state *regs = cur_regs(env); 5051 struct bpf_map *map = regs[regno].map_ptr; 5052 u32 cap = bpf_map_flags_to_cap(map); 5053 5054 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 5055 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 5056 map->value_size, off, size); 5057 return -EACCES; 5058 } 5059 5060 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 5061 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 5062 map->value_size, off, size); 5063 return -EACCES; 5064 } 5065 5066 return 0; 5067 } 5068 5069 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 5070 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 5071 int off, int size, u32 mem_size, 5072 bool zero_size_allowed) 5073 { 5074 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 5075 struct bpf_reg_state *reg; 5076 5077 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 5078 return 0; 5079 5080 reg = &cur_regs(env)[regno]; 5081 switch (reg->type) { 5082 case PTR_TO_MAP_KEY: 5083 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 5084 mem_size, off, size); 5085 break; 5086 case PTR_TO_MAP_VALUE: 5087 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 5088 mem_size, off, size); 5089 break; 5090 case PTR_TO_PACKET: 5091 case PTR_TO_PACKET_META: 5092 case PTR_TO_PACKET_END: 5093 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 5094 off, size, regno, reg->id, off, mem_size); 5095 break; 5096 case PTR_TO_MEM: 5097 default: 5098 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 5099 mem_size, off, size); 5100 } 5101 5102 return -EACCES; 5103 } 5104 5105 /* check read/write into a memory region with possible variable offset */ 5106 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 5107 int off, int size, u32 mem_size, 5108 bool zero_size_allowed) 5109 { 5110 struct bpf_verifier_state *vstate = env->cur_state; 5111 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5112 struct bpf_reg_state *reg = &state->regs[regno]; 5113 int err; 5114 5115 /* We may have adjusted the register pointing to memory region, so we 5116 * need to try adding each of min_value and max_value to off 5117 * to make sure our theoretical access will be safe. 5118 * 5119 * The minimum value is only important with signed 5120 * comparisons where we can't assume the floor of a 5121 * value is 0. If we are using signed variables for our 5122 * index'es we need to make sure that whatever we use 5123 * will have a set floor within our range. 5124 */ 5125 if (reg->smin_value < 0 && 5126 (reg->smin_value == S64_MIN || 5127 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 5128 reg->smin_value + off < 0)) { 5129 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5130 regno); 5131 return -EACCES; 5132 } 5133 err = __check_mem_access(env, regno, reg->smin_value + off, size, 5134 mem_size, zero_size_allowed); 5135 if (err) { 5136 verbose(env, "R%d min value is outside of the allowed memory range\n", 5137 regno); 5138 return err; 5139 } 5140 5141 /* If we haven't set a max value then we need to bail since we can't be 5142 * sure we won't do bad things. 5143 * If reg->umax_value + off could overflow, treat that as unbounded too. 5144 */ 5145 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 5146 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 5147 regno); 5148 return -EACCES; 5149 } 5150 err = __check_mem_access(env, regno, reg->umax_value + off, size, 5151 mem_size, zero_size_allowed); 5152 if (err) { 5153 verbose(env, "R%d max value is outside of the allowed memory range\n", 5154 regno); 5155 return err; 5156 } 5157 5158 return 0; 5159 } 5160 5161 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 5162 const struct bpf_reg_state *reg, int regno, 5163 bool fixed_off_ok) 5164 { 5165 /* Access to this pointer-typed register or passing it to a helper 5166 * is only allowed in its original, unmodified form. 5167 */ 5168 5169 if (reg->off < 0) { 5170 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 5171 reg_type_str(env, reg->type), regno, reg->off); 5172 return -EACCES; 5173 } 5174 5175 if (!fixed_off_ok && reg->off) { 5176 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 5177 reg_type_str(env, reg->type), regno, reg->off); 5178 return -EACCES; 5179 } 5180 5181 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5182 char tn_buf[48]; 5183 5184 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5185 verbose(env, "variable %s access var_off=%s disallowed\n", 5186 reg_type_str(env, reg->type), tn_buf); 5187 return -EACCES; 5188 } 5189 5190 return 0; 5191 } 5192 5193 static int check_ptr_off_reg(struct bpf_verifier_env *env, 5194 const struct bpf_reg_state *reg, int regno) 5195 { 5196 return __check_ptr_off_reg(env, reg, regno, false); 5197 } 5198 5199 static int map_kptr_match_type(struct bpf_verifier_env *env, 5200 struct btf_field *kptr_field, 5201 struct bpf_reg_state *reg, u32 regno) 5202 { 5203 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 5204 int perm_flags; 5205 const char *reg_name = ""; 5206 5207 if (btf_is_kernel(reg->btf)) { 5208 perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 5209 5210 /* Only unreferenced case accepts untrusted pointers */ 5211 if (kptr_field->type == BPF_KPTR_UNREF) 5212 perm_flags |= PTR_UNTRUSTED; 5213 } else { 5214 perm_flags = PTR_MAYBE_NULL | MEM_ALLOC; 5215 if (kptr_field->type == BPF_KPTR_PERCPU) 5216 perm_flags |= MEM_PERCPU; 5217 } 5218 5219 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 5220 goto bad_type; 5221 5222 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 5223 reg_name = btf_type_name(reg->btf, reg->btf_id); 5224 5225 /* For ref_ptr case, release function check should ensure we get one 5226 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 5227 * normal store of unreferenced kptr, we must ensure var_off is zero. 5228 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 5229 * reg->off and reg->ref_obj_id are not needed here. 5230 */ 5231 if (__check_ptr_off_reg(env, reg, regno, true)) 5232 return -EACCES; 5233 5234 /* A full type match is needed, as BTF can be vmlinux, module or prog BTF, and 5235 * we also need to take into account the reg->off. 5236 * 5237 * We want to support cases like: 5238 * 5239 * struct foo { 5240 * struct bar br; 5241 * struct baz bz; 5242 * }; 5243 * 5244 * struct foo *v; 5245 * v = func(); // PTR_TO_BTF_ID 5246 * val->foo = v; // reg->off is zero, btf and btf_id match type 5247 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 5248 * // first member type of struct after comparison fails 5249 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 5250 * // to match type 5251 * 5252 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 5253 * is zero. We must also ensure that btf_struct_ids_match does not walk 5254 * the struct to match type against first member of struct, i.e. reject 5255 * second case from above. Hence, when type is BPF_KPTR_REF, we set 5256 * strict mode to true for type match. 5257 */ 5258 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5259 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 5260 kptr_field->type != BPF_KPTR_UNREF)) 5261 goto bad_type; 5262 return 0; 5263 bad_type: 5264 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 5265 reg_type_str(env, reg->type), reg_name); 5266 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 5267 if (kptr_field->type == BPF_KPTR_UNREF) 5268 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 5269 targ_name); 5270 else 5271 verbose(env, "\n"); 5272 return -EINVAL; 5273 } 5274 5275 static bool in_sleepable(struct bpf_verifier_env *env) 5276 { 5277 return env->prog->sleepable; 5278 } 5279 5280 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 5281 * can dereference RCU protected pointers and result is PTR_TRUSTED. 5282 */ 5283 static bool in_rcu_cs(struct bpf_verifier_env *env) 5284 { 5285 return env->cur_state->active_rcu_lock || 5286 env->cur_state->active_lock.ptr || 5287 !in_sleepable(env); 5288 } 5289 5290 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 5291 BTF_SET_START(rcu_protected_types) 5292 BTF_ID(struct, prog_test_ref_kfunc) 5293 #ifdef CONFIG_CGROUPS 5294 BTF_ID(struct, cgroup) 5295 #endif 5296 #ifdef CONFIG_BPF_JIT 5297 BTF_ID(struct, bpf_cpumask) 5298 #endif 5299 BTF_ID(struct, task_struct) 5300 BTF_SET_END(rcu_protected_types) 5301 5302 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 5303 { 5304 if (!btf_is_kernel(btf)) 5305 return true; 5306 return btf_id_set_contains(&rcu_protected_types, btf_id); 5307 } 5308 5309 static struct btf_record *kptr_pointee_btf_record(struct btf_field *kptr_field) 5310 { 5311 struct btf_struct_meta *meta; 5312 5313 if (btf_is_kernel(kptr_field->kptr.btf)) 5314 return NULL; 5315 5316 meta = btf_find_struct_meta(kptr_field->kptr.btf, 5317 kptr_field->kptr.btf_id); 5318 5319 return meta ? meta->record : NULL; 5320 } 5321 5322 static bool rcu_safe_kptr(const struct btf_field *field) 5323 { 5324 const struct btf_field_kptr *kptr = &field->kptr; 5325 5326 return field->type == BPF_KPTR_PERCPU || 5327 (field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id)); 5328 } 5329 5330 static u32 btf_ld_kptr_type(struct bpf_verifier_env *env, struct btf_field *kptr_field) 5331 { 5332 struct btf_record *rec; 5333 u32 ret; 5334 5335 ret = PTR_MAYBE_NULL; 5336 if (rcu_safe_kptr(kptr_field) && in_rcu_cs(env)) { 5337 ret |= MEM_RCU; 5338 if (kptr_field->type == BPF_KPTR_PERCPU) 5339 ret |= MEM_PERCPU; 5340 else if (!btf_is_kernel(kptr_field->kptr.btf)) 5341 ret |= MEM_ALLOC; 5342 5343 rec = kptr_pointee_btf_record(kptr_field); 5344 if (rec && btf_record_has_field(rec, BPF_GRAPH_NODE)) 5345 ret |= NON_OWN_REF; 5346 } else { 5347 ret |= PTR_UNTRUSTED; 5348 } 5349 5350 return ret; 5351 } 5352 5353 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 5354 int value_regno, int insn_idx, 5355 struct btf_field *kptr_field) 5356 { 5357 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 5358 int class = BPF_CLASS(insn->code); 5359 struct bpf_reg_state *val_reg; 5360 5361 /* Things we already checked for in check_map_access and caller: 5362 * - Reject cases where variable offset may touch kptr 5363 * - size of access (must be BPF_DW) 5364 * - tnum_is_const(reg->var_off) 5365 * - kptr_field->offset == off + reg->var_off.value 5366 */ 5367 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 5368 if (BPF_MODE(insn->code) != BPF_MEM) { 5369 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 5370 return -EACCES; 5371 } 5372 5373 /* We only allow loading referenced kptr, since it will be marked as 5374 * untrusted, similar to unreferenced kptr. 5375 */ 5376 if (class != BPF_LDX && 5377 (kptr_field->type == BPF_KPTR_REF || kptr_field->type == BPF_KPTR_PERCPU)) { 5378 verbose(env, "store to referenced kptr disallowed\n"); 5379 return -EACCES; 5380 } 5381 5382 if (class == BPF_LDX) { 5383 val_reg = reg_state(env, value_regno); 5384 /* We can simply mark the value_regno receiving the pointer 5385 * value from map as PTR_TO_BTF_ID, with the correct type. 5386 */ 5387 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 5388 kptr_field->kptr.btf_id, btf_ld_kptr_type(env, kptr_field)); 5389 /* For mark_ptr_or_null_reg */ 5390 val_reg->id = ++env->id_gen; 5391 } else if (class == BPF_STX) { 5392 val_reg = reg_state(env, value_regno); 5393 if (!register_is_null(val_reg) && 5394 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 5395 return -EACCES; 5396 } else if (class == BPF_ST) { 5397 if (insn->imm) { 5398 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 5399 kptr_field->offset); 5400 return -EACCES; 5401 } 5402 } else { 5403 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 5404 return -EACCES; 5405 } 5406 return 0; 5407 } 5408 5409 /* check read/write into a map element with possible variable offset */ 5410 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 5411 int off, int size, bool zero_size_allowed, 5412 enum bpf_access_src src) 5413 { 5414 struct bpf_verifier_state *vstate = env->cur_state; 5415 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5416 struct bpf_reg_state *reg = &state->regs[regno]; 5417 struct bpf_map *map = reg->map_ptr; 5418 struct btf_record *rec; 5419 int err, i; 5420 5421 err = check_mem_region_access(env, regno, off, size, map->value_size, 5422 zero_size_allowed); 5423 if (err) 5424 return err; 5425 5426 if (IS_ERR_OR_NULL(map->record)) 5427 return 0; 5428 rec = map->record; 5429 for (i = 0; i < rec->cnt; i++) { 5430 struct btf_field *field = &rec->fields[i]; 5431 u32 p = field->offset; 5432 5433 /* If any part of a field can be touched by load/store, reject 5434 * this program. To check that [x1, x2) overlaps with [y1, y2), 5435 * it is sufficient to check x1 < y2 && y1 < x2. 5436 */ 5437 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 5438 p < reg->umax_value + off + size) { 5439 switch (field->type) { 5440 case BPF_KPTR_UNREF: 5441 case BPF_KPTR_REF: 5442 case BPF_KPTR_PERCPU: 5443 if (src != ACCESS_DIRECT) { 5444 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 5445 return -EACCES; 5446 } 5447 if (!tnum_is_const(reg->var_off)) { 5448 verbose(env, "kptr access cannot have variable offset\n"); 5449 return -EACCES; 5450 } 5451 if (p != off + reg->var_off.value) { 5452 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 5453 p, off + reg->var_off.value); 5454 return -EACCES; 5455 } 5456 if (size != bpf_size_to_bytes(BPF_DW)) { 5457 verbose(env, "kptr access size must be BPF_DW\n"); 5458 return -EACCES; 5459 } 5460 break; 5461 default: 5462 verbose(env, "%s cannot be accessed directly by load/store\n", 5463 btf_field_type_name(field->type)); 5464 return -EACCES; 5465 } 5466 } 5467 } 5468 return 0; 5469 } 5470 5471 #define MAX_PACKET_OFF 0xffff 5472 5473 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 5474 const struct bpf_call_arg_meta *meta, 5475 enum bpf_access_type t) 5476 { 5477 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 5478 5479 switch (prog_type) { 5480 /* Program types only with direct read access go here! */ 5481 case BPF_PROG_TYPE_LWT_IN: 5482 case BPF_PROG_TYPE_LWT_OUT: 5483 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 5484 case BPF_PROG_TYPE_SK_REUSEPORT: 5485 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5486 case BPF_PROG_TYPE_CGROUP_SKB: 5487 if (t == BPF_WRITE) 5488 return false; 5489 fallthrough; 5490 5491 /* Program types with direct read + write access go here! */ 5492 case BPF_PROG_TYPE_SCHED_CLS: 5493 case BPF_PROG_TYPE_SCHED_ACT: 5494 case BPF_PROG_TYPE_XDP: 5495 case BPF_PROG_TYPE_LWT_XMIT: 5496 case BPF_PROG_TYPE_SK_SKB: 5497 case BPF_PROG_TYPE_SK_MSG: 5498 if (meta) 5499 return meta->pkt_access; 5500 5501 env->seen_direct_write = true; 5502 return true; 5503 5504 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 5505 if (t == BPF_WRITE) 5506 env->seen_direct_write = true; 5507 5508 return true; 5509 5510 default: 5511 return false; 5512 } 5513 } 5514 5515 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 5516 int size, bool zero_size_allowed) 5517 { 5518 struct bpf_reg_state *regs = cur_regs(env); 5519 struct bpf_reg_state *reg = ®s[regno]; 5520 int err; 5521 5522 /* We may have added a variable offset to the packet pointer; but any 5523 * reg->range we have comes after that. We are only checking the fixed 5524 * offset. 5525 */ 5526 5527 /* We don't allow negative numbers, because we aren't tracking enough 5528 * detail to prove they're safe. 5529 */ 5530 if (reg->smin_value < 0) { 5531 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5532 regno); 5533 return -EACCES; 5534 } 5535 5536 err = reg->range < 0 ? -EINVAL : 5537 __check_mem_access(env, regno, off, size, reg->range, 5538 zero_size_allowed); 5539 if (err) { 5540 verbose(env, "R%d offset is outside of the packet\n", regno); 5541 return err; 5542 } 5543 5544 /* __check_mem_access has made sure "off + size - 1" is within u16. 5545 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5546 * otherwise find_good_pkt_pointers would have refused to set range info 5547 * that __check_mem_access would have rejected this pkt access. 5548 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5549 */ 5550 env->prog->aux->max_pkt_offset = 5551 max_t(u32, env->prog->aux->max_pkt_offset, 5552 off + reg->umax_value + size - 1); 5553 5554 return err; 5555 } 5556 5557 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5558 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5559 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5560 struct btf **btf, u32 *btf_id) 5561 { 5562 struct bpf_insn_access_aux info = { 5563 .reg_type = *reg_type, 5564 .log = &env->log, 5565 }; 5566 5567 if (env->ops->is_valid_access && 5568 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5569 /* A non zero info.ctx_field_size indicates that this field is a 5570 * candidate for later verifier transformation to load the whole 5571 * field and then apply a mask when accessed with a narrower 5572 * access than actual ctx access size. A zero info.ctx_field_size 5573 * will only allow for whole field access and rejects any other 5574 * type of narrower access. 5575 */ 5576 *reg_type = info.reg_type; 5577 5578 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5579 *btf = info.btf; 5580 *btf_id = info.btf_id; 5581 } else { 5582 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5583 } 5584 /* remember the offset of last byte accessed in ctx */ 5585 if (env->prog->aux->max_ctx_offset < off + size) 5586 env->prog->aux->max_ctx_offset = off + size; 5587 return 0; 5588 } 5589 5590 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5591 return -EACCES; 5592 } 5593 5594 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5595 int size) 5596 { 5597 if (size < 0 || off < 0 || 5598 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5599 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5600 off, size); 5601 return -EACCES; 5602 } 5603 return 0; 5604 } 5605 5606 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5607 u32 regno, int off, int size, 5608 enum bpf_access_type t) 5609 { 5610 struct bpf_reg_state *regs = cur_regs(env); 5611 struct bpf_reg_state *reg = ®s[regno]; 5612 struct bpf_insn_access_aux info = {}; 5613 bool valid; 5614 5615 if (reg->smin_value < 0) { 5616 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5617 regno); 5618 return -EACCES; 5619 } 5620 5621 switch (reg->type) { 5622 case PTR_TO_SOCK_COMMON: 5623 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5624 break; 5625 case PTR_TO_SOCKET: 5626 valid = bpf_sock_is_valid_access(off, size, t, &info); 5627 break; 5628 case PTR_TO_TCP_SOCK: 5629 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5630 break; 5631 case PTR_TO_XDP_SOCK: 5632 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5633 break; 5634 default: 5635 valid = false; 5636 } 5637 5638 5639 if (valid) { 5640 env->insn_aux_data[insn_idx].ctx_field_size = 5641 info.ctx_field_size; 5642 return 0; 5643 } 5644 5645 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5646 regno, reg_type_str(env, reg->type), off, size); 5647 5648 return -EACCES; 5649 } 5650 5651 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5652 { 5653 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5654 } 5655 5656 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5657 { 5658 const struct bpf_reg_state *reg = reg_state(env, regno); 5659 5660 return reg->type == PTR_TO_CTX; 5661 } 5662 5663 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5664 { 5665 const struct bpf_reg_state *reg = reg_state(env, regno); 5666 5667 return type_is_sk_pointer(reg->type); 5668 } 5669 5670 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5671 { 5672 const struct bpf_reg_state *reg = reg_state(env, regno); 5673 5674 return type_is_pkt_pointer(reg->type); 5675 } 5676 5677 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5678 { 5679 const struct bpf_reg_state *reg = reg_state(env, regno); 5680 5681 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5682 return reg->type == PTR_TO_FLOW_KEYS; 5683 } 5684 5685 static bool is_arena_reg(struct bpf_verifier_env *env, int regno) 5686 { 5687 const struct bpf_reg_state *reg = reg_state(env, regno); 5688 5689 return reg->type == PTR_TO_ARENA; 5690 } 5691 5692 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 5693 #ifdef CONFIG_NET 5694 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 5695 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5696 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 5697 #endif 5698 [CONST_PTR_TO_MAP] = btf_bpf_map_id, 5699 }; 5700 5701 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5702 { 5703 /* A referenced register is always trusted. */ 5704 if (reg->ref_obj_id) 5705 return true; 5706 5707 /* Types listed in the reg2btf_ids are always trusted */ 5708 if (reg2btf_ids[base_type(reg->type)]) 5709 return true; 5710 5711 /* If a register is not referenced, it is trusted if it has the 5712 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5713 * other type modifiers may be safe, but we elect to take an opt-in 5714 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5715 * not. 5716 * 5717 * Eventually, we should make PTR_TRUSTED the single source of truth 5718 * for whether a register is trusted. 5719 */ 5720 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5721 !bpf_type_has_unsafe_modifiers(reg->type); 5722 } 5723 5724 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5725 { 5726 return reg->type & MEM_RCU; 5727 } 5728 5729 static void clear_trusted_flags(enum bpf_type_flag *flag) 5730 { 5731 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5732 } 5733 5734 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5735 const struct bpf_reg_state *reg, 5736 int off, int size, bool strict) 5737 { 5738 struct tnum reg_off; 5739 int ip_align; 5740 5741 /* Byte size accesses are always allowed. */ 5742 if (!strict || size == 1) 5743 return 0; 5744 5745 /* For platforms that do not have a Kconfig enabling 5746 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5747 * NET_IP_ALIGN is universally set to '2'. And on platforms 5748 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5749 * to this code only in strict mode where we want to emulate 5750 * the NET_IP_ALIGN==2 checking. Therefore use an 5751 * unconditional IP align value of '2'. 5752 */ 5753 ip_align = 2; 5754 5755 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5756 if (!tnum_is_aligned(reg_off, size)) { 5757 char tn_buf[48]; 5758 5759 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5760 verbose(env, 5761 "misaligned packet access off %d+%s+%d+%d size %d\n", 5762 ip_align, tn_buf, reg->off, off, size); 5763 return -EACCES; 5764 } 5765 5766 return 0; 5767 } 5768 5769 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5770 const struct bpf_reg_state *reg, 5771 const char *pointer_desc, 5772 int off, int size, bool strict) 5773 { 5774 struct tnum reg_off; 5775 5776 /* Byte size accesses are always allowed. */ 5777 if (!strict || size == 1) 5778 return 0; 5779 5780 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5781 if (!tnum_is_aligned(reg_off, size)) { 5782 char tn_buf[48]; 5783 5784 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5785 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5786 pointer_desc, tn_buf, reg->off, off, size); 5787 return -EACCES; 5788 } 5789 5790 return 0; 5791 } 5792 5793 static int check_ptr_alignment(struct bpf_verifier_env *env, 5794 const struct bpf_reg_state *reg, int off, 5795 int size, bool strict_alignment_once) 5796 { 5797 bool strict = env->strict_alignment || strict_alignment_once; 5798 const char *pointer_desc = ""; 5799 5800 switch (reg->type) { 5801 case PTR_TO_PACKET: 5802 case PTR_TO_PACKET_META: 5803 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5804 * right in front, treat it the very same way. 5805 */ 5806 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5807 case PTR_TO_FLOW_KEYS: 5808 pointer_desc = "flow keys "; 5809 break; 5810 case PTR_TO_MAP_KEY: 5811 pointer_desc = "key "; 5812 break; 5813 case PTR_TO_MAP_VALUE: 5814 pointer_desc = "value "; 5815 break; 5816 case PTR_TO_CTX: 5817 pointer_desc = "context "; 5818 break; 5819 case PTR_TO_STACK: 5820 pointer_desc = "stack "; 5821 /* The stack spill tracking logic in check_stack_write_fixed_off() 5822 * and check_stack_read_fixed_off() relies on stack accesses being 5823 * aligned. 5824 */ 5825 strict = true; 5826 break; 5827 case PTR_TO_SOCKET: 5828 pointer_desc = "sock "; 5829 break; 5830 case PTR_TO_SOCK_COMMON: 5831 pointer_desc = "sock_common "; 5832 break; 5833 case PTR_TO_TCP_SOCK: 5834 pointer_desc = "tcp_sock "; 5835 break; 5836 case PTR_TO_XDP_SOCK: 5837 pointer_desc = "xdp_sock "; 5838 break; 5839 case PTR_TO_ARENA: 5840 return 0; 5841 default: 5842 break; 5843 } 5844 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5845 strict); 5846 } 5847 5848 static int round_up_stack_depth(struct bpf_verifier_env *env, int stack_depth) 5849 { 5850 if (env->prog->jit_requested) 5851 return round_up(stack_depth, 16); 5852 5853 /* round up to 32-bytes, since this is granularity 5854 * of interpreter stack size 5855 */ 5856 return round_up(max_t(u32, stack_depth, 1), 32); 5857 } 5858 5859 /* starting from main bpf function walk all instructions of the function 5860 * and recursively walk all callees that given function can call. 5861 * Ignore jump and exit insns. 5862 * Since recursion is prevented by check_cfg() this algorithm 5863 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5864 */ 5865 static int check_max_stack_depth_subprog(struct bpf_verifier_env *env, int idx) 5866 { 5867 struct bpf_subprog_info *subprog = env->subprog_info; 5868 struct bpf_insn *insn = env->prog->insnsi; 5869 int depth = 0, frame = 0, i, subprog_end; 5870 bool tail_call_reachable = false; 5871 int ret_insn[MAX_CALL_FRAMES]; 5872 int ret_prog[MAX_CALL_FRAMES]; 5873 int j; 5874 5875 i = subprog[idx].start; 5876 process_func: 5877 /* protect against potential stack overflow that might happen when 5878 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5879 * depth for such case down to 256 so that the worst case scenario 5880 * would result in 8k stack size (32 which is tailcall limit * 256 = 5881 * 8k). 5882 * 5883 * To get the idea what might happen, see an example: 5884 * func1 -> sub rsp, 128 5885 * subfunc1 -> sub rsp, 256 5886 * tailcall1 -> add rsp, 256 5887 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5888 * subfunc2 -> sub rsp, 64 5889 * subfunc22 -> sub rsp, 128 5890 * tailcall2 -> add rsp, 128 5891 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5892 * 5893 * tailcall will unwind the current stack frame but it will not get rid 5894 * of caller's stack as shown on the example above. 5895 */ 5896 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5897 verbose(env, 5898 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5899 depth); 5900 return -EACCES; 5901 } 5902 depth += round_up_stack_depth(env, subprog[idx].stack_depth); 5903 if (depth > MAX_BPF_STACK) { 5904 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5905 frame + 1, depth); 5906 return -EACCES; 5907 } 5908 continue_func: 5909 subprog_end = subprog[idx + 1].start; 5910 for (; i < subprog_end; i++) { 5911 int next_insn, sidx; 5912 5913 if (bpf_pseudo_kfunc_call(insn + i) && !insn[i].off) { 5914 bool err = false; 5915 5916 if (!is_bpf_throw_kfunc(insn + i)) 5917 continue; 5918 if (subprog[idx].is_cb) 5919 err = true; 5920 for (int c = 0; c < frame && !err; c++) { 5921 if (subprog[ret_prog[c]].is_cb) { 5922 err = true; 5923 break; 5924 } 5925 } 5926 if (!err) 5927 continue; 5928 verbose(env, 5929 "bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n", 5930 i, idx); 5931 return -EINVAL; 5932 } 5933 5934 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5935 continue; 5936 /* remember insn and function to return to */ 5937 ret_insn[frame] = i + 1; 5938 ret_prog[frame] = idx; 5939 5940 /* find the callee */ 5941 next_insn = i + insn[i].imm + 1; 5942 sidx = find_subprog(env, next_insn); 5943 if (sidx < 0) { 5944 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5945 next_insn); 5946 return -EFAULT; 5947 } 5948 if (subprog[sidx].is_async_cb) { 5949 if (subprog[sidx].has_tail_call) { 5950 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5951 return -EFAULT; 5952 } 5953 /* async callbacks don't increase bpf prog stack size unless called directly */ 5954 if (!bpf_pseudo_call(insn + i)) 5955 continue; 5956 if (subprog[sidx].is_exception_cb) { 5957 verbose(env, "insn %d cannot call exception cb directly\n", i); 5958 return -EINVAL; 5959 } 5960 } 5961 i = next_insn; 5962 idx = sidx; 5963 5964 if (subprog[idx].has_tail_call) 5965 tail_call_reachable = true; 5966 5967 frame++; 5968 if (frame >= MAX_CALL_FRAMES) { 5969 verbose(env, "the call stack of %d frames is too deep !\n", 5970 frame); 5971 return -E2BIG; 5972 } 5973 goto process_func; 5974 } 5975 /* if tail call got detected across bpf2bpf calls then mark each of the 5976 * currently present subprog frames as tail call reachable subprogs; 5977 * this info will be utilized by JIT so that we will be preserving the 5978 * tail call counter throughout bpf2bpf calls combined with tailcalls 5979 */ 5980 if (tail_call_reachable) 5981 for (j = 0; j < frame; j++) { 5982 if (subprog[ret_prog[j]].is_exception_cb) { 5983 verbose(env, "cannot tail call within exception cb\n"); 5984 return -EINVAL; 5985 } 5986 subprog[ret_prog[j]].tail_call_reachable = true; 5987 } 5988 if (subprog[0].tail_call_reachable) 5989 env->prog->aux->tail_call_reachable = true; 5990 5991 /* end of for() loop means the last insn of the 'subprog' 5992 * was reached. Doesn't matter whether it was JA or EXIT 5993 */ 5994 if (frame == 0) 5995 return 0; 5996 depth -= round_up_stack_depth(env, subprog[idx].stack_depth); 5997 frame--; 5998 i = ret_insn[frame]; 5999 idx = ret_prog[frame]; 6000 goto continue_func; 6001 } 6002 6003 static int check_max_stack_depth(struct bpf_verifier_env *env) 6004 { 6005 struct bpf_subprog_info *si = env->subprog_info; 6006 int ret; 6007 6008 for (int i = 0; i < env->subprog_cnt; i++) { 6009 if (!i || si[i].is_async_cb) { 6010 ret = check_max_stack_depth_subprog(env, i); 6011 if (ret < 0) 6012 return ret; 6013 } 6014 continue; 6015 } 6016 return 0; 6017 } 6018 6019 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 6020 static int get_callee_stack_depth(struct bpf_verifier_env *env, 6021 const struct bpf_insn *insn, int idx) 6022 { 6023 int start = idx + insn->imm + 1, subprog; 6024 6025 subprog = find_subprog(env, start); 6026 if (subprog < 0) { 6027 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 6028 start); 6029 return -EFAULT; 6030 } 6031 return env->subprog_info[subprog].stack_depth; 6032 } 6033 #endif 6034 6035 static int __check_buffer_access(struct bpf_verifier_env *env, 6036 const char *buf_info, 6037 const struct bpf_reg_state *reg, 6038 int regno, int off, int size) 6039 { 6040 if (off < 0) { 6041 verbose(env, 6042 "R%d invalid %s buffer access: off=%d, size=%d\n", 6043 regno, buf_info, off, size); 6044 return -EACCES; 6045 } 6046 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6047 char tn_buf[48]; 6048 6049 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6050 verbose(env, 6051 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 6052 regno, off, tn_buf); 6053 return -EACCES; 6054 } 6055 6056 return 0; 6057 } 6058 6059 static int check_tp_buffer_access(struct bpf_verifier_env *env, 6060 const struct bpf_reg_state *reg, 6061 int regno, int off, int size) 6062 { 6063 int err; 6064 6065 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 6066 if (err) 6067 return err; 6068 6069 if (off + size > env->prog->aux->max_tp_access) 6070 env->prog->aux->max_tp_access = off + size; 6071 6072 return 0; 6073 } 6074 6075 static int check_buffer_access(struct bpf_verifier_env *env, 6076 const struct bpf_reg_state *reg, 6077 int regno, int off, int size, 6078 bool zero_size_allowed, 6079 u32 *max_access) 6080 { 6081 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 6082 int err; 6083 6084 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 6085 if (err) 6086 return err; 6087 6088 if (off + size > *max_access) 6089 *max_access = off + size; 6090 6091 return 0; 6092 } 6093 6094 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 6095 static void zext_32_to_64(struct bpf_reg_state *reg) 6096 { 6097 reg->var_off = tnum_subreg(reg->var_off); 6098 __reg_assign_32_into_64(reg); 6099 } 6100 6101 /* truncate register to smaller size (in bytes) 6102 * must be called with size < BPF_REG_SIZE 6103 */ 6104 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 6105 { 6106 u64 mask; 6107 6108 /* clear high bits in bit representation */ 6109 reg->var_off = tnum_cast(reg->var_off, size); 6110 6111 /* fix arithmetic bounds */ 6112 mask = ((u64)1 << (size * 8)) - 1; 6113 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 6114 reg->umin_value &= mask; 6115 reg->umax_value &= mask; 6116 } else { 6117 reg->umin_value = 0; 6118 reg->umax_value = mask; 6119 } 6120 reg->smin_value = reg->umin_value; 6121 reg->smax_value = reg->umax_value; 6122 6123 /* If size is smaller than 32bit register the 32bit register 6124 * values are also truncated so we push 64-bit bounds into 6125 * 32-bit bounds. Above were truncated < 32-bits already. 6126 */ 6127 if (size < 4) 6128 __mark_reg32_unbounded(reg); 6129 6130 reg_bounds_sync(reg); 6131 } 6132 6133 static void set_sext64_default_val(struct bpf_reg_state *reg, int size) 6134 { 6135 if (size == 1) { 6136 reg->smin_value = reg->s32_min_value = S8_MIN; 6137 reg->smax_value = reg->s32_max_value = S8_MAX; 6138 } else if (size == 2) { 6139 reg->smin_value = reg->s32_min_value = S16_MIN; 6140 reg->smax_value = reg->s32_max_value = S16_MAX; 6141 } else { 6142 /* size == 4 */ 6143 reg->smin_value = reg->s32_min_value = S32_MIN; 6144 reg->smax_value = reg->s32_max_value = S32_MAX; 6145 } 6146 reg->umin_value = reg->u32_min_value = 0; 6147 reg->umax_value = U64_MAX; 6148 reg->u32_max_value = U32_MAX; 6149 reg->var_off = tnum_unknown; 6150 } 6151 6152 static void coerce_reg_to_size_sx(struct bpf_reg_state *reg, int size) 6153 { 6154 s64 init_s64_max, init_s64_min, s64_max, s64_min, u64_cval; 6155 u64 top_smax_value, top_smin_value; 6156 u64 num_bits = size * 8; 6157 6158 if (tnum_is_const(reg->var_off)) { 6159 u64_cval = reg->var_off.value; 6160 if (size == 1) 6161 reg->var_off = tnum_const((s8)u64_cval); 6162 else if (size == 2) 6163 reg->var_off = tnum_const((s16)u64_cval); 6164 else 6165 /* size == 4 */ 6166 reg->var_off = tnum_const((s32)u64_cval); 6167 6168 u64_cval = reg->var_off.value; 6169 reg->smax_value = reg->smin_value = u64_cval; 6170 reg->umax_value = reg->umin_value = u64_cval; 6171 reg->s32_max_value = reg->s32_min_value = u64_cval; 6172 reg->u32_max_value = reg->u32_min_value = u64_cval; 6173 return; 6174 } 6175 6176 top_smax_value = ((u64)reg->smax_value >> num_bits) << num_bits; 6177 top_smin_value = ((u64)reg->smin_value >> num_bits) << num_bits; 6178 6179 if (top_smax_value != top_smin_value) 6180 goto out; 6181 6182 /* find the s64_min and s64_min after sign extension */ 6183 if (size == 1) { 6184 init_s64_max = (s8)reg->smax_value; 6185 init_s64_min = (s8)reg->smin_value; 6186 } else if (size == 2) { 6187 init_s64_max = (s16)reg->smax_value; 6188 init_s64_min = (s16)reg->smin_value; 6189 } else { 6190 init_s64_max = (s32)reg->smax_value; 6191 init_s64_min = (s32)reg->smin_value; 6192 } 6193 6194 s64_max = max(init_s64_max, init_s64_min); 6195 s64_min = min(init_s64_max, init_s64_min); 6196 6197 /* both of s64_max/s64_min positive or negative */ 6198 if ((s64_max >= 0) == (s64_min >= 0)) { 6199 reg->smin_value = reg->s32_min_value = s64_min; 6200 reg->smax_value = reg->s32_max_value = s64_max; 6201 reg->umin_value = reg->u32_min_value = s64_min; 6202 reg->umax_value = reg->u32_max_value = s64_max; 6203 reg->var_off = tnum_range(s64_min, s64_max); 6204 return; 6205 } 6206 6207 out: 6208 set_sext64_default_val(reg, size); 6209 } 6210 6211 static void set_sext32_default_val(struct bpf_reg_state *reg, int size) 6212 { 6213 if (size == 1) { 6214 reg->s32_min_value = S8_MIN; 6215 reg->s32_max_value = S8_MAX; 6216 } else { 6217 /* size == 2 */ 6218 reg->s32_min_value = S16_MIN; 6219 reg->s32_max_value = S16_MAX; 6220 } 6221 reg->u32_min_value = 0; 6222 reg->u32_max_value = U32_MAX; 6223 } 6224 6225 static void coerce_subreg_to_size_sx(struct bpf_reg_state *reg, int size) 6226 { 6227 s32 init_s32_max, init_s32_min, s32_max, s32_min, u32_val; 6228 u32 top_smax_value, top_smin_value; 6229 u32 num_bits = size * 8; 6230 6231 if (tnum_is_const(reg->var_off)) { 6232 u32_val = reg->var_off.value; 6233 if (size == 1) 6234 reg->var_off = tnum_const((s8)u32_val); 6235 else 6236 reg->var_off = tnum_const((s16)u32_val); 6237 6238 u32_val = reg->var_off.value; 6239 reg->s32_min_value = reg->s32_max_value = u32_val; 6240 reg->u32_min_value = reg->u32_max_value = u32_val; 6241 return; 6242 } 6243 6244 top_smax_value = ((u32)reg->s32_max_value >> num_bits) << num_bits; 6245 top_smin_value = ((u32)reg->s32_min_value >> num_bits) << num_bits; 6246 6247 if (top_smax_value != top_smin_value) 6248 goto out; 6249 6250 /* find the s32_min and s32_min after sign extension */ 6251 if (size == 1) { 6252 init_s32_max = (s8)reg->s32_max_value; 6253 init_s32_min = (s8)reg->s32_min_value; 6254 } else { 6255 /* size == 2 */ 6256 init_s32_max = (s16)reg->s32_max_value; 6257 init_s32_min = (s16)reg->s32_min_value; 6258 } 6259 s32_max = max(init_s32_max, init_s32_min); 6260 s32_min = min(init_s32_max, init_s32_min); 6261 6262 if ((s32_min >= 0) == (s32_max >= 0)) { 6263 reg->s32_min_value = s32_min; 6264 reg->s32_max_value = s32_max; 6265 reg->u32_min_value = (u32)s32_min; 6266 reg->u32_max_value = (u32)s32_max; 6267 return; 6268 } 6269 6270 out: 6271 set_sext32_default_val(reg, size); 6272 } 6273 6274 static bool bpf_map_is_rdonly(const struct bpf_map *map) 6275 { 6276 /* A map is considered read-only if the following condition are true: 6277 * 6278 * 1) BPF program side cannot change any of the map content. The 6279 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 6280 * and was set at map creation time. 6281 * 2) The map value(s) have been initialized from user space by a 6282 * loader and then "frozen", such that no new map update/delete 6283 * operations from syscall side are possible for the rest of 6284 * the map's lifetime from that point onwards. 6285 * 3) Any parallel/pending map update/delete operations from syscall 6286 * side have been completed. Only after that point, it's safe to 6287 * assume that map value(s) are immutable. 6288 */ 6289 return (map->map_flags & BPF_F_RDONLY_PROG) && 6290 READ_ONCE(map->frozen) && 6291 !bpf_map_write_active(map); 6292 } 6293 6294 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val, 6295 bool is_ldsx) 6296 { 6297 void *ptr; 6298 u64 addr; 6299 int err; 6300 6301 err = map->ops->map_direct_value_addr(map, &addr, off); 6302 if (err) 6303 return err; 6304 ptr = (void *)(long)addr + off; 6305 6306 switch (size) { 6307 case sizeof(u8): 6308 *val = is_ldsx ? (s64)*(s8 *)ptr : (u64)*(u8 *)ptr; 6309 break; 6310 case sizeof(u16): 6311 *val = is_ldsx ? (s64)*(s16 *)ptr : (u64)*(u16 *)ptr; 6312 break; 6313 case sizeof(u32): 6314 *val = is_ldsx ? (s64)*(s32 *)ptr : (u64)*(u32 *)ptr; 6315 break; 6316 case sizeof(u64): 6317 *val = *(u64 *)ptr; 6318 break; 6319 default: 6320 return -EINVAL; 6321 } 6322 return 0; 6323 } 6324 6325 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 6326 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 6327 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 6328 6329 /* 6330 * Allow list few fields as RCU trusted or full trusted. 6331 * This logic doesn't allow mix tagging and will be removed once GCC supports 6332 * btf_type_tag. 6333 */ 6334 6335 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 6336 BTF_TYPE_SAFE_RCU(struct task_struct) { 6337 const cpumask_t *cpus_ptr; 6338 struct css_set __rcu *cgroups; 6339 struct task_struct __rcu *real_parent; 6340 struct task_struct *group_leader; 6341 }; 6342 6343 BTF_TYPE_SAFE_RCU(struct cgroup) { 6344 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 6345 struct kernfs_node *kn; 6346 }; 6347 6348 BTF_TYPE_SAFE_RCU(struct css_set) { 6349 struct cgroup *dfl_cgrp; 6350 }; 6351 6352 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 6353 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 6354 struct file __rcu *exe_file; 6355 }; 6356 6357 /* skb->sk, req->sk are not RCU protected, but we mark them as such 6358 * because bpf prog accessible sockets are SOCK_RCU_FREE. 6359 */ 6360 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 6361 struct sock *sk; 6362 }; 6363 6364 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 6365 struct sock *sk; 6366 }; 6367 6368 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 6369 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 6370 struct seq_file *seq; 6371 }; 6372 6373 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 6374 struct bpf_iter_meta *meta; 6375 struct task_struct *task; 6376 }; 6377 6378 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 6379 struct file *file; 6380 }; 6381 6382 BTF_TYPE_SAFE_TRUSTED(struct file) { 6383 struct inode *f_inode; 6384 }; 6385 6386 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 6387 /* no negative dentry-s in places where bpf can see it */ 6388 struct inode *d_inode; 6389 }; 6390 6391 BTF_TYPE_SAFE_TRUSTED(struct socket) { 6392 struct sock *sk; 6393 }; 6394 6395 static bool type_is_rcu(struct bpf_verifier_env *env, 6396 struct bpf_reg_state *reg, 6397 const char *field_name, u32 btf_id) 6398 { 6399 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 6400 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 6401 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 6402 6403 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 6404 } 6405 6406 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 6407 struct bpf_reg_state *reg, 6408 const char *field_name, u32 btf_id) 6409 { 6410 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 6411 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 6412 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 6413 6414 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 6415 } 6416 6417 static bool type_is_trusted(struct bpf_verifier_env *env, 6418 struct bpf_reg_state *reg, 6419 const char *field_name, u32 btf_id) 6420 { 6421 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 6422 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 6423 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 6424 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 6425 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 6426 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 6427 6428 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 6429 } 6430 6431 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 6432 struct bpf_reg_state *regs, 6433 int regno, int off, int size, 6434 enum bpf_access_type atype, 6435 int value_regno) 6436 { 6437 struct bpf_reg_state *reg = regs + regno; 6438 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 6439 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 6440 const char *field_name = NULL; 6441 enum bpf_type_flag flag = 0; 6442 u32 btf_id = 0; 6443 int ret; 6444 6445 if (!env->allow_ptr_leaks) { 6446 verbose(env, 6447 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6448 tname); 6449 return -EPERM; 6450 } 6451 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 6452 verbose(env, 6453 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 6454 tname); 6455 return -EINVAL; 6456 } 6457 if (off < 0) { 6458 verbose(env, 6459 "R%d is ptr_%s invalid negative access: off=%d\n", 6460 regno, tname, off); 6461 return -EACCES; 6462 } 6463 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 6464 char tn_buf[48]; 6465 6466 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6467 verbose(env, 6468 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 6469 regno, tname, off, tn_buf); 6470 return -EACCES; 6471 } 6472 6473 if (reg->type & MEM_USER) { 6474 verbose(env, 6475 "R%d is ptr_%s access user memory: off=%d\n", 6476 regno, tname, off); 6477 return -EACCES; 6478 } 6479 6480 if (reg->type & MEM_PERCPU) { 6481 verbose(env, 6482 "R%d is ptr_%s access percpu memory: off=%d\n", 6483 regno, tname, off); 6484 return -EACCES; 6485 } 6486 6487 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 6488 if (!btf_is_kernel(reg->btf)) { 6489 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 6490 return -EFAULT; 6491 } 6492 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 6493 } else { 6494 /* Writes are permitted with default btf_struct_access for 6495 * program allocated objects (which always have ref_obj_id > 0), 6496 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 6497 */ 6498 if (atype != BPF_READ && !type_is_ptr_alloc_obj(reg->type)) { 6499 verbose(env, "only read is supported\n"); 6500 return -EACCES; 6501 } 6502 6503 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 6504 !(reg->type & MEM_RCU) && !reg->ref_obj_id) { 6505 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 6506 return -EFAULT; 6507 } 6508 6509 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 6510 } 6511 6512 if (ret < 0) 6513 return ret; 6514 6515 if (ret != PTR_TO_BTF_ID) { 6516 /* just mark; */ 6517 6518 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 6519 /* If this is an untrusted pointer, all pointers formed by walking it 6520 * also inherit the untrusted flag. 6521 */ 6522 flag = PTR_UNTRUSTED; 6523 6524 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 6525 /* By default any pointer obtained from walking a trusted pointer is no 6526 * longer trusted, unless the field being accessed has explicitly been 6527 * marked as inheriting its parent's state of trust (either full or RCU). 6528 * For example: 6529 * 'cgroups' pointer is untrusted if task->cgroups dereference 6530 * happened in a sleepable program outside of bpf_rcu_read_lock() 6531 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 6532 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 6533 * 6534 * A regular RCU-protected pointer with __rcu tag can also be deemed 6535 * trusted if we are in an RCU CS. Such pointer can be NULL. 6536 */ 6537 if (type_is_trusted(env, reg, field_name, btf_id)) { 6538 flag |= PTR_TRUSTED; 6539 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 6540 if (type_is_rcu(env, reg, field_name, btf_id)) { 6541 /* ignore __rcu tag and mark it MEM_RCU */ 6542 flag |= MEM_RCU; 6543 } else if (flag & MEM_RCU || 6544 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 6545 /* __rcu tagged pointers can be NULL */ 6546 flag |= MEM_RCU | PTR_MAYBE_NULL; 6547 6548 /* We always trust them */ 6549 if (type_is_rcu_or_null(env, reg, field_name, btf_id) && 6550 flag & PTR_UNTRUSTED) 6551 flag &= ~PTR_UNTRUSTED; 6552 } else if (flag & (MEM_PERCPU | MEM_USER)) { 6553 /* keep as-is */ 6554 } else { 6555 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 6556 clear_trusted_flags(&flag); 6557 } 6558 } else { 6559 /* 6560 * If not in RCU CS or MEM_RCU pointer can be NULL then 6561 * aggressively mark as untrusted otherwise such 6562 * pointers will be plain PTR_TO_BTF_ID without flags 6563 * and will be allowed to be passed into helpers for 6564 * compat reasons. 6565 */ 6566 flag = PTR_UNTRUSTED; 6567 } 6568 } else { 6569 /* Old compat. Deprecated */ 6570 clear_trusted_flags(&flag); 6571 } 6572 6573 if (atype == BPF_READ && value_regno >= 0) 6574 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 6575 6576 return 0; 6577 } 6578 6579 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 6580 struct bpf_reg_state *regs, 6581 int regno, int off, int size, 6582 enum bpf_access_type atype, 6583 int value_regno) 6584 { 6585 struct bpf_reg_state *reg = regs + regno; 6586 struct bpf_map *map = reg->map_ptr; 6587 struct bpf_reg_state map_reg; 6588 enum bpf_type_flag flag = 0; 6589 const struct btf_type *t; 6590 const char *tname; 6591 u32 btf_id; 6592 int ret; 6593 6594 if (!btf_vmlinux) { 6595 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 6596 return -ENOTSUPP; 6597 } 6598 6599 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 6600 verbose(env, "map_ptr access not supported for map type %d\n", 6601 map->map_type); 6602 return -ENOTSUPP; 6603 } 6604 6605 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 6606 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 6607 6608 if (!env->allow_ptr_leaks) { 6609 verbose(env, 6610 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 6611 tname); 6612 return -EPERM; 6613 } 6614 6615 if (off < 0) { 6616 verbose(env, "R%d is %s invalid negative access: off=%d\n", 6617 regno, tname, off); 6618 return -EACCES; 6619 } 6620 6621 if (atype != BPF_READ) { 6622 verbose(env, "only read from %s is supported\n", tname); 6623 return -EACCES; 6624 } 6625 6626 /* Simulate access to a PTR_TO_BTF_ID */ 6627 memset(&map_reg, 0, sizeof(map_reg)); 6628 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 6629 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 6630 if (ret < 0) 6631 return ret; 6632 6633 if (value_regno >= 0) 6634 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 6635 6636 return 0; 6637 } 6638 6639 /* Check that the stack access at the given offset is within bounds. The 6640 * maximum valid offset is -1. 6641 * 6642 * The minimum valid offset is -MAX_BPF_STACK for writes, and 6643 * -state->allocated_stack for reads. 6644 */ 6645 static int check_stack_slot_within_bounds(struct bpf_verifier_env *env, 6646 s64 off, 6647 struct bpf_func_state *state, 6648 enum bpf_access_type t) 6649 { 6650 int min_valid_off; 6651 6652 if (t == BPF_WRITE || env->allow_uninit_stack) 6653 min_valid_off = -MAX_BPF_STACK; 6654 else 6655 min_valid_off = -state->allocated_stack; 6656 6657 if (off < min_valid_off || off > -1) 6658 return -EACCES; 6659 return 0; 6660 } 6661 6662 /* Check that the stack access at 'regno + off' falls within the maximum stack 6663 * bounds. 6664 * 6665 * 'off' includes `regno->offset`, but not its dynamic part (if any). 6666 */ 6667 static int check_stack_access_within_bounds( 6668 struct bpf_verifier_env *env, 6669 int regno, int off, int access_size, 6670 enum bpf_access_src src, enum bpf_access_type type) 6671 { 6672 struct bpf_reg_state *regs = cur_regs(env); 6673 struct bpf_reg_state *reg = regs + regno; 6674 struct bpf_func_state *state = func(env, reg); 6675 s64 min_off, max_off; 6676 int err; 6677 char *err_extra; 6678 6679 if (src == ACCESS_HELPER) 6680 /* We don't know if helpers are reading or writing (or both). */ 6681 err_extra = " indirect access to"; 6682 else if (type == BPF_READ) 6683 err_extra = " read from"; 6684 else 6685 err_extra = " write to"; 6686 6687 if (tnum_is_const(reg->var_off)) { 6688 min_off = (s64)reg->var_off.value + off; 6689 max_off = min_off + access_size; 6690 } else { 6691 if (reg->smax_value >= BPF_MAX_VAR_OFF || 6692 reg->smin_value <= -BPF_MAX_VAR_OFF) { 6693 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 6694 err_extra, regno); 6695 return -EACCES; 6696 } 6697 min_off = reg->smin_value + off; 6698 max_off = reg->smax_value + off + access_size; 6699 } 6700 6701 err = check_stack_slot_within_bounds(env, min_off, state, type); 6702 if (!err && max_off > 0) 6703 err = -EINVAL; /* out of stack access into non-negative offsets */ 6704 6705 if (err) { 6706 if (tnum_is_const(reg->var_off)) { 6707 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 6708 err_extra, regno, off, access_size); 6709 } else { 6710 char tn_buf[48]; 6711 6712 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6713 verbose(env, "invalid variable-offset%s stack R%d var_off=%s off=%d size=%d\n", 6714 err_extra, regno, tn_buf, off, access_size); 6715 } 6716 return err; 6717 } 6718 6719 /* Note that there is no stack access with offset zero, so the needed stack 6720 * size is -min_off, not -min_off+1. 6721 */ 6722 return grow_stack_state(env, state, -min_off /* size */); 6723 } 6724 6725 /* check whether memory at (regno + off) is accessible for t = (read | write) 6726 * if t==write, value_regno is a register which value is stored into memory 6727 * if t==read, value_regno is a register which will receive the value from memory 6728 * if t==write && value_regno==-1, some unknown value is stored into memory 6729 * if t==read && value_regno==-1, don't care what we read from memory 6730 */ 6731 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 6732 int off, int bpf_size, enum bpf_access_type t, 6733 int value_regno, bool strict_alignment_once, bool is_ldsx) 6734 { 6735 struct bpf_reg_state *regs = cur_regs(env); 6736 struct bpf_reg_state *reg = regs + regno; 6737 int size, err = 0; 6738 6739 size = bpf_size_to_bytes(bpf_size); 6740 if (size < 0) 6741 return size; 6742 6743 /* alignment checks will add in reg->off themselves */ 6744 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6745 if (err) 6746 return err; 6747 6748 /* for access checks, reg->off is just part of off */ 6749 off += reg->off; 6750 6751 if (reg->type == PTR_TO_MAP_KEY) { 6752 if (t == BPF_WRITE) { 6753 verbose(env, "write to change key R%d not allowed\n", regno); 6754 return -EACCES; 6755 } 6756 6757 err = check_mem_region_access(env, regno, off, size, 6758 reg->map_ptr->key_size, false); 6759 if (err) 6760 return err; 6761 if (value_regno >= 0) 6762 mark_reg_unknown(env, regs, value_regno); 6763 } else if (reg->type == PTR_TO_MAP_VALUE) { 6764 struct btf_field *kptr_field = NULL; 6765 6766 if (t == BPF_WRITE && value_regno >= 0 && 6767 is_pointer_value(env, value_regno)) { 6768 verbose(env, "R%d leaks addr into map\n", value_regno); 6769 return -EACCES; 6770 } 6771 err = check_map_access_type(env, regno, off, size, t); 6772 if (err) 6773 return err; 6774 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6775 if (err) 6776 return err; 6777 if (tnum_is_const(reg->var_off)) 6778 kptr_field = btf_record_find(reg->map_ptr->record, 6779 off + reg->var_off.value, BPF_KPTR); 6780 if (kptr_field) { 6781 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6782 } else if (t == BPF_READ && value_regno >= 0) { 6783 struct bpf_map *map = reg->map_ptr; 6784 6785 /* if map is read-only, track its contents as scalars */ 6786 if (tnum_is_const(reg->var_off) && 6787 bpf_map_is_rdonly(map) && 6788 map->ops->map_direct_value_addr) { 6789 int map_off = off + reg->var_off.value; 6790 u64 val = 0; 6791 6792 err = bpf_map_direct_read(map, map_off, size, 6793 &val, is_ldsx); 6794 if (err) 6795 return err; 6796 6797 regs[value_regno].type = SCALAR_VALUE; 6798 __mark_reg_known(®s[value_regno], val); 6799 } else { 6800 mark_reg_unknown(env, regs, value_regno); 6801 } 6802 } 6803 } else if (base_type(reg->type) == PTR_TO_MEM) { 6804 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6805 6806 if (type_may_be_null(reg->type)) { 6807 verbose(env, "R%d invalid mem access '%s'\n", regno, 6808 reg_type_str(env, reg->type)); 6809 return -EACCES; 6810 } 6811 6812 if (t == BPF_WRITE && rdonly_mem) { 6813 verbose(env, "R%d cannot write into %s\n", 6814 regno, reg_type_str(env, reg->type)); 6815 return -EACCES; 6816 } 6817 6818 if (t == BPF_WRITE && value_regno >= 0 && 6819 is_pointer_value(env, value_regno)) { 6820 verbose(env, "R%d leaks addr into mem\n", value_regno); 6821 return -EACCES; 6822 } 6823 6824 err = check_mem_region_access(env, regno, off, size, 6825 reg->mem_size, false); 6826 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6827 mark_reg_unknown(env, regs, value_regno); 6828 } else if (reg->type == PTR_TO_CTX) { 6829 enum bpf_reg_type reg_type = SCALAR_VALUE; 6830 struct btf *btf = NULL; 6831 u32 btf_id = 0; 6832 6833 if (t == BPF_WRITE && value_regno >= 0 && 6834 is_pointer_value(env, value_regno)) { 6835 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6836 return -EACCES; 6837 } 6838 6839 err = check_ptr_off_reg(env, reg, regno); 6840 if (err < 0) 6841 return err; 6842 6843 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6844 &btf_id); 6845 if (err) 6846 verbose_linfo(env, insn_idx, "; "); 6847 if (!err && t == BPF_READ && value_regno >= 0) { 6848 /* ctx access returns either a scalar, or a 6849 * PTR_TO_PACKET[_META,_END]. In the latter 6850 * case, we know the offset is zero. 6851 */ 6852 if (reg_type == SCALAR_VALUE) { 6853 mark_reg_unknown(env, regs, value_regno); 6854 } else { 6855 mark_reg_known_zero(env, regs, 6856 value_regno); 6857 if (type_may_be_null(reg_type)) 6858 regs[value_regno].id = ++env->id_gen; 6859 /* A load of ctx field could have different 6860 * actual load size with the one encoded in the 6861 * insn. When the dst is PTR, it is for sure not 6862 * a sub-register. 6863 */ 6864 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6865 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6866 regs[value_regno].btf = btf; 6867 regs[value_regno].btf_id = btf_id; 6868 } 6869 } 6870 regs[value_regno].type = reg_type; 6871 } 6872 6873 } else if (reg->type == PTR_TO_STACK) { 6874 /* Basic bounds checks. */ 6875 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6876 if (err) 6877 return err; 6878 6879 if (t == BPF_READ) 6880 err = check_stack_read(env, regno, off, size, 6881 value_regno); 6882 else 6883 err = check_stack_write(env, regno, off, size, 6884 value_regno, insn_idx); 6885 } else if (reg_is_pkt_pointer(reg)) { 6886 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6887 verbose(env, "cannot write into packet\n"); 6888 return -EACCES; 6889 } 6890 if (t == BPF_WRITE && value_regno >= 0 && 6891 is_pointer_value(env, value_regno)) { 6892 verbose(env, "R%d leaks addr into packet\n", 6893 value_regno); 6894 return -EACCES; 6895 } 6896 err = check_packet_access(env, regno, off, size, false); 6897 if (!err && t == BPF_READ && value_regno >= 0) 6898 mark_reg_unknown(env, regs, value_regno); 6899 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6900 if (t == BPF_WRITE && value_regno >= 0 && 6901 is_pointer_value(env, value_regno)) { 6902 verbose(env, "R%d leaks addr into flow keys\n", 6903 value_regno); 6904 return -EACCES; 6905 } 6906 6907 err = check_flow_keys_access(env, off, size); 6908 if (!err && t == BPF_READ && value_regno >= 0) 6909 mark_reg_unknown(env, regs, value_regno); 6910 } else if (type_is_sk_pointer(reg->type)) { 6911 if (t == BPF_WRITE) { 6912 verbose(env, "R%d cannot write into %s\n", 6913 regno, reg_type_str(env, reg->type)); 6914 return -EACCES; 6915 } 6916 err = check_sock_access(env, insn_idx, regno, off, size, t); 6917 if (!err && value_regno >= 0) 6918 mark_reg_unknown(env, regs, value_regno); 6919 } else if (reg->type == PTR_TO_TP_BUFFER) { 6920 err = check_tp_buffer_access(env, reg, regno, off, size); 6921 if (!err && t == BPF_READ && value_regno >= 0) 6922 mark_reg_unknown(env, regs, value_regno); 6923 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6924 !type_may_be_null(reg->type)) { 6925 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6926 value_regno); 6927 } else if (reg->type == CONST_PTR_TO_MAP) { 6928 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6929 value_regno); 6930 } else if (base_type(reg->type) == PTR_TO_BUF) { 6931 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6932 u32 *max_access; 6933 6934 if (rdonly_mem) { 6935 if (t == BPF_WRITE) { 6936 verbose(env, "R%d cannot write into %s\n", 6937 regno, reg_type_str(env, reg->type)); 6938 return -EACCES; 6939 } 6940 max_access = &env->prog->aux->max_rdonly_access; 6941 } else { 6942 max_access = &env->prog->aux->max_rdwr_access; 6943 } 6944 6945 err = check_buffer_access(env, reg, regno, off, size, false, 6946 max_access); 6947 6948 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6949 mark_reg_unknown(env, regs, value_regno); 6950 } else if (reg->type == PTR_TO_ARENA) { 6951 if (t == BPF_READ && value_regno >= 0) 6952 mark_reg_unknown(env, regs, value_regno); 6953 } else { 6954 verbose(env, "R%d invalid mem access '%s'\n", regno, 6955 reg_type_str(env, reg->type)); 6956 return -EACCES; 6957 } 6958 6959 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6960 regs[value_regno].type == SCALAR_VALUE) { 6961 if (!is_ldsx) 6962 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6963 coerce_reg_to_size(®s[value_regno], size); 6964 else 6965 coerce_reg_to_size_sx(®s[value_regno], size); 6966 } 6967 return err; 6968 } 6969 6970 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6971 { 6972 int load_reg; 6973 int err; 6974 6975 switch (insn->imm) { 6976 case BPF_ADD: 6977 case BPF_ADD | BPF_FETCH: 6978 case BPF_AND: 6979 case BPF_AND | BPF_FETCH: 6980 case BPF_OR: 6981 case BPF_OR | BPF_FETCH: 6982 case BPF_XOR: 6983 case BPF_XOR | BPF_FETCH: 6984 case BPF_XCHG: 6985 case BPF_CMPXCHG: 6986 break; 6987 default: 6988 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6989 return -EINVAL; 6990 } 6991 6992 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6993 verbose(env, "invalid atomic operand size\n"); 6994 return -EINVAL; 6995 } 6996 6997 /* check src1 operand */ 6998 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6999 if (err) 7000 return err; 7001 7002 /* check src2 operand */ 7003 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7004 if (err) 7005 return err; 7006 7007 if (insn->imm == BPF_CMPXCHG) { 7008 /* Check comparison of R0 with memory location */ 7009 const u32 aux_reg = BPF_REG_0; 7010 7011 err = check_reg_arg(env, aux_reg, SRC_OP); 7012 if (err) 7013 return err; 7014 7015 if (is_pointer_value(env, aux_reg)) { 7016 verbose(env, "R%d leaks addr into mem\n", aux_reg); 7017 return -EACCES; 7018 } 7019 } 7020 7021 if (is_pointer_value(env, insn->src_reg)) { 7022 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 7023 return -EACCES; 7024 } 7025 7026 if (is_ctx_reg(env, insn->dst_reg) || 7027 is_pkt_reg(env, insn->dst_reg) || 7028 is_flow_key_reg(env, insn->dst_reg) || 7029 is_sk_reg(env, insn->dst_reg) || 7030 is_arena_reg(env, insn->dst_reg)) { 7031 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 7032 insn->dst_reg, 7033 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 7034 return -EACCES; 7035 } 7036 7037 if (insn->imm & BPF_FETCH) { 7038 if (insn->imm == BPF_CMPXCHG) 7039 load_reg = BPF_REG_0; 7040 else 7041 load_reg = insn->src_reg; 7042 7043 /* check and record load of old value */ 7044 err = check_reg_arg(env, load_reg, DST_OP); 7045 if (err) 7046 return err; 7047 } else { 7048 /* This instruction accesses a memory location but doesn't 7049 * actually load it into a register. 7050 */ 7051 load_reg = -1; 7052 } 7053 7054 /* Check whether we can read the memory, with second call for fetch 7055 * case to simulate the register fill. 7056 */ 7057 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7058 BPF_SIZE(insn->code), BPF_READ, -1, true, false); 7059 if (!err && load_reg >= 0) 7060 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7061 BPF_SIZE(insn->code), BPF_READ, load_reg, 7062 true, false); 7063 if (err) 7064 return err; 7065 7066 /* Check whether we can write into the same memory. */ 7067 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 7068 BPF_SIZE(insn->code), BPF_WRITE, -1, true, false); 7069 if (err) 7070 return err; 7071 return 0; 7072 } 7073 7074 /* When register 'regno' is used to read the stack (either directly or through 7075 * a helper function) make sure that it's within stack boundary and, depending 7076 * on the access type and privileges, that all elements of the stack are 7077 * initialized. 7078 * 7079 * 'off' includes 'regno->off', but not its dynamic part (if any). 7080 * 7081 * All registers that have been spilled on the stack in the slots within the 7082 * read offsets are marked as read. 7083 */ 7084 static int check_stack_range_initialized( 7085 struct bpf_verifier_env *env, int regno, int off, 7086 int access_size, bool zero_size_allowed, 7087 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 7088 { 7089 struct bpf_reg_state *reg = reg_state(env, regno); 7090 struct bpf_func_state *state = func(env, reg); 7091 int err, min_off, max_off, i, j, slot, spi; 7092 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 7093 enum bpf_access_type bounds_check_type; 7094 /* Some accesses can write anything into the stack, others are 7095 * read-only. 7096 */ 7097 bool clobber = false; 7098 7099 if (access_size == 0 && !zero_size_allowed) { 7100 verbose(env, "invalid zero-sized read\n"); 7101 return -EACCES; 7102 } 7103 7104 if (type == ACCESS_HELPER) { 7105 /* The bounds checks for writes are more permissive than for 7106 * reads. However, if raw_mode is not set, we'll do extra 7107 * checks below. 7108 */ 7109 bounds_check_type = BPF_WRITE; 7110 clobber = true; 7111 } else { 7112 bounds_check_type = BPF_READ; 7113 } 7114 err = check_stack_access_within_bounds(env, regno, off, access_size, 7115 type, bounds_check_type); 7116 if (err) 7117 return err; 7118 7119 7120 if (tnum_is_const(reg->var_off)) { 7121 min_off = max_off = reg->var_off.value + off; 7122 } else { 7123 /* Variable offset is prohibited for unprivileged mode for 7124 * simplicity since it requires corresponding support in 7125 * Spectre masking for stack ALU. 7126 * See also retrieve_ptr_limit(). 7127 */ 7128 if (!env->bypass_spec_v1) { 7129 char tn_buf[48]; 7130 7131 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7132 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 7133 regno, err_extra, tn_buf); 7134 return -EACCES; 7135 } 7136 /* Only initialized buffer on stack is allowed to be accessed 7137 * with variable offset. With uninitialized buffer it's hard to 7138 * guarantee that whole memory is marked as initialized on 7139 * helper return since specific bounds are unknown what may 7140 * cause uninitialized stack leaking. 7141 */ 7142 if (meta && meta->raw_mode) 7143 meta = NULL; 7144 7145 min_off = reg->smin_value + off; 7146 max_off = reg->smax_value + off; 7147 } 7148 7149 if (meta && meta->raw_mode) { 7150 /* Ensure we won't be overwriting dynptrs when simulating byte 7151 * by byte access in check_helper_call using meta.access_size. 7152 * This would be a problem if we have a helper in the future 7153 * which takes: 7154 * 7155 * helper(uninit_mem, len, dynptr) 7156 * 7157 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 7158 * may end up writing to dynptr itself when touching memory from 7159 * arg 1. This can be relaxed on a case by case basis for known 7160 * safe cases, but reject due to the possibilitiy of aliasing by 7161 * default. 7162 */ 7163 for (i = min_off; i < max_off + access_size; i++) { 7164 int stack_off = -i - 1; 7165 7166 spi = __get_spi(i); 7167 /* raw_mode may write past allocated_stack */ 7168 if (state->allocated_stack <= stack_off) 7169 continue; 7170 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 7171 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 7172 return -EACCES; 7173 } 7174 } 7175 meta->access_size = access_size; 7176 meta->regno = regno; 7177 return 0; 7178 } 7179 7180 for (i = min_off; i < max_off + access_size; i++) { 7181 u8 *stype; 7182 7183 slot = -i - 1; 7184 spi = slot / BPF_REG_SIZE; 7185 if (state->allocated_stack <= slot) { 7186 verbose(env, "verifier bug: allocated_stack too small"); 7187 return -EFAULT; 7188 } 7189 7190 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 7191 if (*stype == STACK_MISC) 7192 goto mark; 7193 if ((*stype == STACK_ZERO) || 7194 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 7195 if (clobber) { 7196 /* helper can write anything into the stack */ 7197 *stype = STACK_MISC; 7198 } 7199 goto mark; 7200 } 7201 7202 if (is_spilled_reg(&state->stack[spi]) && 7203 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 7204 env->allow_ptr_leaks)) { 7205 if (clobber) { 7206 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 7207 for (j = 0; j < BPF_REG_SIZE; j++) 7208 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 7209 } 7210 goto mark; 7211 } 7212 7213 if (tnum_is_const(reg->var_off)) { 7214 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 7215 err_extra, regno, min_off, i - min_off, access_size); 7216 } else { 7217 char tn_buf[48]; 7218 7219 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7220 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 7221 err_extra, regno, tn_buf, i - min_off, access_size); 7222 } 7223 return -EACCES; 7224 mark: 7225 /* reading any byte out of 8-byte 'spill_slot' will cause 7226 * the whole slot to be marked as 'read' 7227 */ 7228 mark_reg_read(env, &state->stack[spi].spilled_ptr, 7229 state->stack[spi].spilled_ptr.parent, 7230 REG_LIVE_READ64); 7231 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 7232 * be sure that whether stack slot is written to or not. Hence, 7233 * we must still conservatively propagate reads upwards even if 7234 * helper may write to the entire memory range. 7235 */ 7236 } 7237 return 0; 7238 } 7239 7240 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 7241 int access_size, bool zero_size_allowed, 7242 struct bpf_call_arg_meta *meta) 7243 { 7244 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7245 u32 *max_access; 7246 7247 switch (base_type(reg->type)) { 7248 case PTR_TO_PACKET: 7249 case PTR_TO_PACKET_META: 7250 return check_packet_access(env, regno, reg->off, access_size, 7251 zero_size_allowed); 7252 case PTR_TO_MAP_KEY: 7253 if (meta && meta->raw_mode) { 7254 verbose(env, "R%d cannot write into %s\n", regno, 7255 reg_type_str(env, reg->type)); 7256 return -EACCES; 7257 } 7258 return check_mem_region_access(env, regno, reg->off, access_size, 7259 reg->map_ptr->key_size, false); 7260 case PTR_TO_MAP_VALUE: 7261 if (check_map_access_type(env, regno, reg->off, access_size, 7262 meta && meta->raw_mode ? BPF_WRITE : 7263 BPF_READ)) 7264 return -EACCES; 7265 return check_map_access(env, regno, reg->off, access_size, 7266 zero_size_allowed, ACCESS_HELPER); 7267 case PTR_TO_MEM: 7268 if (type_is_rdonly_mem(reg->type)) { 7269 if (meta && meta->raw_mode) { 7270 verbose(env, "R%d cannot write into %s\n", regno, 7271 reg_type_str(env, reg->type)); 7272 return -EACCES; 7273 } 7274 } 7275 return check_mem_region_access(env, regno, reg->off, 7276 access_size, reg->mem_size, 7277 zero_size_allowed); 7278 case PTR_TO_BUF: 7279 if (type_is_rdonly_mem(reg->type)) { 7280 if (meta && meta->raw_mode) { 7281 verbose(env, "R%d cannot write into %s\n", regno, 7282 reg_type_str(env, reg->type)); 7283 return -EACCES; 7284 } 7285 7286 max_access = &env->prog->aux->max_rdonly_access; 7287 } else { 7288 max_access = &env->prog->aux->max_rdwr_access; 7289 } 7290 return check_buffer_access(env, reg, regno, reg->off, 7291 access_size, zero_size_allowed, 7292 max_access); 7293 case PTR_TO_STACK: 7294 return check_stack_range_initialized( 7295 env, 7296 regno, reg->off, access_size, 7297 zero_size_allowed, ACCESS_HELPER, meta); 7298 case PTR_TO_BTF_ID: 7299 return check_ptr_to_btf_access(env, regs, regno, reg->off, 7300 access_size, BPF_READ, -1); 7301 case PTR_TO_CTX: 7302 /* in case the function doesn't know how to access the context, 7303 * (because we are in a program of type SYSCALL for example), we 7304 * can not statically check its size. 7305 * Dynamically check it now. 7306 */ 7307 if (!env->ops->convert_ctx_access) { 7308 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 7309 int offset = access_size - 1; 7310 7311 /* Allow zero-byte read from PTR_TO_CTX */ 7312 if (access_size == 0) 7313 return zero_size_allowed ? 0 : -EACCES; 7314 7315 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 7316 atype, -1, false, false); 7317 } 7318 7319 fallthrough; 7320 default: /* scalar_value or invalid ptr */ 7321 /* Allow zero-byte read from NULL, regardless of pointer type */ 7322 if (zero_size_allowed && access_size == 0 && 7323 register_is_null(reg)) 7324 return 0; 7325 7326 verbose(env, "R%d type=%s ", regno, 7327 reg_type_str(env, reg->type)); 7328 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 7329 return -EACCES; 7330 } 7331 } 7332 7333 /* verify arguments to helpers or kfuncs consisting of a pointer and an access 7334 * size. 7335 * 7336 * @regno is the register containing the access size. regno-1 is the register 7337 * containing the pointer. 7338 */ 7339 static int check_mem_size_reg(struct bpf_verifier_env *env, 7340 struct bpf_reg_state *reg, u32 regno, 7341 bool zero_size_allowed, 7342 struct bpf_call_arg_meta *meta) 7343 { 7344 int err; 7345 7346 /* This is used to refine r0 return value bounds for helpers 7347 * that enforce this value as an upper bound on return values. 7348 * See do_refine_retval_range() for helpers that can refine 7349 * the return value. C type of helper is u32 so we pull register 7350 * bound from umax_value however, if negative verifier errors 7351 * out. Only upper bounds can be learned because retval is an 7352 * int type and negative retvals are allowed. 7353 */ 7354 meta->msize_max_value = reg->umax_value; 7355 7356 /* The register is SCALAR_VALUE; the access check 7357 * happens using its boundaries. 7358 */ 7359 if (!tnum_is_const(reg->var_off)) 7360 /* For unprivileged variable accesses, disable raw 7361 * mode so that the program is required to 7362 * initialize all the memory that the helper could 7363 * just partially fill up. 7364 */ 7365 meta = NULL; 7366 7367 if (reg->smin_value < 0) { 7368 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 7369 regno); 7370 return -EACCES; 7371 } 7372 7373 if (reg->umin_value == 0 && !zero_size_allowed) { 7374 verbose(env, "R%d invalid zero-sized read: u64=[%lld,%lld]\n", 7375 regno, reg->umin_value, reg->umax_value); 7376 return -EACCES; 7377 } 7378 7379 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 7380 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 7381 regno); 7382 return -EACCES; 7383 } 7384 err = check_helper_mem_access(env, regno - 1, 7385 reg->umax_value, 7386 zero_size_allowed, meta); 7387 if (!err) 7388 err = mark_chain_precision(env, regno); 7389 return err; 7390 } 7391 7392 static int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7393 u32 regno, u32 mem_size) 7394 { 7395 bool may_be_null = type_may_be_null(reg->type); 7396 struct bpf_reg_state saved_reg; 7397 struct bpf_call_arg_meta meta; 7398 int err; 7399 7400 if (register_is_null(reg)) 7401 return 0; 7402 7403 memset(&meta, 0, sizeof(meta)); 7404 /* Assuming that the register contains a value check if the memory 7405 * access is safe. Temporarily save and restore the register's state as 7406 * the conversion shouldn't be visible to a caller. 7407 */ 7408 if (may_be_null) { 7409 saved_reg = *reg; 7410 mark_ptr_not_null_reg(reg); 7411 } 7412 7413 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 7414 /* Check access for BPF_WRITE */ 7415 meta.raw_mode = true; 7416 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 7417 7418 if (may_be_null) 7419 *reg = saved_reg; 7420 7421 return err; 7422 } 7423 7424 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 7425 u32 regno) 7426 { 7427 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 7428 bool may_be_null = type_may_be_null(mem_reg->type); 7429 struct bpf_reg_state saved_reg; 7430 struct bpf_call_arg_meta meta; 7431 int err; 7432 7433 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 7434 7435 memset(&meta, 0, sizeof(meta)); 7436 7437 if (may_be_null) { 7438 saved_reg = *mem_reg; 7439 mark_ptr_not_null_reg(mem_reg); 7440 } 7441 7442 err = check_mem_size_reg(env, reg, regno, true, &meta); 7443 /* Check access for BPF_WRITE */ 7444 meta.raw_mode = true; 7445 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 7446 7447 if (may_be_null) 7448 *mem_reg = saved_reg; 7449 return err; 7450 } 7451 7452 /* Implementation details: 7453 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 7454 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 7455 * Two bpf_map_lookups (even with the same key) will have different reg->id. 7456 * Two separate bpf_obj_new will also have different reg->id. 7457 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 7458 * clears reg->id after value_or_null->value transition, since the verifier only 7459 * cares about the range of access to valid map value pointer and doesn't care 7460 * about actual address of the map element. 7461 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 7462 * reg->id > 0 after value_or_null->value transition. By doing so 7463 * two bpf_map_lookups will be considered two different pointers that 7464 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 7465 * returned from bpf_obj_new. 7466 * The verifier allows taking only one bpf_spin_lock at a time to avoid 7467 * dead-locks. 7468 * Since only one bpf_spin_lock is allowed the checks are simpler than 7469 * reg_is_refcounted() logic. The verifier needs to remember only 7470 * one spin_lock instead of array of acquired_refs. 7471 * cur_state->active_lock remembers which map value element or allocated 7472 * object got locked and clears it after bpf_spin_unlock. 7473 */ 7474 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 7475 bool is_lock) 7476 { 7477 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7478 struct bpf_verifier_state *cur = env->cur_state; 7479 bool is_const = tnum_is_const(reg->var_off); 7480 u64 val = reg->var_off.value; 7481 struct bpf_map *map = NULL; 7482 struct btf *btf = NULL; 7483 struct btf_record *rec; 7484 7485 if (!is_const) { 7486 verbose(env, 7487 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 7488 regno); 7489 return -EINVAL; 7490 } 7491 if (reg->type == PTR_TO_MAP_VALUE) { 7492 map = reg->map_ptr; 7493 if (!map->btf) { 7494 verbose(env, 7495 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 7496 map->name); 7497 return -EINVAL; 7498 } 7499 } else { 7500 btf = reg->btf; 7501 } 7502 7503 rec = reg_btf_record(reg); 7504 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 7505 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 7506 map ? map->name : "kptr"); 7507 return -EINVAL; 7508 } 7509 if (rec->spin_lock_off != val + reg->off) { 7510 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 7511 val + reg->off, rec->spin_lock_off); 7512 return -EINVAL; 7513 } 7514 if (is_lock) { 7515 if (cur->active_lock.ptr) { 7516 verbose(env, 7517 "Locking two bpf_spin_locks are not allowed\n"); 7518 return -EINVAL; 7519 } 7520 if (map) 7521 cur->active_lock.ptr = map; 7522 else 7523 cur->active_lock.ptr = btf; 7524 cur->active_lock.id = reg->id; 7525 } else { 7526 void *ptr; 7527 7528 if (map) 7529 ptr = map; 7530 else 7531 ptr = btf; 7532 7533 if (!cur->active_lock.ptr) { 7534 verbose(env, "bpf_spin_unlock without taking a lock\n"); 7535 return -EINVAL; 7536 } 7537 if (cur->active_lock.ptr != ptr || 7538 cur->active_lock.id != reg->id) { 7539 verbose(env, "bpf_spin_unlock of different lock\n"); 7540 return -EINVAL; 7541 } 7542 7543 invalidate_non_owning_refs(env); 7544 7545 cur->active_lock.ptr = NULL; 7546 cur->active_lock.id = 0; 7547 } 7548 return 0; 7549 } 7550 7551 static int process_timer_func(struct bpf_verifier_env *env, int regno, 7552 struct bpf_call_arg_meta *meta) 7553 { 7554 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7555 bool is_const = tnum_is_const(reg->var_off); 7556 struct bpf_map *map = reg->map_ptr; 7557 u64 val = reg->var_off.value; 7558 7559 if (!is_const) { 7560 verbose(env, 7561 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 7562 regno); 7563 return -EINVAL; 7564 } 7565 if (!map->btf) { 7566 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 7567 map->name); 7568 return -EINVAL; 7569 } 7570 if (!btf_record_has_field(map->record, BPF_TIMER)) { 7571 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 7572 return -EINVAL; 7573 } 7574 if (map->record->timer_off != val + reg->off) { 7575 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 7576 val + reg->off, map->record->timer_off); 7577 return -EINVAL; 7578 } 7579 if (meta->map_ptr) { 7580 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 7581 return -EFAULT; 7582 } 7583 meta->map_uid = reg->map_uid; 7584 meta->map_ptr = map; 7585 return 0; 7586 } 7587 7588 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 7589 struct bpf_call_arg_meta *meta) 7590 { 7591 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7592 struct bpf_map *map_ptr = reg->map_ptr; 7593 struct btf_field *kptr_field; 7594 u32 kptr_off; 7595 7596 if (!tnum_is_const(reg->var_off)) { 7597 verbose(env, 7598 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 7599 regno); 7600 return -EINVAL; 7601 } 7602 if (!map_ptr->btf) { 7603 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 7604 map_ptr->name); 7605 return -EINVAL; 7606 } 7607 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 7608 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 7609 return -EINVAL; 7610 } 7611 7612 meta->map_ptr = map_ptr; 7613 kptr_off = reg->off + reg->var_off.value; 7614 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 7615 if (!kptr_field) { 7616 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 7617 return -EACCES; 7618 } 7619 if (kptr_field->type != BPF_KPTR_REF && kptr_field->type != BPF_KPTR_PERCPU) { 7620 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 7621 return -EACCES; 7622 } 7623 meta->kptr_field = kptr_field; 7624 return 0; 7625 } 7626 7627 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 7628 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 7629 * 7630 * In both cases we deal with the first 8 bytes, but need to mark the next 8 7631 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 7632 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 7633 * 7634 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 7635 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 7636 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 7637 * mutate the view of the dynptr and also possibly destroy it. In the latter 7638 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 7639 * memory that dynptr points to. 7640 * 7641 * The verifier will keep track both levels of mutation (bpf_dynptr's in 7642 * reg->type and the memory's in reg->dynptr.type), but there is no support for 7643 * readonly dynptr view yet, hence only the first case is tracked and checked. 7644 * 7645 * This is consistent with how C applies the const modifier to a struct object, 7646 * where the pointer itself inside bpf_dynptr becomes const but not what it 7647 * points to. 7648 * 7649 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 7650 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 7651 */ 7652 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 7653 enum bpf_arg_type arg_type, int clone_ref_obj_id) 7654 { 7655 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7656 int err; 7657 7658 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 7659 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 7660 */ 7661 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 7662 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 7663 return -EFAULT; 7664 } 7665 7666 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 7667 * constructing a mutable bpf_dynptr object. 7668 * 7669 * Currently, this is only possible with PTR_TO_STACK 7670 * pointing to a region of at least 16 bytes which doesn't 7671 * contain an existing bpf_dynptr. 7672 * 7673 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 7674 * mutated or destroyed. However, the memory it points to 7675 * may be mutated. 7676 * 7677 * None - Points to a initialized dynptr that can be mutated and 7678 * destroyed, including mutation of the memory it points 7679 * to. 7680 */ 7681 if (arg_type & MEM_UNINIT) { 7682 int i; 7683 7684 if (!is_dynptr_reg_valid_uninit(env, reg)) { 7685 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 7686 return -EINVAL; 7687 } 7688 7689 /* we write BPF_DW bits (8 bytes) at a time */ 7690 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7691 err = check_mem_access(env, insn_idx, regno, 7692 i, BPF_DW, BPF_WRITE, -1, false, false); 7693 if (err) 7694 return err; 7695 } 7696 7697 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 7698 } else /* MEM_RDONLY and None case from above */ { 7699 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 7700 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 7701 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 7702 return -EINVAL; 7703 } 7704 7705 if (!is_dynptr_reg_valid_init(env, reg)) { 7706 verbose(env, 7707 "Expected an initialized dynptr as arg #%d\n", 7708 regno); 7709 return -EINVAL; 7710 } 7711 7712 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 7713 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 7714 verbose(env, 7715 "Expected a dynptr of type %s as arg #%d\n", 7716 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 7717 return -EINVAL; 7718 } 7719 7720 err = mark_dynptr_read(env, reg); 7721 } 7722 return err; 7723 } 7724 7725 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 7726 { 7727 struct bpf_func_state *state = func(env, reg); 7728 7729 return state->stack[spi].spilled_ptr.ref_obj_id; 7730 } 7731 7732 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7733 { 7734 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 7735 } 7736 7737 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7738 { 7739 return meta->kfunc_flags & KF_ITER_NEW; 7740 } 7741 7742 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7743 { 7744 return meta->kfunc_flags & KF_ITER_NEXT; 7745 } 7746 7747 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 7748 { 7749 return meta->kfunc_flags & KF_ITER_DESTROY; 7750 } 7751 7752 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7753 { 7754 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7755 * kfunc is iter state pointer 7756 */ 7757 return arg == 0 && is_iter_kfunc(meta); 7758 } 7759 7760 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7761 struct bpf_kfunc_call_arg_meta *meta) 7762 { 7763 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7764 const struct btf_type *t; 7765 const struct btf_param *arg; 7766 int spi, err, i, nr_slots; 7767 u32 btf_id; 7768 7769 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7770 arg = &btf_params(meta->func_proto)[0]; 7771 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7772 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7773 nr_slots = t->size / BPF_REG_SIZE; 7774 7775 if (is_iter_new_kfunc(meta)) { 7776 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7777 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7778 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7779 iter_type_str(meta->btf, btf_id), regno); 7780 return -EINVAL; 7781 } 7782 7783 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7784 err = check_mem_access(env, insn_idx, regno, 7785 i, BPF_DW, BPF_WRITE, -1, false, false); 7786 if (err) 7787 return err; 7788 } 7789 7790 err = mark_stack_slots_iter(env, meta, reg, insn_idx, meta->btf, btf_id, nr_slots); 7791 if (err) 7792 return err; 7793 } else { 7794 /* iter_next() or iter_destroy() expect initialized iter state*/ 7795 err = is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots); 7796 switch (err) { 7797 case 0: 7798 break; 7799 case -EINVAL: 7800 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7801 iter_type_str(meta->btf, btf_id), regno); 7802 return err; 7803 case -EPROTO: 7804 verbose(env, "expected an RCU CS when using %s\n", meta->func_name); 7805 return err; 7806 default: 7807 return err; 7808 } 7809 7810 spi = iter_get_spi(env, reg, nr_slots); 7811 if (spi < 0) 7812 return spi; 7813 7814 err = mark_iter_read(env, reg, spi, nr_slots); 7815 if (err) 7816 return err; 7817 7818 /* remember meta->iter info for process_iter_next_call() */ 7819 meta->iter.spi = spi; 7820 meta->iter.frameno = reg->frameno; 7821 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7822 7823 if (is_iter_destroy_kfunc(meta)) { 7824 err = unmark_stack_slots_iter(env, reg, nr_slots); 7825 if (err) 7826 return err; 7827 } 7828 } 7829 7830 return 0; 7831 } 7832 7833 /* Look for a previous loop entry at insn_idx: nearest parent state 7834 * stopped at insn_idx with callsites matching those in cur->frame. 7835 */ 7836 static struct bpf_verifier_state *find_prev_entry(struct bpf_verifier_env *env, 7837 struct bpf_verifier_state *cur, 7838 int insn_idx) 7839 { 7840 struct bpf_verifier_state_list *sl; 7841 struct bpf_verifier_state *st; 7842 7843 /* Explored states are pushed in stack order, most recent states come first */ 7844 sl = *explored_state(env, insn_idx); 7845 for (; sl; sl = sl->next) { 7846 /* If st->branches != 0 state is a part of current DFS verification path, 7847 * hence cur & st for a loop. 7848 */ 7849 st = &sl->state; 7850 if (st->insn_idx == insn_idx && st->branches && same_callsites(st, cur) && 7851 st->dfs_depth < cur->dfs_depth) 7852 return st; 7853 } 7854 7855 return NULL; 7856 } 7857 7858 static void reset_idmap_scratch(struct bpf_verifier_env *env); 7859 static bool regs_exact(const struct bpf_reg_state *rold, 7860 const struct bpf_reg_state *rcur, 7861 struct bpf_idmap *idmap); 7862 7863 static void maybe_widen_reg(struct bpf_verifier_env *env, 7864 struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7865 struct bpf_idmap *idmap) 7866 { 7867 if (rold->type != SCALAR_VALUE) 7868 return; 7869 if (rold->type != rcur->type) 7870 return; 7871 if (rold->precise || rcur->precise || regs_exact(rold, rcur, idmap)) 7872 return; 7873 __mark_reg_unknown(env, rcur); 7874 } 7875 7876 static int widen_imprecise_scalars(struct bpf_verifier_env *env, 7877 struct bpf_verifier_state *old, 7878 struct bpf_verifier_state *cur) 7879 { 7880 struct bpf_func_state *fold, *fcur; 7881 int i, fr; 7882 7883 reset_idmap_scratch(env); 7884 for (fr = old->curframe; fr >= 0; fr--) { 7885 fold = old->frame[fr]; 7886 fcur = cur->frame[fr]; 7887 7888 for (i = 0; i < MAX_BPF_REG; i++) 7889 maybe_widen_reg(env, 7890 &fold->regs[i], 7891 &fcur->regs[i], 7892 &env->idmap_scratch); 7893 7894 for (i = 0; i < fold->allocated_stack / BPF_REG_SIZE; i++) { 7895 if (!is_spilled_reg(&fold->stack[i]) || 7896 !is_spilled_reg(&fcur->stack[i])) 7897 continue; 7898 7899 maybe_widen_reg(env, 7900 &fold->stack[i].spilled_ptr, 7901 &fcur->stack[i].spilled_ptr, 7902 &env->idmap_scratch); 7903 } 7904 } 7905 return 0; 7906 } 7907 7908 /* process_iter_next_call() is called when verifier gets to iterator's next 7909 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7910 * to it as just "iter_next()" in comments below. 7911 * 7912 * BPF verifier relies on a crucial contract for any iter_next() 7913 * implementation: it should *eventually* return NULL, and once that happens 7914 * it should keep returning NULL. That is, once iterator exhausts elements to 7915 * iterate, it should never reset or spuriously return new elements. 7916 * 7917 * With the assumption of such contract, process_iter_next_call() simulates 7918 * a fork in the verifier state to validate loop logic correctness and safety 7919 * without having to simulate infinite amount of iterations. 7920 * 7921 * In current state, we first assume that iter_next() returned NULL and 7922 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7923 * conditions we should not form an infinite loop and should eventually reach 7924 * exit. 7925 * 7926 * Besides that, we also fork current state and enqueue it for later 7927 * verification. In a forked state we keep iterator state as ACTIVE 7928 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7929 * also bump iteration depth to prevent erroneous infinite loop detection 7930 * later on (see iter_active_depths_differ() comment for details). In this 7931 * state we assume that we'll eventually loop back to another iter_next() 7932 * calls (it could be in exactly same location or in some other instruction, 7933 * it doesn't matter, we don't make any unnecessary assumptions about this, 7934 * everything revolves around iterator state in a stack slot, not which 7935 * instruction is calling iter_next()). When that happens, we either will come 7936 * to iter_next() with equivalent state and can conclude that next iteration 7937 * will proceed in exactly the same way as we just verified, so it's safe to 7938 * assume that loop converges. If not, we'll go on another iteration 7939 * simulation with a different input state, until all possible starting states 7940 * are validated or we reach maximum number of instructions limit. 7941 * 7942 * This way, we will either exhaustively discover all possible input states 7943 * that iterator loop can start with and eventually will converge, or we'll 7944 * effectively regress into bounded loop simulation logic and either reach 7945 * maximum number of instructions if loop is not provably convergent, or there 7946 * is some statically known limit on number of iterations (e.g., if there is 7947 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7948 * 7949 * Iteration convergence logic in is_state_visited() relies on exact 7950 * states comparison, which ignores read and precision marks. 7951 * This is necessary because read and precision marks are not finalized 7952 * while in the loop. Exact comparison might preclude convergence for 7953 * simple programs like below: 7954 * 7955 * i = 0; 7956 * while(iter_next(&it)) 7957 * i++; 7958 * 7959 * At each iteration step i++ would produce a new distinct state and 7960 * eventually instruction processing limit would be reached. 7961 * 7962 * To avoid such behavior speculatively forget (widen) range for 7963 * imprecise scalar registers, if those registers were not precise at the 7964 * end of the previous iteration and do not match exactly. 7965 * 7966 * This is a conservative heuristic that allows to verify wide range of programs, 7967 * however it precludes verification of programs that conjure an 7968 * imprecise value on the first loop iteration and use it as precise on a second. 7969 * For example, the following safe program would fail to verify: 7970 * 7971 * struct bpf_num_iter it; 7972 * int arr[10]; 7973 * int i = 0, a = 0; 7974 * bpf_iter_num_new(&it, 0, 10); 7975 * while (bpf_iter_num_next(&it)) { 7976 * if (a == 0) { 7977 * a = 1; 7978 * i = 7; // Because i changed verifier would forget 7979 * // it's range on second loop entry. 7980 * } else { 7981 * arr[i] = 42; // This would fail to verify. 7982 * } 7983 * } 7984 * bpf_iter_num_destroy(&it); 7985 */ 7986 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7987 struct bpf_kfunc_call_arg_meta *meta) 7988 { 7989 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 7990 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7991 struct bpf_reg_state *cur_iter, *queued_iter; 7992 int iter_frameno = meta->iter.frameno; 7993 int iter_spi = meta->iter.spi; 7994 7995 BTF_TYPE_EMIT(struct bpf_iter); 7996 7997 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7998 7999 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 8000 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 8001 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 8002 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 8003 return -EFAULT; 8004 } 8005 8006 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 8007 /* Because iter_next() call is a checkpoint is_state_visitied() 8008 * should guarantee parent state with same call sites and insn_idx. 8009 */ 8010 if (!cur_st->parent || cur_st->parent->insn_idx != insn_idx || 8011 !same_callsites(cur_st->parent, cur_st)) { 8012 verbose(env, "bug: bad parent state for iter next call"); 8013 return -EFAULT; 8014 } 8015 /* Note cur_st->parent in the call below, it is necessary to skip 8016 * checkpoint created for cur_st by is_state_visited() 8017 * right at this instruction. 8018 */ 8019 prev_st = find_prev_entry(env, cur_st->parent, insn_idx); 8020 /* branch out active iter state */ 8021 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 8022 if (!queued_st) 8023 return -ENOMEM; 8024 8025 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 8026 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 8027 queued_iter->iter.depth++; 8028 if (prev_st) 8029 widen_imprecise_scalars(env, prev_st, queued_st); 8030 8031 queued_fr = queued_st->frame[queued_st->curframe]; 8032 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 8033 } 8034 8035 /* switch to DRAINED state, but keep the depth unchanged */ 8036 /* mark current iter state as drained and assume returned NULL */ 8037 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 8038 __mark_reg_const_zero(env, &cur_fr->regs[BPF_REG_0]); 8039 8040 return 0; 8041 } 8042 8043 static bool arg_type_is_mem_size(enum bpf_arg_type type) 8044 { 8045 return type == ARG_CONST_SIZE || 8046 type == ARG_CONST_SIZE_OR_ZERO; 8047 } 8048 8049 static bool arg_type_is_release(enum bpf_arg_type type) 8050 { 8051 return type & OBJ_RELEASE; 8052 } 8053 8054 static bool arg_type_is_dynptr(enum bpf_arg_type type) 8055 { 8056 return base_type(type) == ARG_PTR_TO_DYNPTR; 8057 } 8058 8059 static int int_ptr_type_to_size(enum bpf_arg_type type) 8060 { 8061 if (type == ARG_PTR_TO_INT) 8062 return sizeof(u32); 8063 else if (type == ARG_PTR_TO_LONG) 8064 return sizeof(u64); 8065 8066 return -EINVAL; 8067 } 8068 8069 static int resolve_map_arg_type(struct bpf_verifier_env *env, 8070 const struct bpf_call_arg_meta *meta, 8071 enum bpf_arg_type *arg_type) 8072 { 8073 if (!meta->map_ptr) { 8074 /* kernel subsystem misconfigured verifier */ 8075 verbose(env, "invalid map_ptr to access map->type\n"); 8076 return -EACCES; 8077 } 8078 8079 switch (meta->map_ptr->map_type) { 8080 case BPF_MAP_TYPE_SOCKMAP: 8081 case BPF_MAP_TYPE_SOCKHASH: 8082 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 8083 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 8084 } else { 8085 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 8086 return -EINVAL; 8087 } 8088 break; 8089 case BPF_MAP_TYPE_BLOOM_FILTER: 8090 if (meta->func_id == BPF_FUNC_map_peek_elem) 8091 *arg_type = ARG_PTR_TO_MAP_VALUE; 8092 break; 8093 default: 8094 break; 8095 } 8096 return 0; 8097 } 8098 8099 struct bpf_reg_types { 8100 const enum bpf_reg_type types[10]; 8101 u32 *btf_id; 8102 }; 8103 8104 static const struct bpf_reg_types sock_types = { 8105 .types = { 8106 PTR_TO_SOCK_COMMON, 8107 PTR_TO_SOCKET, 8108 PTR_TO_TCP_SOCK, 8109 PTR_TO_XDP_SOCK, 8110 }, 8111 }; 8112 8113 #ifdef CONFIG_NET 8114 static const struct bpf_reg_types btf_id_sock_common_types = { 8115 .types = { 8116 PTR_TO_SOCK_COMMON, 8117 PTR_TO_SOCKET, 8118 PTR_TO_TCP_SOCK, 8119 PTR_TO_XDP_SOCK, 8120 PTR_TO_BTF_ID, 8121 PTR_TO_BTF_ID | PTR_TRUSTED, 8122 }, 8123 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8124 }; 8125 #endif 8126 8127 static const struct bpf_reg_types mem_types = { 8128 .types = { 8129 PTR_TO_STACK, 8130 PTR_TO_PACKET, 8131 PTR_TO_PACKET_META, 8132 PTR_TO_MAP_KEY, 8133 PTR_TO_MAP_VALUE, 8134 PTR_TO_MEM, 8135 PTR_TO_MEM | MEM_RINGBUF, 8136 PTR_TO_BUF, 8137 PTR_TO_BTF_ID | PTR_TRUSTED, 8138 }, 8139 }; 8140 8141 static const struct bpf_reg_types int_ptr_types = { 8142 .types = { 8143 PTR_TO_STACK, 8144 PTR_TO_PACKET, 8145 PTR_TO_PACKET_META, 8146 PTR_TO_MAP_KEY, 8147 PTR_TO_MAP_VALUE, 8148 }, 8149 }; 8150 8151 static const struct bpf_reg_types spin_lock_types = { 8152 .types = { 8153 PTR_TO_MAP_VALUE, 8154 PTR_TO_BTF_ID | MEM_ALLOC, 8155 } 8156 }; 8157 8158 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 8159 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 8160 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 8161 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 8162 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 8163 static const struct bpf_reg_types btf_ptr_types = { 8164 .types = { 8165 PTR_TO_BTF_ID, 8166 PTR_TO_BTF_ID | PTR_TRUSTED, 8167 PTR_TO_BTF_ID | MEM_RCU, 8168 }, 8169 }; 8170 static const struct bpf_reg_types percpu_btf_ptr_types = { 8171 .types = { 8172 PTR_TO_BTF_ID | MEM_PERCPU, 8173 PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU, 8174 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 8175 } 8176 }; 8177 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 8178 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 8179 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8180 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 8181 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 8182 static const struct bpf_reg_types dynptr_types = { 8183 .types = { 8184 PTR_TO_STACK, 8185 CONST_PTR_TO_DYNPTR, 8186 } 8187 }; 8188 8189 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 8190 [ARG_PTR_TO_MAP_KEY] = &mem_types, 8191 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 8192 [ARG_CONST_SIZE] = &scalar_types, 8193 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 8194 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 8195 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 8196 [ARG_PTR_TO_CTX] = &context_types, 8197 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 8198 #ifdef CONFIG_NET 8199 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 8200 #endif 8201 [ARG_PTR_TO_SOCKET] = &fullsock_types, 8202 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 8203 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 8204 [ARG_PTR_TO_MEM] = &mem_types, 8205 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 8206 [ARG_PTR_TO_INT] = &int_ptr_types, 8207 [ARG_PTR_TO_LONG] = &int_ptr_types, 8208 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 8209 [ARG_PTR_TO_FUNC] = &func_ptr_types, 8210 [ARG_PTR_TO_STACK] = &stack_ptr_types, 8211 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 8212 [ARG_PTR_TO_TIMER] = &timer_types, 8213 [ARG_PTR_TO_KPTR] = &kptr_types, 8214 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 8215 }; 8216 8217 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 8218 enum bpf_arg_type arg_type, 8219 const u32 *arg_btf_id, 8220 struct bpf_call_arg_meta *meta) 8221 { 8222 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8223 enum bpf_reg_type expected, type = reg->type; 8224 const struct bpf_reg_types *compatible; 8225 int i, j; 8226 8227 compatible = compatible_reg_types[base_type(arg_type)]; 8228 if (!compatible) { 8229 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 8230 return -EFAULT; 8231 } 8232 8233 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 8234 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 8235 * 8236 * Same for MAYBE_NULL: 8237 * 8238 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 8239 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 8240 * 8241 * ARG_PTR_TO_MEM is compatible with PTR_TO_MEM that is tagged with a dynptr type. 8242 * 8243 * Therefore we fold these flags depending on the arg_type before comparison. 8244 */ 8245 if (arg_type & MEM_RDONLY) 8246 type &= ~MEM_RDONLY; 8247 if (arg_type & PTR_MAYBE_NULL) 8248 type &= ~PTR_MAYBE_NULL; 8249 if (base_type(arg_type) == ARG_PTR_TO_MEM) 8250 type &= ~DYNPTR_TYPE_FLAG_MASK; 8251 8252 if (meta->func_id == BPF_FUNC_kptr_xchg && type_is_alloc(type)) { 8253 type &= ~MEM_ALLOC; 8254 type &= ~MEM_PERCPU; 8255 } 8256 8257 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 8258 expected = compatible->types[i]; 8259 if (expected == NOT_INIT) 8260 break; 8261 8262 if (type == expected) 8263 goto found; 8264 } 8265 8266 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 8267 for (j = 0; j + 1 < i; j++) 8268 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 8269 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 8270 return -EACCES; 8271 8272 found: 8273 if (base_type(reg->type) != PTR_TO_BTF_ID) 8274 return 0; 8275 8276 if (compatible == &mem_types) { 8277 if (!(arg_type & MEM_RDONLY)) { 8278 verbose(env, 8279 "%s() may write into memory pointed by R%d type=%s\n", 8280 func_id_name(meta->func_id), 8281 regno, reg_type_str(env, reg->type)); 8282 return -EACCES; 8283 } 8284 return 0; 8285 } 8286 8287 switch ((int)reg->type) { 8288 case PTR_TO_BTF_ID: 8289 case PTR_TO_BTF_ID | PTR_TRUSTED: 8290 case PTR_TO_BTF_ID | PTR_TRUSTED | PTR_MAYBE_NULL: 8291 case PTR_TO_BTF_ID | MEM_RCU: 8292 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 8293 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 8294 { 8295 /* For bpf_sk_release, it needs to match against first member 8296 * 'struct sock_common', hence make an exception for it. This 8297 * allows bpf_sk_release to work for multiple socket types. 8298 */ 8299 bool strict_type_match = arg_type_is_release(arg_type) && 8300 meta->func_id != BPF_FUNC_sk_release; 8301 8302 if (type_may_be_null(reg->type) && 8303 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 8304 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 8305 return -EACCES; 8306 } 8307 8308 if (!arg_btf_id) { 8309 if (!compatible->btf_id) { 8310 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 8311 return -EFAULT; 8312 } 8313 arg_btf_id = compatible->btf_id; 8314 } 8315 8316 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8317 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8318 return -EACCES; 8319 } else { 8320 if (arg_btf_id == BPF_PTR_POISON) { 8321 verbose(env, "verifier internal error:"); 8322 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 8323 regno); 8324 return -EACCES; 8325 } 8326 8327 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 8328 btf_vmlinux, *arg_btf_id, 8329 strict_type_match)) { 8330 verbose(env, "R%d is of type %s but %s is expected\n", 8331 regno, btf_type_name(reg->btf, reg->btf_id), 8332 btf_type_name(btf_vmlinux, *arg_btf_id)); 8333 return -EACCES; 8334 } 8335 } 8336 break; 8337 } 8338 case PTR_TO_BTF_ID | MEM_ALLOC: 8339 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_ALLOC: 8340 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 8341 meta->func_id != BPF_FUNC_kptr_xchg) { 8342 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 8343 return -EFAULT; 8344 } 8345 if (meta->func_id == BPF_FUNC_kptr_xchg) { 8346 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 8347 return -EACCES; 8348 } 8349 break; 8350 case PTR_TO_BTF_ID | MEM_PERCPU: 8351 case PTR_TO_BTF_ID | MEM_PERCPU | MEM_RCU: 8352 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 8353 /* Handled by helper specific checks */ 8354 break; 8355 default: 8356 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 8357 return -EFAULT; 8358 } 8359 return 0; 8360 } 8361 8362 static struct btf_field * 8363 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 8364 { 8365 struct btf_field *field; 8366 struct btf_record *rec; 8367 8368 rec = reg_btf_record(reg); 8369 if (!rec) 8370 return NULL; 8371 8372 field = btf_record_find(rec, off, fields); 8373 if (!field) 8374 return NULL; 8375 8376 return field; 8377 } 8378 8379 static int check_func_arg_reg_off(struct bpf_verifier_env *env, 8380 const struct bpf_reg_state *reg, int regno, 8381 enum bpf_arg_type arg_type) 8382 { 8383 u32 type = reg->type; 8384 8385 /* When referenced register is passed to release function, its fixed 8386 * offset must be 0. 8387 * 8388 * We will check arg_type_is_release reg has ref_obj_id when storing 8389 * meta->release_regno. 8390 */ 8391 if (arg_type_is_release(arg_type)) { 8392 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 8393 * may not directly point to the object being released, but to 8394 * dynptr pointing to such object, which might be at some offset 8395 * on the stack. In that case, we simply to fallback to the 8396 * default handling. 8397 */ 8398 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 8399 return 0; 8400 8401 /* Doing check_ptr_off_reg check for the offset will catch this 8402 * because fixed_off_ok is false, but checking here allows us 8403 * to give the user a better error message. 8404 */ 8405 if (reg->off) { 8406 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 8407 regno); 8408 return -EINVAL; 8409 } 8410 return __check_ptr_off_reg(env, reg, regno, false); 8411 } 8412 8413 switch (type) { 8414 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 8415 case PTR_TO_STACK: 8416 case PTR_TO_PACKET: 8417 case PTR_TO_PACKET_META: 8418 case PTR_TO_MAP_KEY: 8419 case PTR_TO_MAP_VALUE: 8420 case PTR_TO_MEM: 8421 case PTR_TO_MEM | MEM_RDONLY: 8422 case PTR_TO_MEM | MEM_RINGBUF: 8423 case PTR_TO_BUF: 8424 case PTR_TO_BUF | MEM_RDONLY: 8425 case PTR_TO_ARENA: 8426 case SCALAR_VALUE: 8427 return 0; 8428 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 8429 * fixed offset. 8430 */ 8431 case PTR_TO_BTF_ID: 8432 case PTR_TO_BTF_ID | MEM_ALLOC: 8433 case PTR_TO_BTF_ID | PTR_TRUSTED: 8434 case PTR_TO_BTF_ID | MEM_RCU: 8435 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 8436 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF | MEM_RCU: 8437 /* When referenced PTR_TO_BTF_ID is passed to release function, 8438 * its fixed offset must be 0. In the other cases, fixed offset 8439 * can be non-zero. This was already checked above. So pass 8440 * fixed_off_ok as true to allow fixed offset for all other 8441 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 8442 * still need to do checks instead of returning. 8443 */ 8444 return __check_ptr_off_reg(env, reg, regno, true); 8445 default: 8446 return __check_ptr_off_reg(env, reg, regno, false); 8447 } 8448 } 8449 8450 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 8451 const struct bpf_func_proto *fn, 8452 struct bpf_reg_state *regs) 8453 { 8454 struct bpf_reg_state *state = NULL; 8455 int i; 8456 8457 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 8458 if (arg_type_is_dynptr(fn->arg_type[i])) { 8459 if (state) { 8460 verbose(env, "verifier internal error: multiple dynptr args\n"); 8461 return NULL; 8462 } 8463 state = ®s[BPF_REG_1 + i]; 8464 } 8465 8466 if (!state) 8467 verbose(env, "verifier internal error: no dynptr arg found\n"); 8468 8469 return state; 8470 } 8471 8472 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8473 { 8474 struct bpf_func_state *state = func(env, reg); 8475 int spi; 8476 8477 if (reg->type == CONST_PTR_TO_DYNPTR) 8478 return reg->id; 8479 spi = dynptr_get_spi(env, reg); 8480 if (spi < 0) 8481 return spi; 8482 return state->stack[spi].spilled_ptr.id; 8483 } 8484 8485 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8486 { 8487 struct bpf_func_state *state = func(env, reg); 8488 int spi; 8489 8490 if (reg->type == CONST_PTR_TO_DYNPTR) 8491 return reg->ref_obj_id; 8492 spi = dynptr_get_spi(env, reg); 8493 if (spi < 0) 8494 return spi; 8495 return state->stack[spi].spilled_ptr.ref_obj_id; 8496 } 8497 8498 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 8499 struct bpf_reg_state *reg) 8500 { 8501 struct bpf_func_state *state = func(env, reg); 8502 int spi; 8503 8504 if (reg->type == CONST_PTR_TO_DYNPTR) 8505 return reg->dynptr.type; 8506 8507 spi = __get_spi(reg->off); 8508 if (spi < 0) { 8509 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 8510 return BPF_DYNPTR_TYPE_INVALID; 8511 } 8512 8513 return state->stack[spi].spilled_ptr.dynptr.type; 8514 } 8515 8516 static int check_reg_const_str(struct bpf_verifier_env *env, 8517 struct bpf_reg_state *reg, u32 regno) 8518 { 8519 struct bpf_map *map = reg->map_ptr; 8520 int err; 8521 int map_off; 8522 u64 map_addr; 8523 char *str_ptr; 8524 8525 if (reg->type != PTR_TO_MAP_VALUE) 8526 return -EINVAL; 8527 8528 if (!bpf_map_is_rdonly(map)) { 8529 verbose(env, "R%d does not point to a readonly map'\n", regno); 8530 return -EACCES; 8531 } 8532 8533 if (!tnum_is_const(reg->var_off)) { 8534 verbose(env, "R%d is not a constant address'\n", regno); 8535 return -EACCES; 8536 } 8537 8538 if (!map->ops->map_direct_value_addr) { 8539 verbose(env, "no direct value access support for this map type\n"); 8540 return -EACCES; 8541 } 8542 8543 err = check_map_access(env, regno, reg->off, 8544 map->value_size - reg->off, false, 8545 ACCESS_HELPER); 8546 if (err) 8547 return err; 8548 8549 map_off = reg->off + reg->var_off.value; 8550 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 8551 if (err) { 8552 verbose(env, "direct value access on string failed\n"); 8553 return err; 8554 } 8555 8556 str_ptr = (char *)(long)(map_addr); 8557 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 8558 verbose(env, "string is not zero-terminated\n"); 8559 return -EINVAL; 8560 } 8561 return 0; 8562 } 8563 8564 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 8565 struct bpf_call_arg_meta *meta, 8566 const struct bpf_func_proto *fn, 8567 int insn_idx) 8568 { 8569 u32 regno = BPF_REG_1 + arg; 8570 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 8571 enum bpf_arg_type arg_type = fn->arg_type[arg]; 8572 enum bpf_reg_type type = reg->type; 8573 u32 *arg_btf_id = NULL; 8574 int err = 0; 8575 8576 if (arg_type == ARG_DONTCARE) 8577 return 0; 8578 8579 err = check_reg_arg(env, regno, SRC_OP); 8580 if (err) 8581 return err; 8582 8583 if (arg_type == ARG_ANYTHING) { 8584 if (is_pointer_value(env, regno)) { 8585 verbose(env, "R%d leaks addr into helper function\n", 8586 regno); 8587 return -EACCES; 8588 } 8589 return 0; 8590 } 8591 8592 if (type_is_pkt_pointer(type) && 8593 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 8594 verbose(env, "helper access to the packet is not allowed\n"); 8595 return -EACCES; 8596 } 8597 8598 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 8599 err = resolve_map_arg_type(env, meta, &arg_type); 8600 if (err) 8601 return err; 8602 } 8603 8604 if (register_is_null(reg) && type_may_be_null(arg_type)) 8605 /* A NULL register has a SCALAR_VALUE type, so skip 8606 * type checking. 8607 */ 8608 goto skip_type_check; 8609 8610 /* arg_btf_id and arg_size are in a union. */ 8611 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 8612 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 8613 arg_btf_id = fn->arg_btf_id[arg]; 8614 8615 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 8616 if (err) 8617 return err; 8618 8619 err = check_func_arg_reg_off(env, reg, regno, arg_type); 8620 if (err) 8621 return err; 8622 8623 skip_type_check: 8624 if (arg_type_is_release(arg_type)) { 8625 if (arg_type_is_dynptr(arg_type)) { 8626 struct bpf_func_state *state = func(env, reg); 8627 int spi; 8628 8629 /* Only dynptr created on stack can be released, thus 8630 * the get_spi and stack state checks for spilled_ptr 8631 * should only be done before process_dynptr_func for 8632 * PTR_TO_STACK. 8633 */ 8634 if (reg->type == PTR_TO_STACK) { 8635 spi = dynptr_get_spi(env, reg); 8636 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 8637 verbose(env, "arg %d is an unacquired reference\n", regno); 8638 return -EINVAL; 8639 } 8640 } else { 8641 verbose(env, "cannot release unowned const bpf_dynptr\n"); 8642 return -EINVAL; 8643 } 8644 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 8645 verbose(env, "R%d must be referenced when passed to release function\n", 8646 regno); 8647 return -EINVAL; 8648 } 8649 if (meta->release_regno) { 8650 verbose(env, "verifier internal error: more than one release argument\n"); 8651 return -EFAULT; 8652 } 8653 meta->release_regno = regno; 8654 } 8655 8656 if (reg->ref_obj_id) { 8657 if (meta->ref_obj_id) { 8658 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8659 regno, reg->ref_obj_id, 8660 meta->ref_obj_id); 8661 return -EFAULT; 8662 } 8663 meta->ref_obj_id = reg->ref_obj_id; 8664 } 8665 8666 switch (base_type(arg_type)) { 8667 case ARG_CONST_MAP_PTR: 8668 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 8669 if (meta->map_ptr) { 8670 /* Use map_uid (which is unique id of inner map) to reject: 8671 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 8672 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 8673 * if (inner_map1 && inner_map2) { 8674 * timer = bpf_map_lookup_elem(inner_map1); 8675 * if (timer) 8676 * // mismatch would have been allowed 8677 * bpf_timer_init(timer, inner_map2); 8678 * } 8679 * 8680 * Comparing map_ptr is enough to distinguish normal and outer maps. 8681 */ 8682 if (meta->map_ptr != reg->map_ptr || 8683 meta->map_uid != reg->map_uid) { 8684 verbose(env, 8685 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 8686 meta->map_uid, reg->map_uid); 8687 return -EINVAL; 8688 } 8689 } 8690 meta->map_ptr = reg->map_ptr; 8691 meta->map_uid = reg->map_uid; 8692 break; 8693 case ARG_PTR_TO_MAP_KEY: 8694 /* bpf_map_xxx(..., map_ptr, ..., key) call: 8695 * check that [key, key + map->key_size) are within 8696 * stack limits and initialized 8697 */ 8698 if (!meta->map_ptr) { 8699 /* in function declaration map_ptr must come before 8700 * map_key, so that it's verified and known before 8701 * we have to check map_key here. Otherwise it means 8702 * that kernel subsystem misconfigured verifier 8703 */ 8704 verbose(env, "invalid map_ptr to access map->key\n"); 8705 return -EACCES; 8706 } 8707 err = check_helper_mem_access(env, regno, 8708 meta->map_ptr->key_size, false, 8709 NULL); 8710 break; 8711 case ARG_PTR_TO_MAP_VALUE: 8712 if (type_may_be_null(arg_type) && register_is_null(reg)) 8713 return 0; 8714 8715 /* bpf_map_xxx(..., map_ptr, ..., value) call: 8716 * check [value, value + map->value_size) validity 8717 */ 8718 if (!meta->map_ptr) { 8719 /* kernel subsystem misconfigured verifier */ 8720 verbose(env, "invalid map_ptr to access map->value\n"); 8721 return -EACCES; 8722 } 8723 meta->raw_mode = arg_type & MEM_UNINIT; 8724 err = check_helper_mem_access(env, regno, 8725 meta->map_ptr->value_size, false, 8726 meta); 8727 break; 8728 case ARG_PTR_TO_PERCPU_BTF_ID: 8729 if (!reg->btf_id) { 8730 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 8731 return -EACCES; 8732 } 8733 meta->ret_btf = reg->btf; 8734 meta->ret_btf_id = reg->btf_id; 8735 break; 8736 case ARG_PTR_TO_SPIN_LOCK: 8737 if (in_rbtree_lock_required_cb(env)) { 8738 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 8739 return -EACCES; 8740 } 8741 if (meta->func_id == BPF_FUNC_spin_lock) { 8742 err = process_spin_lock(env, regno, true); 8743 if (err) 8744 return err; 8745 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 8746 err = process_spin_lock(env, regno, false); 8747 if (err) 8748 return err; 8749 } else { 8750 verbose(env, "verifier internal error\n"); 8751 return -EFAULT; 8752 } 8753 break; 8754 case ARG_PTR_TO_TIMER: 8755 err = process_timer_func(env, regno, meta); 8756 if (err) 8757 return err; 8758 break; 8759 case ARG_PTR_TO_FUNC: 8760 meta->subprogno = reg->subprogno; 8761 break; 8762 case ARG_PTR_TO_MEM: 8763 /* The access to this pointer is only checked when we hit the 8764 * next is_mem_size argument below. 8765 */ 8766 meta->raw_mode = arg_type & MEM_UNINIT; 8767 if (arg_type & MEM_FIXED_SIZE) { 8768 err = check_helper_mem_access(env, regno, 8769 fn->arg_size[arg], false, 8770 meta); 8771 } 8772 break; 8773 case ARG_CONST_SIZE: 8774 err = check_mem_size_reg(env, reg, regno, false, meta); 8775 break; 8776 case ARG_CONST_SIZE_OR_ZERO: 8777 err = check_mem_size_reg(env, reg, regno, true, meta); 8778 break; 8779 case ARG_PTR_TO_DYNPTR: 8780 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 8781 if (err) 8782 return err; 8783 break; 8784 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 8785 if (!tnum_is_const(reg->var_off)) { 8786 verbose(env, "R%d is not a known constant'\n", 8787 regno); 8788 return -EACCES; 8789 } 8790 meta->mem_size = reg->var_off.value; 8791 err = mark_chain_precision(env, regno); 8792 if (err) 8793 return err; 8794 break; 8795 case ARG_PTR_TO_INT: 8796 case ARG_PTR_TO_LONG: 8797 { 8798 int size = int_ptr_type_to_size(arg_type); 8799 8800 err = check_helper_mem_access(env, regno, size, false, meta); 8801 if (err) 8802 return err; 8803 err = check_ptr_alignment(env, reg, 0, size, true); 8804 break; 8805 } 8806 case ARG_PTR_TO_CONST_STR: 8807 { 8808 err = check_reg_const_str(env, reg, regno); 8809 if (err) 8810 return err; 8811 break; 8812 } 8813 case ARG_PTR_TO_KPTR: 8814 err = process_kptr_func(env, regno, meta); 8815 if (err) 8816 return err; 8817 break; 8818 } 8819 8820 return err; 8821 } 8822 8823 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 8824 { 8825 enum bpf_attach_type eatype = env->prog->expected_attach_type; 8826 enum bpf_prog_type type = resolve_prog_type(env->prog); 8827 8828 if (func_id != BPF_FUNC_map_update_elem) 8829 return false; 8830 8831 /* It's not possible to get access to a locked struct sock in these 8832 * contexts, so updating is safe. 8833 */ 8834 switch (type) { 8835 case BPF_PROG_TYPE_TRACING: 8836 if (eatype == BPF_TRACE_ITER) 8837 return true; 8838 break; 8839 case BPF_PROG_TYPE_SOCKET_FILTER: 8840 case BPF_PROG_TYPE_SCHED_CLS: 8841 case BPF_PROG_TYPE_SCHED_ACT: 8842 case BPF_PROG_TYPE_XDP: 8843 case BPF_PROG_TYPE_SK_REUSEPORT: 8844 case BPF_PROG_TYPE_FLOW_DISSECTOR: 8845 case BPF_PROG_TYPE_SK_LOOKUP: 8846 return true; 8847 default: 8848 break; 8849 } 8850 8851 verbose(env, "cannot update sockmap in this context\n"); 8852 return false; 8853 } 8854 8855 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 8856 { 8857 return env->prog->jit_requested && 8858 bpf_jit_supports_subprog_tailcalls(); 8859 } 8860 8861 static int check_map_func_compatibility(struct bpf_verifier_env *env, 8862 struct bpf_map *map, int func_id) 8863 { 8864 if (!map) 8865 return 0; 8866 8867 /* We need a two way check, first is from map perspective ... */ 8868 switch (map->map_type) { 8869 case BPF_MAP_TYPE_PROG_ARRAY: 8870 if (func_id != BPF_FUNC_tail_call) 8871 goto error; 8872 break; 8873 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 8874 if (func_id != BPF_FUNC_perf_event_read && 8875 func_id != BPF_FUNC_perf_event_output && 8876 func_id != BPF_FUNC_skb_output && 8877 func_id != BPF_FUNC_perf_event_read_value && 8878 func_id != BPF_FUNC_xdp_output) 8879 goto error; 8880 break; 8881 case BPF_MAP_TYPE_RINGBUF: 8882 if (func_id != BPF_FUNC_ringbuf_output && 8883 func_id != BPF_FUNC_ringbuf_reserve && 8884 func_id != BPF_FUNC_ringbuf_query && 8885 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 8886 func_id != BPF_FUNC_ringbuf_submit_dynptr && 8887 func_id != BPF_FUNC_ringbuf_discard_dynptr) 8888 goto error; 8889 break; 8890 case BPF_MAP_TYPE_USER_RINGBUF: 8891 if (func_id != BPF_FUNC_user_ringbuf_drain) 8892 goto error; 8893 break; 8894 case BPF_MAP_TYPE_STACK_TRACE: 8895 if (func_id != BPF_FUNC_get_stackid) 8896 goto error; 8897 break; 8898 case BPF_MAP_TYPE_CGROUP_ARRAY: 8899 if (func_id != BPF_FUNC_skb_under_cgroup && 8900 func_id != BPF_FUNC_current_task_under_cgroup) 8901 goto error; 8902 break; 8903 case BPF_MAP_TYPE_CGROUP_STORAGE: 8904 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8905 if (func_id != BPF_FUNC_get_local_storage) 8906 goto error; 8907 break; 8908 case BPF_MAP_TYPE_DEVMAP: 8909 case BPF_MAP_TYPE_DEVMAP_HASH: 8910 if (func_id != BPF_FUNC_redirect_map && 8911 func_id != BPF_FUNC_map_lookup_elem) 8912 goto error; 8913 break; 8914 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8915 * appear. 8916 */ 8917 case BPF_MAP_TYPE_CPUMAP: 8918 if (func_id != BPF_FUNC_redirect_map) 8919 goto error; 8920 break; 8921 case BPF_MAP_TYPE_XSKMAP: 8922 if (func_id != BPF_FUNC_redirect_map && 8923 func_id != BPF_FUNC_map_lookup_elem) 8924 goto error; 8925 break; 8926 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8927 case BPF_MAP_TYPE_HASH_OF_MAPS: 8928 if (func_id != BPF_FUNC_map_lookup_elem) 8929 goto error; 8930 break; 8931 case BPF_MAP_TYPE_SOCKMAP: 8932 if (func_id != BPF_FUNC_sk_redirect_map && 8933 func_id != BPF_FUNC_sock_map_update && 8934 func_id != BPF_FUNC_map_delete_elem && 8935 func_id != BPF_FUNC_msg_redirect_map && 8936 func_id != BPF_FUNC_sk_select_reuseport && 8937 func_id != BPF_FUNC_map_lookup_elem && 8938 !may_update_sockmap(env, func_id)) 8939 goto error; 8940 break; 8941 case BPF_MAP_TYPE_SOCKHASH: 8942 if (func_id != BPF_FUNC_sk_redirect_hash && 8943 func_id != BPF_FUNC_sock_hash_update && 8944 func_id != BPF_FUNC_map_delete_elem && 8945 func_id != BPF_FUNC_msg_redirect_hash && 8946 func_id != BPF_FUNC_sk_select_reuseport && 8947 func_id != BPF_FUNC_map_lookup_elem && 8948 !may_update_sockmap(env, func_id)) 8949 goto error; 8950 break; 8951 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8952 if (func_id != BPF_FUNC_sk_select_reuseport) 8953 goto error; 8954 break; 8955 case BPF_MAP_TYPE_QUEUE: 8956 case BPF_MAP_TYPE_STACK: 8957 if (func_id != BPF_FUNC_map_peek_elem && 8958 func_id != BPF_FUNC_map_pop_elem && 8959 func_id != BPF_FUNC_map_push_elem) 8960 goto error; 8961 break; 8962 case BPF_MAP_TYPE_SK_STORAGE: 8963 if (func_id != BPF_FUNC_sk_storage_get && 8964 func_id != BPF_FUNC_sk_storage_delete && 8965 func_id != BPF_FUNC_kptr_xchg) 8966 goto error; 8967 break; 8968 case BPF_MAP_TYPE_INODE_STORAGE: 8969 if (func_id != BPF_FUNC_inode_storage_get && 8970 func_id != BPF_FUNC_inode_storage_delete && 8971 func_id != BPF_FUNC_kptr_xchg) 8972 goto error; 8973 break; 8974 case BPF_MAP_TYPE_TASK_STORAGE: 8975 if (func_id != BPF_FUNC_task_storage_get && 8976 func_id != BPF_FUNC_task_storage_delete && 8977 func_id != BPF_FUNC_kptr_xchg) 8978 goto error; 8979 break; 8980 case BPF_MAP_TYPE_CGRP_STORAGE: 8981 if (func_id != BPF_FUNC_cgrp_storage_get && 8982 func_id != BPF_FUNC_cgrp_storage_delete && 8983 func_id != BPF_FUNC_kptr_xchg) 8984 goto error; 8985 break; 8986 case BPF_MAP_TYPE_BLOOM_FILTER: 8987 if (func_id != BPF_FUNC_map_peek_elem && 8988 func_id != BPF_FUNC_map_push_elem) 8989 goto error; 8990 break; 8991 default: 8992 break; 8993 } 8994 8995 /* ... and second from the function itself. */ 8996 switch (func_id) { 8997 case BPF_FUNC_tail_call: 8998 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8999 goto error; 9000 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 9001 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 9002 return -EINVAL; 9003 } 9004 break; 9005 case BPF_FUNC_perf_event_read: 9006 case BPF_FUNC_perf_event_output: 9007 case BPF_FUNC_perf_event_read_value: 9008 case BPF_FUNC_skb_output: 9009 case BPF_FUNC_xdp_output: 9010 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 9011 goto error; 9012 break; 9013 case BPF_FUNC_ringbuf_output: 9014 case BPF_FUNC_ringbuf_reserve: 9015 case BPF_FUNC_ringbuf_query: 9016 case BPF_FUNC_ringbuf_reserve_dynptr: 9017 case BPF_FUNC_ringbuf_submit_dynptr: 9018 case BPF_FUNC_ringbuf_discard_dynptr: 9019 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 9020 goto error; 9021 break; 9022 case BPF_FUNC_user_ringbuf_drain: 9023 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 9024 goto error; 9025 break; 9026 case BPF_FUNC_get_stackid: 9027 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 9028 goto error; 9029 break; 9030 case BPF_FUNC_current_task_under_cgroup: 9031 case BPF_FUNC_skb_under_cgroup: 9032 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 9033 goto error; 9034 break; 9035 case BPF_FUNC_redirect_map: 9036 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 9037 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 9038 map->map_type != BPF_MAP_TYPE_CPUMAP && 9039 map->map_type != BPF_MAP_TYPE_XSKMAP) 9040 goto error; 9041 break; 9042 case BPF_FUNC_sk_redirect_map: 9043 case BPF_FUNC_msg_redirect_map: 9044 case BPF_FUNC_sock_map_update: 9045 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 9046 goto error; 9047 break; 9048 case BPF_FUNC_sk_redirect_hash: 9049 case BPF_FUNC_msg_redirect_hash: 9050 case BPF_FUNC_sock_hash_update: 9051 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 9052 goto error; 9053 break; 9054 case BPF_FUNC_get_local_storage: 9055 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 9056 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 9057 goto error; 9058 break; 9059 case BPF_FUNC_sk_select_reuseport: 9060 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 9061 map->map_type != BPF_MAP_TYPE_SOCKMAP && 9062 map->map_type != BPF_MAP_TYPE_SOCKHASH) 9063 goto error; 9064 break; 9065 case BPF_FUNC_map_pop_elem: 9066 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9067 map->map_type != BPF_MAP_TYPE_STACK) 9068 goto error; 9069 break; 9070 case BPF_FUNC_map_peek_elem: 9071 case BPF_FUNC_map_push_elem: 9072 if (map->map_type != BPF_MAP_TYPE_QUEUE && 9073 map->map_type != BPF_MAP_TYPE_STACK && 9074 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 9075 goto error; 9076 break; 9077 case BPF_FUNC_map_lookup_percpu_elem: 9078 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 9079 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 9080 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 9081 goto error; 9082 break; 9083 case BPF_FUNC_sk_storage_get: 9084 case BPF_FUNC_sk_storage_delete: 9085 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 9086 goto error; 9087 break; 9088 case BPF_FUNC_inode_storage_get: 9089 case BPF_FUNC_inode_storage_delete: 9090 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 9091 goto error; 9092 break; 9093 case BPF_FUNC_task_storage_get: 9094 case BPF_FUNC_task_storage_delete: 9095 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 9096 goto error; 9097 break; 9098 case BPF_FUNC_cgrp_storage_get: 9099 case BPF_FUNC_cgrp_storage_delete: 9100 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 9101 goto error; 9102 break; 9103 default: 9104 break; 9105 } 9106 9107 return 0; 9108 error: 9109 verbose(env, "cannot pass map_type %d into func %s#%d\n", 9110 map->map_type, func_id_name(func_id), func_id); 9111 return -EINVAL; 9112 } 9113 9114 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 9115 { 9116 int count = 0; 9117 9118 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 9119 count++; 9120 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 9121 count++; 9122 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 9123 count++; 9124 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 9125 count++; 9126 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 9127 count++; 9128 9129 /* We only support one arg being in raw mode at the moment, 9130 * which is sufficient for the helper functions we have 9131 * right now. 9132 */ 9133 return count <= 1; 9134 } 9135 9136 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 9137 { 9138 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 9139 bool has_size = fn->arg_size[arg] != 0; 9140 bool is_next_size = false; 9141 9142 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 9143 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 9144 9145 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 9146 return is_next_size; 9147 9148 return has_size == is_next_size || is_next_size == is_fixed; 9149 } 9150 9151 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 9152 { 9153 /* bpf_xxx(..., buf, len) call will access 'len' 9154 * bytes from memory 'buf'. Both arg types need 9155 * to be paired, so make sure there's no buggy 9156 * helper function specification. 9157 */ 9158 if (arg_type_is_mem_size(fn->arg1_type) || 9159 check_args_pair_invalid(fn, 0) || 9160 check_args_pair_invalid(fn, 1) || 9161 check_args_pair_invalid(fn, 2) || 9162 check_args_pair_invalid(fn, 3) || 9163 check_args_pair_invalid(fn, 4)) 9164 return false; 9165 9166 return true; 9167 } 9168 9169 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 9170 { 9171 int i; 9172 9173 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 9174 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 9175 return !!fn->arg_btf_id[i]; 9176 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 9177 return fn->arg_btf_id[i] == BPF_PTR_POISON; 9178 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 9179 /* arg_btf_id and arg_size are in a union. */ 9180 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 9181 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 9182 return false; 9183 } 9184 9185 return true; 9186 } 9187 9188 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 9189 { 9190 return check_raw_mode_ok(fn) && 9191 check_arg_pair_ok(fn) && 9192 check_btf_id_ok(fn) ? 0 : -EINVAL; 9193 } 9194 9195 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 9196 * are now invalid, so turn them into unknown SCALAR_VALUE. 9197 * 9198 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 9199 * since these slices point to packet data. 9200 */ 9201 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 9202 { 9203 struct bpf_func_state *state; 9204 struct bpf_reg_state *reg; 9205 9206 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9207 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 9208 mark_reg_invalid(env, reg); 9209 })); 9210 } 9211 9212 enum { 9213 AT_PKT_END = -1, 9214 BEYOND_PKT_END = -2, 9215 }; 9216 9217 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 9218 { 9219 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9220 struct bpf_reg_state *reg = &state->regs[regn]; 9221 9222 if (reg->type != PTR_TO_PACKET) 9223 /* PTR_TO_PACKET_META is not supported yet */ 9224 return; 9225 9226 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 9227 * How far beyond pkt_end it goes is unknown. 9228 * if (!range_open) it's the case of pkt >= pkt_end 9229 * if (range_open) it's the case of pkt > pkt_end 9230 * hence this pointer is at least 1 byte bigger than pkt_end 9231 */ 9232 if (range_open) 9233 reg->range = BEYOND_PKT_END; 9234 else 9235 reg->range = AT_PKT_END; 9236 } 9237 9238 /* The pointer with the specified id has released its reference to kernel 9239 * resources. Identify all copies of the same pointer and clear the reference. 9240 */ 9241 static int release_reference(struct bpf_verifier_env *env, 9242 int ref_obj_id) 9243 { 9244 struct bpf_func_state *state; 9245 struct bpf_reg_state *reg; 9246 int err; 9247 9248 err = release_reference_state(cur_func(env), ref_obj_id); 9249 if (err) 9250 return err; 9251 9252 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9253 if (reg->ref_obj_id == ref_obj_id) 9254 mark_reg_invalid(env, reg); 9255 })); 9256 9257 return 0; 9258 } 9259 9260 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 9261 { 9262 struct bpf_func_state *unused; 9263 struct bpf_reg_state *reg; 9264 9265 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9266 if (type_is_non_owning_ref(reg->type)) 9267 mark_reg_invalid(env, reg); 9268 })); 9269 } 9270 9271 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 9272 struct bpf_reg_state *regs) 9273 { 9274 int i; 9275 9276 /* after the call registers r0 - r5 were scratched */ 9277 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9278 mark_reg_not_init(env, regs, caller_saved[i]); 9279 __check_reg_arg(env, regs, caller_saved[i], DST_OP_NO_MARK); 9280 } 9281 } 9282 9283 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 9284 struct bpf_func_state *caller, 9285 struct bpf_func_state *callee, 9286 int insn_idx); 9287 9288 static int set_callee_state(struct bpf_verifier_env *env, 9289 struct bpf_func_state *caller, 9290 struct bpf_func_state *callee, int insn_idx); 9291 9292 static int setup_func_entry(struct bpf_verifier_env *env, int subprog, int callsite, 9293 set_callee_state_fn set_callee_state_cb, 9294 struct bpf_verifier_state *state) 9295 { 9296 struct bpf_func_state *caller, *callee; 9297 int err; 9298 9299 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 9300 verbose(env, "the call stack of %d frames is too deep\n", 9301 state->curframe + 2); 9302 return -E2BIG; 9303 } 9304 9305 if (state->frame[state->curframe + 1]) { 9306 verbose(env, "verifier bug. Frame %d already allocated\n", 9307 state->curframe + 1); 9308 return -EFAULT; 9309 } 9310 9311 caller = state->frame[state->curframe]; 9312 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 9313 if (!callee) 9314 return -ENOMEM; 9315 state->frame[state->curframe + 1] = callee; 9316 9317 /* callee cannot access r0, r6 - r9 for reading and has to write 9318 * into its own stack before reading from it. 9319 * callee can read/write into caller's stack 9320 */ 9321 init_func_state(env, callee, 9322 /* remember the callsite, it will be used by bpf_exit */ 9323 callsite, 9324 state->curframe + 1 /* frameno within this callchain */, 9325 subprog /* subprog number within this prog */); 9326 /* Transfer references to the callee */ 9327 err = copy_reference_state(callee, caller); 9328 err = err ?: set_callee_state_cb(env, caller, callee, callsite); 9329 if (err) 9330 goto err_out; 9331 9332 /* only increment it after check_reg_arg() finished */ 9333 state->curframe++; 9334 9335 return 0; 9336 9337 err_out: 9338 free_func_state(callee); 9339 state->frame[state->curframe + 1] = NULL; 9340 return err; 9341 } 9342 9343 static int btf_check_func_arg_match(struct bpf_verifier_env *env, int subprog, 9344 const struct btf *btf, 9345 struct bpf_reg_state *regs) 9346 { 9347 struct bpf_subprog_info *sub = subprog_info(env, subprog); 9348 struct bpf_verifier_log *log = &env->log; 9349 u32 i; 9350 int ret; 9351 9352 ret = btf_prepare_func_args(env, subprog); 9353 if (ret) 9354 return ret; 9355 9356 /* check that BTF function arguments match actual types that the 9357 * verifier sees. 9358 */ 9359 for (i = 0; i < sub->arg_cnt; i++) { 9360 u32 regno = i + 1; 9361 struct bpf_reg_state *reg = ®s[regno]; 9362 struct bpf_subprog_arg_info *arg = &sub->args[i]; 9363 9364 if (arg->arg_type == ARG_ANYTHING) { 9365 if (reg->type != SCALAR_VALUE) { 9366 bpf_log(log, "R%d is not a scalar\n", regno); 9367 return -EINVAL; 9368 } 9369 } else if (arg->arg_type == ARG_PTR_TO_CTX) { 9370 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9371 if (ret < 0) 9372 return ret; 9373 /* If function expects ctx type in BTF check that caller 9374 * is passing PTR_TO_CTX. 9375 */ 9376 if (reg->type != PTR_TO_CTX) { 9377 bpf_log(log, "arg#%d expects pointer to ctx\n", i); 9378 return -EINVAL; 9379 } 9380 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 9381 ret = check_func_arg_reg_off(env, reg, regno, ARG_DONTCARE); 9382 if (ret < 0) 9383 return ret; 9384 if (check_mem_reg(env, reg, regno, arg->mem_size)) 9385 return -EINVAL; 9386 if (!(arg->arg_type & PTR_MAYBE_NULL) && (reg->type & PTR_MAYBE_NULL)) { 9387 bpf_log(log, "arg#%d is expected to be non-NULL\n", i); 9388 return -EINVAL; 9389 } 9390 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 9391 /* 9392 * Can pass any value and the kernel won't crash, but 9393 * only PTR_TO_ARENA or SCALAR make sense. Everything 9394 * else is a bug in the bpf program. Point it out to 9395 * the user at the verification time instead of 9396 * run-time debug nightmare. 9397 */ 9398 if (reg->type != PTR_TO_ARENA && reg->type != SCALAR_VALUE) { 9399 bpf_log(log, "R%d is not a pointer to arena or scalar.\n", regno); 9400 return -EINVAL; 9401 } 9402 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 9403 ret = process_dynptr_func(env, regno, -1, arg->arg_type, 0); 9404 if (ret) 9405 return ret; 9406 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 9407 struct bpf_call_arg_meta meta; 9408 int err; 9409 9410 if (register_is_null(reg) && type_may_be_null(arg->arg_type)) 9411 continue; 9412 9413 memset(&meta, 0, sizeof(meta)); /* leave func_id as zero */ 9414 err = check_reg_type(env, regno, arg->arg_type, &arg->btf_id, &meta); 9415 err = err ?: check_func_arg_reg_off(env, reg, regno, arg->arg_type); 9416 if (err) 9417 return err; 9418 } else { 9419 bpf_log(log, "verifier bug: unrecognized arg#%d type %d\n", 9420 i, arg->arg_type); 9421 return -EFAULT; 9422 } 9423 } 9424 9425 return 0; 9426 } 9427 9428 /* Compare BTF of a function call with given bpf_reg_state. 9429 * Returns: 9430 * EFAULT - there is a verifier bug. Abort verification. 9431 * EINVAL - there is a type mismatch or BTF is not available. 9432 * 0 - BTF matches with what bpf_reg_state expects. 9433 * Only PTR_TO_CTX and SCALAR_VALUE states are recognized. 9434 */ 9435 static int btf_check_subprog_call(struct bpf_verifier_env *env, int subprog, 9436 struct bpf_reg_state *regs) 9437 { 9438 struct bpf_prog *prog = env->prog; 9439 struct btf *btf = prog->aux->btf; 9440 u32 btf_id; 9441 int err; 9442 9443 if (!prog->aux->func_info) 9444 return -EINVAL; 9445 9446 btf_id = prog->aux->func_info[subprog].type_id; 9447 if (!btf_id) 9448 return -EFAULT; 9449 9450 if (prog->aux->func_info_aux[subprog].unreliable) 9451 return -EINVAL; 9452 9453 err = btf_check_func_arg_match(env, subprog, btf, regs); 9454 /* Compiler optimizations can remove arguments from static functions 9455 * or mismatched type can be passed into a global function. 9456 * In such cases mark the function as unreliable from BTF point of view. 9457 */ 9458 if (err) 9459 prog->aux->func_info_aux[subprog].unreliable = true; 9460 return err; 9461 } 9462 9463 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9464 int insn_idx, int subprog, 9465 set_callee_state_fn set_callee_state_cb) 9466 { 9467 struct bpf_verifier_state *state = env->cur_state, *callback_state; 9468 struct bpf_func_state *caller, *callee; 9469 int err; 9470 9471 caller = state->frame[state->curframe]; 9472 err = btf_check_subprog_call(env, subprog, caller->regs); 9473 if (err == -EFAULT) 9474 return err; 9475 9476 /* set_callee_state is used for direct subprog calls, but we are 9477 * interested in validating only BPF helpers that can call subprogs as 9478 * callbacks 9479 */ 9480 env->subprog_info[subprog].is_cb = true; 9481 if (bpf_pseudo_kfunc_call(insn) && 9482 !is_sync_callback_calling_kfunc(insn->imm)) { 9483 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 9484 func_id_name(insn->imm), insn->imm); 9485 return -EFAULT; 9486 } else if (!bpf_pseudo_kfunc_call(insn) && 9487 !is_callback_calling_function(insn->imm)) { /* helper */ 9488 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 9489 func_id_name(insn->imm), insn->imm); 9490 return -EFAULT; 9491 } 9492 9493 if (is_async_callback_calling_insn(insn)) { 9494 struct bpf_verifier_state *async_cb; 9495 9496 /* there is no real recursion here. timer callbacks are async */ 9497 env->subprog_info[subprog].is_async_cb = true; 9498 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 9499 insn_idx, subprog); 9500 if (!async_cb) 9501 return -EFAULT; 9502 callee = async_cb->frame[0]; 9503 callee->async_entry_cnt = caller->async_entry_cnt + 1; 9504 9505 /* Convert bpf_timer_set_callback() args into timer callback args */ 9506 err = set_callee_state_cb(env, caller, callee, insn_idx); 9507 if (err) 9508 return err; 9509 9510 return 0; 9511 } 9512 9513 /* for callback functions enqueue entry to callback and 9514 * proceed with next instruction within current frame. 9515 */ 9516 callback_state = push_stack(env, env->subprog_info[subprog].start, insn_idx, false); 9517 if (!callback_state) 9518 return -ENOMEM; 9519 9520 err = setup_func_entry(env, subprog, insn_idx, set_callee_state_cb, 9521 callback_state); 9522 if (err) 9523 return err; 9524 9525 callback_state->callback_unroll_depth++; 9526 callback_state->frame[callback_state->curframe - 1]->callback_depth++; 9527 caller->callback_depth = 0; 9528 return 0; 9529 } 9530 9531 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9532 int *insn_idx) 9533 { 9534 struct bpf_verifier_state *state = env->cur_state; 9535 struct bpf_func_state *caller; 9536 int err, subprog, target_insn; 9537 9538 target_insn = *insn_idx + insn->imm + 1; 9539 subprog = find_subprog(env, target_insn); 9540 if (subprog < 0) { 9541 verbose(env, "verifier bug. No program starts at insn %d\n", target_insn); 9542 return -EFAULT; 9543 } 9544 9545 caller = state->frame[state->curframe]; 9546 err = btf_check_subprog_call(env, subprog, caller->regs); 9547 if (err == -EFAULT) 9548 return err; 9549 if (subprog_is_global(env, subprog)) { 9550 const char *sub_name = subprog_name(env, subprog); 9551 9552 /* Only global subprogs cannot be called with a lock held. */ 9553 if (env->cur_state->active_lock.ptr) { 9554 verbose(env, "global function calls are not allowed while holding a lock,\n" 9555 "use static function instead\n"); 9556 return -EINVAL; 9557 } 9558 9559 if (err) { 9560 verbose(env, "Caller passes invalid args into func#%d ('%s')\n", 9561 subprog, sub_name); 9562 return err; 9563 } 9564 9565 verbose(env, "Func#%d ('%s') is global and assumed valid.\n", 9566 subprog, sub_name); 9567 /* mark global subprog for verifying after main prog */ 9568 subprog_aux(env, subprog)->called = true; 9569 clear_caller_saved_regs(env, caller->regs); 9570 9571 /* All global functions return a 64-bit SCALAR_VALUE */ 9572 mark_reg_unknown(env, caller->regs, BPF_REG_0); 9573 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9574 9575 /* continue with next insn after call */ 9576 return 0; 9577 } 9578 9579 /* for regular function entry setup new frame and continue 9580 * from that frame. 9581 */ 9582 err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state); 9583 if (err) 9584 return err; 9585 9586 clear_caller_saved_regs(env, caller->regs); 9587 9588 /* and go analyze first insn of the callee */ 9589 *insn_idx = env->subprog_info[subprog].start - 1; 9590 9591 if (env->log.level & BPF_LOG_LEVEL) { 9592 verbose(env, "caller:\n"); 9593 print_verifier_state(env, caller, true); 9594 verbose(env, "callee:\n"); 9595 print_verifier_state(env, state->frame[state->curframe], true); 9596 } 9597 9598 return 0; 9599 } 9600 9601 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 9602 struct bpf_func_state *caller, 9603 struct bpf_func_state *callee) 9604 { 9605 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 9606 * void *callback_ctx, u64 flags); 9607 * callback_fn(struct bpf_map *map, void *key, void *value, 9608 * void *callback_ctx); 9609 */ 9610 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9611 9612 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9613 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9614 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9615 9616 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9617 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9618 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 9619 9620 /* pointer to stack or null */ 9621 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 9622 9623 /* unused */ 9624 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9625 return 0; 9626 } 9627 9628 static int set_callee_state(struct bpf_verifier_env *env, 9629 struct bpf_func_state *caller, 9630 struct bpf_func_state *callee, int insn_idx) 9631 { 9632 int i; 9633 9634 /* copy r1 - r5 args that callee can access. The copy includes parent 9635 * pointers, which connects us up to the liveness chain 9636 */ 9637 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 9638 callee->regs[i] = caller->regs[i]; 9639 return 0; 9640 } 9641 9642 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 9643 struct bpf_func_state *caller, 9644 struct bpf_func_state *callee, 9645 int insn_idx) 9646 { 9647 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 9648 struct bpf_map *map; 9649 int err; 9650 9651 if (bpf_map_ptr_poisoned(insn_aux)) { 9652 verbose(env, "tail_call abusing map_ptr\n"); 9653 return -EINVAL; 9654 } 9655 9656 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 9657 if (!map->ops->map_set_for_each_callback_args || 9658 !map->ops->map_for_each_callback) { 9659 verbose(env, "callback function not allowed for map\n"); 9660 return -ENOTSUPP; 9661 } 9662 9663 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 9664 if (err) 9665 return err; 9666 9667 callee->in_callback_fn = true; 9668 callee->callback_ret_range = retval_range(0, 1); 9669 return 0; 9670 } 9671 9672 static int set_loop_callback_state(struct bpf_verifier_env *env, 9673 struct bpf_func_state *caller, 9674 struct bpf_func_state *callee, 9675 int insn_idx) 9676 { 9677 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 9678 * u64 flags); 9679 * callback_fn(u32 index, void *callback_ctx); 9680 */ 9681 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 9682 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9683 9684 /* unused */ 9685 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9686 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9687 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9688 9689 callee->in_callback_fn = true; 9690 callee->callback_ret_range = retval_range(0, 1); 9691 return 0; 9692 } 9693 9694 static int set_timer_callback_state(struct bpf_verifier_env *env, 9695 struct bpf_func_state *caller, 9696 struct bpf_func_state *callee, 9697 int insn_idx) 9698 { 9699 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 9700 9701 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 9702 * callback_fn(struct bpf_map *map, void *key, void *value); 9703 */ 9704 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 9705 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 9706 callee->regs[BPF_REG_1].map_ptr = map_ptr; 9707 9708 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 9709 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9710 callee->regs[BPF_REG_2].map_ptr = map_ptr; 9711 9712 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 9713 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 9714 callee->regs[BPF_REG_3].map_ptr = map_ptr; 9715 9716 /* unused */ 9717 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9718 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9719 callee->in_async_callback_fn = true; 9720 callee->callback_ret_range = retval_range(0, 1); 9721 return 0; 9722 } 9723 9724 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 9725 struct bpf_func_state *caller, 9726 struct bpf_func_state *callee, 9727 int insn_idx) 9728 { 9729 /* bpf_find_vma(struct task_struct *task, u64 addr, 9730 * void *callback_fn, void *callback_ctx, u64 flags) 9731 * (callback_fn)(struct task_struct *task, 9732 * struct vm_area_struct *vma, void *callback_ctx); 9733 */ 9734 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 9735 9736 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 9737 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 9738 callee->regs[BPF_REG_2].btf = btf_vmlinux; 9739 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA]; 9740 9741 /* pointer to stack or null */ 9742 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 9743 9744 /* unused */ 9745 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9746 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9747 callee->in_callback_fn = true; 9748 callee->callback_ret_range = retval_range(0, 1); 9749 return 0; 9750 } 9751 9752 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 9753 struct bpf_func_state *caller, 9754 struct bpf_func_state *callee, 9755 int insn_idx) 9756 { 9757 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 9758 * callback_ctx, u64 flags); 9759 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 9760 */ 9761 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 9762 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 9763 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 9764 9765 /* unused */ 9766 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9767 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9768 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9769 9770 callee->in_callback_fn = true; 9771 callee->callback_ret_range = retval_range(0, 1); 9772 return 0; 9773 } 9774 9775 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 9776 struct bpf_func_state *caller, 9777 struct bpf_func_state *callee, 9778 int insn_idx) 9779 { 9780 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 9781 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 9782 * 9783 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 9784 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 9785 * by this point, so look at 'root' 9786 */ 9787 struct btf_field *field; 9788 9789 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 9790 BPF_RB_ROOT); 9791 if (!field || !field->graph_root.value_btf_id) 9792 return -EFAULT; 9793 9794 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 9795 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 9796 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 9797 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 9798 9799 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 9800 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 9801 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 9802 callee->in_callback_fn = true; 9803 callee->callback_ret_range = retval_range(0, 1); 9804 return 0; 9805 } 9806 9807 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 9808 9809 /* Are we currently verifying the callback for a rbtree helper that must 9810 * be called with lock held? If so, no need to complain about unreleased 9811 * lock 9812 */ 9813 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 9814 { 9815 struct bpf_verifier_state *state = env->cur_state; 9816 struct bpf_insn *insn = env->prog->insnsi; 9817 struct bpf_func_state *callee; 9818 int kfunc_btf_id; 9819 9820 if (!state->curframe) 9821 return false; 9822 9823 callee = state->frame[state->curframe]; 9824 9825 if (!callee->in_callback_fn) 9826 return false; 9827 9828 kfunc_btf_id = insn[callee->callsite].imm; 9829 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 9830 } 9831 9832 static bool retval_range_within(struct bpf_retval_range range, const struct bpf_reg_state *reg) 9833 { 9834 return range.minval <= reg->smin_value && reg->smax_value <= range.maxval; 9835 } 9836 9837 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 9838 { 9839 struct bpf_verifier_state *state = env->cur_state, *prev_st; 9840 struct bpf_func_state *caller, *callee; 9841 struct bpf_reg_state *r0; 9842 bool in_callback_fn; 9843 int err; 9844 9845 callee = state->frame[state->curframe]; 9846 r0 = &callee->regs[BPF_REG_0]; 9847 if (r0->type == PTR_TO_STACK) { 9848 /* technically it's ok to return caller's stack pointer 9849 * (or caller's caller's pointer) back to the caller, 9850 * since these pointers are valid. Only current stack 9851 * pointer will be invalid as soon as function exits, 9852 * but let's be conservative 9853 */ 9854 verbose(env, "cannot return stack pointer to the caller\n"); 9855 return -EINVAL; 9856 } 9857 9858 caller = state->frame[state->curframe - 1]; 9859 if (callee->in_callback_fn) { 9860 if (r0->type != SCALAR_VALUE) { 9861 verbose(env, "R0 not a scalar value\n"); 9862 return -EACCES; 9863 } 9864 9865 /* we are going to rely on register's precise value */ 9866 err = mark_reg_read(env, r0, r0->parent, REG_LIVE_READ64); 9867 err = err ?: mark_chain_precision(env, BPF_REG_0); 9868 if (err) 9869 return err; 9870 9871 /* enforce R0 return value range */ 9872 if (!retval_range_within(callee->callback_ret_range, r0)) { 9873 verbose_invalid_scalar(env, r0, callee->callback_ret_range, 9874 "At callback return", "R0"); 9875 return -EINVAL; 9876 } 9877 if (!calls_callback(env, callee->callsite)) { 9878 verbose(env, "BUG: in callback at %d, callsite %d !calls_callback\n", 9879 *insn_idx, callee->callsite); 9880 return -EFAULT; 9881 } 9882 } else { 9883 /* return to the caller whatever r0 had in the callee */ 9884 caller->regs[BPF_REG_0] = *r0; 9885 } 9886 9887 /* callback_fn frame should have released its own additions to parent's 9888 * reference state at this point, or check_reference_leak would 9889 * complain, hence it must be the same as the caller. There is no need 9890 * to copy it back. 9891 */ 9892 if (!callee->in_callback_fn) { 9893 /* Transfer references to the caller */ 9894 err = copy_reference_state(caller, callee); 9895 if (err) 9896 return err; 9897 } 9898 9899 /* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite, 9900 * there function call logic would reschedule callback visit. If iteration 9901 * converges is_state_visited() would prune that visit eventually. 9902 */ 9903 in_callback_fn = callee->in_callback_fn; 9904 if (in_callback_fn) 9905 *insn_idx = callee->callsite; 9906 else 9907 *insn_idx = callee->callsite + 1; 9908 9909 if (env->log.level & BPF_LOG_LEVEL) { 9910 verbose(env, "returning from callee:\n"); 9911 print_verifier_state(env, callee, true); 9912 verbose(env, "to caller at %d:\n", *insn_idx); 9913 print_verifier_state(env, caller, true); 9914 } 9915 /* clear everything in the callee. In case of exceptional exits using 9916 * bpf_throw, this will be done by copy_verifier_state for extra frames. */ 9917 free_func_state(callee); 9918 state->frame[state->curframe--] = NULL; 9919 9920 /* for callbacks widen imprecise scalars to make programs like below verify: 9921 * 9922 * struct ctx { int i; } 9923 * void cb(int idx, struct ctx *ctx) { ctx->i++; ... } 9924 * ... 9925 * struct ctx = { .i = 0; } 9926 * bpf_loop(100, cb, &ctx, 0); 9927 * 9928 * This is similar to what is done in process_iter_next_call() for open 9929 * coded iterators. 9930 */ 9931 prev_st = in_callback_fn ? find_prev_entry(env, state, *insn_idx) : NULL; 9932 if (prev_st) { 9933 err = widen_imprecise_scalars(env, prev_st, state); 9934 if (err) 9935 return err; 9936 } 9937 return 0; 9938 } 9939 9940 static int do_refine_retval_range(struct bpf_verifier_env *env, 9941 struct bpf_reg_state *regs, int ret_type, 9942 int func_id, 9943 struct bpf_call_arg_meta *meta) 9944 { 9945 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 9946 9947 if (ret_type != RET_INTEGER) 9948 return 0; 9949 9950 switch (func_id) { 9951 case BPF_FUNC_get_stack: 9952 case BPF_FUNC_get_task_stack: 9953 case BPF_FUNC_probe_read_str: 9954 case BPF_FUNC_probe_read_kernel_str: 9955 case BPF_FUNC_probe_read_user_str: 9956 ret_reg->smax_value = meta->msize_max_value; 9957 ret_reg->s32_max_value = meta->msize_max_value; 9958 ret_reg->smin_value = -MAX_ERRNO; 9959 ret_reg->s32_min_value = -MAX_ERRNO; 9960 reg_bounds_sync(ret_reg); 9961 break; 9962 case BPF_FUNC_get_smp_processor_id: 9963 ret_reg->umax_value = nr_cpu_ids - 1; 9964 ret_reg->u32_max_value = nr_cpu_ids - 1; 9965 ret_reg->smax_value = nr_cpu_ids - 1; 9966 ret_reg->s32_max_value = nr_cpu_ids - 1; 9967 ret_reg->umin_value = 0; 9968 ret_reg->u32_min_value = 0; 9969 ret_reg->smin_value = 0; 9970 ret_reg->s32_min_value = 0; 9971 reg_bounds_sync(ret_reg); 9972 break; 9973 } 9974 9975 return reg_bounds_sanity_check(env, ret_reg, "retval"); 9976 } 9977 9978 static int 9979 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 9980 int func_id, int insn_idx) 9981 { 9982 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 9983 struct bpf_map *map = meta->map_ptr; 9984 9985 if (func_id != BPF_FUNC_tail_call && 9986 func_id != BPF_FUNC_map_lookup_elem && 9987 func_id != BPF_FUNC_map_update_elem && 9988 func_id != BPF_FUNC_map_delete_elem && 9989 func_id != BPF_FUNC_map_push_elem && 9990 func_id != BPF_FUNC_map_pop_elem && 9991 func_id != BPF_FUNC_map_peek_elem && 9992 func_id != BPF_FUNC_for_each_map_elem && 9993 func_id != BPF_FUNC_redirect_map && 9994 func_id != BPF_FUNC_map_lookup_percpu_elem) 9995 return 0; 9996 9997 if (map == NULL) { 9998 verbose(env, "kernel subsystem misconfigured verifier\n"); 9999 return -EINVAL; 10000 } 10001 10002 /* In case of read-only, some additional restrictions 10003 * need to be applied in order to prevent altering the 10004 * state of the map from program side. 10005 */ 10006 if ((map->map_flags & BPF_F_RDONLY_PROG) && 10007 (func_id == BPF_FUNC_map_delete_elem || 10008 func_id == BPF_FUNC_map_update_elem || 10009 func_id == BPF_FUNC_map_push_elem || 10010 func_id == BPF_FUNC_map_pop_elem)) { 10011 verbose(env, "write into map forbidden\n"); 10012 return -EACCES; 10013 } 10014 10015 if (!BPF_MAP_PTR(aux->map_ptr_state)) 10016 bpf_map_ptr_store(aux, meta->map_ptr, 10017 !meta->map_ptr->bypass_spec_v1); 10018 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 10019 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 10020 !meta->map_ptr->bypass_spec_v1); 10021 return 0; 10022 } 10023 10024 static int 10025 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 10026 int func_id, int insn_idx) 10027 { 10028 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 10029 struct bpf_reg_state *regs = cur_regs(env), *reg; 10030 struct bpf_map *map = meta->map_ptr; 10031 u64 val, max; 10032 int err; 10033 10034 if (func_id != BPF_FUNC_tail_call) 10035 return 0; 10036 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 10037 verbose(env, "kernel subsystem misconfigured verifier\n"); 10038 return -EINVAL; 10039 } 10040 10041 reg = ®s[BPF_REG_3]; 10042 val = reg->var_off.value; 10043 max = map->max_entries; 10044 10045 if (!(is_reg_const(reg, false) && val < max)) { 10046 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10047 return 0; 10048 } 10049 10050 err = mark_chain_precision(env, BPF_REG_3); 10051 if (err) 10052 return err; 10053 if (bpf_map_key_unseen(aux)) 10054 bpf_map_key_store(aux, val); 10055 else if (!bpf_map_key_poisoned(aux) && 10056 bpf_map_key_immediate(aux) != val) 10057 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 10058 return 0; 10059 } 10060 10061 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit) 10062 { 10063 struct bpf_func_state *state = cur_func(env); 10064 bool refs_lingering = false; 10065 int i; 10066 10067 if (!exception_exit && state->frameno && !state->in_callback_fn) 10068 return 0; 10069 10070 for (i = 0; i < state->acquired_refs; i++) { 10071 if (!exception_exit && state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 10072 continue; 10073 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 10074 state->refs[i].id, state->refs[i].insn_idx); 10075 refs_lingering = true; 10076 } 10077 return refs_lingering ? -EINVAL : 0; 10078 } 10079 10080 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 10081 struct bpf_reg_state *regs) 10082 { 10083 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 10084 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 10085 struct bpf_map *fmt_map = fmt_reg->map_ptr; 10086 struct bpf_bprintf_data data = {}; 10087 int err, fmt_map_off, num_args; 10088 u64 fmt_addr; 10089 char *fmt; 10090 10091 /* data must be an array of u64 */ 10092 if (data_len_reg->var_off.value % 8) 10093 return -EINVAL; 10094 num_args = data_len_reg->var_off.value / 8; 10095 10096 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 10097 * and map_direct_value_addr is set. 10098 */ 10099 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 10100 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 10101 fmt_map_off); 10102 if (err) { 10103 verbose(env, "verifier bug\n"); 10104 return -EFAULT; 10105 } 10106 fmt = (char *)(long)fmt_addr + fmt_map_off; 10107 10108 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 10109 * can focus on validating the format specifiers. 10110 */ 10111 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 10112 if (err < 0) 10113 verbose(env, "Invalid format string\n"); 10114 10115 return err; 10116 } 10117 10118 static int check_get_func_ip(struct bpf_verifier_env *env) 10119 { 10120 enum bpf_prog_type type = resolve_prog_type(env->prog); 10121 int func_id = BPF_FUNC_get_func_ip; 10122 10123 if (type == BPF_PROG_TYPE_TRACING) { 10124 if (!bpf_prog_has_trampoline(env->prog)) { 10125 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 10126 func_id_name(func_id), func_id); 10127 return -ENOTSUPP; 10128 } 10129 return 0; 10130 } else if (type == BPF_PROG_TYPE_KPROBE) { 10131 return 0; 10132 } 10133 10134 verbose(env, "func %s#%d not supported for program type %d\n", 10135 func_id_name(func_id), func_id, type); 10136 return -ENOTSUPP; 10137 } 10138 10139 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 10140 { 10141 return &env->insn_aux_data[env->insn_idx]; 10142 } 10143 10144 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 10145 { 10146 struct bpf_reg_state *regs = cur_regs(env); 10147 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 10148 bool reg_is_null = register_is_null(reg); 10149 10150 if (reg_is_null) 10151 mark_chain_precision(env, BPF_REG_4); 10152 10153 return reg_is_null; 10154 } 10155 10156 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 10157 { 10158 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 10159 10160 if (!state->initialized) { 10161 state->initialized = 1; 10162 state->fit_for_inline = loop_flag_is_zero(env); 10163 state->callback_subprogno = subprogno; 10164 return; 10165 } 10166 10167 if (!state->fit_for_inline) 10168 return; 10169 10170 state->fit_for_inline = (loop_flag_is_zero(env) && 10171 state->callback_subprogno == subprogno); 10172 } 10173 10174 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10175 int *insn_idx_p) 10176 { 10177 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 10178 bool returns_cpu_specific_alloc_ptr = false; 10179 const struct bpf_func_proto *fn = NULL; 10180 enum bpf_return_type ret_type; 10181 enum bpf_type_flag ret_flag; 10182 struct bpf_reg_state *regs; 10183 struct bpf_call_arg_meta meta; 10184 int insn_idx = *insn_idx_p; 10185 bool changes_data; 10186 int i, err, func_id; 10187 10188 /* find function prototype */ 10189 func_id = insn->imm; 10190 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 10191 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 10192 func_id); 10193 return -EINVAL; 10194 } 10195 10196 if (env->ops->get_func_proto) 10197 fn = env->ops->get_func_proto(func_id, env->prog); 10198 if (!fn) { 10199 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 10200 func_id); 10201 return -EINVAL; 10202 } 10203 10204 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 10205 if (!env->prog->gpl_compatible && fn->gpl_only) { 10206 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 10207 return -EINVAL; 10208 } 10209 10210 if (fn->allowed && !fn->allowed(env->prog)) { 10211 verbose(env, "helper call is not allowed in probe\n"); 10212 return -EINVAL; 10213 } 10214 10215 if (!in_sleepable(env) && fn->might_sleep) { 10216 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 10217 return -EINVAL; 10218 } 10219 10220 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 10221 changes_data = bpf_helper_changes_pkt_data(fn->func); 10222 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 10223 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 10224 func_id_name(func_id), func_id); 10225 return -EINVAL; 10226 } 10227 10228 memset(&meta, 0, sizeof(meta)); 10229 meta.pkt_access = fn->pkt_access; 10230 10231 err = check_func_proto(fn, func_id); 10232 if (err) { 10233 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 10234 func_id_name(func_id), func_id); 10235 return err; 10236 } 10237 10238 if (env->cur_state->active_rcu_lock) { 10239 if (fn->might_sleep) { 10240 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 10241 func_id_name(func_id), func_id); 10242 return -EINVAL; 10243 } 10244 10245 if (in_sleepable(env) && is_storage_get_function(func_id)) 10246 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 10247 } 10248 10249 meta.func_id = func_id; 10250 /* check args */ 10251 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 10252 err = check_func_arg(env, i, &meta, fn, insn_idx); 10253 if (err) 10254 return err; 10255 } 10256 10257 err = record_func_map(env, &meta, func_id, insn_idx); 10258 if (err) 10259 return err; 10260 10261 err = record_func_key(env, &meta, func_id, insn_idx); 10262 if (err) 10263 return err; 10264 10265 /* Mark slots with STACK_MISC in case of raw mode, stack offset 10266 * is inferred from register state. 10267 */ 10268 for (i = 0; i < meta.access_size; i++) { 10269 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 10270 BPF_WRITE, -1, false, false); 10271 if (err) 10272 return err; 10273 } 10274 10275 regs = cur_regs(env); 10276 10277 if (meta.release_regno) { 10278 err = -EINVAL; 10279 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 10280 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 10281 * is safe to do directly. 10282 */ 10283 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 10284 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 10285 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 10286 return -EFAULT; 10287 } 10288 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 10289 } else if (func_id == BPF_FUNC_kptr_xchg && meta.ref_obj_id) { 10290 u32 ref_obj_id = meta.ref_obj_id; 10291 bool in_rcu = in_rcu_cs(env); 10292 struct bpf_func_state *state; 10293 struct bpf_reg_state *reg; 10294 10295 err = release_reference_state(cur_func(env), ref_obj_id); 10296 if (!err) { 10297 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10298 if (reg->ref_obj_id == ref_obj_id) { 10299 if (in_rcu && (reg->type & MEM_ALLOC) && (reg->type & MEM_PERCPU)) { 10300 reg->ref_obj_id = 0; 10301 reg->type &= ~MEM_ALLOC; 10302 reg->type |= MEM_RCU; 10303 } else { 10304 mark_reg_invalid(env, reg); 10305 } 10306 } 10307 })); 10308 } 10309 } else if (meta.ref_obj_id) { 10310 err = release_reference(env, meta.ref_obj_id); 10311 } else if (register_is_null(®s[meta.release_regno])) { 10312 /* meta.ref_obj_id can only be 0 if register that is meant to be 10313 * released is NULL, which must be > R0. 10314 */ 10315 err = 0; 10316 } 10317 if (err) { 10318 verbose(env, "func %s#%d reference has not been acquired before\n", 10319 func_id_name(func_id), func_id); 10320 return err; 10321 } 10322 } 10323 10324 switch (func_id) { 10325 case BPF_FUNC_tail_call: 10326 err = check_reference_leak(env, false); 10327 if (err) { 10328 verbose(env, "tail_call would lead to reference leak\n"); 10329 return err; 10330 } 10331 break; 10332 case BPF_FUNC_get_local_storage: 10333 /* check that flags argument in get_local_storage(map, flags) is 0, 10334 * this is required because get_local_storage() can't return an error. 10335 */ 10336 if (!register_is_null(®s[BPF_REG_2])) { 10337 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 10338 return -EINVAL; 10339 } 10340 break; 10341 case BPF_FUNC_for_each_map_elem: 10342 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10343 set_map_elem_callback_state); 10344 break; 10345 case BPF_FUNC_timer_set_callback: 10346 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10347 set_timer_callback_state); 10348 break; 10349 case BPF_FUNC_find_vma: 10350 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10351 set_find_vma_callback_state); 10352 break; 10353 case BPF_FUNC_snprintf: 10354 err = check_bpf_snprintf_call(env, regs); 10355 break; 10356 case BPF_FUNC_loop: 10357 update_loop_inline_state(env, meta.subprogno); 10358 /* Verifier relies on R1 value to determine if bpf_loop() iteration 10359 * is finished, thus mark it precise. 10360 */ 10361 err = mark_chain_precision(env, BPF_REG_1); 10362 if (err) 10363 return err; 10364 if (cur_func(env)->callback_depth < regs[BPF_REG_1].umax_value) { 10365 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10366 set_loop_callback_state); 10367 } else { 10368 cur_func(env)->callback_depth = 0; 10369 if (env->log.level & BPF_LOG_LEVEL2) 10370 verbose(env, "frame%d bpf_loop iteration limit reached\n", 10371 env->cur_state->curframe); 10372 } 10373 break; 10374 case BPF_FUNC_dynptr_from_mem: 10375 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 10376 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 10377 reg_type_str(env, regs[BPF_REG_1].type)); 10378 return -EACCES; 10379 } 10380 break; 10381 case BPF_FUNC_set_retval: 10382 if (prog_type == BPF_PROG_TYPE_LSM && 10383 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 10384 if (!env->prog->aux->attach_func_proto->type) { 10385 /* Make sure programs that attach to void 10386 * hooks don't try to modify return value. 10387 */ 10388 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 10389 return -EINVAL; 10390 } 10391 } 10392 break; 10393 case BPF_FUNC_dynptr_data: 10394 { 10395 struct bpf_reg_state *reg; 10396 int id, ref_obj_id; 10397 10398 reg = get_dynptr_arg_reg(env, fn, regs); 10399 if (!reg) 10400 return -EFAULT; 10401 10402 10403 if (meta.dynptr_id) { 10404 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 10405 return -EFAULT; 10406 } 10407 if (meta.ref_obj_id) { 10408 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 10409 return -EFAULT; 10410 } 10411 10412 id = dynptr_id(env, reg); 10413 if (id < 0) { 10414 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10415 return id; 10416 } 10417 10418 ref_obj_id = dynptr_ref_obj_id(env, reg); 10419 if (ref_obj_id < 0) { 10420 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 10421 return ref_obj_id; 10422 } 10423 10424 meta.dynptr_id = id; 10425 meta.ref_obj_id = ref_obj_id; 10426 10427 break; 10428 } 10429 case BPF_FUNC_dynptr_write: 10430 { 10431 enum bpf_dynptr_type dynptr_type; 10432 struct bpf_reg_state *reg; 10433 10434 reg = get_dynptr_arg_reg(env, fn, regs); 10435 if (!reg) 10436 return -EFAULT; 10437 10438 dynptr_type = dynptr_get_type(env, reg); 10439 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 10440 return -EFAULT; 10441 10442 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 10443 /* this will trigger clear_all_pkt_pointers(), which will 10444 * invalidate all dynptr slices associated with the skb 10445 */ 10446 changes_data = true; 10447 10448 break; 10449 } 10450 case BPF_FUNC_per_cpu_ptr: 10451 case BPF_FUNC_this_cpu_ptr: 10452 { 10453 struct bpf_reg_state *reg = ®s[BPF_REG_1]; 10454 const struct btf_type *type; 10455 10456 if (reg->type & MEM_RCU) { 10457 type = btf_type_by_id(reg->btf, reg->btf_id); 10458 if (!type || !btf_type_is_struct(type)) { 10459 verbose(env, "Helper has invalid btf/btf_id in R1\n"); 10460 return -EFAULT; 10461 } 10462 returns_cpu_specific_alloc_ptr = true; 10463 env->insn_aux_data[insn_idx].call_with_percpu_alloc_ptr = true; 10464 } 10465 break; 10466 } 10467 case BPF_FUNC_user_ringbuf_drain: 10468 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 10469 set_user_ringbuf_callback_state); 10470 break; 10471 } 10472 10473 if (err) 10474 return err; 10475 10476 /* reset caller saved regs */ 10477 for (i = 0; i < CALLER_SAVED_REGS; i++) { 10478 mark_reg_not_init(env, regs, caller_saved[i]); 10479 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 10480 } 10481 10482 /* helper call returns 64-bit value. */ 10483 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 10484 10485 /* update return register (already marked as written above) */ 10486 ret_type = fn->ret_type; 10487 ret_flag = type_flag(ret_type); 10488 10489 switch (base_type(ret_type)) { 10490 case RET_INTEGER: 10491 /* sets type to SCALAR_VALUE */ 10492 mark_reg_unknown(env, regs, BPF_REG_0); 10493 break; 10494 case RET_VOID: 10495 regs[BPF_REG_0].type = NOT_INIT; 10496 break; 10497 case RET_PTR_TO_MAP_VALUE: 10498 /* There is no offset yet applied, variable or fixed */ 10499 mark_reg_known_zero(env, regs, BPF_REG_0); 10500 /* remember map_ptr, so that check_map_access() 10501 * can check 'value_size' boundary of memory access 10502 * to map element returned from bpf_map_lookup_elem() 10503 */ 10504 if (meta.map_ptr == NULL) { 10505 verbose(env, 10506 "kernel subsystem misconfigured verifier\n"); 10507 return -EINVAL; 10508 } 10509 regs[BPF_REG_0].map_ptr = meta.map_ptr; 10510 regs[BPF_REG_0].map_uid = meta.map_uid; 10511 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 10512 if (!type_may_be_null(ret_type) && 10513 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 10514 regs[BPF_REG_0].id = ++env->id_gen; 10515 } 10516 break; 10517 case RET_PTR_TO_SOCKET: 10518 mark_reg_known_zero(env, regs, BPF_REG_0); 10519 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 10520 break; 10521 case RET_PTR_TO_SOCK_COMMON: 10522 mark_reg_known_zero(env, regs, BPF_REG_0); 10523 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 10524 break; 10525 case RET_PTR_TO_TCP_SOCK: 10526 mark_reg_known_zero(env, regs, BPF_REG_0); 10527 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 10528 break; 10529 case RET_PTR_TO_MEM: 10530 mark_reg_known_zero(env, regs, BPF_REG_0); 10531 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10532 regs[BPF_REG_0].mem_size = meta.mem_size; 10533 break; 10534 case RET_PTR_TO_MEM_OR_BTF_ID: 10535 { 10536 const struct btf_type *t; 10537 10538 mark_reg_known_zero(env, regs, BPF_REG_0); 10539 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 10540 if (!btf_type_is_struct(t)) { 10541 u32 tsize; 10542 const struct btf_type *ret; 10543 const char *tname; 10544 10545 /* resolve the type size of ksym. */ 10546 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 10547 if (IS_ERR(ret)) { 10548 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 10549 verbose(env, "unable to resolve the size of type '%s': %ld\n", 10550 tname, PTR_ERR(ret)); 10551 return -EINVAL; 10552 } 10553 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 10554 regs[BPF_REG_0].mem_size = tsize; 10555 } else { 10556 if (returns_cpu_specific_alloc_ptr) { 10557 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC | MEM_RCU; 10558 } else { 10559 /* MEM_RDONLY may be carried from ret_flag, but it 10560 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 10561 * it will confuse the check of PTR_TO_BTF_ID in 10562 * check_mem_access(). 10563 */ 10564 ret_flag &= ~MEM_RDONLY; 10565 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10566 } 10567 10568 regs[BPF_REG_0].btf = meta.ret_btf; 10569 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10570 } 10571 break; 10572 } 10573 case RET_PTR_TO_BTF_ID: 10574 { 10575 struct btf *ret_btf; 10576 int ret_btf_id; 10577 10578 mark_reg_known_zero(env, regs, BPF_REG_0); 10579 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 10580 if (func_id == BPF_FUNC_kptr_xchg) { 10581 ret_btf = meta.kptr_field->kptr.btf; 10582 ret_btf_id = meta.kptr_field->kptr.btf_id; 10583 if (!btf_is_kernel(ret_btf)) { 10584 regs[BPF_REG_0].type |= MEM_ALLOC; 10585 if (meta.kptr_field->type == BPF_KPTR_PERCPU) 10586 regs[BPF_REG_0].type |= MEM_PERCPU; 10587 } 10588 } else { 10589 if (fn->ret_btf_id == BPF_PTR_POISON) { 10590 verbose(env, "verifier internal error:"); 10591 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 10592 func_id_name(func_id)); 10593 return -EINVAL; 10594 } 10595 ret_btf = btf_vmlinux; 10596 ret_btf_id = *fn->ret_btf_id; 10597 } 10598 if (ret_btf_id == 0) { 10599 verbose(env, "invalid return type %u of func %s#%d\n", 10600 base_type(ret_type), func_id_name(func_id), 10601 func_id); 10602 return -EINVAL; 10603 } 10604 regs[BPF_REG_0].btf = ret_btf; 10605 regs[BPF_REG_0].btf_id = ret_btf_id; 10606 break; 10607 } 10608 default: 10609 verbose(env, "unknown return type %u of func %s#%d\n", 10610 base_type(ret_type), func_id_name(func_id), func_id); 10611 return -EINVAL; 10612 } 10613 10614 if (type_may_be_null(regs[BPF_REG_0].type)) 10615 regs[BPF_REG_0].id = ++env->id_gen; 10616 10617 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 10618 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 10619 func_id_name(func_id), func_id); 10620 return -EFAULT; 10621 } 10622 10623 if (is_dynptr_ref_function(func_id)) 10624 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 10625 10626 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 10627 /* For release_reference() */ 10628 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10629 } else if (is_acquire_function(func_id, meta.map_ptr)) { 10630 int id = acquire_reference_state(env, insn_idx); 10631 10632 if (id < 0) 10633 return id; 10634 /* For mark_ptr_or_null_reg() */ 10635 regs[BPF_REG_0].id = id; 10636 /* For release_reference() */ 10637 regs[BPF_REG_0].ref_obj_id = id; 10638 } 10639 10640 err = do_refine_retval_range(env, regs, fn->ret_type, func_id, &meta); 10641 if (err) 10642 return err; 10643 10644 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 10645 if (err) 10646 return err; 10647 10648 if ((func_id == BPF_FUNC_get_stack || 10649 func_id == BPF_FUNC_get_task_stack) && 10650 !env->prog->has_callchain_buf) { 10651 const char *err_str; 10652 10653 #ifdef CONFIG_PERF_EVENTS 10654 err = get_callchain_buffers(sysctl_perf_event_max_stack); 10655 err_str = "cannot get callchain buffer for func %s#%d\n"; 10656 #else 10657 err = -ENOTSUPP; 10658 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 10659 #endif 10660 if (err) { 10661 verbose(env, err_str, func_id_name(func_id), func_id); 10662 return err; 10663 } 10664 10665 env->prog->has_callchain_buf = true; 10666 } 10667 10668 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 10669 env->prog->call_get_stack = true; 10670 10671 if (func_id == BPF_FUNC_get_func_ip) { 10672 if (check_get_func_ip(env)) 10673 return -ENOTSUPP; 10674 env->prog->call_get_func_ip = true; 10675 } 10676 10677 if (changes_data) 10678 clear_all_pkt_pointers(env); 10679 return 0; 10680 } 10681 10682 /* mark_btf_func_reg_size() is used when the reg size is determined by 10683 * the BTF func_proto's return value size and argument. 10684 */ 10685 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 10686 size_t reg_size) 10687 { 10688 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 10689 10690 if (regno == BPF_REG_0) { 10691 /* Function return value */ 10692 reg->live |= REG_LIVE_WRITTEN; 10693 reg->subreg_def = reg_size == sizeof(u64) ? 10694 DEF_NOT_SUBREG : env->insn_idx + 1; 10695 } else { 10696 /* Function argument */ 10697 if (reg_size == sizeof(u64)) { 10698 mark_insn_zext(env, reg); 10699 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 10700 } else { 10701 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 10702 } 10703 } 10704 } 10705 10706 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 10707 { 10708 return meta->kfunc_flags & KF_ACQUIRE; 10709 } 10710 10711 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 10712 { 10713 return meta->kfunc_flags & KF_RELEASE; 10714 } 10715 10716 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 10717 { 10718 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 10719 } 10720 10721 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 10722 { 10723 return meta->kfunc_flags & KF_SLEEPABLE; 10724 } 10725 10726 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 10727 { 10728 return meta->kfunc_flags & KF_DESTRUCTIVE; 10729 } 10730 10731 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 10732 { 10733 return meta->kfunc_flags & KF_RCU; 10734 } 10735 10736 static bool is_kfunc_rcu_protected(struct bpf_kfunc_call_arg_meta *meta) 10737 { 10738 return meta->kfunc_flags & KF_RCU_PROTECTED; 10739 } 10740 10741 static bool is_kfunc_arg_mem_size(const struct btf *btf, 10742 const struct btf_param *arg, 10743 const struct bpf_reg_state *reg) 10744 { 10745 const struct btf_type *t; 10746 10747 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10748 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10749 return false; 10750 10751 return btf_param_match_suffix(btf, arg, "__sz"); 10752 } 10753 10754 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 10755 const struct btf_param *arg, 10756 const struct bpf_reg_state *reg) 10757 { 10758 const struct btf_type *t; 10759 10760 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10761 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 10762 return false; 10763 10764 return btf_param_match_suffix(btf, arg, "__szk"); 10765 } 10766 10767 static bool is_kfunc_arg_optional(const struct btf *btf, const struct btf_param *arg) 10768 { 10769 return btf_param_match_suffix(btf, arg, "__opt"); 10770 } 10771 10772 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 10773 { 10774 return btf_param_match_suffix(btf, arg, "__k"); 10775 } 10776 10777 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 10778 { 10779 return btf_param_match_suffix(btf, arg, "__ign"); 10780 } 10781 10782 static bool is_kfunc_arg_map(const struct btf *btf, const struct btf_param *arg) 10783 { 10784 return btf_param_match_suffix(btf, arg, "__map"); 10785 } 10786 10787 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 10788 { 10789 return btf_param_match_suffix(btf, arg, "__alloc"); 10790 } 10791 10792 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 10793 { 10794 return btf_param_match_suffix(btf, arg, "__uninit"); 10795 } 10796 10797 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 10798 { 10799 return btf_param_match_suffix(btf, arg, "__refcounted_kptr"); 10800 } 10801 10802 static bool is_kfunc_arg_nullable(const struct btf *btf, const struct btf_param *arg) 10803 { 10804 return btf_param_match_suffix(btf, arg, "__nullable"); 10805 } 10806 10807 static bool is_kfunc_arg_const_str(const struct btf *btf, const struct btf_param *arg) 10808 { 10809 return btf_param_match_suffix(btf, arg, "__str"); 10810 } 10811 10812 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 10813 const struct btf_param *arg, 10814 const char *name) 10815 { 10816 int len, target_len = strlen(name); 10817 const char *param_name; 10818 10819 param_name = btf_name_by_offset(btf, arg->name_off); 10820 if (str_is_empty(param_name)) 10821 return false; 10822 len = strlen(param_name); 10823 if (len != target_len) 10824 return false; 10825 if (strcmp(param_name, name)) 10826 return false; 10827 10828 return true; 10829 } 10830 10831 enum { 10832 KF_ARG_DYNPTR_ID, 10833 KF_ARG_LIST_HEAD_ID, 10834 KF_ARG_LIST_NODE_ID, 10835 KF_ARG_RB_ROOT_ID, 10836 KF_ARG_RB_NODE_ID, 10837 }; 10838 10839 BTF_ID_LIST(kf_arg_btf_ids) 10840 BTF_ID(struct, bpf_dynptr_kern) 10841 BTF_ID(struct, bpf_list_head) 10842 BTF_ID(struct, bpf_list_node) 10843 BTF_ID(struct, bpf_rb_root) 10844 BTF_ID(struct, bpf_rb_node) 10845 10846 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 10847 const struct btf_param *arg, int type) 10848 { 10849 const struct btf_type *t; 10850 u32 res_id; 10851 10852 t = btf_type_skip_modifiers(btf, arg->type, NULL); 10853 if (!t) 10854 return false; 10855 if (!btf_type_is_ptr(t)) 10856 return false; 10857 t = btf_type_skip_modifiers(btf, t->type, &res_id); 10858 if (!t) 10859 return false; 10860 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 10861 } 10862 10863 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 10864 { 10865 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 10866 } 10867 10868 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 10869 { 10870 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 10871 } 10872 10873 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 10874 { 10875 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 10876 } 10877 10878 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 10879 { 10880 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 10881 } 10882 10883 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 10884 { 10885 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 10886 } 10887 10888 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 10889 const struct btf_param *arg) 10890 { 10891 const struct btf_type *t; 10892 10893 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 10894 if (!t) 10895 return false; 10896 10897 return true; 10898 } 10899 10900 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 10901 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 10902 const struct btf *btf, 10903 const struct btf_type *t, int rec) 10904 { 10905 const struct btf_type *member_type; 10906 const struct btf_member *member; 10907 u32 i; 10908 10909 if (!btf_type_is_struct(t)) 10910 return false; 10911 10912 for_each_member(i, t, member) { 10913 const struct btf_array *array; 10914 10915 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 10916 if (btf_type_is_struct(member_type)) { 10917 if (rec >= 3) { 10918 verbose(env, "max struct nesting depth exceeded\n"); 10919 return false; 10920 } 10921 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 10922 return false; 10923 continue; 10924 } 10925 if (btf_type_is_array(member_type)) { 10926 array = btf_array(member_type); 10927 if (!array->nelems) 10928 return false; 10929 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 10930 if (!btf_type_is_scalar(member_type)) 10931 return false; 10932 continue; 10933 } 10934 if (!btf_type_is_scalar(member_type)) 10935 return false; 10936 } 10937 return true; 10938 } 10939 10940 enum kfunc_ptr_arg_type { 10941 KF_ARG_PTR_TO_CTX, 10942 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 10943 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 10944 KF_ARG_PTR_TO_DYNPTR, 10945 KF_ARG_PTR_TO_ITER, 10946 KF_ARG_PTR_TO_LIST_HEAD, 10947 KF_ARG_PTR_TO_LIST_NODE, 10948 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 10949 KF_ARG_PTR_TO_MEM, 10950 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 10951 KF_ARG_PTR_TO_CALLBACK, 10952 KF_ARG_PTR_TO_RB_ROOT, 10953 KF_ARG_PTR_TO_RB_NODE, 10954 KF_ARG_PTR_TO_NULL, 10955 KF_ARG_PTR_TO_CONST_STR, 10956 KF_ARG_PTR_TO_MAP, 10957 }; 10958 10959 enum special_kfunc_type { 10960 KF_bpf_obj_new_impl, 10961 KF_bpf_obj_drop_impl, 10962 KF_bpf_refcount_acquire_impl, 10963 KF_bpf_list_push_front_impl, 10964 KF_bpf_list_push_back_impl, 10965 KF_bpf_list_pop_front, 10966 KF_bpf_list_pop_back, 10967 KF_bpf_cast_to_kern_ctx, 10968 KF_bpf_rdonly_cast, 10969 KF_bpf_rcu_read_lock, 10970 KF_bpf_rcu_read_unlock, 10971 KF_bpf_rbtree_remove, 10972 KF_bpf_rbtree_add_impl, 10973 KF_bpf_rbtree_first, 10974 KF_bpf_dynptr_from_skb, 10975 KF_bpf_dynptr_from_xdp, 10976 KF_bpf_dynptr_slice, 10977 KF_bpf_dynptr_slice_rdwr, 10978 KF_bpf_dynptr_clone, 10979 KF_bpf_percpu_obj_new_impl, 10980 KF_bpf_percpu_obj_drop_impl, 10981 KF_bpf_throw, 10982 KF_bpf_iter_css_task_new, 10983 }; 10984 10985 BTF_SET_START(special_kfunc_set) 10986 BTF_ID(func, bpf_obj_new_impl) 10987 BTF_ID(func, bpf_obj_drop_impl) 10988 BTF_ID(func, bpf_refcount_acquire_impl) 10989 BTF_ID(func, bpf_list_push_front_impl) 10990 BTF_ID(func, bpf_list_push_back_impl) 10991 BTF_ID(func, bpf_list_pop_front) 10992 BTF_ID(func, bpf_list_pop_back) 10993 BTF_ID(func, bpf_cast_to_kern_ctx) 10994 BTF_ID(func, bpf_rdonly_cast) 10995 BTF_ID(func, bpf_rbtree_remove) 10996 BTF_ID(func, bpf_rbtree_add_impl) 10997 BTF_ID(func, bpf_rbtree_first) 10998 BTF_ID(func, bpf_dynptr_from_skb) 10999 BTF_ID(func, bpf_dynptr_from_xdp) 11000 BTF_ID(func, bpf_dynptr_slice) 11001 BTF_ID(func, bpf_dynptr_slice_rdwr) 11002 BTF_ID(func, bpf_dynptr_clone) 11003 BTF_ID(func, bpf_percpu_obj_new_impl) 11004 BTF_ID(func, bpf_percpu_obj_drop_impl) 11005 BTF_ID(func, bpf_throw) 11006 #ifdef CONFIG_CGROUPS 11007 BTF_ID(func, bpf_iter_css_task_new) 11008 #endif 11009 BTF_SET_END(special_kfunc_set) 11010 11011 BTF_ID_LIST(special_kfunc_list) 11012 BTF_ID(func, bpf_obj_new_impl) 11013 BTF_ID(func, bpf_obj_drop_impl) 11014 BTF_ID(func, bpf_refcount_acquire_impl) 11015 BTF_ID(func, bpf_list_push_front_impl) 11016 BTF_ID(func, bpf_list_push_back_impl) 11017 BTF_ID(func, bpf_list_pop_front) 11018 BTF_ID(func, bpf_list_pop_back) 11019 BTF_ID(func, bpf_cast_to_kern_ctx) 11020 BTF_ID(func, bpf_rdonly_cast) 11021 BTF_ID(func, bpf_rcu_read_lock) 11022 BTF_ID(func, bpf_rcu_read_unlock) 11023 BTF_ID(func, bpf_rbtree_remove) 11024 BTF_ID(func, bpf_rbtree_add_impl) 11025 BTF_ID(func, bpf_rbtree_first) 11026 BTF_ID(func, bpf_dynptr_from_skb) 11027 BTF_ID(func, bpf_dynptr_from_xdp) 11028 BTF_ID(func, bpf_dynptr_slice) 11029 BTF_ID(func, bpf_dynptr_slice_rdwr) 11030 BTF_ID(func, bpf_dynptr_clone) 11031 BTF_ID(func, bpf_percpu_obj_new_impl) 11032 BTF_ID(func, bpf_percpu_obj_drop_impl) 11033 BTF_ID(func, bpf_throw) 11034 #ifdef CONFIG_CGROUPS 11035 BTF_ID(func, bpf_iter_css_task_new) 11036 #else 11037 BTF_ID_UNUSED 11038 #endif 11039 11040 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 11041 { 11042 if (meta->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 11043 meta->arg_owning_ref) { 11044 return false; 11045 } 11046 11047 return meta->kfunc_flags & KF_RET_NULL; 11048 } 11049 11050 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 11051 { 11052 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 11053 } 11054 11055 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 11056 { 11057 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 11058 } 11059 11060 static enum kfunc_ptr_arg_type 11061 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 11062 struct bpf_kfunc_call_arg_meta *meta, 11063 const struct btf_type *t, const struct btf_type *ref_t, 11064 const char *ref_tname, const struct btf_param *args, 11065 int argno, int nargs) 11066 { 11067 u32 regno = argno + 1; 11068 struct bpf_reg_state *regs = cur_regs(env); 11069 struct bpf_reg_state *reg = ®s[regno]; 11070 bool arg_mem_size = false; 11071 11072 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 11073 return KF_ARG_PTR_TO_CTX; 11074 11075 /* In this function, we verify the kfunc's BTF as per the argument type, 11076 * leaving the rest of the verification with respect to the register 11077 * type to our caller. When a set of conditions hold in the BTF type of 11078 * arguments, we resolve it to a known kfunc_ptr_arg_type. 11079 */ 11080 if (btf_is_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 11081 return KF_ARG_PTR_TO_CTX; 11082 11083 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 11084 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 11085 11086 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 11087 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 11088 11089 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 11090 return KF_ARG_PTR_TO_DYNPTR; 11091 11092 if (is_kfunc_arg_iter(meta, argno)) 11093 return KF_ARG_PTR_TO_ITER; 11094 11095 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 11096 return KF_ARG_PTR_TO_LIST_HEAD; 11097 11098 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 11099 return KF_ARG_PTR_TO_LIST_NODE; 11100 11101 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 11102 return KF_ARG_PTR_TO_RB_ROOT; 11103 11104 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 11105 return KF_ARG_PTR_TO_RB_NODE; 11106 11107 if (is_kfunc_arg_const_str(meta->btf, &args[argno])) 11108 return KF_ARG_PTR_TO_CONST_STR; 11109 11110 if (is_kfunc_arg_map(meta->btf, &args[argno])) 11111 return KF_ARG_PTR_TO_MAP; 11112 11113 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 11114 if (!btf_type_is_struct(ref_t)) { 11115 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 11116 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 11117 return -EINVAL; 11118 } 11119 return KF_ARG_PTR_TO_BTF_ID; 11120 } 11121 11122 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 11123 return KF_ARG_PTR_TO_CALLBACK; 11124 11125 if (is_kfunc_arg_nullable(meta->btf, &args[argno]) && register_is_null(reg)) 11126 return KF_ARG_PTR_TO_NULL; 11127 11128 if (argno + 1 < nargs && 11129 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 11130 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 11131 arg_mem_size = true; 11132 11133 /* This is the catch all argument type of register types supported by 11134 * check_helper_mem_access. However, we only allow when argument type is 11135 * pointer to scalar, or struct composed (recursively) of scalars. When 11136 * arg_mem_size is true, the pointer can be void *. 11137 */ 11138 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 11139 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 11140 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 11141 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 11142 return -EINVAL; 11143 } 11144 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 11145 } 11146 11147 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 11148 struct bpf_reg_state *reg, 11149 const struct btf_type *ref_t, 11150 const char *ref_tname, u32 ref_id, 11151 struct bpf_kfunc_call_arg_meta *meta, 11152 int argno) 11153 { 11154 const struct btf_type *reg_ref_t; 11155 bool strict_type_match = false; 11156 const struct btf *reg_btf; 11157 const char *reg_ref_tname; 11158 u32 reg_ref_id; 11159 11160 if (base_type(reg->type) == PTR_TO_BTF_ID) { 11161 reg_btf = reg->btf; 11162 reg_ref_id = reg->btf_id; 11163 } else { 11164 reg_btf = btf_vmlinux; 11165 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 11166 } 11167 11168 /* Enforce strict type matching for calls to kfuncs that are acquiring 11169 * or releasing a reference, or are no-cast aliases. We do _not_ 11170 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 11171 * as we want to enable BPF programs to pass types that are bitwise 11172 * equivalent without forcing them to explicitly cast with something 11173 * like bpf_cast_to_kern_ctx(). 11174 * 11175 * For example, say we had a type like the following: 11176 * 11177 * struct bpf_cpumask { 11178 * cpumask_t cpumask; 11179 * refcount_t usage; 11180 * }; 11181 * 11182 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 11183 * to a struct cpumask, so it would be safe to pass a struct 11184 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 11185 * 11186 * The philosophy here is similar to how we allow scalars of different 11187 * types to be passed to kfuncs as long as the size is the same. The 11188 * only difference here is that we're simply allowing 11189 * btf_struct_ids_match() to walk the struct at the 0th offset, and 11190 * resolve types. 11191 */ 11192 if (is_kfunc_acquire(meta) || 11193 (is_kfunc_release(meta) && reg->ref_obj_id) || 11194 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 11195 strict_type_match = true; 11196 11197 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 11198 11199 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 11200 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 11201 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 11202 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 11203 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 11204 btf_type_str(reg_ref_t), reg_ref_tname); 11205 return -EINVAL; 11206 } 11207 return 0; 11208 } 11209 11210 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11211 { 11212 struct bpf_verifier_state *state = env->cur_state; 11213 struct btf_record *rec = reg_btf_record(reg); 11214 11215 if (!state->active_lock.ptr) { 11216 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 11217 return -EFAULT; 11218 } 11219 11220 if (type_flag(reg->type) & NON_OWN_REF) { 11221 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 11222 return -EFAULT; 11223 } 11224 11225 reg->type |= NON_OWN_REF; 11226 if (rec->refcount_off >= 0) 11227 reg->type |= MEM_RCU; 11228 11229 return 0; 11230 } 11231 11232 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 11233 { 11234 struct bpf_func_state *state, *unused; 11235 struct bpf_reg_state *reg; 11236 int i; 11237 11238 state = cur_func(env); 11239 11240 if (!ref_obj_id) { 11241 verbose(env, "verifier internal error: ref_obj_id is zero for " 11242 "owning -> non-owning conversion\n"); 11243 return -EFAULT; 11244 } 11245 11246 for (i = 0; i < state->acquired_refs; i++) { 11247 if (state->refs[i].id != ref_obj_id) 11248 continue; 11249 11250 /* Clear ref_obj_id here so release_reference doesn't clobber 11251 * the whole reg 11252 */ 11253 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 11254 if (reg->ref_obj_id == ref_obj_id) { 11255 reg->ref_obj_id = 0; 11256 ref_set_non_owning(env, reg); 11257 } 11258 })); 11259 return 0; 11260 } 11261 11262 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 11263 return -EFAULT; 11264 } 11265 11266 /* Implementation details: 11267 * 11268 * Each register points to some region of memory, which we define as an 11269 * allocation. Each allocation may embed a bpf_spin_lock which protects any 11270 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 11271 * allocation. The lock and the data it protects are colocated in the same 11272 * memory region. 11273 * 11274 * Hence, everytime a register holds a pointer value pointing to such 11275 * allocation, the verifier preserves a unique reg->id for it. 11276 * 11277 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 11278 * bpf_spin_lock is called. 11279 * 11280 * To enable this, lock state in the verifier captures two values: 11281 * active_lock.ptr = Register's type specific pointer 11282 * active_lock.id = A unique ID for each register pointer value 11283 * 11284 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 11285 * supported register types. 11286 * 11287 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 11288 * allocated objects is the reg->btf pointer. 11289 * 11290 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 11291 * can establish the provenance of the map value statically for each distinct 11292 * lookup into such maps. They always contain a single map value hence unique 11293 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 11294 * 11295 * So, in case of global variables, they use array maps with max_entries = 1, 11296 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 11297 * into the same map value as max_entries is 1, as described above). 11298 * 11299 * In case of inner map lookups, the inner map pointer has same map_ptr as the 11300 * outer map pointer (in verifier context), but each lookup into an inner map 11301 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 11302 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 11303 * will get different reg->id assigned to each lookup, hence different 11304 * active_lock.id. 11305 * 11306 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 11307 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 11308 * returned from bpf_obj_new. Each allocation receives a new reg->id. 11309 */ 11310 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 11311 { 11312 void *ptr; 11313 u32 id; 11314 11315 switch ((int)reg->type) { 11316 case PTR_TO_MAP_VALUE: 11317 ptr = reg->map_ptr; 11318 break; 11319 case PTR_TO_BTF_ID | MEM_ALLOC: 11320 ptr = reg->btf; 11321 break; 11322 default: 11323 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 11324 return -EFAULT; 11325 } 11326 id = reg->id; 11327 11328 if (!env->cur_state->active_lock.ptr) 11329 return -EINVAL; 11330 if (env->cur_state->active_lock.ptr != ptr || 11331 env->cur_state->active_lock.id != id) { 11332 verbose(env, "held lock and object are not in the same allocation\n"); 11333 return -EINVAL; 11334 } 11335 return 0; 11336 } 11337 11338 static bool is_bpf_list_api_kfunc(u32 btf_id) 11339 { 11340 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11341 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 11342 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 11343 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 11344 } 11345 11346 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 11347 { 11348 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 11349 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11350 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 11351 } 11352 11353 static bool is_bpf_graph_api_kfunc(u32 btf_id) 11354 { 11355 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 11356 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 11357 } 11358 11359 static bool is_sync_callback_calling_kfunc(u32 btf_id) 11360 { 11361 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 11362 } 11363 11364 static bool is_bpf_throw_kfunc(struct bpf_insn *insn) 11365 { 11366 return bpf_pseudo_kfunc_call(insn) && insn->off == 0 && 11367 insn->imm == special_kfunc_list[KF_bpf_throw]; 11368 } 11369 11370 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 11371 { 11372 return is_bpf_rbtree_api_kfunc(btf_id); 11373 } 11374 11375 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 11376 enum btf_field_type head_field_type, 11377 u32 kfunc_btf_id) 11378 { 11379 bool ret; 11380 11381 switch (head_field_type) { 11382 case BPF_LIST_HEAD: 11383 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 11384 break; 11385 case BPF_RB_ROOT: 11386 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 11387 break; 11388 default: 11389 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 11390 btf_field_type_name(head_field_type)); 11391 return false; 11392 } 11393 11394 if (!ret) 11395 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 11396 btf_field_type_name(head_field_type)); 11397 return ret; 11398 } 11399 11400 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 11401 enum btf_field_type node_field_type, 11402 u32 kfunc_btf_id) 11403 { 11404 bool ret; 11405 11406 switch (node_field_type) { 11407 case BPF_LIST_NODE: 11408 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 11409 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 11410 break; 11411 case BPF_RB_NODE: 11412 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11413 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 11414 break; 11415 default: 11416 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 11417 btf_field_type_name(node_field_type)); 11418 return false; 11419 } 11420 11421 if (!ret) 11422 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 11423 btf_field_type_name(node_field_type)); 11424 return ret; 11425 } 11426 11427 static int 11428 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 11429 struct bpf_reg_state *reg, u32 regno, 11430 struct bpf_kfunc_call_arg_meta *meta, 11431 enum btf_field_type head_field_type, 11432 struct btf_field **head_field) 11433 { 11434 const char *head_type_name; 11435 struct btf_field *field; 11436 struct btf_record *rec; 11437 u32 head_off; 11438 11439 if (meta->btf != btf_vmlinux) { 11440 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11441 return -EFAULT; 11442 } 11443 11444 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 11445 return -EFAULT; 11446 11447 head_type_name = btf_field_type_name(head_field_type); 11448 if (!tnum_is_const(reg->var_off)) { 11449 verbose(env, 11450 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11451 regno, head_type_name); 11452 return -EINVAL; 11453 } 11454 11455 rec = reg_btf_record(reg); 11456 head_off = reg->off + reg->var_off.value; 11457 field = btf_record_find(rec, head_off, head_field_type); 11458 if (!field) { 11459 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 11460 return -EINVAL; 11461 } 11462 11463 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 11464 if (check_reg_allocation_locked(env, reg)) { 11465 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 11466 rec->spin_lock_off, head_type_name); 11467 return -EINVAL; 11468 } 11469 11470 if (*head_field) { 11471 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 11472 return -EFAULT; 11473 } 11474 *head_field = field; 11475 return 0; 11476 } 11477 11478 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 11479 struct bpf_reg_state *reg, u32 regno, 11480 struct bpf_kfunc_call_arg_meta *meta) 11481 { 11482 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 11483 &meta->arg_list_head.field); 11484 } 11485 11486 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 11487 struct bpf_reg_state *reg, u32 regno, 11488 struct bpf_kfunc_call_arg_meta *meta) 11489 { 11490 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 11491 &meta->arg_rbtree_root.field); 11492 } 11493 11494 static int 11495 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 11496 struct bpf_reg_state *reg, u32 regno, 11497 struct bpf_kfunc_call_arg_meta *meta, 11498 enum btf_field_type head_field_type, 11499 enum btf_field_type node_field_type, 11500 struct btf_field **node_field) 11501 { 11502 const char *node_type_name; 11503 const struct btf_type *et, *t; 11504 struct btf_field *field; 11505 u32 node_off; 11506 11507 if (meta->btf != btf_vmlinux) { 11508 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 11509 return -EFAULT; 11510 } 11511 11512 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 11513 return -EFAULT; 11514 11515 node_type_name = btf_field_type_name(node_field_type); 11516 if (!tnum_is_const(reg->var_off)) { 11517 verbose(env, 11518 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 11519 regno, node_type_name); 11520 return -EINVAL; 11521 } 11522 11523 node_off = reg->off + reg->var_off.value; 11524 field = reg_find_field_offset(reg, node_off, node_field_type); 11525 if (!field || field->offset != node_off) { 11526 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 11527 return -EINVAL; 11528 } 11529 11530 field = *node_field; 11531 11532 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 11533 t = btf_type_by_id(reg->btf, reg->btf_id); 11534 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 11535 field->graph_root.value_btf_id, true)) { 11536 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 11537 "in struct %s, but arg is at offset=%d in struct %s\n", 11538 btf_field_type_name(head_field_type), 11539 btf_field_type_name(node_field_type), 11540 field->graph_root.node_offset, 11541 btf_name_by_offset(field->graph_root.btf, et->name_off), 11542 node_off, btf_name_by_offset(reg->btf, t->name_off)); 11543 return -EINVAL; 11544 } 11545 meta->arg_btf = reg->btf; 11546 meta->arg_btf_id = reg->btf_id; 11547 11548 if (node_off != field->graph_root.node_offset) { 11549 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 11550 node_off, btf_field_type_name(node_field_type), 11551 field->graph_root.node_offset, 11552 btf_name_by_offset(field->graph_root.btf, et->name_off)); 11553 return -EINVAL; 11554 } 11555 11556 return 0; 11557 } 11558 11559 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 11560 struct bpf_reg_state *reg, u32 regno, 11561 struct bpf_kfunc_call_arg_meta *meta) 11562 { 11563 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11564 BPF_LIST_HEAD, BPF_LIST_NODE, 11565 &meta->arg_list_head.field); 11566 } 11567 11568 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 11569 struct bpf_reg_state *reg, u32 regno, 11570 struct bpf_kfunc_call_arg_meta *meta) 11571 { 11572 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 11573 BPF_RB_ROOT, BPF_RB_NODE, 11574 &meta->arg_rbtree_root.field); 11575 } 11576 11577 /* 11578 * css_task iter allowlist is needed to avoid dead locking on css_set_lock. 11579 * LSM hooks and iters (both sleepable and non-sleepable) are safe. 11580 * Any sleepable progs are also safe since bpf_check_attach_target() enforce 11581 * them can only be attached to some specific hook points. 11582 */ 11583 static bool check_css_task_iter_allowlist(struct bpf_verifier_env *env) 11584 { 11585 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 11586 11587 switch (prog_type) { 11588 case BPF_PROG_TYPE_LSM: 11589 return true; 11590 case BPF_PROG_TYPE_TRACING: 11591 if (env->prog->expected_attach_type == BPF_TRACE_ITER) 11592 return true; 11593 fallthrough; 11594 default: 11595 return in_sleepable(env); 11596 } 11597 } 11598 11599 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 11600 int insn_idx) 11601 { 11602 const char *func_name = meta->func_name, *ref_tname; 11603 const struct btf *btf = meta->btf; 11604 const struct btf_param *args; 11605 struct btf_record *rec; 11606 u32 i, nargs; 11607 int ret; 11608 11609 args = (const struct btf_param *)(meta->func_proto + 1); 11610 nargs = btf_type_vlen(meta->func_proto); 11611 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 11612 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 11613 MAX_BPF_FUNC_REG_ARGS); 11614 return -EINVAL; 11615 } 11616 11617 /* Check that BTF function arguments match actual types that the 11618 * verifier sees. 11619 */ 11620 for (i = 0; i < nargs; i++) { 11621 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 11622 const struct btf_type *t, *ref_t, *resolve_ret; 11623 enum bpf_arg_type arg_type = ARG_DONTCARE; 11624 u32 regno = i + 1, ref_id, type_size; 11625 bool is_ret_buf_sz = false; 11626 int kf_arg_type; 11627 11628 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 11629 11630 if (is_kfunc_arg_ignore(btf, &args[i])) 11631 continue; 11632 11633 if (btf_type_is_scalar(t)) { 11634 if (reg->type != SCALAR_VALUE) { 11635 verbose(env, "R%d is not a scalar\n", regno); 11636 return -EINVAL; 11637 } 11638 11639 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 11640 if (meta->arg_constant.found) { 11641 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11642 return -EFAULT; 11643 } 11644 if (!tnum_is_const(reg->var_off)) { 11645 verbose(env, "R%d must be a known constant\n", regno); 11646 return -EINVAL; 11647 } 11648 ret = mark_chain_precision(env, regno); 11649 if (ret < 0) 11650 return ret; 11651 meta->arg_constant.found = true; 11652 meta->arg_constant.value = reg->var_off.value; 11653 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 11654 meta->r0_rdonly = true; 11655 is_ret_buf_sz = true; 11656 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 11657 is_ret_buf_sz = true; 11658 } 11659 11660 if (is_ret_buf_sz) { 11661 if (meta->r0_size) { 11662 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 11663 return -EINVAL; 11664 } 11665 11666 if (!tnum_is_const(reg->var_off)) { 11667 verbose(env, "R%d is not a const\n", regno); 11668 return -EINVAL; 11669 } 11670 11671 meta->r0_size = reg->var_off.value; 11672 ret = mark_chain_precision(env, regno); 11673 if (ret) 11674 return ret; 11675 } 11676 continue; 11677 } 11678 11679 if (!btf_type_is_ptr(t)) { 11680 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 11681 return -EINVAL; 11682 } 11683 11684 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 11685 (register_is_null(reg) || type_may_be_null(reg->type)) && 11686 !is_kfunc_arg_nullable(meta->btf, &args[i])) { 11687 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 11688 return -EACCES; 11689 } 11690 11691 if (reg->ref_obj_id) { 11692 if (is_kfunc_release(meta) && meta->ref_obj_id) { 11693 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 11694 regno, reg->ref_obj_id, 11695 meta->ref_obj_id); 11696 return -EFAULT; 11697 } 11698 meta->ref_obj_id = reg->ref_obj_id; 11699 if (is_kfunc_release(meta)) 11700 meta->release_regno = regno; 11701 } 11702 11703 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 11704 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11705 11706 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 11707 if (kf_arg_type < 0) 11708 return kf_arg_type; 11709 11710 switch (kf_arg_type) { 11711 case KF_ARG_PTR_TO_NULL: 11712 continue; 11713 case KF_ARG_PTR_TO_MAP: 11714 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11715 case KF_ARG_PTR_TO_BTF_ID: 11716 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 11717 break; 11718 11719 if (!is_trusted_reg(reg)) { 11720 if (!is_kfunc_rcu(meta)) { 11721 verbose(env, "R%d must be referenced or trusted\n", regno); 11722 return -EINVAL; 11723 } 11724 if (!is_rcu_reg(reg)) { 11725 verbose(env, "R%d must be a rcu pointer\n", regno); 11726 return -EINVAL; 11727 } 11728 } 11729 11730 fallthrough; 11731 case KF_ARG_PTR_TO_CTX: 11732 /* Trusted arguments have the same offset checks as release arguments */ 11733 arg_type |= OBJ_RELEASE; 11734 break; 11735 case KF_ARG_PTR_TO_DYNPTR: 11736 case KF_ARG_PTR_TO_ITER: 11737 case KF_ARG_PTR_TO_LIST_HEAD: 11738 case KF_ARG_PTR_TO_LIST_NODE: 11739 case KF_ARG_PTR_TO_RB_ROOT: 11740 case KF_ARG_PTR_TO_RB_NODE: 11741 case KF_ARG_PTR_TO_MEM: 11742 case KF_ARG_PTR_TO_MEM_SIZE: 11743 case KF_ARG_PTR_TO_CALLBACK: 11744 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 11745 case KF_ARG_PTR_TO_CONST_STR: 11746 /* Trusted by default */ 11747 break; 11748 default: 11749 WARN_ON_ONCE(1); 11750 return -EFAULT; 11751 } 11752 11753 if (is_kfunc_release(meta) && reg->ref_obj_id) 11754 arg_type |= OBJ_RELEASE; 11755 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 11756 if (ret < 0) 11757 return ret; 11758 11759 switch (kf_arg_type) { 11760 case KF_ARG_PTR_TO_CTX: 11761 if (reg->type != PTR_TO_CTX) { 11762 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 11763 return -EINVAL; 11764 } 11765 11766 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11767 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 11768 if (ret < 0) 11769 return -EINVAL; 11770 meta->ret_btf_id = ret; 11771 } 11772 break; 11773 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 11774 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC)) { 11775 if (meta->func_id != special_kfunc_list[KF_bpf_obj_drop_impl]) { 11776 verbose(env, "arg#%d expected for bpf_obj_drop_impl()\n", i); 11777 return -EINVAL; 11778 } 11779 } else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC | MEM_PERCPU)) { 11780 if (meta->func_id != special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 11781 verbose(env, "arg#%d expected for bpf_percpu_obj_drop_impl()\n", i); 11782 return -EINVAL; 11783 } 11784 } else { 11785 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11786 return -EINVAL; 11787 } 11788 if (!reg->ref_obj_id) { 11789 verbose(env, "allocated object must be referenced\n"); 11790 return -EINVAL; 11791 } 11792 if (meta->btf == btf_vmlinux) { 11793 meta->arg_btf = reg->btf; 11794 meta->arg_btf_id = reg->btf_id; 11795 } 11796 break; 11797 case KF_ARG_PTR_TO_DYNPTR: 11798 { 11799 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 11800 int clone_ref_obj_id = 0; 11801 11802 if (reg->type != PTR_TO_STACK && 11803 reg->type != CONST_PTR_TO_DYNPTR) { 11804 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 11805 return -EINVAL; 11806 } 11807 11808 if (reg->type == CONST_PTR_TO_DYNPTR) 11809 dynptr_arg_type |= MEM_RDONLY; 11810 11811 if (is_kfunc_arg_uninit(btf, &args[i])) 11812 dynptr_arg_type |= MEM_UNINIT; 11813 11814 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 11815 dynptr_arg_type |= DYNPTR_TYPE_SKB; 11816 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 11817 dynptr_arg_type |= DYNPTR_TYPE_XDP; 11818 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 11819 (dynptr_arg_type & MEM_UNINIT)) { 11820 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 11821 11822 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 11823 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 11824 return -EFAULT; 11825 } 11826 11827 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 11828 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 11829 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 11830 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 11831 return -EFAULT; 11832 } 11833 } 11834 11835 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 11836 if (ret < 0) 11837 return ret; 11838 11839 if (!(dynptr_arg_type & MEM_UNINIT)) { 11840 int id = dynptr_id(env, reg); 11841 11842 if (id < 0) { 11843 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 11844 return id; 11845 } 11846 meta->initialized_dynptr.id = id; 11847 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 11848 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 11849 } 11850 11851 break; 11852 } 11853 case KF_ARG_PTR_TO_ITER: 11854 if (meta->func_id == special_kfunc_list[KF_bpf_iter_css_task_new]) { 11855 if (!check_css_task_iter_allowlist(env)) { 11856 verbose(env, "css_task_iter is only allowed in bpf_lsm, bpf_iter and sleepable progs\n"); 11857 return -EINVAL; 11858 } 11859 } 11860 ret = process_iter_arg(env, regno, insn_idx, meta); 11861 if (ret < 0) 11862 return ret; 11863 break; 11864 case KF_ARG_PTR_TO_LIST_HEAD: 11865 if (reg->type != PTR_TO_MAP_VALUE && 11866 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11867 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11868 return -EINVAL; 11869 } 11870 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11871 verbose(env, "allocated object must be referenced\n"); 11872 return -EINVAL; 11873 } 11874 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 11875 if (ret < 0) 11876 return ret; 11877 break; 11878 case KF_ARG_PTR_TO_RB_ROOT: 11879 if (reg->type != PTR_TO_MAP_VALUE && 11880 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11881 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 11882 return -EINVAL; 11883 } 11884 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 11885 verbose(env, "allocated object must be referenced\n"); 11886 return -EINVAL; 11887 } 11888 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 11889 if (ret < 0) 11890 return ret; 11891 break; 11892 case KF_ARG_PTR_TO_LIST_NODE: 11893 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11894 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11895 return -EINVAL; 11896 } 11897 if (!reg->ref_obj_id) { 11898 verbose(env, "allocated object must be referenced\n"); 11899 return -EINVAL; 11900 } 11901 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 11902 if (ret < 0) 11903 return ret; 11904 break; 11905 case KF_ARG_PTR_TO_RB_NODE: 11906 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 11907 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 11908 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 11909 return -EINVAL; 11910 } 11911 if (in_rbtree_lock_required_cb(env)) { 11912 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 11913 return -EINVAL; 11914 } 11915 } else { 11916 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 11917 verbose(env, "arg#%d expected pointer to allocated object\n", i); 11918 return -EINVAL; 11919 } 11920 if (!reg->ref_obj_id) { 11921 verbose(env, "allocated object must be referenced\n"); 11922 return -EINVAL; 11923 } 11924 } 11925 11926 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 11927 if (ret < 0) 11928 return ret; 11929 break; 11930 case KF_ARG_PTR_TO_MAP: 11931 /* If argument has '__map' suffix expect 'struct bpf_map *' */ 11932 ref_id = *reg2btf_ids[CONST_PTR_TO_MAP]; 11933 ref_t = btf_type_by_id(btf_vmlinux, ref_id); 11934 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 11935 fallthrough; 11936 case KF_ARG_PTR_TO_BTF_ID: 11937 /* Only base_type is checked, further checks are done here */ 11938 if ((base_type(reg->type) != PTR_TO_BTF_ID || 11939 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 11940 !reg2btf_ids[base_type(reg->type)]) { 11941 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 11942 verbose(env, "expected %s or socket\n", 11943 reg_type_str(env, base_type(reg->type) | 11944 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 11945 return -EINVAL; 11946 } 11947 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 11948 if (ret < 0) 11949 return ret; 11950 break; 11951 case KF_ARG_PTR_TO_MEM: 11952 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 11953 if (IS_ERR(resolve_ret)) { 11954 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 11955 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 11956 return -EINVAL; 11957 } 11958 ret = check_mem_reg(env, reg, regno, type_size); 11959 if (ret < 0) 11960 return ret; 11961 break; 11962 case KF_ARG_PTR_TO_MEM_SIZE: 11963 { 11964 struct bpf_reg_state *buff_reg = ®s[regno]; 11965 const struct btf_param *buff_arg = &args[i]; 11966 struct bpf_reg_state *size_reg = ®s[regno + 1]; 11967 const struct btf_param *size_arg = &args[i + 1]; 11968 11969 if (!register_is_null(buff_reg) || !is_kfunc_arg_optional(meta->btf, buff_arg)) { 11970 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 11971 if (ret < 0) { 11972 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 11973 return ret; 11974 } 11975 } 11976 11977 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 11978 if (meta->arg_constant.found) { 11979 verbose(env, "verifier internal error: only one constant argument permitted\n"); 11980 return -EFAULT; 11981 } 11982 if (!tnum_is_const(size_reg->var_off)) { 11983 verbose(env, "R%d must be a known constant\n", regno + 1); 11984 return -EINVAL; 11985 } 11986 meta->arg_constant.found = true; 11987 meta->arg_constant.value = size_reg->var_off.value; 11988 } 11989 11990 /* Skip next '__sz' or '__szk' argument */ 11991 i++; 11992 break; 11993 } 11994 case KF_ARG_PTR_TO_CALLBACK: 11995 if (reg->type != PTR_TO_FUNC) { 11996 verbose(env, "arg%d expected pointer to func\n", i); 11997 return -EINVAL; 11998 } 11999 meta->subprogno = reg->subprogno; 12000 break; 12001 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 12002 if (!type_is_ptr_alloc_obj(reg->type)) { 12003 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 12004 return -EINVAL; 12005 } 12006 if (!type_is_non_owning_ref(reg->type)) 12007 meta->arg_owning_ref = true; 12008 12009 rec = reg_btf_record(reg); 12010 if (!rec) { 12011 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 12012 return -EFAULT; 12013 } 12014 12015 if (rec->refcount_off < 0) { 12016 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 12017 return -EINVAL; 12018 } 12019 12020 meta->arg_btf = reg->btf; 12021 meta->arg_btf_id = reg->btf_id; 12022 break; 12023 case KF_ARG_PTR_TO_CONST_STR: 12024 if (reg->type != PTR_TO_MAP_VALUE) { 12025 verbose(env, "arg#%d doesn't point to a const string\n", i); 12026 return -EINVAL; 12027 } 12028 ret = check_reg_const_str(env, reg, regno); 12029 if (ret) 12030 return ret; 12031 break; 12032 } 12033 } 12034 12035 if (is_kfunc_release(meta) && !meta->release_regno) { 12036 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 12037 func_name); 12038 return -EINVAL; 12039 } 12040 12041 return 0; 12042 } 12043 12044 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 12045 struct bpf_insn *insn, 12046 struct bpf_kfunc_call_arg_meta *meta, 12047 const char **kfunc_name) 12048 { 12049 const struct btf_type *func, *func_proto; 12050 u32 func_id, *kfunc_flags; 12051 const char *func_name; 12052 struct btf *desc_btf; 12053 12054 if (kfunc_name) 12055 *kfunc_name = NULL; 12056 12057 if (!insn->imm) 12058 return -EINVAL; 12059 12060 desc_btf = find_kfunc_desc_btf(env, insn->off); 12061 if (IS_ERR(desc_btf)) 12062 return PTR_ERR(desc_btf); 12063 12064 func_id = insn->imm; 12065 func = btf_type_by_id(desc_btf, func_id); 12066 func_name = btf_name_by_offset(desc_btf, func->name_off); 12067 if (kfunc_name) 12068 *kfunc_name = func_name; 12069 func_proto = btf_type_by_id(desc_btf, func->type); 12070 12071 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, func_id, env->prog); 12072 if (!kfunc_flags) { 12073 return -EACCES; 12074 } 12075 12076 memset(meta, 0, sizeof(*meta)); 12077 meta->btf = desc_btf; 12078 meta->func_id = func_id; 12079 meta->kfunc_flags = *kfunc_flags; 12080 meta->func_proto = func_proto; 12081 meta->func_name = func_name; 12082 12083 return 0; 12084 } 12085 12086 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name); 12087 12088 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 12089 int *insn_idx_p) 12090 { 12091 const struct btf_type *t, *ptr_type; 12092 u32 i, nargs, ptr_type_id, release_ref_obj_id; 12093 struct bpf_reg_state *regs = cur_regs(env); 12094 const char *func_name, *ptr_type_name; 12095 bool sleepable, rcu_lock, rcu_unlock; 12096 struct bpf_kfunc_call_arg_meta meta; 12097 struct bpf_insn_aux_data *insn_aux; 12098 int err, insn_idx = *insn_idx_p; 12099 const struct btf_param *args; 12100 const struct btf_type *ret_t; 12101 struct btf *desc_btf; 12102 12103 /* skip for now, but return error when we find this in fixup_kfunc_call */ 12104 if (!insn->imm) 12105 return 0; 12106 12107 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 12108 if (err == -EACCES && func_name) 12109 verbose(env, "calling kernel function %s is not allowed\n", func_name); 12110 if (err) 12111 return err; 12112 desc_btf = meta.btf; 12113 insn_aux = &env->insn_aux_data[insn_idx]; 12114 12115 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 12116 12117 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 12118 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 12119 return -EACCES; 12120 } 12121 12122 sleepable = is_kfunc_sleepable(&meta); 12123 if (sleepable && !in_sleepable(env)) { 12124 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 12125 return -EACCES; 12126 } 12127 12128 /* Check the arguments */ 12129 err = check_kfunc_args(env, &meta, insn_idx); 12130 if (err < 0) 12131 return err; 12132 12133 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12134 err = push_callback_call(env, insn, insn_idx, meta.subprogno, 12135 set_rbtree_add_callback_state); 12136 if (err) { 12137 verbose(env, "kfunc %s#%d failed callback verification\n", 12138 func_name, meta.func_id); 12139 return err; 12140 } 12141 } 12142 12143 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 12144 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 12145 12146 if (env->cur_state->active_rcu_lock) { 12147 struct bpf_func_state *state; 12148 struct bpf_reg_state *reg; 12149 u32 clear_mask = (1 << STACK_SPILL) | (1 << STACK_ITER); 12150 12151 if (in_rbtree_lock_required_cb(env) && (rcu_lock || rcu_unlock)) { 12152 verbose(env, "Calling bpf_rcu_read_{lock,unlock} in unnecessary rbtree callback\n"); 12153 return -EACCES; 12154 } 12155 12156 if (rcu_lock) { 12157 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 12158 return -EINVAL; 12159 } else if (rcu_unlock) { 12160 bpf_for_each_reg_in_vstate_mask(env->cur_state, state, reg, clear_mask, ({ 12161 if (reg->type & MEM_RCU) { 12162 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 12163 reg->type |= PTR_UNTRUSTED; 12164 } 12165 })); 12166 env->cur_state->active_rcu_lock = false; 12167 } else if (sleepable) { 12168 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 12169 return -EACCES; 12170 } 12171 } else if (rcu_lock) { 12172 env->cur_state->active_rcu_lock = true; 12173 } else if (rcu_unlock) { 12174 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 12175 return -EINVAL; 12176 } 12177 12178 /* In case of release function, we get register number of refcounted 12179 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 12180 */ 12181 if (meta.release_regno) { 12182 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 12183 if (err) { 12184 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12185 func_name, meta.func_id); 12186 return err; 12187 } 12188 } 12189 12190 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 12191 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 12192 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 12193 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 12194 insn_aux->insert_off = regs[BPF_REG_2].off; 12195 insn_aux->kptr_struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id); 12196 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 12197 if (err) { 12198 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 12199 func_name, meta.func_id); 12200 return err; 12201 } 12202 12203 err = release_reference(env, release_ref_obj_id); 12204 if (err) { 12205 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 12206 func_name, meta.func_id); 12207 return err; 12208 } 12209 } 12210 12211 if (meta.func_id == special_kfunc_list[KF_bpf_throw]) { 12212 if (!bpf_jit_supports_exceptions()) { 12213 verbose(env, "JIT does not support calling kfunc %s#%d\n", 12214 func_name, meta.func_id); 12215 return -ENOTSUPP; 12216 } 12217 env->seen_exception = true; 12218 12219 /* In the case of the default callback, the cookie value passed 12220 * to bpf_throw becomes the return value of the program. 12221 */ 12222 if (!env->exception_callback_subprog) { 12223 err = check_return_code(env, BPF_REG_1, "R1"); 12224 if (err < 0) 12225 return err; 12226 } 12227 } 12228 12229 for (i = 0; i < CALLER_SAVED_REGS; i++) 12230 mark_reg_not_init(env, regs, caller_saved[i]); 12231 12232 /* Check return type */ 12233 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 12234 12235 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 12236 /* Only exception is bpf_obj_new_impl */ 12237 if (meta.btf != btf_vmlinux || 12238 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 12239 meta.func_id != special_kfunc_list[KF_bpf_percpu_obj_new_impl] && 12240 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 12241 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 12242 return -EINVAL; 12243 } 12244 } 12245 12246 if (btf_type_is_scalar(t)) { 12247 mark_reg_unknown(env, regs, BPF_REG_0); 12248 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 12249 } else if (btf_type_is_ptr(t)) { 12250 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 12251 12252 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12253 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 12254 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12255 struct btf_struct_meta *struct_meta; 12256 struct btf *ret_btf; 12257 u32 ret_btf_id; 12258 12259 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl] && !bpf_global_ma_set) 12260 return -ENOMEM; 12261 12262 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 12263 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 12264 return -EINVAL; 12265 } 12266 12267 ret_btf = env->prog->aux->btf; 12268 ret_btf_id = meta.arg_constant.value; 12269 12270 /* This may be NULL due to user not supplying a BTF */ 12271 if (!ret_btf) { 12272 verbose(env, "bpf_obj_new/bpf_percpu_obj_new requires prog BTF\n"); 12273 return -EINVAL; 12274 } 12275 12276 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 12277 if (!ret_t || !__btf_type_is_struct(ret_t)) { 12278 verbose(env, "bpf_obj_new/bpf_percpu_obj_new type ID argument must be of a struct\n"); 12279 return -EINVAL; 12280 } 12281 12282 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12283 if (ret_t->size > BPF_GLOBAL_PERCPU_MA_MAX_SIZE) { 12284 verbose(env, "bpf_percpu_obj_new type size (%d) is greater than %d\n", 12285 ret_t->size, BPF_GLOBAL_PERCPU_MA_MAX_SIZE); 12286 return -EINVAL; 12287 } 12288 12289 if (!bpf_global_percpu_ma_set) { 12290 mutex_lock(&bpf_percpu_ma_lock); 12291 if (!bpf_global_percpu_ma_set) { 12292 /* Charge memory allocated with bpf_global_percpu_ma to 12293 * root memcg. The obj_cgroup for root memcg is NULL. 12294 */ 12295 err = bpf_mem_alloc_percpu_init(&bpf_global_percpu_ma, NULL); 12296 if (!err) 12297 bpf_global_percpu_ma_set = true; 12298 } 12299 mutex_unlock(&bpf_percpu_ma_lock); 12300 if (err) 12301 return err; 12302 } 12303 12304 mutex_lock(&bpf_percpu_ma_lock); 12305 err = bpf_mem_alloc_percpu_unit_init(&bpf_global_percpu_ma, ret_t->size); 12306 mutex_unlock(&bpf_percpu_ma_lock); 12307 if (err) 12308 return err; 12309 } 12310 12311 struct_meta = btf_find_struct_meta(ret_btf, ret_btf_id); 12312 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 12313 if (!__btf_type_is_scalar_struct(env, ret_btf, ret_t, 0)) { 12314 verbose(env, "bpf_percpu_obj_new type ID argument must be of a struct of scalars\n"); 12315 return -EINVAL; 12316 } 12317 12318 if (struct_meta) { 12319 verbose(env, "bpf_percpu_obj_new type ID argument must not contain special fields\n"); 12320 return -EINVAL; 12321 } 12322 } 12323 12324 mark_reg_known_zero(env, regs, BPF_REG_0); 12325 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12326 regs[BPF_REG_0].btf = ret_btf; 12327 regs[BPF_REG_0].btf_id = ret_btf_id; 12328 if (meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) 12329 regs[BPF_REG_0].type |= MEM_PERCPU; 12330 12331 insn_aux->obj_new_size = ret_t->size; 12332 insn_aux->kptr_struct_meta = struct_meta; 12333 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 12334 mark_reg_known_zero(env, regs, BPF_REG_0); 12335 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 12336 regs[BPF_REG_0].btf = meta.arg_btf; 12337 regs[BPF_REG_0].btf_id = meta.arg_btf_id; 12338 12339 insn_aux->kptr_struct_meta = 12340 btf_find_struct_meta(meta.arg_btf, 12341 meta.arg_btf_id); 12342 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 12343 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 12344 struct btf_field *field = meta.arg_list_head.field; 12345 12346 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12347 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 12348 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12349 struct btf_field *field = meta.arg_rbtree_root.field; 12350 12351 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 12352 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 12353 mark_reg_known_zero(env, regs, BPF_REG_0); 12354 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 12355 regs[BPF_REG_0].btf = desc_btf; 12356 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 12357 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 12358 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 12359 if (!ret_t || !btf_type_is_struct(ret_t)) { 12360 verbose(env, 12361 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 12362 return -EINVAL; 12363 } 12364 12365 mark_reg_known_zero(env, regs, BPF_REG_0); 12366 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 12367 regs[BPF_REG_0].btf = desc_btf; 12368 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 12369 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 12370 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 12371 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 12372 12373 mark_reg_known_zero(env, regs, BPF_REG_0); 12374 12375 if (!meta.arg_constant.found) { 12376 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 12377 return -EFAULT; 12378 } 12379 12380 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 12381 12382 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 12383 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 12384 12385 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 12386 regs[BPF_REG_0].type |= MEM_RDONLY; 12387 } else { 12388 /* this will set env->seen_direct_write to true */ 12389 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 12390 verbose(env, "the prog does not allow writes to packet data\n"); 12391 return -EINVAL; 12392 } 12393 } 12394 12395 if (!meta.initialized_dynptr.id) { 12396 verbose(env, "verifier internal error: no dynptr id\n"); 12397 return -EFAULT; 12398 } 12399 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 12400 12401 /* we don't need to set BPF_REG_0's ref obj id 12402 * because packet slices are not refcounted (see 12403 * dynptr_type_refcounted) 12404 */ 12405 } else { 12406 verbose(env, "kernel function %s unhandled dynamic return type\n", 12407 meta.func_name); 12408 return -EFAULT; 12409 } 12410 } else if (btf_type_is_void(ptr_type)) { 12411 /* kfunc returning 'void *' is equivalent to returning scalar */ 12412 mark_reg_unknown(env, regs, BPF_REG_0); 12413 } else if (!__btf_type_is_struct(ptr_type)) { 12414 if (!meta.r0_size) { 12415 __u32 sz; 12416 12417 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 12418 meta.r0_size = sz; 12419 meta.r0_rdonly = true; 12420 } 12421 } 12422 if (!meta.r0_size) { 12423 ptr_type_name = btf_name_by_offset(desc_btf, 12424 ptr_type->name_off); 12425 verbose(env, 12426 "kernel function %s returns pointer type %s %s is not supported\n", 12427 func_name, 12428 btf_type_str(ptr_type), 12429 ptr_type_name); 12430 return -EINVAL; 12431 } 12432 12433 mark_reg_known_zero(env, regs, BPF_REG_0); 12434 regs[BPF_REG_0].type = PTR_TO_MEM; 12435 regs[BPF_REG_0].mem_size = meta.r0_size; 12436 12437 if (meta.r0_rdonly) 12438 regs[BPF_REG_0].type |= MEM_RDONLY; 12439 12440 /* Ensures we don't access the memory after a release_reference() */ 12441 if (meta.ref_obj_id) 12442 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 12443 } else { 12444 mark_reg_known_zero(env, regs, BPF_REG_0); 12445 regs[BPF_REG_0].btf = desc_btf; 12446 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 12447 regs[BPF_REG_0].btf_id = ptr_type_id; 12448 } 12449 12450 if (is_kfunc_ret_null(&meta)) { 12451 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 12452 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 12453 regs[BPF_REG_0].id = ++env->id_gen; 12454 } 12455 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 12456 if (is_kfunc_acquire(&meta)) { 12457 int id = acquire_reference_state(env, insn_idx); 12458 12459 if (id < 0) 12460 return id; 12461 if (is_kfunc_ret_null(&meta)) 12462 regs[BPF_REG_0].id = id; 12463 regs[BPF_REG_0].ref_obj_id = id; 12464 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 12465 ref_set_non_owning(env, ®s[BPF_REG_0]); 12466 } 12467 12468 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 12469 regs[BPF_REG_0].id = ++env->id_gen; 12470 } else if (btf_type_is_void(t)) { 12471 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 12472 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 12473 meta.func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl]) { 12474 insn_aux->kptr_struct_meta = 12475 btf_find_struct_meta(meta.arg_btf, 12476 meta.arg_btf_id); 12477 } 12478 } 12479 } 12480 12481 nargs = btf_type_vlen(meta.func_proto); 12482 args = (const struct btf_param *)(meta.func_proto + 1); 12483 for (i = 0; i < nargs; i++) { 12484 u32 regno = i + 1; 12485 12486 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 12487 if (btf_type_is_ptr(t)) 12488 mark_btf_func_reg_size(env, regno, sizeof(void *)); 12489 else 12490 /* scalar. ensured by btf_check_kfunc_arg_match() */ 12491 mark_btf_func_reg_size(env, regno, t->size); 12492 } 12493 12494 if (is_iter_next_kfunc(&meta)) { 12495 err = process_iter_next_call(env, insn_idx, &meta); 12496 if (err) 12497 return err; 12498 } 12499 12500 return 0; 12501 } 12502 12503 static bool signed_add_overflows(s64 a, s64 b) 12504 { 12505 /* Do the add in u64, where overflow is well-defined */ 12506 s64 res = (s64)((u64)a + (u64)b); 12507 12508 if (b < 0) 12509 return res > a; 12510 return res < a; 12511 } 12512 12513 static bool signed_add32_overflows(s32 a, s32 b) 12514 { 12515 /* Do the add in u32, where overflow is well-defined */ 12516 s32 res = (s32)((u32)a + (u32)b); 12517 12518 if (b < 0) 12519 return res > a; 12520 return res < a; 12521 } 12522 12523 static bool signed_sub_overflows(s64 a, s64 b) 12524 { 12525 /* Do the sub in u64, where overflow is well-defined */ 12526 s64 res = (s64)((u64)a - (u64)b); 12527 12528 if (b < 0) 12529 return res < a; 12530 return res > a; 12531 } 12532 12533 static bool signed_sub32_overflows(s32 a, s32 b) 12534 { 12535 /* Do the sub in u32, where overflow is well-defined */ 12536 s32 res = (s32)((u32)a - (u32)b); 12537 12538 if (b < 0) 12539 return res < a; 12540 return res > a; 12541 } 12542 12543 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 12544 const struct bpf_reg_state *reg, 12545 enum bpf_reg_type type) 12546 { 12547 bool known = tnum_is_const(reg->var_off); 12548 s64 val = reg->var_off.value; 12549 s64 smin = reg->smin_value; 12550 12551 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 12552 verbose(env, "math between %s pointer and %lld is not allowed\n", 12553 reg_type_str(env, type), val); 12554 return false; 12555 } 12556 12557 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 12558 verbose(env, "%s pointer offset %d is not allowed\n", 12559 reg_type_str(env, type), reg->off); 12560 return false; 12561 } 12562 12563 if (smin == S64_MIN) { 12564 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 12565 reg_type_str(env, type)); 12566 return false; 12567 } 12568 12569 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 12570 verbose(env, "value %lld makes %s pointer be out of bounds\n", 12571 smin, reg_type_str(env, type)); 12572 return false; 12573 } 12574 12575 return true; 12576 } 12577 12578 enum { 12579 REASON_BOUNDS = -1, 12580 REASON_TYPE = -2, 12581 REASON_PATHS = -3, 12582 REASON_LIMIT = -4, 12583 REASON_STACK = -5, 12584 }; 12585 12586 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 12587 u32 *alu_limit, bool mask_to_left) 12588 { 12589 u32 max = 0, ptr_limit = 0; 12590 12591 switch (ptr_reg->type) { 12592 case PTR_TO_STACK: 12593 /* Offset 0 is out-of-bounds, but acceptable start for the 12594 * left direction, see BPF_REG_FP. Also, unknown scalar 12595 * offset where we would need to deal with min/max bounds is 12596 * currently prohibited for unprivileged. 12597 */ 12598 max = MAX_BPF_STACK + mask_to_left; 12599 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 12600 break; 12601 case PTR_TO_MAP_VALUE: 12602 max = ptr_reg->map_ptr->value_size; 12603 ptr_limit = (mask_to_left ? 12604 ptr_reg->smin_value : 12605 ptr_reg->umax_value) + ptr_reg->off; 12606 break; 12607 default: 12608 return REASON_TYPE; 12609 } 12610 12611 if (ptr_limit >= max) 12612 return REASON_LIMIT; 12613 *alu_limit = ptr_limit; 12614 return 0; 12615 } 12616 12617 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 12618 const struct bpf_insn *insn) 12619 { 12620 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 12621 } 12622 12623 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 12624 u32 alu_state, u32 alu_limit) 12625 { 12626 /* If we arrived here from different branches with different 12627 * state or limits to sanitize, then this won't work. 12628 */ 12629 if (aux->alu_state && 12630 (aux->alu_state != alu_state || 12631 aux->alu_limit != alu_limit)) 12632 return REASON_PATHS; 12633 12634 /* Corresponding fixup done in do_misc_fixups(). */ 12635 aux->alu_state = alu_state; 12636 aux->alu_limit = alu_limit; 12637 return 0; 12638 } 12639 12640 static int sanitize_val_alu(struct bpf_verifier_env *env, 12641 struct bpf_insn *insn) 12642 { 12643 struct bpf_insn_aux_data *aux = cur_aux(env); 12644 12645 if (can_skip_alu_sanitation(env, insn)) 12646 return 0; 12647 12648 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 12649 } 12650 12651 static bool sanitize_needed(u8 opcode) 12652 { 12653 return opcode == BPF_ADD || opcode == BPF_SUB; 12654 } 12655 12656 struct bpf_sanitize_info { 12657 struct bpf_insn_aux_data aux; 12658 bool mask_to_left; 12659 }; 12660 12661 static struct bpf_verifier_state * 12662 sanitize_speculative_path(struct bpf_verifier_env *env, 12663 const struct bpf_insn *insn, 12664 u32 next_idx, u32 curr_idx) 12665 { 12666 struct bpf_verifier_state *branch; 12667 struct bpf_reg_state *regs; 12668 12669 branch = push_stack(env, next_idx, curr_idx, true); 12670 if (branch && insn) { 12671 regs = branch->frame[branch->curframe]->regs; 12672 if (BPF_SRC(insn->code) == BPF_K) { 12673 mark_reg_unknown(env, regs, insn->dst_reg); 12674 } else if (BPF_SRC(insn->code) == BPF_X) { 12675 mark_reg_unknown(env, regs, insn->dst_reg); 12676 mark_reg_unknown(env, regs, insn->src_reg); 12677 } 12678 } 12679 return branch; 12680 } 12681 12682 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 12683 struct bpf_insn *insn, 12684 const struct bpf_reg_state *ptr_reg, 12685 const struct bpf_reg_state *off_reg, 12686 struct bpf_reg_state *dst_reg, 12687 struct bpf_sanitize_info *info, 12688 const bool commit_window) 12689 { 12690 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 12691 struct bpf_verifier_state *vstate = env->cur_state; 12692 bool off_is_imm = tnum_is_const(off_reg->var_off); 12693 bool off_is_neg = off_reg->smin_value < 0; 12694 bool ptr_is_dst_reg = ptr_reg == dst_reg; 12695 u8 opcode = BPF_OP(insn->code); 12696 u32 alu_state, alu_limit; 12697 struct bpf_reg_state tmp; 12698 bool ret; 12699 int err; 12700 12701 if (can_skip_alu_sanitation(env, insn)) 12702 return 0; 12703 12704 /* We already marked aux for masking from non-speculative 12705 * paths, thus we got here in the first place. We only care 12706 * to explore bad access from here. 12707 */ 12708 if (vstate->speculative) 12709 goto do_sim; 12710 12711 if (!commit_window) { 12712 if (!tnum_is_const(off_reg->var_off) && 12713 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 12714 return REASON_BOUNDS; 12715 12716 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 12717 (opcode == BPF_SUB && !off_is_neg); 12718 } 12719 12720 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 12721 if (err < 0) 12722 return err; 12723 12724 if (commit_window) { 12725 /* In commit phase we narrow the masking window based on 12726 * the observed pointer move after the simulated operation. 12727 */ 12728 alu_state = info->aux.alu_state; 12729 alu_limit = abs(info->aux.alu_limit - alu_limit); 12730 } else { 12731 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 12732 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 12733 alu_state |= ptr_is_dst_reg ? 12734 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 12735 12736 /* Limit pruning on unknown scalars to enable deep search for 12737 * potential masking differences from other program paths. 12738 */ 12739 if (!off_is_imm) 12740 env->explore_alu_limits = true; 12741 } 12742 12743 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 12744 if (err < 0) 12745 return err; 12746 do_sim: 12747 /* If we're in commit phase, we're done here given we already 12748 * pushed the truncated dst_reg into the speculative verification 12749 * stack. 12750 * 12751 * Also, when register is a known constant, we rewrite register-based 12752 * operation to immediate-based, and thus do not need masking (and as 12753 * a consequence, do not need to simulate the zero-truncation either). 12754 */ 12755 if (commit_window || off_is_imm) 12756 return 0; 12757 12758 /* Simulate and find potential out-of-bounds access under 12759 * speculative execution from truncation as a result of 12760 * masking when off was not within expected range. If off 12761 * sits in dst, then we temporarily need to move ptr there 12762 * to simulate dst (== 0) +/-= ptr. Needed, for example, 12763 * for cases where we use K-based arithmetic in one direction 12764 * and truncated reg-based in the other in order to explore 12765 * bad access. 12766 */ 12767 if (!ptr_is_dst_reg) { 12768 tmp = *dst_reg; 12769 copy_register_state(dst_reg, ptr_reg); 12770 } 12771 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 12772 env->insn_idx); 12773 if (!ptr_is_dst_reg && ret) 12774 *dst_reg = tmp; 12775 return !ret ? REASON_STACK : 0; 12776 } 12777 12778 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 12779 { 12780 struct bpf_verifier_state *vstate = env->cur_state; 12781 12782 /* If we simulate paths under speculation, we don't update the 12783 * insn as 'seen' such that when we verify unreachable paths in 12784 * the non-speculative domain, sanitize_dead_code() can still 12785 * rewrite/sanitize them. 12786 */ 12787 if (!vstate->speculative) 12788 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 12789 } 12790 12791 static int sanitize_err(struct bpf_verifier_env *env, 12792 const struct bpf_insn *insn, int reason, 12793 const struct bpf_reg_state *off_reg, 12794 const struct bpf_reg_state *dst_reg) 12795 { 12796 static const char *err = "pointer arithmetic with it prohibited for !root"; 12797 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 12798 u32 dst = insn->dst_reg, src = insn->src_reg; 12799 12800 switch (reason) { 12801 case REASON_BOUNDS: 12802 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 12803 off_reg == dst_reg ? dst : src, err); 12804 break; 12805 case REASON_TYPE: 12806 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 12807 off_reg == dst_reg ? src : dst, err); 12808 break; 12809 case REASON_PATHS: 12810 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 12811 dst, op, err); 12812 break; 12813 case REASON_LIMIT: 12814 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 12815 dst, op, err); 12816 break; 12817 case REASON_STACK: 12818 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 12819 dst, err); 12820 break; 12821 default: 12822 verbose(env, "verifier internal error: unknown reason (%d)\n", 12823 reason); 12824 break; 12825 } 12826 12827 return -EACCES; 12828 } 12829 12830 /* check that stack access falls within stack limits and that 'reg' doesn't 12831 * have a variable offset. 12832 * 12833 * Variable offset is prohibited for unprivileged mode for simplicity since it 12834 * requires corresponding support in Spectre masking for stack ALU. See also 12835 * retrieve_ptr_limit(). 12836 * 12837 * 12838 * 'off' includes 'reg->off'. 12839 */ 12840 static int check_stack_access_for_ptr_arithmetic( 12841 struct bpf_verifier_env *env, 12842 int regno, 12843 const struct bpf_reg_state *reg, 12844 int off) 12845 { 12846 if (!tnum_is_const(reg->var_off)) { 12847 char tn_buf[48]; 12848 12849 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 12850 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 12851 regno, tn_buf, off); 12852 return -EACCES; 12853 } 12854 12855 if (off >= 0 || off < -MAX_BPF_STACK) { 12856 verbose(env, "R%d stack pointer arithmetic goes out of range, " 12857 "prohibited for !root; off=%d\n", regno, off); 12858 return -EACCES; 12859 } 12860 12861 return 0; 12862 } 12863 12864 static int sanitize_check_bounds(struct bpf_verifier_env *env, 12865 const struct bpf_insn *insn, 12866 const struct bpf_reg_state *dst_reg) 12867 { 12868 u32 dst = insn->dst_reg; 12869 12870 /* For unprivileged we require that resulting offset must be in bounds 12871 * in order to be able to sanitize access later on. 12872 */ 12873 if (env->bypass_spec_v1) 12874 return 0; 12875 12876 switch (dst_reg->type) { 12877 case PTR_TO_STACK: 12878 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 12879 dst_reg->off + dst_reg->var_off.value)) 12880 return -EACCES; 12881 break; 12882 case PTR_TO_MAP_VALUE: 12883 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 12884 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 12885 "prohibited for !root\n", dst); 12886 return -EACCES; 12887 } 12888 break; 12889 default: 12890 break; 12891 } 12892 12893 return 0; 12894 } 12895 12896 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 12897 * Caller should also handle BPF_MOV case separately. 12898 * If we return -EACCES, caller may want to try again treating pointer as a 12899 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 12900 */ 12901 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 12902 struct bpf_insn *insn, 12903 const struct bpf_reg_state *ptr_reg, 12904 const struct bpf_reg_state *off_reg) 12905 { 12906 struct bpf_verifier_state *vstate = env->cur_state; 12907 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12908 struct bpf_reg_state *regs = state->regs, *dst_reg; 12909 bool known = tnum_is_const(off_reg->var_off); 12910 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 12911 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 12912 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 12913 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 12914 struct bpf_sanitize_info info = {}; 12915 u8 opcode = BPF_OP(insn->code); 12916 u32 dst = insn->dst_reg; 12917 int ret; 12918 12919 dst_reg = ®s[dst]; 12920 12921 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 12922 smin_val > smax_val || umin_val > umax_val) { 12923 /* Taint dst register if offset had invalid bounds derived from 12924 * e.g. dead branches. 12925 */ 12926 __mark_reg_unknown(env, dst_reg); 12927 return 0; 12928 } 12929 12930 if (BPF_CLASS(insn->code) != BPF_ALU64) { 12931 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 12932 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12933 __mark_reg_unknown(env, dst_reg); 12934 return 0; 12935 } 12936 12937 verbose(env, 12938 "R%d 32-bit pointer arithmetic prohibited\n", 12939 dst); 12940 return -EACCES; 12941 } 12942 12943 if (ptr_reg->type & PTR_MAYBE_NULL) { 12944 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 12945 dst, reg_type_str(env, ptr_reg->type)); 12946 return -EACCES; 12947 } 12948 12949 switch (base_type(ptr_reg->type)) { 12950 case PTR_TO_CTX: 12951 case PTR_TO_MAP_VALUE: 12952 case PTR_TO_MAP_KEY: 12953 case PTR_TO_STACK: 12954 case PTR_TO_PACKET_META: 12955 case PTR_TO_PACKET: 12956 case PTR_TO_TP_BUFFER: 12957 case PTR_TO_BTF_ID: 12958 case PTR_TO_MEM: 12959 case PTR_TO_BUF: 12960 case PTR_TO_FUNC: 12961 case CONST_PTR_TO_DYNPTR: 12962 break; 12963 case PTR_TO_FLOW_KEYS: 12964 if (known) 12965 break; 12966 fallthrough; 12967 case CONST_PTR_TO_MAP: 12968 /* smin_val represents the known value */ 12969 if (known && smin_val == 0 && opcode == BPF_ADD) 12970 break; 12971 fallthrough; 12972 default: 12973 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 12974 dst, reg_type_str(env, ptr_reg->type)); 12975 return -EACCES; 12976 } 12977 12978 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 12979 * The id may be overwritten later if we create a new variable offset. 12980 */ 12981 dst_reg->type = ptr_reg->type; 12982 dst_reg->id = ptr_reg->id; 12983 12984 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 12985 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 12986 return -EINVAL; 12987 12988 /* pointer types do not carry 32-bit bounds at the moment. */ 12989 __mark_reg32_unbounded(dst_reg); 12990 12991 if (sanitize_needed(opcode)) { 12992 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 12993 &info, false); 12994 if (ret < 0) 12995 return sanitize_err(env, insn, ret, off_reg, dst_reg); 12996 } 12997 12998 switch (opcode) { 12999 case BPF_ADD: 13000 /* We can take a fixed offset as long as it doesn't overflow 13001 * the s32 'off' field 13002 */ 13003 if (known && (ptr_reg->off + smin_val == 13004 (s64)(s32)(ptr_reg->off + smin_val))) { 13005 /* pointer += K. Accumulate it into fixed offset */ 13006 dst_reg->smin_value = smin_ptr; 13007 dst_reg->smax_value = smax_ptr; 13008 dst_reg->umin_value = umin_ptr; 13009 dst_reg->umax_value = umax_ptr; 13010 dst_reg->var_off = ptr_reg->var_off; 13011 dst_reg->off = ptr_reg->off + smin_val; 13012 dst_reg->raw = ptr_reg->raw; 13013 break; 13014 } 13015 /* A new variable offset is created. Note that off_reg->off 13016 * == 0, since it's a scalar. 13017 * dst_reg gets the pointer type and since some positive 13018 * integer value was added to the pointer, give it a new 'id' 13019 * if it's a PTR_TO_PACKET. 13020 * this creates a new 'base' pointer, off_reg (variable) gets 13021 * added into the variable offset, and we copy the fixed offset 13022 * from ptr_reg. 13023 */ 13024 if (signed_add_overflows(smin_ptr, smin_val) || 13025 signed_add_overflows(smax_ptr, smax_val)) { 13026 dst_reg->smin_value = S64_MIN; 13027 dst_reg->smax_value = S64_MAX; 13028 } else { 13029 dst_reg->smin_value = smin_ptr + smin_val; 13030 dst_reg->smax_value = smax_ptr + smax_val; 13031 } 13032 if (umin_ptr + umin_val < umin_ptr || 13033 umax_ptr + umax_val < umax_ptr) { 13034 dst_reg->umin_value = 0; 13035 dst_reg->umax_value = U64_MAX; 13036 } else { 13037 dst_reg->umin_value = umin_ptr + umin_val; 13038 dst_reg->umax_value = umax_ptr + umax_val; 13039 } 13040 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 13041 dst_reg->off = ptr_reg->off; 13042 dst_reg->raw = ptr_reg->raw; 13043 if (reg_is_pkt_pointer(ptr_reg)) { 13044 dst_reg->id = ++env->id_gen; 13045 /* something was added to pkt_ptr, set range to zero */ 13046 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13047 } 13048 break; 13049 case BPF_SUB: 13050 if (dst_reg == off_reg) { 13051 /* scalar -= pointer. Creates an unknown scalar */ 13052 verbose(env, "R%d tried to subtract pointer from scalar\n", 13053 dst); 13054 return -EACCES; 13055 } 13056 /* We don't allow subtraction from FP, because (according to 13057 * test_verifier.c test "invalid fp arithmetic", JITs might not 13058 * be able to deal with it. 13059 */ 13060 if (ptr_reg->type == PTR_TO_STACK) { 13061 verbose(env, "R%d subtraction from stack pointer prohibited\n", 13062 dst); 13063 return -EACCES; 13064 } 13065 if (known && (ptr_reg->off - smin_val == 13066 (s64)(s32)(ptr_reg->off - smin_val))) { 13067 /* pointer -= K. Subtract it from fixed offset */ 13068 dst_reg->smin_value = smin_ptr; 13069 dst_reg->smax_value = smax_ptr; 13070 dst_reg->umin_value = umin_ptr; 13071 dst_reg->umax_value = umax_ptr; 13072 dst_reg->var_off = ptr_reg->var_off; 13073 dst_reg->id = ptr_reg->id; 13074 dst_reg->off = ptr_reg->off - smin_val; 13075 dst_reg->raw = ptr_reg->raw; 13076 break; 13077 } 13078 /* A new variable offset is created. If the subtrahend is known 13079 * nonnegative, then any reg->range we had before is still good. 13080 */ 13081 if (signed_sub_overflows(smin_ptr, smax_val) || 13082 signed_sub_overflows(smax_ptr, smin_val)) { 13083 /* Overflow possible, we know nothing */ 13084 dst_reg->smin_value = S64_MIN; 13085 dst_reg->smax_value = S64_MAX; 13086 } else { 13087 dst_reg->smin_value = smin_ptr - smax_val; 13088 dst_reg->smax_value = smax_ptr - smin_val; 13089 } 13090 if (umin_ptr < umax_val) { 13091 /* Overflow possible, we know nothing */ 13092 dst_reg->umin_value = 0; 13093 dst_reg->umax_value = U64_MAX; 13094 } else { 13095 /* Cannot overflow (as long as bounds are consistent) */ 13096 dst_reg->umin_value = umin_ptr - umax_val; 13097 dst_reg->umax_value = umax_ptr - umin_val; 13098 } 13099 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 13100 dst_reg->off = ptr_reg->off; 13101 dst_reg->raw = ptr_reg->raw; 13102 if (reg_is_pkt_pointer(ptr_reg)) { 13103 dst_reg->id = ++env->id_gen; 13104 /* something was added to pkt_ptr, set range to zero */ 13105 if (smin_val < 0) 13106 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 13107 } 13108 break; 13109 case BPF_AND: 13110 case BPF_OR: 13111 case BPF_XOR: 13112 /* bitwise ops on pointers are troublesome, prohibit. */ 13113 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 13114 dst, bpf_alu_string[opcode >> 4]); 13115 return -EACCES; 13116 default: 13117 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 13118 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 13119 dst, bpf_alu_string[opcode >> 4]); 13120 return -EACCES; 13121 } 13122 13123 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 13124 return -EINVAL; 13125 reg_bounds_sync(dst_reg); 13126 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 13127 return -EACCES; 13128 if (sanitize_needed(opcode)) { 13129 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 13130 &info, true); 13131 if (ret < 0) 13132 return sanitize_err(env, insn, ret, off_reg, dst_reg); 13133 } 13134 13135 return 0; 13136 } 13137 13138 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 13139 struct bpf_reg_state *src_reg) 13140 { 13141 s32 smin_val = src_reg->s32_min_value; 13142 s32 smax_val = src_reg->s32_max_value; 13143 u32 umin_val = src_reg->u32_min_value; 13144 u32 umax_val = src_reg->u32_max_value; 13145 13146 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 13147 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 13148 dst_reg->s32_min_value = S32_MIN; 13149 dst_reg->s32_max_value = S32_MAX; 13150 } else { 13151 dst_reg->s32_min_value += smin_val; 13152 dst_reg->s32_max_value += smax_val; 13153 } 13154 if (dst_reg->u32_min_value + umin_val < umin_val || 13155 dst_reg->u32_max_value + umax_val < umax_val) { 13156 dst_reg->u32_min_value = 0; 13157 dst_reg->u32_max_value = U32_MAX; 13158 } else { 13159 dst_reg->u32_min_value += umin_val; 13160 dst_reg->u32_max_value += umax_val; 13161 } 13162 } 13163 13164 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 13165 struct bpf_reg_state *src_reg) 13166 { 13167 s64 smin_val = src_reg->smin_value; 13168 s64 smax_val = src_reg->smax_value; 13169 u64 umin_val = src_reg->umin_value; 13170 u64 umax_val = src_reg->umax_value; 13171 13172 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 13173 signed_add_overflows(dst_reg->smax_value, smax_val)) { 13174 dst_reg->smin_value = S64_MIN; 13175 dst_reg->smax_value = S64_MAX; 13176 } else { 13177 dst_reg->smin_value += smin_val; 13178 dst_reg->smax_value += smax_val; 13179 } 13180 if (dst_reg->umin_value + umin_val < umin_val || 13181 dst_reg->umax_value + umax_val < umax_val) { 13182 dst_reg->umin_value = 0; 13183 dst_reg->umax_value = U64_MAX; 13184 } else { 13185 dst_reg->umin_value += umin_val; 13186 dst_reg->umax_value += umax_val; 13187 } 13188 } 13189 13190 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 13191 struct bpf_reg_state *src_reg) 13192 { 13193 s32 smin_val = src_reg->s32_min_value; 13194 s32 smax_val = src_reg->s32_max_value; 13195 u32 umin_val = src_reg->u32_min_value; 13196 u32 umax_val = src_reg->u32_max_value; 13197 13198 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 13199 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 13200 /* Overflow possible, we know nothing */ 13201 dst_reg->s32_min_value = S32_MIN; 13202 dst_reg->s32_max_value = S32_MAX; 13203 } else { 13204 dst_reg->s32_min_value -= smax_val; 13205 dst_reg->s32_max_value -= smin_val; 13206 } 13207 if (dst_reg->u32_min_value < umax_val) { 13208 /* Overflow possible, we know nothing */ 13209 dst_reg->u32_min_value = 0; 13210 dst_reg->u32_max_value = U32_MAX; 13211 } else { 13212 /* Cannot overflow (as long as bounds are consistent) */ 13213 dst_reg->u32_min_value -= umax_val; 13214 dst_reg->u32_max_value -= umin_val; 13215 } 13216 } 13217 13218 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 13219 struct bpf_reg_state *src_reg) 13220 { 13221 s64 smin_val = src_reg->smin_value; 13222 s64 smax_val = src_reg->smax_value; 13223 u64 umin_val = src_reg->umin_value; 13224 u64 umax_val = src_reg->umax_value; 13225 13226 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 13227 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 13228 /* Overflow possible, we know nothing */ 13229 dst_reg->smin_value = S64_MIN; 13230 dst_reg->smax_value = S64_MAX; 13231 } else { 13232 dst_reg->smin_value -= smax_val; 13233 dst_reg->smax_value -= smin_val; 13234 } 13235 if (dst_reg->umin_value < umax_val) { 13236 /* Overflow possible, we know nothing */ 13237 dst_reg->umin_value = 0; 13238 dst_reg->umax_value = U64_MAX; 13239 } else { 13240 /* Cannot overflow (as long as bounds are consistent) */ 13241 dst_reg->umin_value -= umax_val; 13242 dst_reg->umax_value -= umin_val; 13243 } 13244 } 13245 13246 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 13247 struct bpf_reg_state *src_reg) 13248 { 13249 s32 smin_val = src_reg->s32_min_value; 13250 u32 umin_val = src_reg->u32_min_value; 13251 u32 umax_val = src_reg->u32_max_value; 13252 13253 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 13254 /* Ain't nobody got time to multiply that sign */ 13255 __mark_reg32_unbounded(dst_reg); 13256 return; 13257 } 13258 /* Both values are positive, so we can work with unsigned and 13259 * copy the result to signed (unless it exceeds S32_MAX). 13260 */ 13261 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 13262 /* Potential overflow, we know nothing */ 13263 __mark_reg32_unbounded(dst_reg); 13264 return; 13265 } 13266 dst_reg->u32_min_value *= umin_val; 13267 dst_reg->u32_max_value *= umax_val; 13268 if (dst_reg->u32_max_value > S32_MAX) { 13269 /* Overflow possible, we know nothing */ 13270 dst_reg->s32_min_value = S32_MIN; 13271 dst_reg->s32_max_value = S32_MAX; 13272 } else { 13273 dst_reg->s32_min_value = dst_reg->u32_min_value; 13274 dst_reg->s32_max_value = dst_reg->u32_max_value; 13275 } 13276 } 13277 13278 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 13279 struct bpf_reg_state *src_reg) 13280 { 13281 s64 smin_val = src_reg->smin_value; 13282 u64 umin_val = src_reg->umin_value; 13283 u64 umax_val = src_reg->umax_value; 13284 13285 if (smin_val < 0 || dst_reg->smin_value < 0) { 13286 /* Ain't nobody got time to multiply that sign */ 13287 __mark_reg64_unbounded(dst_reg); 13288 return; 13289 } 13290 /* Both values are positive, so we can work with unsigned and 13291 * copy the result to signed (unless it exceeds S64_MAX). 13292 */ 13293 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 13294 /* Potential overflow, we know nothing */ 13295 __mark_reg64_unbounded(dst_reg); 13296 return; 13297 } 13298 dst_reg->umin_value *= umin_val; 13299 dst_reg->umax_value *= umax_val; 13300 if (dst_reg->umax_value > S64_MAX) { 13301 /* Overflow possible, we know nothing */ 13302 dst_reg->smin_value = S64_MIN; 13303 dst_reg->smax_value = S64_MAX; 13304 } else { 13305 dst_reg->smin_value = dst_reg->umin_value; 13306 dst_reg->smax_value = dst_reg->umax_value; 13307 } 13308 } 13309 13310 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 13311 struct bpf_reg_state *src_reg) 13312 { 13313 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13314 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13315 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13316 s32 smin_val = src_reg->s32_min_value; 13317 u32 umax_val = src_reg->u32_max_value; 13318 13319 if (src_known && dst_known) { 13320 __mark_reg32_known(dst_reg, var32_off.value); 13321 return; 13322 } 13323 13324 /* We get our minimum from the var_off, since that's inherently 13325 * bitwise. Our maximum is the minimum of the operands' maxima. 13326 */ 13327 dst_reg->u32_min_value = var32_off.value; 13328 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 13329 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13330 /* Lose signed bounds when ANDing negative numbers, 13331 * ain't nobody got time for that. 13332 */ 13333 dst_reg->s32_min_value = S32_MIN; 13334 dst_reg->s32_max_value = S32_MAX; 13335 } else { 13336 /* ANDing two positives gives a positive, so safe to 13337 * cast result into s64. 13338 */ 13339 dst_reg->s32_min_value = dst_reg->u32_min_value; 13340 dst_reg->s32_max_value = dst_reg->u32_max_value; 13341 } 13342 } 13343 13344 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 13345 struct bpf_reg_state *src_reg) 13346 { 13347 bool src_known = tnum_is_const(src_reg->var_off); 13348 bool dst_known = tnum_is_const(dst_reg->var_off); 13349 s64 smin_val = src_reg->smin_value; 13350 u64 umax_val = src_reg->umax_value; 13351 13352 if (src_known && dst_known) { 13353 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13354 return; 13355 } 13356 13357 /* We get our minimum from the var_off, since that's inherently 13358 * bitwise. Our maximum is the minimum of the operands' maxima. 13359 */ 13360 dst_reg->umin_value = dst_reg->var_off.value; 13361 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 13362 if (dst_reg->smin_value < 0 || smin_val < 0) { 13363 /* Lose signed bounds when ANDing negative numbers, 13364 * ain't nobody got time for that. 13365 */ 13366 dst_reg->smin_value = S64_MIN; 13367 dst_reg->smax_value = S64_MAX; 13368 } else { 13369 /* ANDing two positives gives a positive, so safe to 13370 * cast result into s64. 13371 */ 13372 dst_reg->smin_value = dst_reg->umin_value; 13373 dst_reg->smax_value = dst_reg->umax_value; 13374 } 13375 /* We may learn something more from the var_off */ 13376 __update_reg_bounds(dst_reg); 13377 } 13378 13379 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 13380 struct bpf_reg_state *src_reg) 13381 { 13382 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13383 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13384 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13385 s32 smin_val = src_reg->s32_min_value; 13386 u32 umin_val = src_reg->u32_min_value; 13387 13388 if (src_known && dst_known) { 13389 __mark_reg32_known(dst_reg, var32_off.value); 13390 return; 13391 } 13392 13393 /* We get our maximum from the var_off, and our minimum is the 13394 * maximum of the operands' minima 13395 */ 13396 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 13397 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13398 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 13399 /* Lose signed bounds when ORing negative numbers, 13400 * ain't nobody got time for that. 13401 */ 13402 dst_reg->s32_min_value = S32_MIN; 13403 dst_reg->s32_max_value = S32_MAX; 13404 } else { 13405 /* ORing two positives gives a positive, so safe to 13406 * cast result into s64. 13407 */ 13408 dst_reg->s32_min_value = dst_reg->u32_min_value; 13409 dst_reg->s32_max_value = dst_reg->u32_max_value; 13410 } 13411 } 13412 13413 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 13414 struct bpf_reg_state *src_reg) 13415 { 13416 bool src_known = tnum_is_const(src_reg->var_off); 13417 bool dst_known = tnum_is_const(dst_reg->var_off); 13418 s64 smin_val = src_reg->smin_value; 13419 u64 umin_val = src_reg->umin_value; 13420 13421 if (src_known && dst_known) { 13422 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13423 return; 13424 } 13425 13426 /* We get our maximum from the var_off, and our minimum is the 13427 * maximum of the operands' minima 13428 */ 13429 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 13430 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13431 if (dst_reg->smin_value < 0 || smin_val < 0) { 13432 /* Lose signed bounds when ORing negative numbers, 13433 * ain't nobody got time for that. 13434 */ 13435 dst_reg->smin_value = S64_MIN; 13436 dst_reg->smax_value = S64_MAX; 13437 } else { 13438 /* ORing two positives gives a positive, so safe to 13439 * cast result into s64. 13440 */ 13441 dst_reg->smin_value = dst_reg->umin_value; 13442 dst_reg->smax_value = dst_reg->umax_value; 13443 } 13444 /* We may learn something more from the var_off */ 13445 __update_reg_bounds(dst_reg); 13446 } 13447 13448 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 13449 struct bpf_reg_state *src_reg) 13450 { 13451 bool src_known = tnum_subreg_is_const(src_reg->var_off); 13452 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 13453 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 13454 s32 smin_val = src_reg->s32_min_value; 13455 13456 if (src_known && dst_known) { 13457 __mark_reg32_known(dst_reg, var32_off.value); 13458 return; 13459 } 13460 13461 /* We get both minimum and maximum from the var32_off. */ 13462 dst_reg->u32_min_value = var32_off.value; 13463 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 13464 13465 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 13466 /* XORing two positive sign numbers gives a positive, 13467 * so safe to cast u32 result into s32. 13468 */ 13469 dst_reg->s32_min_value = dst_reg->u32_min_value; 13470 dst_reg->s32_max_value = dst_reg->u32_max_value; 13471 } else { 13472 dst_reg->s32_min_value = S32_MIN; 13473 dst_reg->s32_max_value = S32_MAX; 13474 } 13475 } 13476 13477 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 13478 struct bpf_reg_state *src_reg) 13479 { 13480 bool src_known = tnum_is_const(src_reg->var_off); 13481 bool dst_known = tnum_is_const(dst_reg->var_off); 13482 s64 smin_val = src_reg->smin_value; 13483 13484 if (src_known && dst_known) { 13485 /* dst_reg->var_off.value has been updated earlier */ 13486 __mark_reg_known(dst_reg, dst_reg->var_off.value); 13487 return; 13488 } 13489 13490 /* We get both minimum and maximum from the var_off. */ 13491 dst_reg->umin_value = dst_reg->var_off.value; 13492 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 13493 13494 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 13495 /* XORing two positive sign numbers gives a positive, 13496 * so safe to cast u64 result into s64. 13497 */ 13498 dst_reg->smin_value = dst_reg->umin_value; 13499 dst_reg->smax_value = dst_reg->umax_value; 13500 } else { 13501 dst_reg->smin_value = S64_MIN; 13502 dst_reg->smax_value = S64_MAX; 13503 } 13504 13505 __update_reg_bounds(dst_reg); 13506 } 13507 13508 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13509 u64 umin_val, u64 umax_val) 13510 { 13511 /* We lose all sign bit information (except what we can pick 13512 * up from var_off) 13513 */ 13514 dst_reg->s32_min_value = S32_MIN; 13515 dst_reg->s32_max_value = S32_MAX; 13516 /* If we might shift our top bit out, then we know nothing */ 13517 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 13518 dst_reg->u32_min_value = 0; 13519 dst_reg->u32_max_value = U32_MAX; 13520 } else { 13521 dst_reg->u32_min_value <<= umin_val; 13522 dst_reg->u32_max_value <<= umax_val; 13523 } 13524 } 13525 13526 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 13527 struct bpf_reg_state *src_reg) 13528 { 13529 u32 umax_val = src_reg->u32_max_value; 13530 u32 umin_val = src_reg->u32_min_value; 13531 /* u32 alu operation will zext upper bits */ 13532 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13533 13534 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13535 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 13536 /* Not required but being careful mark reg64 bounds as unknown so 13537 * that we are forced to pick them up from tnum and zext later and 13538 * if some path skips this step we are still safe. 13539 */ 13540 __mark_reg64_unbounded(dst_reg); 13541 __update_reg32_bounds(dst_reg); 13542 } 13543 13544 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 13545 u64 umin_val, u64 umax_val) 13546 { 13547 /* Special case <<32 because it is a common compiler pattern to sign 13548 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 13549 * positive we know this shift will also be positive so we can track 13550 * bounds correctly. Otherwise we lose all sign bit information except 13551 * what we can pick up from var_off. Perhaps we can generalize this 13552 * later to shifts of any length. 13553 */ 13554 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 13555 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 13556 else 13557 dst_reg->smax_value = S64_MAX; 13558 13559 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 13560 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 13561 else 13562 dst_reg->smin_value = S64_MIN; 13563 13564 /* If we might shift our top bit out, then we know nothing */ 13565 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 13566 dst_reg->umin_value = 0; 13567 dst_reg->umax_value = U64_MAX; 13568 } else { 13569 dst_reg->umin_value <<= umin_val; 13570 dst_reg->umax_value <<= umax_val; 13571 } 13572 } 13573 13574 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 13575 struct bpf_reg_state *src_reg) 13576 { 13577 u64 umax_val = src_reg->umax_value; 13578 u64 umin_val = src_reg->umin_value; 13579 13580 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 13581 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 13582 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 13583 13584 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 13585 /* We may learn something more from the var_off */ 13586 __update_reg_bounds(dst_reg); 13587 } 13588 13589 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 13590 struct bpf_reg_state *src_reg) 13591 { 13592 struct tnum subreg = tnum_subreg(dst_reg->var_off); 13593 u32 umax_val = src_reg->u32_max_value; 13594 u32 umin_val = src_reg->u32_min_value; 13595 13596 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13597 * be negative, then either: 13598 * 1) src_reg might be zero, so the sign bit of the result is 13599 * unknown, so we lose our signed bounds 13600 * 2) it's known negative, thus the unsigned bounds capture the 13601 * signed bounds 13602 * 3) the signed bounds cross zero, so they tell us nothing 13603 * about the result 13604 * If the value in dst_reg is known nonnegative, then again the 13605 * unsigned bounds capture the signed bounds. 13606 * Thus, in all cases it suffices to blow away our signed bounds 13607 * and rely on inferring new ones from the unsigned bounds and 13608 * var_off of the result. 13609 */ 13610 dst_reg->s32_min_value = S32_MIN; 13611 dst_reg->s32_max_value = S32_MAX; 13612 13613 dst_reg->var_off = tnum_rshift(subreg, umin_val); 13614 dst_reg->u32_min_value >>= umax_val; 13615 dst_reg->u32_max_value >>= umin_val; 13616 13617 __mark_reg64_unbounded(dst_reg); 13618 __update_reg32_bounds(dst_reg); 13619 } 13620 13621 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 13622 struct bpf_reg_state *src_reg) 13623 { 13624 u64 umax_val = src_reg->umax_value; 13625 u64 umin_val = src_reg->umin_value; 13626 13627 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 13628 * be negative, then either: 13629 * 1) src_reg might be zero, so the sign bit of the result is 13630 * unknown, so we lose our signed bounds 13631 * 2) it's known negative, thus the unsigned bounds capture the 13632 * signed bounds 13633 * 3) the signed bounds cross zero, so they tell us nothing 13634 * about the result 13635 * If the value in dst_reg is known nonnegative, then again the 13636 * unsigned bounds capture the signed bounds. 13637 * Thus, in all cases it suffices to blow away our signed bounds 13638 * and rely on inferring new ones from the unsigned bounds and 13639 * var_off of the result. 13640 */ 13641 dst_reg->smin_value = S64_MIN; 13642 dst_reg->smax_value = S64_MAX; 13643 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 13644 dst_reg->umin_value >>= umax_val; 13645 dst_reg->umax_value >>= umin_val; 13646 13647 /* Its not easy to operate on alu32 bounds here because it depends 13648 * on bits being shifted in. Take easy way out and mark unbounded 13649 * so we can recalculate later from tnum. 13650 */ 13651 __mark_reg32_unbounded(dst_reg); 13652 __update_reg_bounds(dst_reg); 13653 } 13654 13655 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 13656 struct bpf_reg_state *src_reg) 13657 { 13658 u64 umin_val = src_reg->u32_min_value; 13659 13660 /* Upon reaching here, src_known is true and 13661 * umax_val is equal to umin_val. 13662 */ 13663 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 13664 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 13665 13666 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 13667 13668 /* blow away the dst_reg umin_value/umax_value and rely on 13669 * dst_reg var_off to refine the result. 13670 */ 13671 dst_reg->u32_min_value = 0; 13672 dst_reg->u32_max_value = U32_MAX; 13673 13674 __mark_reg64_unbounded(dst_reg); 13675 __update_reg32_bounds(dst_reg); 13676 } 13677 13678 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 13679 struct bpf_reg_state *src_reg) 13680 { 13681 u64 umin_val = src_reg->umin_value; 13682 13683 /* Upon reaching here, src_known is true and umax_val is equal 13684 * to umin_val. 13685 */ 13686 dst_reg->smin_value >>= umin_val; 13687 dst_reg->smax_value >>= umin_val; 13688 13689 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 13690 13691 /* blow away the dst_reg umin_value/umax_value and rely on 13692 * dst_reg var_off to refine the result. 13693 */ 13694 dst_reg->umin_value = 0; 13695 dst_reg->umax_value = U64_MAX; 13696 13697 /* Its not easy to operate on alu32 bounds here because it depends 13698 * on bits being shifted in from upper 32-bits. Take easy way out 13699 * and mark unbounded so we can recalculate later from tnum. 13700 */ 13701 __mark_reg32_unbounded(dst_reg); 13702 __update_reg_bounds(dst_reg); 13703 } 13704 13705 /* WARNING: This function does calculations on 64-bit values, but the actual 13706 * execution may occur on 32-bit values. Therefore, things like bitshifts 13707 * need extra checks in the 32-bit case. 13708 */ 13709 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 13710 struct bpf_insn *insn, 13711 struct bpf_reg_state *dst_reg, 13712 struct bpf_reg_state src_reg) 13713 { 13714 struct bpf_reg_state *regs = cur_regs(env); 13715 u8 opcode = BPF_OP(insn->code); 13716 bool src_known; 13717 s64 smin_val, smax_val; 13718 u64 umin_val, umax_val; 13719 s32 s32_min_val, s32_max_val; 13720 u32 u32_min_val, u32_max_val; 13721 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 13722 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 13723 int ret; 13724 13725 smin_val = src_reg.smin_value; 13726 smax_val = src_reg.smax_value; 13727 umin_val = src_reg.umin_value; 13728 umax_val = src_reg.umax_value; 13729 13730 s32_min_val = src_reg.s32_min_value; 13731 s32_max_val = src_reg.s32_max_value; 13732 u32_min_val = src_reg.u32_min_value; 13733 u32_max_val = src_reg.u32_max_value; 13734 13735 if (alu32) { 13736 src_known = tnum_subreg_is_const(src_reg.var_off); 13737 if ((src_known && 13738 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 13739 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 13740 /* Taint dst register if offset had invalid bounds 13741 * derived from e.g. dead branches. 13742 */ 13743 __mark_reg_unknown(env, dst_reg); 13744 return 0; 13745 } 13746 } else { 13747 src_known = tnum_is_const(src_reg.var_off); 13748 if ((src_known && 13749 (smin_val != smax_val || umin_val != umax_val)) || 13750 smin_val > smax_val || umin_val > umax_val) { 13751 /* Taint dst register if offset had invalid bounds 13752 * derived from e.g. dead branches. 13753 */ 13754 __mark_reg_unknown(env, dst_reg); 13755 return 0; 13756 } 13757 } 13758 13759 if (!src_known && 13760 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 13761 __mark_reg_unknown(env, dst_reg); 13762 return 0; 13763 } 13764 13765 if (sanitize_needed(opcode)) { 13766 ret = sanitize_val_alu(env, insn); 13767 if (ret < 0) 13768 return sanitize_err(env, insn, ret, NULL, NULL); 13769 } 13770 13771 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 13772 * There are two classes of instructions: The first class we track both 13773 * alu32 and alu64 sign/unsigned bounds independently this provides the 13774 * greatest amount of precision when alu operations are mixed with jmp32 13775 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 13776 * and BPF_OR. This is possible because these ops have fairly easy to 13777 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 13778 * See alu32 verifier tests for examples. The second class of 13779 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 13780 * with regards to tracking sign/unsigned bounds because the bits may 13781 * cross subreg boundaries in the alu64 case. When this happens we mark 13782 * the reg unbounded in the subreg bound space and use the resulting 13783 * tnum to calculate an approximation of the sign/unsigned bounds. 13784 */ 13785 switch (opcode) { 13786 case BPF_ADD: 13787 scalar32_min_max_add(dst_reg, &src_reg); 13788 scalar_min_max_add(dst_reg, &src_reg); 13789 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 13790 break; 13791 case BPF_SUB: 13792 scalar32_min_max_sub(dst_reg, &src_reg); 13793 scalar_min_max_sub(dst_reg, &src_reg); 13794 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 13795 break; 13796 case BPF_MUL: 13797 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 13798 scalar32_min_max_mul(dst_reg, &src_reg); 13799 scalar_min_max_mul(dst_reg, &src_reg); 13800 break; 13801 case BPF_AND: 13802 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 13803 scalar32_min_max_and(dst_reg, &src_reg); 13804 scalar_min_max_and(dst_reg, &src_reg); 13805 break; 13806 case BPF_OR: 13807 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 13808 scalar32_min_max_or(dst_reg, &src_reg); 13809 scalar_min_max_or(dst_reg, &src_reg); 13810 break; 13811 case BPF_XOR: 13812 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 13813 scalar32_min_max_xor(dst_reg, &src_reg); 13814 scalar_min_max_xor(dst_reg, &src_reg); 13815 break; 13816 case BPF_LSH: 13817 if (umax_val >= insn_bitness) { 13818 /* Shifts greater than 31 or 63 are undefined. 13819 * This includes shifts by a negative number. 13820 */ 13821 mark_reg_unknown(env, regs, insn->dst_reg); 13822 break; 13823 } 13824 if (alu32) 13825 scalar32_min_max_lsh(dst_reg, &src_reg); 13826 else 13827 scalar_min_max_lsh(dst_reg, &src_reg); 13828 break; 13829 case BPF_RSH: 13830 if (umax_val >= insn_bitness) { 13831 /* Shifts greater than 31 or 63 are undefined. 13832 * This includes shifts by a negative number. 13833 */ 13834 mark_reg_unknown(env, regs, insn->dst_reg); 13835 break; 13836 } 13837 if (alu32) 13838 scalar32_min_max_rsh(dst_reg, &src_reg); 13839 else 13840 scalar_min_max_rsh(dst_reg, &src_reg); 13841 break; 13842 case BPF_ARSH: 13843 if (umax_val >= insn_bitness) { 13844 /* Shifts greater than 31 or 63 are undefined. 13845 * This includes shifts by a negative number. 13846 */ 13847 mark_reg_unknown(env, regs, insn->dst_reg); 13848 break; 13849 } 13850 if (alu32) 13851 scalar32_min_max_arsh(dst_reg, &src_reg); 13852 else 13853 scalar_min_max_arsh(dst_reg, &src_reg); 13854 break; 13855 default: 13856 mark_reg_unknown(env, regs, insn->dst_reg); 13857 break; 13858 } 13859 13860 /* ALU32 ops are zero extended into 64bit register */ 13861 if (alu32) 13862 zext_32_to_64(dst_reg); 13863 reg_bounds_sync(dst_reg); 13864 return 0; 13865 } 13866 13867 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 13868 * and var_off. 13869 */ 13870 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 13871 struct bpf_insn *insn) 13872 { 13873 struct bpf_verifier_state *vstate = env->cur_state; 13874 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13875 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 13876 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 13877 u8 opcode = BPF_OP(insn->code); 13878 int err; 13879 13880 dst_reg = ®s[insn->dst_reg]; 13881 src_reg = NULL; 13882 13883 if (dst_reg->type == PTR_TO_ARENA) { 13884 struct bpf_insn_aux_data *aux = cur_aux(env); 13885 13886 if (BPF_CLASS(insn->code) == BPF_ALU64) 13887 /* 13888 * 32-bit operations zero upper bits automatically. 13889 * 64-bit operations need to be converted to 32. 13890 */ 13891 aux->needs_zext = true; 13892 13893 /* Any arithmetic operations are allowed on arena pointers */ 13894 return 0; 13895 } 13896 13897 if (dst_reg->type != SCALAR_VALUE) 13898 ptr_reg = dst_reg; 13899 else 13900 /* Make sure ID is cleared otherwise dst_reg min/max could be 13901 * incorrectly propagated into other registers by find_equal_scalars() 13902 */ 13903 dst_reg->id = 0; 13904 if (BPF_SRC(insn->code) == BPF_X) { 13905 src_reg = ®s[insn->src_reg]; 13906 if (src_reg->type != SCALAR_VALUE) { 13907 if (dst_reg->type != SCALAR_VALUE) { 13908 /* Combining two pointers by any ALU op yields 13909 * an arbitrary scalar. Disallow all math except 13910 * pointer subtraction 13911 */ 13912 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 13913 mark_reg_unknown(env, regs, insn->dst_reg); 13914 return 0; 13915 } 13916 verbose(env, "R%d pointer %s pointer prohibited\n", 13917 insn->dst_reg, 13918 bpf_alu_string[opcode >> 4]); 13919 return -EACCES; 13920 } else { 13921 /* scalar += pointer 13922 * This is legal, but we have to reverse our 13923 * src/dest handling in computing the range 13924 */ 13925 err = mark_chain_precision(env, insn->dst_reg); 13926 if (err) 13927 return err; 13928 return adjust_ptr_min_max_vals(env, insn, 13929 src_reg, dst_reg); 13930 } 13931 } else if (ptr_reg) { 13932 /* pointer += scalar */ 13933 err = mark_chain_precision(env, insn->src_reg); 13934 if (err) 13935 return err; 13936 return adjust_ptr_min_max_vals(env, insn, 13937 dst_reg, src_reg); 13938 } else if (dst_reg->precise) { 13939 /* if dst_reg is precise, src_reg should be precise as well */ 13940 err = mark_chain_precision(env, insn->src_reg); 13941 if (err) 13942 return err; 13943 } 13944 } else { 13945 /* Pretend the src is a reg with a known value, since we only 13946 * need to be able to read from this state. 13947 */ 13948 off_reg.type = SCALAR_VALUE; 13949 __mark_reg_known(&off_reg, insn->imm); 13950 src_reg = &off_reg; 13951 if (ptr_reg) /* pointer += K */ 13952 return adjust_ptr_min_max_vals(env, insn, 13953 ptr_reg, src_reg); 13954 } 13955 13956 /* Got here implies adding two SCALAR_VALUEs */ 13957 if (WARN_ON_ONCE(ptr_reg)) { 13958 print_verifier_state(env, state, true); 13959 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 13960 return -EINVAL; 13961 } 13962 if (WARN_ON(!src_reg)) { 13963 print_verifier_state(env, state, true); 13964 verbose(env, "verifier internal error: no src_reg\n"); 13965 return -EINVAL; 13966 } 13967 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 13968 } 13969 13970 /* check validity of 32-bit and 64-bit arithmetic operations */ 13971 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 13972 { 13973 struct bpf_reg_state *regs = cur_regs(env); 13974 u8 opcode = BPF_OP(insn->code); 13975 int err; 13976 13977 if (opcode == BPF_END || opcode == BPF_NEG) { 13978 if (opcode == BPF_NEG) { 13979 if (BPF_SRC(insn->code) != BPF_K || 13980 insn->src_reg != BPF_REG_0 || 13981 insn->off != 0 || insn->imm != 0) { 13982 verbose(env, "BPF_NEG uses reserved fields\n"); 13983 return -EINVAL; 13984 } 13985 } else { 13986 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 13987 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 13988 (BPF_CLASS(insn->code) == BPF_ALU64 && 13989 BPF_SRC(insn->code) != BPF_TO_LE)) { 13990 verbose(env, "BPF_END uses reserved fields\n"); 13991 return -EINVAL; 13992 } 13993 } 13994 13995 /* check src operand */ 13996 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13997 if (err) 13998 return err; 13999 14000 if (is_pointer_value(env, insn->dst_reg)) { 14001 verbose(env, "R%d pointer arithmetic prohibited\n", 14002 insn->dst_reg); 14003 return -EACCES; 14004 } 14005 14006 /* check dest operand */ 14007 err = check_reg_arg(env, insn->dst_reg, DST_OP); 14008 if (err) 14009 return err; 14010 14011 } else if (opcode == BPF_MOV) { 14012 14013 if (BPF_SRC(insn->code) == BPF_X) { 14014 if (BPF_CLASS(insn->code) == BPF_ALU) { 14015 if ((insn->off != 0 && insn->off != 8 && insn->off != 16) || 14016 insn->imm) { 14017 verbose(env, "BPF_MOV uses reserved fields\n"); 14018 return -EINVAL; 14019 } 14020 } else if (insn->off == BPF_ADDR_SPACE_CAST) { 14021 if (insn->imm != 1 && insn->imm != 1u << 16) { 14022 verbose(env, "addr_space_cast insn can only convert between address space 1 and 0\n"); 14023 return -EINVAL; 14024 } 14025 if (!env->prog->aux->arena) { 14026 verbose(env, "addr_space_cast insn can only be used in a program that has an associated arena\n"); 14027 return -EINVAL; 14028 } 14029 } else { 14030 if ((insn->off != 0 && insn->off != 8 && insn->off != 16 && 14031 insn->off != 32) || insn->imm) { 14032 verbose(env, "BPF_MOV uses reserved fields\n"); 14033 return -EINVAL; 14034 } 14035 } 14036 14037 /* check src operand */ 14038 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14039 if (err) 14040 return err; 14041 } else { 14042 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 14043 verbose(env, "BPF_MOV uses reserved fields\n"); 14044 return -EINVAL; 14045 } 14046 } 14047 14048 /* check dest operand, mark as required later */ 14049 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14050 if (err) 14051 return err; 14052 14053 if (BPF_SRC(insn->code) == BPF_X) { 14054 struct bpf_reg_state *src_reg = regs + insn->src_reg; 14055 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 14056 14057 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14058 if (insn->imm) { 14059 /* off == BPF_ADDR_SPACE_CAST */ 14060 mark_reg_unknown(env, regs, insn->dst_reg); 14061 if (insn->imm == 1) { /* cast from as(1) to as(0) */ 14062 dst_reg->type = PTR_TO_ARENA; 14063 /* PTR_TO_ARENA is 32-bit */ 14064 dst_reg->subreg_def = env->insn_idx + 1; 14065 } 14066 } else if (insn->off == 0) { 14067 /* case: R1 = R2 14068 * copy register state to dest reg 14069 */ 14070 assign_scalar_id_before_mov(env, src_reg); 14071 copy_register_state(dst_reg, src_reg); 14072 dst_reg->live |= REG_LIVE_WRITTEN; 14073 dst_reg->subreg_def = DEF_NOT_SUBREG; 14074 } else { 14075 /* case: R1 = (s8, s16 s32)R2 */ 14076 if (is_pointer_value(env, insn->src_reg)) { 14077 verbose(env, 14078 "R%d sign-extension part of pointer\n", 14079 insn->src_reg); 14080 return -EACCES; 14081 } else if (src_reg->type == SCALAR_VALUE) { 14082 bool no_sext; 14083 14084 no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14085 if (no_sext) 14086 assign_scalar_id_before_mov(env, src_reg); 14087 copy_register_state(dst_reg, src_reg); 14088 if (!no_sext) 14089 dst_reg->id = 0; 14090 coerce_reg_to_size_sx(dst_reg, insn->off >> 3); 14091 dst_reg->live |= REG_LIVE_WRITTEN; 14092 dst_reg->subreg_def = DEF_NOT_SUBREG; 14093 } else { 14094 mark_reg_unknown(env, regs, insn->dst_reg); 14095 } 14096 } 14097 } else { 14098 /* R1 = (u32) R2 */ 14099 if (is_pointer_value(env, insn->src_reg)) { 14100 verbose(env, 14101 "R%d partial copy of pointer\n", 14102 insn->src_reg); 14103 return -EACCES; 14104 } else if (src_reg->type == SCALAR_VALUE) { 14105 if (insn->off == 0) { 14106 bool is_src_reg_u32 = get_reg_width(src_reg) <= 32; 14107 14108 if (is_src_reg_u32) 14109 assign_scalar_id_before_mov(env, src_reg); 14110 copy_register_state(dst_reg, src_reg); 14111 /* Make sure ID is cleared if src_reg is not in u32 14112 * range otherwise dst_reg min/max could be incorrectly 14113 * propagated into src_reg by find_equal_scalars() 14114 */ 14115 if (!is_src_reg_u32) 14116 dst_reg->id = 0; 14117 dst_reg->live |= REG_LIVE_WRITTEN; 14118 dst_reg->subreg_def = env->insn_idx + 1; 14119 } else { 14120 /* case: W1 = (s8, s16)W2 */ 14121 bool no_sext = src_reg->umax_value < (1ULL << (insn->off - 1)); 14122 14123 if (no_sext) 14124 assign_scalar_id_before_mov(env, src_reg); 14125 copy_register_state(dst_reg, src_reg); 14126 if (!no_sext) 14127 dst_reg->id = 0; 14128 dst_reg->live |= REG_LIVE_WRITTEN; 14129 dst_reg->subreg_def = env->insn_idx + 1; 14130 coerce_subreg_to_size_sx(dst_reg, insn->off >> 3); 14131 } 14132 } else { 14133 mark_reg_unknown(env, regs, 14134 insn->dst_reg); 14135 } 14136 zext_32_to_64(dst_reg); 14137 reg_bounds_sync(dst_reg); 14138 } 14139 } else { 14140 /* case: R = imm 14141 * remember the value we stored into this reg 14142 */ 14143 /* clear any state __mark_reg_known doesn't set */ 14144 mark_reg_unknown(env, regs, insn->dst_reg); 14145 regs[insn->dst_reg].type = SCALAR_VALUE; 14146 if (BPF_CLASS(insn->code) == BPF_ALU64) { 14147 __mark_reg_known(regs + insn->dst_reg, 14148 insn->imm); 14149 } else { 14150 __mark_reg_known(regs + insn->dst_reg, 14151 (u32)insn->imm); 14152 } 14153 } 14154 14155 } else if (opcode > BPF_END) { 14156 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 14157 return -EINVAL; 14158 14159 } else { /* all other ALU ops: and, sub, xor, add, ... */ 14160 14161 if (BPF_SRC(insn->code) == BPF_X) { 14162 if (insn->imm != 0 || insn->off > 1 || 14163 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14164 verbose(env, "BPF_ALU uses reserved fields\n"); 14165 return -EINVAL; 14166 } 14167 /* check src1 operand */ 14168 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14169 if (err) 14170 return err; 14171 } else { 14172 if (insn->src_reg != BPF_REG_0 || insn->off > 1 || 14173 (insn->off == 1 && opcode != BPF_MOD && opcode != BPF_DIV)) { 14174 verbose(env, "BPF_ALU uses reserved fields\n"); 14175 return -EINVAL; 14176 } 14177 } 14178 14179 /* check src2 operand */ 14180 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14181 if (err) 14182 return err; 14183 14184 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 14185 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 14186 verbose(env, "div by zero\n"); 14187 return -EINVAL; 14188 } 14189 14190 if ((opcode == BPF_LSH || opcode == BPF_RSH || 14191 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 14192 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 14193 14194 if (insn->imm < 0 || insn->imm >= size) { 14195 verbose(env, "invalid shift %d\n", insn->imm); 14196 return -EINVAL; 14197 } 14198 } 14199 14200 /* check dest operand */ 14201 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14202 err = err ?: adjust_reg_min_max_vals(env, insn); 14203 if (err) 14204 return err; 14205 } 14206 14207 return reg_bounds_sanity_check(env, ®s[insn->dst_reg], "alu"); 14208 } 14209 14210 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 14211 struct bpf_reg_state *dst_reg, 14212 enum bpf_reg_type type, 14213 bool range_right_open) 14214 { 14215 struct bpf_func_state *state; 14216 struct bpf_reg_state *reg; 14217 int new_range; 14218 14219 if (dst_reg->off < 0 || 14220 (dst_reg->off == 0 && range_right_open)) 14221 /* This doesn't give us any range */ 14222 return; 14223 14224 if (dst_reg->umax_value > MAX_PACKET_OFF || 14225 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 14226 /* Risk of overflow. For instance, ptr + (1<<63) may be less 14227 * than pkt_end, but that's because it's also less than pkt. 14228 */ 14229 return; 14230 14231 new_range = dst_reg->off; 14232 if (range_right_open) 14233 new_range++; 14234 14235 /* Examples for register markings: 14236 * 14237 * pkt_data in dst register: 14238 * 14239 * r2 = r3; 14240 * r2 += 8; 14241 * if (r2 > pkt_end) goto <handle exception> 14242 * <access okay> 14243 * 14244 * r2 = r3; 14245 * r2 += 8; 14246 * if (r2 < pkt_end) goto <access okay> 14247 * <handle exception> 14248 * 14249 * Where: 14250 * r2 == dst_reg, pkt_end == src_reg 14251 * r2=pkt(id=n,off=8,r=0) 14252 * r3=pkt(id=n,off=0,r=0) 14253 * 14254 * pkt_data in src register: 14255 * 14256 * r2 = r3; 14257 * r2 += 8; 14258 * if (pkt_end >= r2) goto <access okay> 14259 * <handle exception> 14260 * 14261 * r2 = r3; 14262 * r2 += 8; 14263 * if (pkt_end <= r2) goto <handle exception> 14264 * <access okay> 14265 * 14266 * Where: 14267 * pkt_end == dst_reg, r2 == src_reg 14268 * r2=pkt(id=n,off=8,r=0) 14269 * r3=pkt(id=n,off=0,r=0) 14270 * 14271 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 14272 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 14273 * and [r3, r3 + 8-1) respectively is safe to access depending on 14274 * the check. 14275 */ 14276 14277 /* If our ids match, then we must have the same max_value. And we 14278 * don't care about the other reg's fixed offset, since if it's too big 14279 * the range won't allow anything. 14280 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 14281 */ 14282 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14283 if (reg->type == type && reg->id == dst_reg->id) 14284 /* keep the maximum range already checked */ 14285 reg->range = max(reg->range, new_range); 14286 })); 14287 } 14288 14289 /* 14290 * <reg1> <op> <reg2>, currently assuming reg2 is a constant 14291 */ 14292 static int is_scalar_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14293 u8 opcode, bool is_jmp32) 14294 { 14295 struct tnum t1 = is_jmp32 ? tnum_subreg(reg1->var_off) : reg1->var_off; 14296 struct tnum t2 = is_jmp32 ? tnum_subreg(reg2->var_off) : reg2->var_off; 14297 u64 umin1 = is_jmp32 ? (u64)reg1->u32_min_value : reg1->umin_value; 14298 u64 umax1 = is_jmp32 ? (u64)reg1->u32_max_value : reg1->umax_value; 14299 s64 smin1 = is_jmp32 ? (s64)reg1->s32_min_value : reg1->smin_value; 14300 s64 smax1 = is_jmp32 ? (s64)reg1->s32_max_value : reg1->smax_value; 14301 u64 umin2 = is_jmp32 ? (u64)reg2->u32_min_value : reg2->umin_value; 14302 u64 umax2 = is_jmp32 ? (u64)reg2->u32_max_value : reg2->umax_value; 14303 s64 smin2 = is_jmp32 ? (s64)reg2->s32_min_value : reg2->smin_value; 14304 s64 smax2 = is_jmp32 ? (s64)reg2->s32_max_value : reg2->smax_value; 14305 14306 switch (opcode) { 14307 case BPF_JEQ: 14308 /* constants, umin/umax and smin/smax checks would be 14309 * redundant in this case because they all should match 14310 */ 14311 if (tnum_is_const(t1) && tnum_is_const(t2)) 14312 return t1.value == t2.value; 14313 /* non-overlapping ranges */ 14314 if (umin1 > umax2 || umax1 < umin2) 14315 return 0; 14316 if (smin1 > smax2 || smax1 < smin2) 14317 return 0; 14318 if (!is_jmp32) { 14319 /* if 64-bit ranges are inconclusive, see if we can 14320 * utilize 32-bit subrange knowledge to eliminate 14321 * branches that can't be taken a priori 14322 */ 14323 if (reg1->u32_min_value > reg2->u32_max_value || 14324 reg1->u32_max_value < reg2->u32_min_value) 14325 return 0; 14326 if (reg1->s32_min_value > reg2->s32_max_value || 14327 reg1->s32_max_value < reg2->s32_min_value) 14328 return 0; 14329 } 14330 break; 14331 case BPF_JNE: 14332 /* constants, umin/umax and smin/smax checks would be 14333 * redundant in this case because they all should match 14334 */ 14335 if (tnum_is_const(t1) && tnum_is_const(t2)) 14336 return t1.value != t2.value; 14337 /* non-overlapping ranges */ 14338 if (umin1 > umax2 || umax1 < umin2) 14339 return 1; 14340 if (smin1 > smax2 || smax1 < smin2) 14341 return 1; 14342 if (!is_jmp32) { 14343 /* if 64-bit ranges are inconclusive, see if we can 14344 * utilize 32-bit subrange knowledge to eliminate 14345 * branches that can't be taken a priori 14346 */ 14347 if (reg1->u32_min_value > reg2->u32_max_value || 14348 reg1->u32_max_value < reg2->u32_min_value) 14349 return 1; 14350 if (reg1->s32_min_value > reg2->s32_max_value || 14351 reg1->s32_max_value < reg2->s32_min_value) 14352 return 1; 14353 } 14354 break; 14355 case BPF_JSET: 14356 if (!is_reg_const(reg2, is_jmp32)) { 14357 swap(reg1, reg2); 14358 swap(t1, t2); 14359 } 14360 if (!is_reg_const(reg2, is_jmp32)) 14361 return -1; 14362 if ((~t1.mask & t1.value) & t2.value) 14363 return 1; 14364 if (!((t1.mask | t1.value) & t2.value)) 14365 return 0; 14366 break; 14367 case BPF_JGT: 14368 if (umin1 > umax2) 14369 return 1; 14370 else if (umax1 <= umin2) 14371 return 0; 14372 break; 14373 case BPF_JSGT: 14374 if (smin1 > smax2) 14375 return 1; 14376 else if (smax1 <= smin2) 14377 return 0; 14378 break; 14379 case BPF_JLT: 14380 if (umax1 < umin2) 14381 return 1; 14382 else if (umin1 >= umax2) 14383 return 0; 14384 break; 14385 case BPF_JSLT: 14386 if (smax1 < smin2) 14387 return 1; 14388 else if (smin1 >= smax2) 14389 return 0; 14390 break; 14391 case BPF_JGE: 14392 if (umin1 >= umax2) 14393 return 1; 14394 else if (umax1 < umin2) 14395 return 0; 14396 break; 14397 case BPF_JSGE: 14398 if (smin1 >= smax2) 14399 return 1; 14400 else if (smax1 < smin2) 14401 return 0; 14402 break; 14403 case BPF_JLE: 14404 if (umax1 <= umin2) 14405 return 1; 14406 else if (umin1 > umax2) 14407 return 0; 14408 break; 14409 case BPF_JSLE: 14410 if (smax1 <= smin2) 14411 return 1; 14412 else if (smin1 > smax2) 14413 return 0; 14414 break; 14415 } 14416 14417 return -1; 14418 } 14419 14420 static int flip_opcode(u32 opcode) 14421 { 14422 /* How can we transform "a <op> b" into "b <op> a"? */ 14423 static const u8 opcode_flip[16] = { 14424 /* these stay the same */ 14425 [BPF_JEQ >> 4] = BPF_JEQ, 14426 [BPF_JNE >> 4] = BPF_JNE, 14427 [BPF_JSET >> 4] = BPF_JSET, 14428 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 14429 [BPF_JGE >> 4] = BPF_JLE, 14430 [BPF_JGT >> 4] = BPF_JLT, 14431 [BPF_JLE >> 4] = BPF_JGE, 14432 [BPF_JLT >> 4] = BPF_JGT, 14433 [BPF_JSGE >> 4] = BPF_JSLE, 14434 [BPF_JSGT >> 4] = BPF_JSLT, 14435 [BPF_JSLE >> 4] = BPF_JSGE, 14436 [BPF_JSLT >> 4] = BPF_JSGT 14437 }; 14438 return opcode_flip[opcode >> 4]; 14439 } 14440 14441 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 14442 struct bpf_reg_state *src_reg, 14443 u8 opcode) 14444 { 14445 struct bpf_reg_state *pkt; 14446 14447 if (src_reg->type == PTR_TO_PACKET_END) { 14448 pkt = dst_reg; 14449 } else if (dst_reg->type == PTR_TO_PACKET_END) { 14450 pkt = src_reg; 14451 opcode = flip_opcode(opcode); 14452 } else { 14453 return -1; 14454 } 14455 14456 if (pkt->range >= 0) 14457 return -1; 14458 14459 switch (opcode) { 14460 case BPF_JLE: 14461 /* pkt <= pkt_end */ 14462 fallthrough; 14463 case BPF_JGT: 14464 /* pkt > pkt_end */ 14465 if (pkt->range == BEYOND_PKT_END) 14466 /* pkt has at last one extra byte beyond pkt_end */ 14467 return opcode == BPF_JGT; 14468 break; 14469 case BPF_JLT: 14470 /* pkt < pkt_end */ 14471 fallthrough; 14472 case BPF_JGE: 14473 /* pkt >= pkt_end */ 14474 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 14475 return opcode == BPF_JGE; 14476 break; 14477 } 14478 return -1; 14479 } 14480 14481 /* compute branch direction of the expression "if (<reg1> opcode <reg2>) goto target;" 14482 * and return: 14483 * 1 - branch will be taken and "goto target" will be executed 14484 * 0 - branch will not be taken and fall-through to next insn 14485 * -1 - unknown. Example: "if (reg1 < 5)" is unknown when register value 14486 * range [0,10] 14487 */ 14488 static int is_branch_taken(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14489 u8 opcode, bool is_jmp32) 14490 { 14491 if (reg_is_pkt_pointer_any(reg1) && reg_is_pkt_pointer_any(reg2) && !is_jmp32) 14492 return is_pkt_ptr_branch_taken(reg1, reg2, opcode); 14493 14494 if (__is_pointer_value(false, reg1) || __is_pointer_value(false, reg2)) { 14495 u64 val; 14496 14497 /* arrange that reg2 is a scalar, and reg1 is a pointer */ 14498 if (!is_reg_const(reg2, is_jmp32)) { 14499 opcode = flip_opcode(opcode); 14500 swap(reg1, reg2); 14501 } 14502 /* and ensure that reg2 is a constant */ 14503 if (!is_reg_const(reg2, is_jmp32)) 14504 return -1; 14505 14506 if (!reg_not_null(reg1)) 14507 return -1; 14508 14509 /* If pointer is valid tests against zero will fail so we can 14510 * use this to direct branch taken. 14511 */ 14512 val = reg_const_value(reg2, is_jmp32); 14513 if (val != 0) 14514 return -1; 14515 14516 switch (opcode) { 14517 case BPF_JEQ: 14518 return 0; 14519 case BPF_JNE: 14520 return 1; 14521 default: 14522 return -1; 14523 } 14524 } 14525 14526 /* now deal with two scalars, but not necessarily constants */ 14527 return is_scalar_branch_taken(reg1, reg2, opcode, is_jmp32); 14528 } 14529 14530 /* Opcode that corresponds to a *false* branch condition. 14531 * E.g., if r1 < r2, then reverse (false) condition is r1 >= r2 14532 */ 14533 static u8 rev_opcode(u8 opcode) 14534 { 14535 switch (opcode) { 14536 case BPF_JEQ: return BPF_JNE; 14537 case BPF_JNE: return BPF_JEQ; 14538 /* JSET doesn't have it's reverse opcode in BPF, so add 14539 * BPF_X flag to denote the reverse of that operation 14540 */ 14541 case BPF_JSET: return BPF_JSET | BPF_X; 14542 case BPF_JSET | BPF_X: return BPF_JSET; 14543 case BPF_JGE: return BPF_JLT; 14544 case BPF_JGT: return BPF_JLE; 14545 case BPF_JLE: return BPF_JGT; 14546 case BPF_JLT: return BPF_JGE; 14547 case BPF_JSGE: return BPF_JSLT; 14548 case BPF_JSGT: return BPF_JSLE; 14549 case BPF_JSLE: return BPF_JSGT; 14550 case BPF_JSLT: return BPF_JSGE; 14551 default: return 0; 14552 } 14553 } 14554 14555 /* Refine range knowledge for <reg1> <op> <reg>2 conditional operation. */ 14556 static void regs_refine_cond_op(struct bpf_reg_state *reg1, struct bpf_reg_state *reg2, 14557 u8 opcode, bool is_jmp32) 14558 { 14559 struct tnum t; 14560 u64 val; 14561 14562 again: 14563 switch (opcode) { 14564 case BPF_JEQ: 14565 if (is_jmp32) { 14566 reg1->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14567 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14568 reg1->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14569 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14570 reg2->u32_min_value = reg1->u32_min_value; 14571 reg2->u32_max_value = reg1->u32_max_value; 14572 reg2->s32_min_value = reg1->s32_min_value; 14573 reg2->s32_max_value = reg1->s32_max_value; 14574 14575 t = tnum_intersect(tnum_subreg(reg1->var_off), tnum_subreg(reg2->var_off)); 14576 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14577 reg2->var_off = tnum_with_subreg(reg2->var_off, t); 14578 } else { 14579 reg1->umin_value = max(reg1->umin_value, reg2->umin_value); 14580 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14581 reg1->smin_value = max(reg1->smin_value, reg2->smin_value); 14582 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14583 reg2->umin_value = reg1->umin_value; 14584 reg2->umax_value = reg1->umax_value; 14585 reg2->smin_value = reg1->smin_value; 14586 reg2->smax_value = reg1->smax_value; 14587 14588 reg1->var_off = tnum_intersect(reg1->var_off, reg2->var_off); 14589 reg2->var_off = reg1->var_off; 14590 } 14591 break; 14592 case BPF_JNE: 14593 if (!is_reg_const(reg2, is_jmp32)) 14594 swap(reg1, reg2); 14595 if (!is_reg_const(reg2, is_jmp32)) 14596 break; 14597 14598 /* try to recompute the bound of reg1 if reg2 is a const and 14599 * is exactly the edge of reg1. 14600 */ 14601 val = reg_const_value(reg2, is_jmp32); 14602 if (is_jmp32) { 14603 /* u32_min_value is not equal to 0xffffffff at this point, 14604 * because otherwise u32_max_value is 0xffffffff as well, 14605 * in such a case both reg1 and reg2 would be constants, 14606 * jump would be predicted and reg_set_min_max() won't 14607 * be called. 14608 * 14609 * Same reasoning works for all {u,s}{min,max}{32,64} cases 14610 * below. 14611 */ 14612 if (reg1->u32_min_value == (u32)val) 14613 reg1->u32_min_value++; 14614 if (reg1->u32_max_value == (u32)val) 14615 reg1->u32_max_value--; 14616 if (reg1->s32_min_value == (s32)val) 14617 reg1->s32_min_value++; 14618 if (reg1->s32_max_value == (s32)val) 14619 reg1->s32_max_value--; 14620 } else { 14621 if (reg1->umin_value == (u64)val) 14622 reg1->umin_value++; 14623 if (reg1->umax_value == (u64)val) 14624 reg1->umax_value--; 14625 if (reg1->smin_value == (s64)val) 14626 reg1->smin_value++; 14627 if (reg1->smax_value == (s64)val) 14628 reg1->smax_value--; 14629 } 14630 break; 14631 case BPF_JSET: 14632 if (!is_reg_const(reg2, is_jmp32)) 14633 swap(reg1, reg2); 14634 if (!is_reg_const(reg2, is_jmp32)) 14635 break; 14636 val = reg_const_value(reg2, is_jmp32); 14637 /* BPF_JSET (i.e., TRUE branch, *not* BPF_JSET | BPF_X) 14638 * requires single bit to learn something useful. E.g., if we 14639 * know that `r1 & 0x3` is true, then which bits (0, 1, or both) 14640 * are actually set? We can learn something definite only if 14641 * it's a single-bit value to begin with. 14642 * 14643 * BPF_JSET | BPF_X (i.e., negation of BPF_JSET) doesn't have 14644 * this restriction. I.e., !(r1 & 0x3) means neither bit 0 nor 14645 * bit 1 is set, which we can readily use in adjustments. 14646 */ 14647 if (!is_power_of_2(val)) 14648 break; 14649 if (is_jmp32) { 14650 t = tnum_or(tnum_subreg(reg1->var_off), tnum_const(val)); 14651 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14652 } else { 14653 reg1->var_off = tnum_or(reg1->var_off, tnum_const(val)); 14654 } 14655 break; 14656 case BPF_JSET | BPF_X: /* reverse of BPF_JSET, see rev_opcode() */ 14657 if (!is_reg_const(reg2, is_jmp32)) 14658 swap(reg1, reg2); 14659 if (!is_reg_const(reg2, is_jmp32)) 14660 break; 14661 val = reg_const_value(reg2, is_jmp32); 14662 if (is_jmp32) { 14663 t = tnum_and(tnum_subreg(reg1->var_off), tnum_const(~val)); 14664 reg1->var_off = tnum_with_subreg(reg1->var_off, t); 14665 } else { 14666 reg1->var_off = tnum_and(reg1->var_off, tnum_const(~val)); 14667 } 14668 break; 14669 case BPF_JLE: 14670 if (is_jmp32) { 14671 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value); 14672 reg2->u32_min_value = max(reg1->u32_min_value, reg2->u32_min_value); 14673 } else { 14674 reg1->umax_value = min(reg1->umax_value, reg2->umax_value); 14675 reg2->umin_value = max(reg1->umin_value, reg2->umin_value); 14676 } 14677 break; 14678 case BPF_JLT: 14679 if (is_jmp32) { 14680 reg1->u32_max_value = min(reg1->u32_max_value, reg2->u32_max_value - 1); 14681 reg2->u32_min_value = max(reg1->u32_min_value + 1, reg2->u32_min_value); 14682 } else { 14683 reg1->umax_value = min(reg1->umax_value, reg2->umax_value - 1); 14684 reg2->umin_value = max(reg1->umin_value + 1, reg2->umin_value); 14685 } 14686 break; 14687 case BPF_JSLE: 14688 if (is_jmp32) { 14689 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value); 14690 reg2->s32_min_value = max(reg1->s32_min_value, reg2->s32_min_value); 14691 } else { 14692 reg1->smax_value = min(reg1->smax_value, reg2->smax_value); 14693 reg2->smin_value = max(reg1->smin_value, reg2->smin_value); 14694 } 14695 break; 14696 case BPF_JSLT: 14697 if (is_jmp32) { 14698 reg1->s32_max_value = min(reg1->s32_max_value, reg2->s32_max_value - 1); 14699 reg2->s32_min_value = max(reg1->s32_min_value + 1, reg2->s32_min_value); 14700 } else { 14701 reg1->smax_value = min(reg1->smax_value, reg2->smax_value - 1); 14702 reg2->smin_value = max(reg1->smin_value + 1, reg2->smin_value); 14703 } 14704 break; 14705 case BPF_JGE: 14706 case BPF_JGT: 14707 case BPF_JSGE: 14708 case BPF_JSGT: 14709 /* just reuse LE/LT logic above */ 14710 opcode = flip_opcode(opcode); 14711 swap(reg1, reg2); 14712 goto again; 14713 default: 14714 return; 14715 } 14716 } 14717 14718 /* Adjusts the register min/max values in the case that the dst_reg and 14719 * src_reg are both SCALAR_VALUE registers (or we are simply doing a BPF_K 14720 * check, in which case we havea fake SCALAR_VALUE representing insn->imm). 14721 * Technically we can do similar adjustments for pointers to the same object, 14722 * but we don't support that right now. 14723 */ 14724 static int reg_set_min_max(struct bpf_verifier_env *env, 14725 struct bpf_reg_state *true_reg1, 14726 struct bpf_reg_state *true_reg2, 14727 struct bpf_reg_state *false_reg1, 14728 struct bpf_reg_state *false_reg2, 14729 u8 opcode, bool is_jmp32) 14730 { 14731 int err; 14732 14733 /* If either register is a pointer, we can't learn anything about its 14734 * variable offset from the compare (unless they were a pointer into 14735 * the same object, but we don't bother with that). 14736 */ 14737 if (false_reg1->type != SCALAR_VALUE || false_reg2->type != SCALAR_VALUE) 14738 return 0; 14739 14740 /* fallthrough (FALSE) branch */ 14741 regs_refine_cond_op(false_reg1, false_reg2, rev_opcode(opcode), is_jmp32); 14742 reg_bounds_sync(false_reg1); 14743 reg_bounds_sync(false_reg2); 14744 14745 /* jump (TRUE) branch */ 14746 regs_refine_cond_op(true_reg1, true_reg2, opcode, is_jmp32); 14747 reg_bounds_sync(true_reg1); 14748 reg_bounds_sync(true_reg2); 14749 14750 err = reg_bounds_sanity_check(env, true_reg1, "true_reg1"); 14751 err = err ?: reg_bounds_sanity_check(env, true_reg2, "true_reg2"); 14752 err = err ?: reg_bounds_sanity_check(env, false_reg1, "false_reg1"); 14753 err = err ?: reg_bounds_sanity_check(env, false_reg2, "false_reg2"); 14754 return err; 14755 } 14756 14757 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 14758 struct bpf_reg_state *reg, u32 id, 14759 bool is_null) 14760 { 14761 if (type_may_be_null(reg->type) && reg->id == id && 14762 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 14763 /* Old offset (both fixed and variable parts) should have been 14764 * known-zero, because we don't allow pointer arithmetic on 14765 * pointers that might be NULL. If we see this happening, don't 14766 * convert the register. 14767 * 14768 * But in some cases, some helpers that return local kptrs 14769 * advance offset for the returned pointer. In those cases, it 14770 * is fine to expect to see reg->off. 14771 */ 14772 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 14773 return; 14774 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 14775 WARN_ON_ONCE(reg->off)) 14776 return; 14777 14778 if (is_null) { 14779 reg->type = SCALAR_VALUE; 14780 /* We don't need id and ref_obj_id from this point 14781 * onwards anymore, thus we should better reset it, 14782 * so that state pruning has chances to take effect. 14783 */ 14784 reg->id = 0; 14785 reg->ref_obj_id = 0; 14786 14787 return; 14788 } 14789 14790 mark_ptr_not_null_reg(reg); 14791 14792 if (!reg_may_point_to_spin_lock(reg)) { 14793 /* For not-NULL ptr, reg->ref_obj_id will be reset 14794 * in release_reference(). 14795 * 14796 * reg->id is still used by spin_lock ptr. Other 14797 * than spin_lock ptr type, reg->id can be reset. 14798 */ 14799 reg->id = 0; 14800 } 14801 } 14802 } 14803 14804 /* The logic is similar to find_good_pkt_pointers(), both could eventually 14805 * be folded together at some point. 14806 */ 14807 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 14808 bool is_null) 14809 { 14810 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 14811 struct bpf_reg_state *regs = state->regs, *reg; 14812 u32 ref_obj_id = regs[regno].ref_obj_id; 14813 u32 id = regs[regno].id; 14814 14815 if (ref_obj_id && ref_obj_id == id && is_null) 14816 /* regs[regno] is in the " == NULL" branch. 14817 * No one could have freed the reference state before 14818 * doing the NULL check. 14819 */ 14820 WARN_ON_ONCE(release_reference_state(state, id)); 14821 14822 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14823 mark_ptr_or_null_reg(state, reg, id, is_null); 14824 })); 14825 } 14826 14827 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 14828 struct bpf_reg_state *dst_reg, 14829 struct bpf_reg_state *src_reg, 14830 struct bpf_verifier_state *this_branch, 14831 struct bpf_verifier_state *other_branch) 14832 { 14833 if (BPF_SRC(insn->code) != BPF_X) 14834 return false; 14835 14836 /* Pointers are always 64-bit. */ 14837 if (BPF_CLASS(insn->code) == BPF_JMP32) 14838 return false; 14839 14840 switch (BPF_OP(insn->code)) { 14841 case BPF_JGT: 14842 if ((dst_reg->type == PTR_TO_PACKET && 14843 src_reg->type == PTR_TO_PACKET_END) || 14844 (dst_reg->type == PTR_TO_PACKET_META && 14845 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14846 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 14847 find_good_pkt_pointers(this_branch, dst_reg, 14848 dst_reg->type, false); 14849 mark_pkt_end(other_branch, insn->dst_reg, true); 14850 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14851 src_reg->type == PTR_TO_PACKET) || 14852 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14853 src_reg->type == PTR_TO_PACKET_META)) { 14854 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 14855 find_good_pkt_pointers(other_branch, src_reg, 14856 src_reg->type, true); 14857 mark_pkt_end(this_branch, insn->src_reg, false); 14858 } else { 14859 return false; 14860 } 14861 break; 14862 case BPF_JLT: 14863 if ((dst_reg->type == PTR_TO_PACKET && 14864 src_reg->type == PTR_TO_PACKET_END) || 14865 (dst_reg->type == PTR_TO_PACKET_META && 14866 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14867 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 14868 find_good_pkt_pointers(other_branch, dst_reg, 14869 dst_reg->type, true); 14870 mark_pkt_end(this_branch, insn->dst_reg, false); 14871 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14872 src_reg->type == PTR_TO_PACKET) || 14873 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14874 src_reg->type == PTR_TO_PACKET_META)) { 14875 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 14876 find_good_pkt_pointers(this_branch, src_reg, 14877 src_reg->type, false); 14878 mark_pkt_end(other_branch, insn->src_reg, true); 14879 } else { 14880 return false; 14881 } 14882 break; 14883 case BPF_JGE: 14884 if ((dst_reg->type == PTR_TO_PACKET && 14885 src_reg->type == PTR_TO_PACKET_END) || 14886 (dst_reg->type == PTR_TO_PACKET_META && 14887 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14888 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 14889 find_good_pkt_pointers(this_branch, dst_reg, 14890 dst_reg->type, true); 14891 mark_pkt_end(other_branch, insn->dst_reg, false); 14892 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14893 src_reg->type == PTR_TO_PACKET) || 14894 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14895 src_reg->type == PTR_TO_PACKET_META)) { 14896 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 14897 find_good_pkt_pointers(other_branch, src_reg, 14898 src_reg->type, false); 14899 mark_pkt_end(this_branch, insn->src_reg, true); 14900 } else { 14901 return false; 14902 } 14903 break; 14904 case BPF_JLE: 14905 if ((dst_reg->type == PTR_TO_PACKET && 14906 src_reg->type == PTR_TO_PACKET_END) || 14907 (dst_reg->type == PTR_TO_PACKET_META && 14908 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 14909 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 14910 find_good_pkt_pointers(other_branch, dst_reg, 14911 dst_reg->type, false); 14912 mark_pkt_end(this_branch, insn->dst_reg, true); 14913 } else if ((dst_reg->type == PTR_TO_PACKET_END && 14914 src_reg->type == PTR_TO_PACKET) || 14915 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 14916 src_reg->type == PTR_TO_PACKET_META)) { 14917 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 14918 find_good_pkt_pointers(this_branch, src_reg, 14919 src_reg->type, true); 14920 mark_pkt_end(other_branch, insn->src_reg, false); 14921 } else { 14922 return false; 14923 } 14924 break; 14925 default: 14926 return false; 14927 } 14928 14929 return true; 14930 } 14931 14932 static void find_equal_scalars(struct bpf_verifier_state *vstate, 14933 struct bpf_reg_state *known_reg) 14934 { 14935 struct bpf_func_state *state; 14936 struct bpf_reg_state *reg; 14937 14938 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 14939 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 14940 copy_register_state(reg, known_reg); 14941 })); 14942 } 14943 14944 static int check_cond_jmp_op(struct bpf_verifier_env *env, 14945 struct bpf_insn *insn, int *insn_idx) 14946 { 14947 struct bpf_verifier_state *this_branch = env->cur_state; 14948 struct bpf_verifier_state *other_branch; 14949 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 14950 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 14951 struct bpf_reg_state *eq_branch_regs; 14952 struct bpf_reg_state fake_reg = {}; 14953 u8 opcode = BPF_OP(insn->code); 14954 bool is_jmp32; 14955 int pred = -1; 14956 int err; 14957 14958 /* Only conditional jumps are expected to reach here. */ 14959 if (opcode == BPF_JA || opcode > BPF_JCOND) { 14960 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 14961 return -EINVAL; 14962 } 14963 14964 if (opcode == BPF_JCOND) { 14965 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st, *prev_st; 14966 int idx = *insn_idx; 14967 14968 if (insn->code != (BPF_JMP | BPF_JCOND) || 14969 insn->src_reg != BPF_MAY_GOTO || 14970 insn->dst_reg || insn->imm || insn->off == 0) { 14971 verbose(env, "invalid may_goto off %d imm %d\n", 14972 insn->off, insn->imm); 14973 return -EINVAL; 14974 } 14975 prev_st = find_prev_entry(env, cur_st->parent, idx); 14976 14977 /* branch out 'fallthrough' insn as a new state to explore */ 14978 queued_st = push_stack(env, idx + 1, idx, false); 14979 if (!queued_st) 14980 return -ENOMEM; 14981 14982 queued_st->may_goto_depth++; 14983 if (prev_st) 14984 widen_imprecise_scalars(env, prev_st, queued_st); 14985 *insn_idx += insn->off; 14986 return 0; 14987 } 14988 14989 /* check src2 operand */ 14990 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14991 if (err) 14992 return err; 14993 14994 dst_reg = ®s[insn->dst_reg]; 14995 if (BPF_SRC(insn->code) == BPF_X) { 14996 if (insn->imm != 0) { 14997 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 14998 return -EINVAL; 14999 } 15000 15001 /* check src1 operand */ 15002 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15003 if (err) 15004 return err; 15005 15006 src_reg = ®s[insn->src_reg]; 15007 if (!(reg_is_pkt_pointer_any(dst_reg) && reg_is_pkt_pointer_any(src_reg)) && 15008 is_pointer_value(env, insn->src_reg)) { 15009 verbose(env, "R%d pointer comparison prohibited\n", 15010 insn->src_reg); 15011 return -EACCES; 15012 } 15013 } else { 15014 if (insn->src_reg != BPF_REG_0) { 15015 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 15016 return -EINVAL; 15017 } 15018 src_reg = &fake_reg; 15019 src_reg->type = SCALAR_VALUE; 15020 __mark_reg_known(src_reg, insn->imm); 15021 } 15022 15023 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 15024 pred = is_branch_taken(dst_reg, src_reg, opcode, is_jmp32); 15025 if (pred >= 0) { 15026 /* If we get here with a dst_reg pointer type it is because 15027 * above is_branch_taken() special cased the 0 comparison. 15028 */ 15029 if (!__is_pointer_value(false, dst_reg)) 15030 err = mark_chain_precision(env, insn->dst_reg); 15031 if (BPF_SRC(insn->code) == BPF_X && !err && 15032 !__is_pointer_value(false, src_reg)) 15033 err = mark_chain_precision(env, insn->src_reg); 15034 if (err) 15035 return err; 15036 } 15037 15038 if (pred == 1) { 15039 /* Only follow the goto, ignore fall-through. If needed, push 15040 * the fall-through branch for simulation under speculative 15041 * execution. 15042 */ 15043 if (!env->bypass_spec_v1 && 15044 !sanitize_speculative_path(env, insn, *insn_idx + 1, 15045 *insn_idx)) 15046 return -EFAULT; 15047 if (env->log.level & BPF_LOG_LEVEL) 15048 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15049 *insn_idx += insn->off; 15050 return 0; 15051 } else if (pred == 0) { 15052 /* Only follow the fall-through branch, since that's where the 15053 * program will go. If needed, push the goto branch for 15054 * simulation under speculative execution. 15055 */ 15056 if (!env->bypass_spec_v1 && 15057 !sanitize_speculative_path(env, insn, 15058 *insn_idx + insn->off + 1, 15059 *insn_idx)) 15060 return -EFAULT; 15061 if (env->log.level & BPF_LOG_LEVEL) 15062 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15063 return 0; 15064 } 15065 15066 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 15067 false); 15068 if (!other_branch) 15069 return -EFAULT; 15070 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 15071 15072 if (BPF_SRC(insn->code) == BPF_X) { 15073 err = reg_set_min_max(env, 15074 &other_branch_regs[insn->dst_reg], 15075 &other_branch_regs[insn->src_reg], 15076 dst_reg, src_reg, opcode, is_jmp32); 15077 } else /* BPF_SRC(insn->code) == BPF_K */ { 15078 err = reg_set_min_max(env, 15079 &other_branch_regs[insn->dst_reg], 15080 src_reg /* fake one */, 15081 dst_reg, src_reg /* same fake one */, 15082 opcode, is_jmp32); 15083 } 15084 if (err) 15085 return err; 15086 15087 if (BPF_SRC(insn->code) == BPF_X && 15088 src_reg->type == SCALAR_VALUE && src_reg->id && 15089 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 15090 find_equal_scalars(this_branch, src_reg); 15091 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 15092 } 15093 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 15094 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 15095 find_equal_scalars(this_branch, dst_reg); 15096 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 15097 } 15098 15099 /* if one pointer register is compared to another pointer 15100 * register check if PTR_MAYBE_NULL could be lifted. 15101 * E.g. register A - maybe null 15102 * register B - not null 15103 * for JNE A, B, ... - A is not null in the false branch; 15104 * for JEQ A, B, ... - A is not null in the true branch. 15105 * 15106 * Since PTR_TO_BTF_ID points to a kernel struct that does 15107 * not need to be null checked by the BPF program, i.e., 15108 * could be null even without PTR_MAYBE_NULL marking, so 15109 * only propagate nullness when neither reg is that type. 15110 */ 15111 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 15112 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 15113 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 15114 base_type(src_reg->type) != PTR_TO_BTF_ID && 15115 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 15116 eq_branch_regs = NULL; 15117 switch (opcode) { 15118 case BPF_JEQ: 15119 eq_branch_regs = other_branch_regs; 15120 break; 15121 case BPF_JNE: 15122 eq_branch_regs = regs; 15123 break; 15124 default: 15125 /* do nothing */ 15126 break; 15127 } 15128 if (eq_branch_regs) { 15129 if (type_may_be_null(src_reg->type)) 15130 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 15131 else 15132 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 15133 } 15134 } 15135 15136 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 15137 * NOTE: these optimizations below are related with pointer comparison 15138 * which will never be JMP32. 15139 */ 15140 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 15141 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 15142 type_may_be_null(dst_reg->type)) { 15143 /* Mark all identical registers in each branch as either 15144 * safe or unknown depending R == 0 or R != 0 conditional. 15145 */ 15146 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 15147 opcode == BPF_JNE); 15148 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 15149 opcode == BPF_JEQ); 15150 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 15151 this_branch, other_branch) && 15152 is_pointer_value(env, insn->dst_reg)) { 15153 verbose(env, "R%d pointer comparison prohibited\n", 15154 insn->dst_reg); 15155 return -EACCES; 15156 } 15157 if (env->log.level & BPF_LOG_LEVEL) 15158 print_insn_state(env, this_branch->frame[this_branch->curframe]); 15159 return 0; 15160 } 15161 15162 /* verify BPF_LD_IMM64 instruction */ 15163 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 15164 { 15165 struct bpf_insn_aux_data *aux = cur_aux(env); 15166 struct bpf_reg_state *regs = cur_regs(env); 15167 struct bpf_reg_state *dst_reg; 15168 struct bpf_map *map; 15169 int err; 15170 15171 if (BPF_SIZE(insn->code) != BPF_DW) { 15172 verbose(env, "invalid BPF_LD_IMM insn\n"); 15173 return -EINVAL; 15174 } 15175 if (insn->off != 0) { 15176 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 15177 return -EINVAL; 15178 } 15179 15180 err = check_reg_arg(env, insn->dst_reg, DST_OP); 15181 if (err) 15182 return err; 15183 15184 dst_reg = ®s[insn->dst_reg]; 15185 if (insn->src_reg == 0) { 15186 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 15187 15188 dst_reg->type = SCALAR_VALUE; 15189 __mark_reg_known(®s[insn->dst_reg], imm); 15190 return 0; 15191 } 15192 15193 /* All special src_reg cases are listed below. From this point onwards 15194 * we either succeed and assign a corresponding dst_reg->type after 15195 * zeroing the offset, or fail and reject the program. 15196 */ 15197 mark_reg_known_zero(env, regs, insn->dst_reg); 15198 15199 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 15200 dst_reg->type = aux->btf_var.reg_type; 15201 switch (base_type(dst_reg->type)) { 15202 case PTR_TO_MEM: 15203 dst_reg->mem_size = aux->btf_var.mem_size; 15204 break; 15205 case PTR_TO_BTF_ID: 15206 dst_reg->btf = aux->btf_var.btf; 15207 dst_reg->btf_id = aux->btf_var.btf_id; 15208 break; 15209 default: 15210 verbose(env, "bpf verifier is misconfigured\n"); 15211 return -EFAULT; 15212 } 15213 return 0; 15214 } 15215 15216 if (insn->src_reg == BPF_PSEUDO_FUNC) { 15217 struct bpf_prog_aux *aux = env->prog->aux; 15218 u32 subprogno = find_subprog(env, 15219 env->insn_idx + insn->imm + 1); 15220 15221 if (!aux->func_info) { 15222 verbose(env, "missing btf func_info\n"); 15223 return -EINVAL; 15224 } 15225 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 15226 verbose(env, "callback function not static\n"); 15227 return -EINVAL; 15228 } 15229 15230 dst_reg->type = PTR_TO_FUNC; 15231 dst_reg->subprogno = subprogno; 15232 return 0; 15233 } 15234 15235 map = env->used_maps[aux->map_index]; 15236 dst_reg->map_ptr = map; 15237 15238 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 15239 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 15240 if (map->map_type == BPF_MAP_TYPE_ARENA) { 15241 __mark_reg_unknown(env, dst_reg); 15242 return 0; 15243 } 15244 dst_reg->type = PTR_TO_MAP_VALUE; 15245 dst_reg->off = aux->map_off; 15246 WARN_ON_ONCE(map->max_entries != 1); 15247 /* We want reg->id to be same (0) as map_value is not distinct */ 15248 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 15249 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 15250 dst_reg->type = CONST_PTR_TO_MAP; 15251 } else { 15252 verbose(env, "bpf verifier is misconfigured\n"); 15253 return -EINVAL; 15254 } 15255 15256 return 0; 15257 } 15258 15259 static bool may_access_skb(enum bpf_prog_type type) 15260 { 15261 switch (type) { 15262 case BPF_PROG_TYPE_SOCKET_FILTER: 15263 case BPF_PROG_TYPE_SCHED_CLS: 15264 case BPF_PROG_TYPE_SCHED_ACT: 15265 return true; 15266 default: 15267 return false; 15268 } 15269 } 15270 15271 /* verify safety of LD_ABS|LD_IND instructions: 15272 * - they can only appear in the programs where ctx == skb 15273 * - since they are wrappers of function calls, they scratch R1-R5 registers, 15274 * preserve R6-R9, and store return value into R0 15275 * 15276 * Implicit input: 15277 * ctx == skb == R6 == CTX 15278 * 15279 * Explicit input: 15280 * SRC == any register 15281 * IMM == 32-bit immediate 15282 * 15283 * Output: 15284 * R0 - 8/16/32-bit skb data converted to cpu endianness 15285 */ 15286 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 15287 { 15288 struct bpf_reg_state *regs = cur_regs(env); 15289 static const int ctx_reg = BPF_REG_6; 15290 u8 mode = BPF_MODE(insn->code); 15291 int i, err; 15292 15293 if (!may_access_skb(resolve_prog_type(env->prog))) { 15294 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 15295 return -EINVAL; 15296 } 15297 15298 if (!env->ops->gen_ld_abs) { 15299 verbose(env, "bpf verifier is misconfigured\n"); 15300 return -EINVAL; 15301 } 15302 15303 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 15304 BPF_SIZE(insn->code) == BPF_DW || 15305 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 15306 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 15307 return -EINVAL; 15308 } 15309 15310 /* check whether implicit source operand (register R6) is readable */ 15311 err = check_reg_arg(env, ctx_reg, SRC_OP); 15312 if (err) 15313 return err; 15314 15315 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 15316 * gen_ld_abs() may terminate the program at runtime, leading to 15317 * reference leak. 15318 */ 15319 err = check_reference_leak(env, false); 15320 if (err) { 15321 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 15322 return err; 15323 } 15324 15325 if (env->cur_state->active_lock.ptr) { 15326 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 15327 return -EINVAL; 15328 } 15329 15330 if (env->cur_state->active_rcu_lock) { 15331 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 15332 return -EINVAL; 15333 } 15334 15335 if (regs[ctx_reg].type != PTR_TO_CTX) { 15336 verbose(env, 15337 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 15338 return -EINVAL; 15339 } 15340 15341 if (mode == BPF_IND) { 15342 /* check explicit source operand */ 15343 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15344 if (err) 15345 return err; 15346 } 15347 15348 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 15349 if (err < 0) 15350 return err; 15351 15352 /* reset caller saved regs to unreadable */ 15353 for (i = 0; i < CALLER_SAVED_REGS; i++) { 15354 mark_reg_not_init(env, regs, caller_saved[i]); 15355 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 15356 } 15357 15358 /* mark destination R0 register as readable, since it contains 15359 * the value fetched from the packet. 15360 * Already marked as written above. 15361 */ 15362 mark_reg_unknown(env, regs, BPF_REG_0); 15363 /* ld_abs load up to 32-bit skb data. */ 15364 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 15365 return 0; 15366 } 15367 15368 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name) 15369 { 15370 const char *exit_ctx = "At program exit"; 15371 struct tnum enforce_attach_type_range = tnum_unknown; 15372 const struct bpf_prog *prog = env->prog; 15373 struct bpf_reg_state *reg; 15374 struct bpf_retval_range range = retval_range(0, 1); 15375 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 15376 int err; 15377 struct bpf_func_state *frame = env->cur_state->frame[0]; 15378 const bool is_subprog = frame->subprogno; 15379 15380 /* LSM and struct_ops func-ptr's return type could be "void" */ 15381 if (!is_subprog || frame->in_exception_callback_fn) { 15382 switch (prog_type) { 15383 case BPF_PROG_TYPE_LSM: 15384 if (prog->expected_attach_type == BPF_LSM_CGROUP) 15385 /* See below, can be 0 or 0-1 depending on hook. */ 15386 break; 15387 fallthrough; 15388 case BPF_PROG_TYPE_STRUCT_OPS: 15389 if (!prog->aux->attach_func_proto->type) 15390 return 0; 15391 break; 15392 default: 15393 break; 15394 } 15395 } 15396 15397 /* eBPF calling convention is such that R0 is used 15398 * to return the value from eBPF program. 15399 * Make sure that it's readable at this time 15400 * of bpf_exit, which means that program wrote 15401 * something into it earlier 15402 */ 15403 err = check_reg_arg(env, regno, SRC_OP); 15404 if (err) 15405 return err; 15406 15407 if (is_pointer_value(env, regno)) { 15408 verbose(env, "R%d leaks addr as return value\n", regno); 15409 return -EACCES; 15410 } 15411 15412 reg = cur_regs(env) + regno; 15413 15414 if (frame->in_async_callback_fn) { 15415 /* enforce return zero from async callbacks like timer */ 15416 exit_ctx = "At async callback return"; 15417 range = retval_range(0, 0); 15418 goto enforce_retval; 15419 } 15420 15421 if (is_subprog && !frame->in_exception_callback_fn) { 15422 if (reg->type != SCALAR_VALUE) { 15423 verbose(env, "At subprogram exit the register R%d is not a scalar value (%s)\n", 15424 regno, reg_type_str(env, reg->type)); 15425 return -EINVAL; 15426 } 15427 return 0; 15428 } 15429 15430 switch (prog_type) { 15431 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 15432 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 15433 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 15434 env->prog->expected_attach_type == BPF_CGROUP_UNIX_RECVMSG || 15435 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 15436 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 15437 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETPEERNAME || 15438 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 15439 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME || 15440 env->prog->expected_attach_type == BPF_CGROUP_UNIX_GETSOCKNAME) 15441 range = retval_range(1, 1); 15442 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 15443 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 15444 range = retval_range(0, 3); 15445 break; 15446 case BPF_PROG_TYPE_CGROUP_SKB: 15447 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 15448 range = retval_range(0, 3); 15449 enforce_attach_type_range = tnum_range(2, 3); 15450 } 15451 break; 15452 case BPF_PROG_TYPE_CGROUP_SOCK: 15453 case BPF_PROG_TYPE_SOCK_OPS: 15454 case BPF_PROG_TYPE_CGROUP_DEVICE: 15455 case BPF_PROG_TYPE_CGROUP_SYSCTL: 15456 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 15457 break; 15458 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15459 if (!env->prog->aux->attach_btf_id) 15460 return 0; 15461 range = retval_range(0, 0); 15462 break; 15463 case BPF_PROG_TYPE_TRACING: 15464 switch (env->prog->expected_attach_type) { 15465 case BPF_TRACE_FENTRY: 15466 case BPF_TRACE_FEXIT: 15467 range = retval_range(0, 0); 15468 break; 15469 case BPF_TRACE_RAW_TP: 15470 case BPF_MODIFY_RETURN: 15471 return 0; 15472 case BPF_TRACE_ITER: 15473 break; 15474 default: 15475 return -ENOTSUPP; 15476 } 15477 break; 15478 case BPF_PROG_TYPE_SK_LOOKUP: 15479 range = retval_range(SK_DROP, SK_PASS); 15480 break; 15481 15482 case BPF_PROG_TYPE_LSM: 15483 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 15484 /* Regular BPF_PROG_TYPE_LSM programs can return 15485 * any value. 15486 */ 15487 return 0; 15488 } 15489 if (!env->prog->aux->attach_func_proto->type) { 15490 /* Make sure programs that attach to void 15491 * hooks don't try to modify return value. 15492 */ 15493 range = retval_range(1, 1); 15494 } 15495 break; 15496 15497 case BPF_PROG_TYPE_NETFILTER: 15498 range = retval_range(NF_DROP, NF_ACCEPT); 15499 break; 15500 case BPF_PROG_TYPE_EXT: 15501 /* freplace program can return anything as its return value 15502 * depends on the to-be-replaced kernel func or bpf program. 15503 */ 15504 default: 15505 return 0; 15506 } 15507 15508 enforce_retval: 15509 if (reg->type != SCALAR_VALUE) { 15510 verbose(env, "%s the register R%d is not a known value (%s)\n", 15511 exit_ctx, regno, reg_type_str(env, reg->type)); 15512 return -EINVAL; 15513 } 15514 15515 err = mark_chain_precision(env, regno); 15516 if (err) 15517 return err; 15518 15519 if (!retval_range_within(range, reg)) { 15520 verbose_invalid_scalar(env, reg, range, exit_ctx, reg_name); 15521 if (!is_subprog && 15522 prog->expected_attach_type == BPF_LSM_CGROUP && 15523 prog_type == BPF_PROG_TYPE_LSM && 15524 !prog->aux->attach_func_proto->type) 15525 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 15526 return -EINVAL; 15527 } 15528 15529 if (!tnum_is_unknown(enforce_attach_type_range) && 15530 tnum_in(enforce_attach_type_range, reg->var_off)) 15531 env->prog->enforce_expected_attach_type = 1; 15532 return 0; 15533 } 15534 15535 /* non-recursive DFS pseudo code 15536 * 1 procedure DFS-iterative(G,v): 15537 * 2 label v as discovered 15538 * 3 let S be a stack 15539 * 4 S.push(v) 15540 * 5 while S is not empty 15541 * 6 t <- S.peek() 15542 * 7 if t is what we're looking for: 15543 * 8 return t 15544 * 9 for all edges e in G.adjacentEdges(t) do 15545 * 10 if edge e is already labelled 15546 * 11 continue with the next edge 15547 * 12 w <- G.adjacentVertex(t,e) 15548 * 13 if vertex w is not discovered and not explored 15549 * 14 label e as tree-edge 15550 * 15 label w as discovered 15551 * 16 S.push(w) 15552 * 17 continue at 5 15553 * 18 else if vertex w is discovered 15554 * 19 label e as back-edge 15555 * 20 else 15556 * 21 // vertex w is explored 15557 * 22 label e as forward- or cross-edge 15558 * 23 label t as explored 15559 * 24 S.pop() 15560 * 15561 * convention: 15562 * 0x10 - discovered 15563 * 0x11 - discovered and fall-through edge labelled 15564 * 0x12 - discovered and fall-through and branch edges labelled 15565 * 0x20 - explored 15566 */ 15567 15568 enum { 15569 DISCOVERED = 0x10, 15570 EXPLORED = 0x20, 15571 FALLTHROUGH = 1, 15572 BRANCH = 2, 15573 }; 15574 15575 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 15576 { 15577 env->insn_aux_data[idx].prune_point = true; 15578 } 15579 15580 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 15581 { 15582 return env->insn_aux_data[insn_idx].prune_point; 15583 } 15584 15585 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 15586 { 15587 env->insn_aux_data[idx].force_checkpoint = true; 15588 } 15589 15590 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 15591 { 15592 return env->insn_aux_data[insn_idx].force_checkpoint; 15593 } 15594 15595 static void mark_calls_callback(struct bpf_verifier_env *env, int idx) 15596 { 15597 env->insn_aux_data[idx].calls_callback = true; 15598 } 15599 15600 static bool calls_callback(struct bpf_verifier_env *env, int insn_idx) 15601 { 15602 return env->insn_aux_data[insn_idx].calls_callback; 15603 } 15604 15605 enum { 15606 DONE_EXPLORING = 0, 15607 KEEP_EXPLORING = 1, 15608 }; 15609 15610 /* t, w, e - match pseudo-code above: 15611 * t - index of current instruction 15612 * w - next instruction 15613 * e - edge 15614 */ 15615 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 15616 { 15617 int *insn_stack = env->cfg.insn_stack; 15618 int *insn_state = env->cfg.insn_state; 15619 15620 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 15621 return DONE_EXPLORING; 15622 15623 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 15624 return DONE_EXPLORING; 15625 15626 if (w < 0 || w >= env->prog->len) { 15627 verbose_linfo(env, t, "%d: ", t); 15628 verbose(env, "jump out of range from insn %d to %d\n", t, w); 15629 return -EINVAL; 15630 } 15631 15632 if (e == BRANCH) { 15633 /* mark branch target for state pruning */ 15634 mark_prune_point(env, w); 15635 mark_jmp_point(env, w); 15636 } 15637 15638 if (insn_state[w] == 0) { 15639 /* tree-edge */ 15640 insn_state[t] = DISCOVERED | e; 15641 insn_state[w] = DISCOVERED; 15642 if (env->cfg.cur_stack >= env->prog->len) 15643 return -E2BIG; 15644 insn_stack[env->cfg.cur_stack++] = w; 15645 return KEEP_EXPLORING; 15646 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 15647 if (env->bpf_capable) 15648 return DONE_EXPLORING; 15649 verbose_linfo(env, t, "%d: ", t); 15650 verbose_linfo(env, w, "%d: ", w); 15651 verbose(env, "back-edge from insn %d to %d\n", t, w); 15652 return -EINVAL; 15653 } else if (insn_state[w] == EXPLORED) { 15654 /* forward- or cross-edge */ 15655 insn_state[t] = DISCOVERED | e; 15656 } else { 15657 verbose(env, "insn state internal bug\n"); 15658 return -EFAULT; 15659 } 15660 return DONE_EXPLORING; 15661 } 15662 15663 static int visit_func_call_insn(int t, struct bpf_insn *insns, 15664 struct bpf_verifier_env *env, 15665 bool visit_callee) 15666 { 15667 int ret, insn_sz; 15668 15669 insn_sz = bpf_is_ldimm64(&insns[t]) ? 2 : 1; 15670 ret = push_insn(t, t + insn_sz, FALLTHROUGH, env); 15671 if (ret) 15672 return ret; 15673 15674 mark_prune_point(env, t + insn_sz); 15675 /* when we exit from subprog, we need to record non-linear history */ 15676 mark_jmp_point(env, t + insn_sz); 15677 15678 if (visit_callee) { 15679 mark_prune_point(env, t); 15680 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 15681 } 15682 return ret; 15683 } 15684 15685 /* Visits the instruction at index t and returns one of the following: 15686 * < 0 - an error occurred 15687 * DONE_EXPLORING - the instruction was fully explored 15688 * KEEP_EXPLORING - there is still work to be done before it is fully explored 15689 */ 15690 static int visit_insn(int t, struct bpf_verifier_env *env) 15691 { 15692 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 15693 int ret, off, insn_sz; 15694 15695 if (bpf_pseudo_func(insn)) 15696 return visit_func_call_insn(t, insns, env, true); 15697 15698 /* All non-branch instructions have a single fall-through edge. */ 15699 if (BPF_CLASS(insn->code) != BPF_JMP && 15700 BPF_CLASS(insn->code) != BPF_JMP32) { 15701 insn_sz = bpf_is_ldimm64(insn) ? 2 : 1; 15702 return push_insn(t, t + insn_sz, FALLTHROUGH, env); 15703 } 15704 15705 switch (BPF_OP(insn->code)) { 15706 case BPF_EXIT: 15707 return DONE_EXPLORING; 15708 15709 case BPF_CALL: 15710 if (is_async_callback_calling_insn(insn)) 15711 /* Mark this call insn as a prune point to trigger 15712 * is_state_visited() check before call itself is 15713 * processed by __check_func_call(). Otherwise new 15714 * async state will be pushed for further exploration. 15715 */ 15716 mark_prune_point(env, t); 15717 /* For functions that invoke callbacks it is not known how many times 15718 * callback would be called. Verifier models callback calling functions 15719 * by repeatedly visiting callback bodies and returning to origin call 15720 * instruction. 15721 * In order to stop such iteration verifier needs to identify when a 15722 * state identical some state from a previous iteration is reached. 15723 * Check below forces creation of checkpoint before callback calling 15724 * instruction to allow search for such identical states. 15725 */ 15726 if (is_sync_callback_calling_insn(insn)) { 15727 mark_calls_callback(env, t); 15728 mark_force_checkpoint(env, t); 15729 mark_prune_point(env, t); 15730 mark_jmp_point(env, t); 15731 } 15732 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15733 struct bpf_kfunc_call_arg_meta meta; 15734 15735 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 15736 if (ret == 0 && is_iter_next_kfunc(&meta)) { 15737 mark_prune_point(env, t); 15738 /* Checking and saving state checkpoints at iter_next() call 15739 * is crucial for fast convergence of open-coded iterator loop 15740 * logic, so we need to force it. If we don't do that, 15741 * is_state_visited() might skip saving a checkpoint, causing 15742 * unnecessarily long sequence of not checkpointed 15743 * instructions and jumps, leading to exhaustion of jump 15744 * history buffer, and potentially other undesired outcomes. 15745 * It is expected that with correct open-coded iterators 15746 * convergence will happen quickly, so we don't run a risk of 15747 * exhausting memory. 15748 */ 15749 mark_force_checkpoint(env, t); 15750 } 15751 } 15752 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 15753 15754 case BPF_JA: 15755 if (BPF_SRC(insn->code) != BPF_K) 15756 return -EINVAL; 15757 15758 if (BPF_CLASS(insn->code) == BPF_JMP) 15759 off = insn->off; 15760 else 15761 off = insn->imm; 15762 15763 /* unconditional jump with single edge */ 15764 ret = push_insn(t, t + off + 1, FALLTHROUGH, env); 15765 if (ret) 15766 return ret; 15767 15768 mark_prune_point(env, t + off + 1); 15769 mark_jmp_point(env, t + off + 1); 15770 15771 return ret; 15772 15773 default: 15774 /* conditional jump with two edges */ 15775 mark_prune_point(env, t); 15776 if (is_may_goto_insn(insn)) 15777 mark_force_checkpoint(env, t); 15778 15779 ret = push_insn(t, t + 1, FALLTHROUGH, env); 15780 if (ret) 15781 return ret; 15782 15783 return push_insn(t, t + insn->off + 1, BRANCH, env); 15784 } 15785 } 15786 15787 /* non-recursive depth-first-search to detect loops in BPF program 15788 * loop == back-edge in directed graph 15789 */ 15790 static int check_cfg(struct bpf_verifier_env *env) 15791 { 15792 int insn_cnt = env->prog->len; 15793 int *insn_stack, *insn_state; 15794 int ex_insn_beg, i, ret = 0; 15795 bool ex_done = false; 15796 15797 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15798 if (!insn_state) 15799 return -ENOMEM; 15800 15801 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 15802 if (!insn_stack) { 15803 kvfree(insn_state); 15804 return -ENOMEM; 15805 } 15806 15807 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 15808 insn_stack[0] = 0; /* 0 is the first instruction */ 15809 env->cfg.cur_stack = 1; 15810 15811 walk_cfg: 15812 while (env->cfg.cur_stack > 0) { 15813 int t = insn_stack[env->cfg.cur_stack - 1]; 15814 15815 ret = visit_insn(t, env); 15816 switch (ret) { 15817 case DONE_EXPLORING: 15818 insn_state[t] = EXPLORED; 15819 env->cfg.cur_stack--; 15820 break; 15821 case KEEP_EXPLORING: 15822 break; 15823 default: 15824 if (ret > 0) { 15825 verbose(env, "visit_insn internal bug\n"); 15826 ret = -EFAULT; 15827 } 15828 goto err_free; 15829 } 15830 } 15831 15832 if (env->cfg.cur_stack < 0) { 15833 verbose(env, "pop stack internal bug\n"); 15834 ret = -EFAULT; 15835 goto err_free; 15836 } 15837 15838 if (env->exception_callback_subprog && !ex_done) { 15839 ex_insn_beg = env->subprog_info[env->exception_callback_subprog].start; 15840 15841 insn_state[ex_insn_beg] = DISCOVERED; 15842 insn_stack[0] = ex_insn_beg; 15843 env->cfg.cur_stack = 1; 15844 ex_done = true; 15845 goto walk_cfg; 15846 } 15847 15848 for (i = 0; i < insn_cnt; i++) { 15849 struct bpf_insn *insn = &env->prog->insnsi[i]; 15850 15851 if (insn_state[i] != EXPLORED) { 15852 verbose(env, "unreachable insn %d\n", i); 15853 ret = -EINVAL; 15854 goto err_free; 15855 } 15856 if (bpf_is_ldimm64(insn)) { 15857 if (insn_state[i + 1] != 0) { 15858 verbose(env, "jump into the middle of ldimm64 insn %d\n", i); 15859 ret = -EINVAL; 15860 goto err_free; 15861 } 15862 i++; /* skip second half of ldimm64 */ 15863 } 15864 } 15865 ret = 0; /* cfg looks good */ 15866 15867 err_free: 15868 kvfree(insn_state); 15869 kvfree(insn_stack); 15870 env->cfg.insn_state = env->cfg.insn_stack = NULL; 15871 return ret; 15872 } 15873 15874 static int check_abnormal_return(struct bpf_verifier_env *env) 15875 { 15876 int i; 15877 15878 for (i = 1; i < env->subprog_cnt; i++) { 15879 if (env->subprog_info[i].has_ld_abs) { 15880 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 15881 return -EINVAL; 15882 } 15883 if (env->subprog_info[i].has_tail_call) { 15884 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 15885 return -EINVAL; 15886 } 15887 } 15888 return 0; 15889 } 15890 15891 /* The minimum supported BTF func info size */ 15892 #define MIN_BPF_FUNCINFO_SIZE 8 15893 #define MAX_FUNCINFO_REC_SIZE 252 15894 15895 static int check_btf_func_early(struct bpf_verifier_env *env, 15896 const union bpf_attr *attr, 15897 bpfptr_t uattr) 15898 { 15899 u32 krec_size = sizeof(struct bpf_func_info); 15900 const struct btf_type *type, *func_proto; 15901 u32 i, nfuncs, urec_size, min_size; 15902 struct bpf_func_info *krecord; 15903 struct bpf_prog *prog; 15904 const struct btf *btf; 15905 u32 prev_offset = 0; 15906 bpfptr_t urecord; 15907 int ret = -ENOMEM; 15908 15909 nfuncs = attr->func_info_cnt; 15910 if (!nfuncs) { 15911 if (check_abnormal_return(env)) 15912 return -EINVAL; 15913 return 0; 15914 } 15915 15916 urec_size = attr->func_info_rec_size; 15917 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 15918 urec_size > MAX_FUNCINFO_REC_SIZE || 15919 urec_size % sizeof(u32)) { 15920 verbose(env, "invalid func info rec size %u\n", urec_size); 15921 return -EINVAL; 15922 } 15923 15924 prog = env->prog; 15925 btf = prog->aux->btf; 15926 15927 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 15928 min_size = min_t(u32, krec_size, urec_size); 15929 15930 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 15931 if (!krecord) 15932 return -ENOMEM; 15933 15934 for (i = 0; i < nfuncs; i++) { 15935 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 15936 if (ret) { 15937 if (ret == -E2BIG) { 15938 verbose(env, "nonzero tailing record in func info"); 15939 /* set the size kernel expects so loader can zero 15940 * out the rest of the record. 15941 */ 15942 if (copy_to_bpfptr_offset(uattr, 15943 offsetof(union bpf_attr, func_info_rec_size), 15944 &min_size, sizeof(min_size))) 15945 ret = -EFAULT; 15946 } 15947 goto err_free; 15948 } 15949 15950 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 15951 ret = -EFAULT; 15952 goto err_free; 15953 } 15954 15955 /* check insn_off */ 15956 ret = -EINVAL; 15957 if (i == 0) { 15958 if (krecord[i].insn_off) { 15959 verbose(env, 15960 "nonzero insn_off %u for the first func info record", 15961 krecord[i].insn_off); 15962 goto err_free; 15963 } 15964 } else if (krecord[i].insn_off <= prev_offset) { 15965 verbose(env, 15966 "same or smaller insn offset (%u) than previous func info record (%u)", 15967 krecord[i].insn_off, prev_offset); 15968 goto err_free; 15969 } 15970 15971 /* check type_id */ 15972 type = btf_type_by_id(btf, krecord[i].type_id); 15973 if (!type || !btf_type_is_func(type)) { 15974 verbose(env, "invalid type id %d in func info", 15975 krecord[i].type_id); 15976 goto err_free; 15977 } 15978 15979 func_proto = btf_type_by_id(btf, type->type); 15980 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 15981 /* btf_func_check() already verified it during BTF load */ 15982 goto err_free; 15983 15984 prev_offset = krecord[i].insn_off; 15985 bpfptr_add(&urecord, urec_size); 15986 } 15987 15988 prog->aux->func_info = krecord; 15989 prog->aux->func_info_cnt = nfuncs; 15990 return 0; 15991 15992 err_free: 15993 kvfree(krecord); 15994 return ret; 15995 } 15996 15997 static int check_btf_func(struct bpf_verifier_env *env, 15998 const union bpf_attr *attr, 15999 bpfptr_t uattr) 16000 { 16001 const struct btf_type *type, *func_proto, *ret_type; 16002 u32 i, nfuncs, urec_size; 16003 struct bpf_func_info *krecord; 16004 struct bpf_func_info_aux *info_aux = NULL; 16005 struct bpf_prog *prog; 16006 const struct btf *btf; 16007 bpfptr_t urecord; 16008 bool scalar_return; 16009 int ret = -ENOMEM; 16010 16011 nfuncs = attr->func_info_cnt; 16012 if (!nfuncs) { 16013 if (check_abnormal_return(env)) 16014 return -EINVAL; 16015 return 0; 16016 } 16017 if (nfuncs != env->subprog_cnt) { 16018 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 16019 return -EINVAL; 16020 } 16021 16022 urec_size = attr->func_info_rec_size; 16023 16024 prog = env->prog; 16025 btf = prog->aux->btf; 16026 16027 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 16028 16029 krecord = prog->aux->func_info; 16030 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 16031 if (!info_aux) 16032 return -ENOMEM; 16033 16034 for (i = 0; i < nfuncs; i++) { 16035 /* check insn_off */ 16036 ret = -EINVAL; 16037 16038 if (env->subprog_info[i].start != krecord[i].insn_off) { 16039 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 16040 goto err_free; 16041 } 16042 16043 /* Already checked type_id */ 16044 type = btf_type_by_id(btf, krecord[i].type_id); 16045 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 16046 /* Already checked func_proto */ 16047 func_proto = btf_type_by_id(btf, type->type); 16048 16049 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 16050 scalar_return = 16051 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 16052 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 16053 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 16054 goto err_free; 16055 } 16056 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 16057 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 16058 goto err_free; 16059 } 16060 16061 bpfptr_add(&urecord, urec_size); 16062 } 16063 16064 prog->aux->func_info_aux = info_aux; 16065 return 0; 16066 16067 err_free: 16068 kfree(info_aux); 16069 return ret; 16070 } 16071 16072 static void adjust_btf_func(struct bpf_verifier_env *env) 16073 { 16074 struct bpf_prog_aux *aux = env->prog->aux; 16075 int i; 16076 16077 if (!aux->func_info) 16078 return; 16079 16080 /* func_info is not available for hidden subprogs */ 16081 for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++) 16082 aux->func_info[i].insn_off = env->subprog_info[i].start; 16083 } 16084 16085 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 16086 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 16087 16088 static int check_btf_line(struct bpf_verifier_env *env, 16089 const union bpf_attr *attr, 16090 bpfptr_t uattr) 16091 { 16092 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 16093 struct bpf_subprog_info *sub; 16094 struct bpf_line_info *linfo; 16095 struct bpf_prog *prog; 16096 const struct btf *btf; 16097 bpfptr_t ulinfo; 16098 int err; 16099 16100 nr_linfo = attr->line_info_cnt; 16101 if (!nr_linfo) 16102 return 0; 16103 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 16104 return -EINVAL; 16105 16106 rec_size = attr->line_info_rec_size; 16107 if (rec_size < MIN_BPF_LINEINFO_SIZE || 16108 rec_size > MAX_LINEINFO_REC_SIZE || 16109 rec_size & (sizeof(u32) - 1)) 16110 return -EINVAL; 16111 16112 /* Need to zero it in case the userspace may 16113 * pass in a smaller bpf_line_info object. 16114 */ 16115 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 16116 GFP_KERNEL | __GFP_NOWARN); 16117 if (!linfo) 16118 return -ENOMEM; 16119 16120 prog = env->prog; 16121 btf = prog->aux->btf; 16122 16123 s = 0; 16124 sub = env->subprog_info; 16125 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 16126 expected_size = sizeof(struct bpf_line_info); 16127 ncopy = min_t(u32, expected_size, rec_size); 16128 for (i = 0; i < nr_linfo; i++) { 16129 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 16130 if (err) { 16131 if (err == -E2BIG) { 16132 verbose(env, "nonzero tailing record in line_info"); 16133 if (copy_to_bpfptr_offset(uattr, 16134 offsetof(union bpf_attr, line_info_rec_size), 16135 &expected_size, sizeof(expected_size))) 16136 err = -EFAULT; 16137 } 16138 goto err_free; 16139 } 16140 16141 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 16142 err = -EFAULT; 16143 goto err_free; 16144 } 16145 16146 /* 16147 * Check insn_off to ensure 16148 * 1) strictly increasing AND 16149 * 2) bounded by prog->len 16150 * 16151 * The linfo[0].insn_off == 0 check logically falls into 16152 * the later "missing bpf_line_info for func..." case 16153 * because the first linfo[0].insn_off must be the 16154 * first sub also and the first sub must have 16155 * subprog_info[0].start == 0. 16156 */ 16157 if ((i && linfo[i].insn_off <= prev_offset) || 16158 linfo[i].insn_off >= prog->len) { 16159 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 16160 i, linfo[i].insn_off, prev_offset, 16161 prog->len); 16162 err = -EINVAL; 16163 goto err_free; 16164 } 16165 16166 if (!prog->insnsi[linfo[i].insn_off].code) { 16167 verbose(env, 16168 "Invalid insn code at line_info[%u].insn_off\n", 16169 i); 16170 err = -EINVAL; 16171 goto err_free; 16172 } 16173 16174 if (!btf_name_by_offset(btf, linfo[i].line_off) || 16175 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 16176 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 16177 err = -EINVAL; 16178 goto err_free; 16179 } 16180 16181 if (s != env->subprog_cnt) { 16182 if (linfo[i].insn_off == sub[s].start) { 16183 sub[s].linfo_idx = i; 16184 s++; 16185 } else if (sub[s].start < linfo[i].insn_off) { 16186 verbose(env, "missing bpf_line_info for func#%u\n", s); 16187 err = -EINVAL; 16188 goto err_free; 16189 } 16190 } 16191 16192 prev_offset = linfo[i].insn_off; 16193 bpfptr_add(&ulinfo, rec_size); 16194 } 16195 16196 if (s != env->subprog_cnt) { 16197 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 16198 env->subprog_cnt - s, s); 16199 err = -EINVAL; 16200 goto err_free; 16201 } 16202 16203 prog->aux->linfo = linfo; 16204 prog->aux->nr_linfo = nr_linfo; 16205 16206 return 0; 16207 16208 err_free: 16209 kvfree(linfo); 16210 return err; 16211 } 16212 16213 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 16214 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 16215 16216 static int check_core_relo(struct bpf_verifier_env *env, 16217 const union bpf_attr *attr, 16218 bpfptr_t uattr) 16219 { 16220 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 16221 struct bpf_core_relo core_relo = {}; 16222 struct bpf_prog *prog = env->prog; 16223 const struct btf *btf = prog->aux->btf; 16224 struct bpf_core_ctx ctx = { 16225 .log = &env->log, 16226 .btf = btf, 16227 }; 16228 bpfptr_t u_core_relo; 16229 int err; 16230 16231 nr_core_relo = attr->core_relo_cnt; 16232 if (!nr_core_relo) 16233 return 0; 16234 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 16235 return -EINVAL; 16236 16237 rec_size = attr->core_relo_rec_size; 16238 if (rec_size < MIN_CORE_RELO_SIZE || 16239 rec_size > MAX_CORE_RELO_SIZE || 16240 rec_size % sizeof(u32)) 16241 return -EINVAL; 16242 16243 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 16244 expected_size = sizeof(struct bpf_core_relo); 16245 ncopy = min_t(u32, expected_size, rec_size); 16246 16247 /* Unlike func_info and line_info, copy and apply each CO-RE 16248 * relocation record one at a time. 16249 */ 16250 for (i = 0; i < nr_core_relo; i++) { 16251 /* future proofing when sizeof(bpf_core_relo) changes */ 16252 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 16253 if (err) { 16254 if (err == -E2BIG) { 16255 verbose(env, "nonzero tailing record in core_relo"); 16256 if (copy_to_bpfptr_offset(uattr, 16257 offsetof(union bpf_attr, core_relo_rec_size), 16258 &expected_size, sizeof(expected_size))) 16259 err = -EFAULT; 16260 } 16261 break; 16262 } 16263 16264 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 16265 err = -EFAULT; 16266 break; 16267 } 16268 16269 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 16270 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 16271 i, core_relo.insn_off, prog->len); 16272 err = -EINVAL; 16273 break; 16274 } 16275 16276 err = bpf_core_apply(&ctx, &core_relo, i, 16277 &prog->insnsi[core_relo.insn_off / 8]); 16278 if (err) 16279 break; 16280 bpfptr_add(&u_core_relo, rec_size); 16281 } 16282 return err; 16283 } 16284 16285 static int check_btf_info_early(struct bpf_verifier_env *env, 16286 const union bpf_attr *attr, 16287 bpfptr_t uattr) 16288 { 16289 struct btf *btf; 16290 int err; 16291 16292 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16293 if (check_abnormal_return(env)) 16294 return -EINVAL; 16295 return 0; 16296 } 16297 16298 btf = btf_get_by_fd(attr->prog_btf_fd); 16299 if (IS_ERR(btf)) 16300 return PTR_ERR(btf); 16301 if (btf_is_kernel(btf)) { 16302 btf_put(btf); 16303 return -EACCES; 16304 } 16305 env->prog->aux->btf = btf; 16306 16307 err = check_btf_func_early(env, attr, uattr); 16308 if (err) 16309 return err; 16310 return 0; 16311 } 16312 16313 static int check_btf_info(struct bpf_verifier_env *env, 16314 const union bpf_attr *attr, 16315 bpfptr_t uattr) 16316 { 16317 int err; 16318 16319 if (!attr->func_info_cnt && !attr->line_info_cnt) { 16320 if (check_abnormal_return(env)) 16321 return -EINVAL; 16322 return 0; 16323 } 16324 16325 err = check_btf_func(env, attr, uattr); 16326 if (err) 16327 return err; 16328 16329 err = check_btf_line(env, attr, uattr); 16330 if (err) 16331 return err; 16332 16333 err = check_core_relo(env, attr, uattr); 16334 if (err) 16335 return err; 16336 16337 return 0; 16338 } 16339 16340 /* check %cur's range satisfies %old's */ 16341 static bool range_within(const struct bpf_reg_state *old, 16342 const struct bpf_reg_state *cur) 16343 { 16344 return old->umin_value <= cur->umin_value && 16345 old->umax_value >= cur->umax_value && 16346 old->smin_value <= cur->smin_value && 16347 old->smax_value >= cur->smax_value && 16348 old->u32_min_value <= cur->u32_min_value && 16349 old->u32_max_value >= cur->u32_max_value && 16350 old->s32_min_value <= cur->s32_min_value && 16351 old->s32_max_value >= cur->s32_max_value; 16352 } 16353 16354 /* If in the old state two registers had the same id, then they need to have 16355 * the same id in the new state as well. But that id could be different from 16356 * the old state, so we need to track the mapping from old to new ids. 16357 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 16358 * regs with old id 5 must also have new id 9 for the new state to be safe. But 16359 * regs with a different old id could still have new id 9, we don't care about 16360 * that. 16361 * So we look through our idmap to see if this old id has been seen before. If 16362 * so, we require the new id to match; otherwise, we add the id pair to the map. 16363 */ 16364 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16365 { 16366 struct bpf_id_pair *map = idmap->map; 16367 unsigned int i; 16368 16369 /* either both IDs should be set or both should be zero */ 16370 if (!!old_id != !!cur_id) 16371 return false; 16372 16373 if (old_id == 0) /* cur_id == 0 as well */ 16374 return true; 16375 16376 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 16377 if (!map[i].old) { 16378 /* Reached an empty slot; haven't seen this id before */ 16379 map[i].old = old_id; 16380 map[i].cur = cur_id; 16381 return true; 16382 } 16383 if (map[i].old == old_id) 16384 return map[i].cur == cur_id; 16385 if (map[i].cur == cur_id) 16386 return false; 16387 } 16388 /* We ran out of idmap slots, which should be impossible */ 16389 WARN_ON_ONCE(1); 16390 return false; 16391 } 16392 16393 /* Similar to check_ids(), but allocate a unique temporary ID 16394 * for 'old_id' or 'cur_id' of zero. 16395 * This makes pairs like '0 vs unique ID', 'unique ID vs 0' valid. 16396 */ 16397 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 16398 { 16399 old_id = old_id ? old_id : ++idmap->tmp_id_gen; 16400 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 16401 16402 return check_ids(old_id, cur_id, idmap); 16403 } 16404 16405 static void clean_func_state(struct bpf_verifier_env *env, 16406 struct bpf_func_state *st) 16407 { 16408 enum bpf_reg_liveness live; 16409 int i, j; 16410 16411 for (i = 0; i < BPF_REG_FP; i++) { 16412 live = st->regs[i].live; 16413 /* liveness must not touch this register anymore */ 16414 st->regs[i].live |= REG_LIVE_DONE; 16415 if (!(live & REG_LIVE_READ)) 16416 /* since the register is unused, clear its state 16417 * to make further comparison simpler 16418 */ 16419 __mark_reg_not_init(env, &st->regs[i]); 16420 } 16421 16422 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 16423 live = st->stack[i].spilled_ptr.live; 16424 /* liveness must not touch this stack slot anymore */ 16425 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 16426 if (!(live & REG_LIVE_READ)) { 16427 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 16428 for (j = 0; j < BPF_REG_SIZE; j++) 16429 st->stack[i].slot_type[j] = STACK_INVALID; 16430 } 16431 } 16432 } 16433 16434 static void clean_verifier_state(struct bpf_verifier_env *env, 16435 struct bpf_verifier_state *st) 16436 { 16437 int i; 16438 16439 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 16440 /* all regs in this state in all frames were already marked */ 16441 return; 16442 16443 for (i = 0; i <= st->curframe; i++) 16444 clean_func_state(env, st->frame[i]); 16445 } 16446 16447 /* the parentage chains form a tree. 16448 * the verifier states are added to state lists at given insn and 16449 * pushed into state stack for future exploration. 16450 * when the verifier reaches bpf_exit insn some of the verifer states 16451 * stored in the state lists have their final liveness state already, 16452 * but a lot of states will get revised from liveness point of view when 16453 * the verifier explores other branches. 16454 * Example: 16455 * 1: r0 = 1 16456 * 2: if r1 == 100 goto pc+1 16457 * 3: r0 = 2 16458 * 4: exit 16459 * when the verifier reaches exit insn the register r0 in the state list of 16460 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 16461 * of insn 2 and goes exploring further. At the insn 4 it will walk the 16462 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 16463 * 16464 * Since the verifier pushes the branch states as it sees them while exploring 16465 * the program the condition of walking the branch instruction for the second 16466 * time means that all states below this branch were already explored and 16467 * their final liveness marks are already propagated. 16468 * Hence when the verifier completes the search of state list in is_state_visited() 16469 * we can call this clean_live_states() function to mark all liveness states 16470 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 16471 * will not be used. 16472 * This function also clears the registers and stack for states that !READ 16473 * to simplify state merging. 16474 * 16475 * Important note here that walking the same branch instruction in the callee 16476 * doesn't meant that the states are DONE. The verifier has to compare 16477 * the callsites 16478 */ 16479 static void clean_live_states(struct bpf_verifier_env *env, int insn, 16480 struct bpf_verifier_state *cur) 16481 { 16482 struct bpf_verifier_state_list *sl; 16483 16484 sl = *explored_state(env, insn); 16485 while (sl) { 16486 if (sl->state.branches) 16487 goto next; 16488 if (sl->state.insn_idx != insn || 16489 !same_callsites(&sl->state, cur)) 16490 goto next; 16491 clean_verifier_state(env, &sl->state); 16492 next: 16493 sl = sl->next; 16494 } 16495 } 16496 16497 static bool regs_exact(const struct bpf_reg_state *rold, 16498 const struct bpf_reg_state *rcur, 16499 struct bpf_idmap *idmap) 16500 { 16501 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16502 check_ids(rold->id, rcur->id, idmap) && 16503 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16504 } 16505 16506 enum exact_level { 16507 NOT_EXACT, 16508 EXACT, 16509 RANGE_WITHIN 16510 }; 16511 16512 /* Returns true if (rold safe implies rcur safe) */ 16513 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 16514 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 16515 enum exact_level exact) 16516 { 16517 if (exact == EXACT) 16518 return regs_exact(rold, rcur, idmap); 16519 16520 if (!(rold->live & REG_LIVE_READ) && exact == NOT_EXACT) 16521 /* explored state didn't use this */ 16522 return true; 16523 if (rold->type == NOT_INIT) { 16524 if (exact == NOT_EXACT || rcur->type == NOT_INIT) 16525 /* explored state can't have used this */ 16526 return true; 16527 } 16528 16529 /* Enforce that register types have to match exactly, including their 16530 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 16531 * rule. 16532 * 16533 * One can make a point that using a pointer register as unbounded 16534 * SCALAR would be technically acceptable, but this could lead to 16535 * pointer leaks because scalars are allowed to leak while pointers 16536 * are not. We could make this safe in special cases if root is 16537 * calling us, but it's probably not worth the hassle. 16538 * 16539 * Also, register types that are *not* MAYBE_NULL could technically be 16540 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 16541 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 16542 * to the same map). 16543 * However, if the old MAYBE_NULL register then got NULL checked, 16544 * doing so could have affected others with the same id, and we can't 16545 * check for that because we lost the id when we converted to 16546 * a non-MAYBE_NULL variant. 16547 * So, as a general rule we don't allow mixing MAYBE_NULL and 16548 * non-MAYBE_NULL registers as well. 16549 */ 16550 if (rold->type != rcur->type) 16551 return false; 16552 16553 switch (base_type(rold->type)) { 16554 case SCALAR_VALUE: 16555 if (env->explore_alu_limits) { 16556 /* explore_alu_limits disables tnum_in() and range_within() 16557 * logic and requires everything to be strict 16558 */ 16559 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 16560 check_scalar_ids(rold->id, rcur->id, idmap); 16561 } 16562 if (!rold->precise && exact == NOT_EXACT) 16563 return true; 16564 /* Why check_ids() for scalar registers? 16565 * 16566 * Consider the following BPF code: 16567 * 1: r6 = ... unbound scalar, ID=a ... 16568 * 2: r7 = ... unbound scalar, ID=b ... 16569 * 3: if (r6 > r7) goto +1 16570 * 4: r6 = r7 16571 * 5: if (r6 > X) goto ... 16572 * 6: ... memory operation using r7 ... 16573 * 16574 * First verification path is [1-6]: 16575 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 16576 * - at (5) r6 would be marked <= X, find_equal_scalars() would also mark 16577 * r7 <= X, because r6 and r7 share same id. 16578 * Next verification path is [1-4, 6]. 16579 * 16580 * Instruction (6) would be reached in two states: 16581 * I. r6{.id=b}, r7{.id=b} via path 1-6; 16582 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 16583 * 16584 * Use check_ids() to distinguish these states. 16585 * --- 16586 * Also verify that new value satisfies old value range knowledge. 16587 */ 16588 return range_within(rold, rcur) && 16589 tnum_in(rold->var_off, rcur->var_off) && 16590 check_scalar_ids(rold->id, rcur->id, idmap); 16591 case PTR_TO_MAP_KEY: 16592 case PTR_TO_MAP_VALUE: 16593 case PTR_TO_MEM: 16594 case PTR_TO_BUF: 16595 case PTR_TO_TP_BUFFER: 16596 /* If the new min/max/var_off satisfy the old ones and 16597 * everything else matches, we are OK. 16598 */ 16599 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 16600 range_within(rold, rcur) && 16601 tnum_in(rold->var_off, rcur->var_off) && 16602 check_ids(rold->id, rcur->id, idmap) && 16603 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 16604 case PTR_TO_PACKET_META: 16605 case PTR_TO_PACKET: 16606 /* We must have at least as much range as the old ptr 16607 * did, so that any accesses which were safe before are 16608 * still safe. This is true even if old range < old off, 16609 * since someone could have accessed through (ptr - k), or 16610 * even done ptr -= k in a register, to get a safe access. 16611 */ 16612 if (rold->range > rcur->range) 16613 return false; 16614 /* If the offsets don't match, we can't trust our alignment; 16615 * nor can we be sure that we won't fall out of range. 16616 */ 16617 if (rold->off != rcur->off) 16618 return false; 16619 /* id relations must be preserved */ 16620 if (!check_ids(rold->id, rcur->id, idmap)) 16621 return false; 16622 /* new val must satisfy old val knowledge */ 16623 return range_within(rold, rcur) && 16624 tnum_in(rold->var_off, rcur->var_off); 16625 case PTR_TO_STACK: 16626 /* two stack pointers are equal only if they're pointing to 16627 * the same stack frame, since fp-8 in foo != fp-8 in bar 16628 */ 16629 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 16630 case PTR_TO_ARENA: 16631 return true; 16632 default: 16633 return regs_exact(rold, rcur, idmap); 16634 } 16635 } 16636 16637 static struct bpf_reg_state unbound_reg; 16638 16639 static __init int unbound_reg_init(void) 16640 { 16641 __mark_reg_unknown_imprecise(&unbound_reg); 16642 unbound_reg.live |= REG_LIVE_READ; 16643 return 0; 16644 } 16645 late_initcall(unbound_reg_init); 16646 16647 static bool is_stack_all_misc(struct bpf_verifier_env *env, 16648 struct bpf_stack_state *stack) 16649 { 16650 u32 i; 16651 16652 for (i = 0; i < ARRAY_SIZE(stack->slot_type); ++i) { 16653 if ((stack->slot_type[i] == STACK_MISC) || 16654 (stack->slot_type[i] == STACK_INVALID && env->allow_uninit_stack)) 16655 continue; 16656 return false; 16657 } 16658 16659 return true; 16660 } 16661 16662 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 16663 struct bpf_stack_state *stack) 16664 { 16665 if (is_spilled_scalar_reg64(stack)) 16666 return &stack->spilled_ptr; 16667 16668 if (is_stack_all_misc(env, stack)) 16669 return &unbound_reg; 16670 16671 return NULL; 16672 } 16673 16674 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 16675 struct bpf_func_state *cur, struct bpf_idmap *idmap, 16676 enum exact_level exact) 16677 { 16678 int i, spi; 16679 16680 /* walk slots of the explored stack and ignore any additional 16681 * slots in the current stack, since explored(safe) state 16682 * didn't use them 16683 */ 16684 for (i = 0; i < old->allocated_stack; i++) { 16685 struct bpf_reg_state *old_reg, *cur_reg; 16686 16687 spi = i / BPF_REG_SIZE; 16688 16689 if (exact != NOT_EXACT && 16690 old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16691 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16692 return false; 16693 16694 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ) 16695 && exact == NOT_EXACT) { 16696 i += BPF_REG_SIZE - 1; 16697 /* explored state didn't use this */ 16698 continue; 16699 } 16700 16701 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 16702 continue; 16703 16704 if (env->allow_uninit_stack && 16705 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 16706 continue; 16707 16708 /* explored stack has more populated slots than current stack 16709 * and these slots were used 16710 */ 16711 if (i >= cur->allocated_stack) 16712 return false; 16713 16714 /* 64-bit scalar spill vs all slots MISC and vice versa. 16715 * Load from all slots MISC produces unbound scalar. 16716 * Construct a fake register for such stack and call 16717 * regsafe() to ensure scalar ids are compared. 16718 */ 16719 old_reg = scalar_reg_for_stack(env, &old->stack[spi]); 16720 cur_reg = scalar_reg_for_stack(env, &cur->stack[spi]); 16721 if (old_reg && cur_reg) { 16722 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 16723 return false; 16724 i += BPF_REG_SIZE - 1; 16725 continue; 16726 } 16727 16728 /* if old state was safe with misc data in the stack 16729 * it will be safe with zero-initialized stack. 16730 * The opposite is not true 16731 */ 16732 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 16733 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 16734 continue; 16735 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 16736 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 16737 /* Ex: old explored (safe) state has STACK_SPILL in 16738 * this stack slot, but current has STACK_MISC -> 16739 * this verifier states are not equivalent, 16740 * return false to continue verification of this path 16741 */ 16742 return false; 16743 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 16744 continue; 16745 /* Both old and cur are having same slot_type */ 16746 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 16747 case STACK_SPILL: 16748 /* when explored and current stack slot are both storing 16749 * spilled registers, check that stored pointers types 16750 * are the same as well. 16751 * Ex: explored safe path could have stored 16752 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 16753 * but current path has stored: 16754 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 16755 * such verifier states are not equivalent. 16756 * return false to continue verification of this path 16757 */ 16758 if (!regsafe(env, &old->stack[spi].spilled_ptr, 16759 &cur->stack[spi].spilled_ptr, idmap, exact)) 16760 return false; 16761 break; 16762 case STACK_DYNPTR: 16763 old_reg = &old->stack[spi].spilled_ptr; 16764 cur_reg = &cur->stack[spi].spilled_ptr; 16765 if (old_reg->dynptr.type != cur_reg->dynptr.type || 16766 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 16767 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16768 return false; 16769 break; 16770 case STACK_ITER: 16771 old_reg = &old->stack[spi].spilled_ptr; 16772 cur_reg = &cur->stack[spi].spilled_ptr; 16773 /* iter.depth is not compared between states as it 16774 * doesn't matter for correctness and would otherwise 16775 * prevent convergence; we maintain it only to prevent 16776 * infinite loop check triggering, see 16777 * iter_active_depths_differ() 16778 */ 16779 if (old_reg->iter.btf != cur_reg->iter.btf || 16780 old_reg->iter.btf_id != cur_reg->iter.btf_id || 16781 old_reg->iter.state != cur_reg->iter.state || 16782 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 16783 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 16784 return false; 16785 break; 16786 case STACK_MISC: 16787 case STACK_ZERO: 16788 case STACK_INVALID: 16789 continue; 16790 /* Ensure that new unhandled slot types return false by default */ 16791 default: 16792 return false; 16793 } 16794 } 16795 return true; 16796 } 16797 16798 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 16799 struct bpf_idmap *idmap) 16800 { 16801 int i; 16802 16803 if (old->acquired_refs != cur->acquired_refs) 16804 return false; 16805 16806 for (i = 0; i < old->acquired_refs; i++) { 16807 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 16808 return false; 16809 } 16810 16811 return true; 16812 } 16813 16814 /* compare two verifier states 16815 * 16816 * all states stored in state_list are known to be valid, since 16817 * verifier reached 'bpf_exit' instruction through them 16818 * 16819 * this function is called when verifier exploring different branches of 16820 * execution popped from the state stack. If it sees an old state that has 16821 * more strict register state and more strict stack state then this execution 16822 * branch doesn't need to be explored further, since verifier already 16823 * concluded that more strict state leads to valid finish. 16824 * 16825 * Therefore two states are equivalent if register state is more conservative 16826 * and explored stack state is more conservative than the current one. 16827 * Example: 16828 * explored current 16829 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 16830 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 16831 * 16832 * In other words if current stack state (one being explored) has more 16833 * valid slots than old one that already passed validation, it means 16834 * the verifier can stop exploring and conclude that current state is valid too 16835 * 16836 * Similarly with registers. If explored state has register type as invalid 16837 * whereas register type in current state is meaningful, it means that 16838 * the current state will reach 'bpf_exit' instruction safely 16839 */ 16840 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 16841 struct bpf_func_state *cur, enum exact_level exact) 16842 { 16843 int i; 16844 16845 if (old->callback_depth > cur->callback_depth) 16846 return false; 16847 16848 for (i = 0; i < MAX_BPF_REG; i++) 16849 if (!regsafe(env, &old->regs[i], &cur->regs[i], 16850 &env->idmap_scratch, exact)) 16851 return false; 16852 16853 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 16854 return false; 16855 16856 if (!refsafe(old, cur, &env->idmap_scratch)) 16857 return false; 16858 16859 return true; 16860 } 16861 16862 static void reset_idmap_scratch(struct bpf_verifier_env *env) 16863 { 16864 env->idmap_scratch.tmp_id_gen = env->id_gen; 16865 memset(&env->idmap_scratch.map, 0, sizeof(env->idmap_scratch.map)); 16866 } 16867 16868 static bool states_equal(struct bpf_verifier_env *env, 16869 struct bpf_verifier_state *old, 16870 struct bpf_verifier_state *cur, 16871 enum exact_level exact) 16872 { 16873 int i; 16874 16875 if (old->curframe != cur->curframe) 16876 return false; 16877 16878 reset_idmap_scratch(env); 16879 16880 /* Verification state from speculative execution simulation 16881 * must never prune a non-speculative execution one. 16882 */ 16883 if (old->speculative && !cur->speculative) 16884 return false; 16885 16886 if (old->active_lock.ptr != cur->active_lock.ptr) 16887 return false; 16888 16889 /* Old and cur active_lock's have to be either both present 16890 * or both absent. 16891 */ 16892 if (!!old->active_lock.id != !!cur->active_lock.id) 16893 return false; 16894 16895 if (old->active_lock.id && 16896 !check_ids(old->active_lock.id, cur->active_lock.id, &env->idmap_scratch)) 16897 return false; 16898 16899 if (old->active_rcu_lock != cur->active_rcu_lock) 16900 return false; 16901 16902 /* for states to be equal callsites have to be the same 16903 * and all frame states need to be equivalent 16904 */ 16905 for (i = 0; i <= old->curframe; i++) { 16906 if (old->frame[i]->callsite != cur->frame[i]->callsite) 16907 return false; 16908 if (!func_states_equal(env, old->frame[i], cur->frame[i], exact)) 16909 return false; 16910 } 16911 return true; 16912 } 16913 16914 /* Return 0 if no propagation happened. Return negative error code if error 16915 * happened. Otherwise, return the propagated bit. 16916 */ 16917 static int propagate_liveness_reg(struct bpf_verifier_env *env, 16918 struct bpf_reg_state *reg, 16919 struct bpf_reg_state *parent_reg) 16920 { 16921 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 16922 u8 flag = reg->live & REG_LIVE_READ; 16923 int err; 16924 16925 /* When comes here, read flags of PARENT_REG or REG could be any of 16926 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 16927 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 16928 */ 16929 if (parent_flag == REG_LIVE_READ64 || 16930 /* Or if there is no read flag from REG. */ 16931 !flag || 16932 /* Or if the read flag from REG is the same as PARENT_REG. */ 16933 parent_flag == flag) 16934 return 0; 16935 16936 err = mark_reg_read(env, reg, parent_reg, flag); 16937 if (err) 16938 return err; 16939 16940 return flag; 16941 } 16942 16943 /* A write screens off any subsequent reads; but write marks come from the 16944 * straight-line code between a state and its parent. When we arrive at an 16945 * equivalent state (jump target or such) we didn't arrive by the straight-line 16946 * code, so read marks in the state must propagate to the parent regardless 16947 * of the state's write marks. That's what 'parent == state->parent' comparison 16948 * in mark_reg_read() is for. 16949 */ 16950 static int propagate_liveness(struct bpf_verifier_env *env, 16951 const struct bpf_verifier_state *vstate, 16952 struct bpf_verifier_state *vparent) 16953 { 16954 struct bpf_reg_state *state_reg, *parent_reg; 16955 struct bpf_func_state *state, *parent; 16956 int i, frame, err = 0; 16957 16958 if (vparent->curframe != vstate->curframe) { 16959 WARN(1, "propagate_live: parent frame %d current frame %d\n", 16960 vparent->curframe, vstate->curframe); 16961 return -EFAULT; 16962 } 16963 /* Propagate read liveness of registers... */ 16964 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 16965 for (frame = 0; frame <= vstate->curframe; frame++) { 16966 parent = vparent->frame[frame]; 16967 state = vstate->frame[frame]; 16968 parent_reg = parent->regs; 16969 state_reg = state->regs; 16970 /* We don't need to worry about FP liveness, it's read-only */ 16971 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 16972 err = propagate_liveness_reg(env, &state_reg[i], 16973 &parent_reg[i]); 16974 if (err < 0) 16975 return err; 16976 if (err == REG_LIVE_READ64) 16977 mark_insn_zext(env, &parent_reg[i]); 16978 } 16979 16980 /* Propagate stack slots. */ 16981 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 16982 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 16983 parent_reg = &parent->stack[i].spilled_ptr; 16984 state_reg = &state->stack[i].spilled_ptr; 16985 err = propagate_liveness_reg(env, state_reg, 16986 parent_reg); 16987 if (err < 0) 16988 return err; 16989 } 16990 } 16991 return 0; 16992 } 16993 16994 /* find precise scalars in the previous equivalent state and 16995 * propagate them into the current state 16996 */ 16997 static int propagate_precision(struct bpf_verifier_env *env, 16998 const struct bpf_verifier_state *old) 16999 { 17000 struct bpf_reg_state *state_reg; 17001 struct bpf_func_state *state; 17002 int i, err = 0, fr; 17003 bool first; 17004 17005 for (fr = old->curframe; fr >= 0; fr--) { 17006 state = old->frame[fr]; 17007 state_reg = state->regs; 17008 first = true; 17009 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 17010 if (state_reg->type != SCALAR_VALUE || 17011 !state_reg->precise || 17012 !(state_reg->live & REG_LIVE_READ)) 17013 continue; 17014 if (env->log.level & BPF_LOG_LEVEL2) { 17015 if (first) 17016 verbose(env, "frame %d: propagating r%d", fr, i); 17017 else 17018 verbose(env, ",r%d", i); 17019 } 17020 bt_set_frame_reg(&env->bt, fr, i); 17021 first = false; 17022 } 17023 17024 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17025 if (!is_spilled_reg(&state->stack[i])) 17026 continue; 17027 state_reg = &state->stack[i].spilled_ptr; 17028 if (state_reg->type != SCALAR_VALUE || 17029 !state_reg->precise || 17030 !(state_reg->live & REG_LIVE_READ)) 17031 continue; 17032 if (env->log.level & BPF_LOG_LEVEL2) { 17033 if (first) 17034 verbose(env, "frame %d: propagating fp%d", 17035 fr, (-i - 1) * BPF_REG_SIZE); 17036 else 17037 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 17038 } 17039 bt_set_frame_slot(&env->bt, fr, i); 17040 first = false; 17041 } 17042 if (!first) 17043 verbose(env, "\n"); 17044 } 17045 17046 err = mark_chain_precision_batch(env); 17047 if (err < 0) 17048 return err; 17049 17050 return 0; 17051 } 17052 17053 static bool states_maybe_looping(struct bpf_verifier_state *old, 17054 struct bpf_verifier_state *cur) 17055 { 17056 struct bpf_func_state *fold, *fcur; 17057 int i, fr = cur->curframe; 17058 17059 if (old->curframe != fr) 17060 return false; 17061 17062 fold = old->frame[fr]; 17063 fcur = cur->frame[fr]; 17064 for (i = 0; i < MAX_BPF_REG; i++) 17065 if (memcmp(&fold->regs[i], &fcur->regs[i], 17066 offsetof(struct bpf_reg_state, parent))) 17067 return false; 17068 return true; 17069 } 17070 17071 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 17072 { 17073 return env->insn_aux_data[insn_idx].is_iter_next; 17074 } 17075 17076 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 17077 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 17078 * states to match, which otherwise would look like an infinite loop. So while 17079 * iter_next() calls are taken care of, we still need to be careful and 17080 * prevent erroneous and too eager declaration of "ininite loop", when 17081 * iterators are involved. 17082 * 17083 * Here's a situation in pseudo-BPF assembly form: 17084 * 17085 * 0: again: ; set up iter_next() call args 17086 * 1: r1 = &it ; <CHECKPOINT HERE> 17087 * 2: call bpf_iter_num_next ; this is iter_next() call 17088 * 3: if r0 == 0 goto done 17089 * 4: ... something useful here ... 17090 * 5: goto again ; another iteration 17091 * 6: done: 17092 * 7: r1 = &it 17093 * 8: call bpf_iter_num_destroy ; clean up iter state 17094 * 9: exit 17095 * 17096 * This is a typical loop. Let's assume that we have a prune point at 1:, 17097 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 17098 * again`, assuming other heuristics don't get in a way). 17099 * 17100 * When we first time come to 1:, let's say we have some state X. We proceed 17101 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 17102 * Now we come back to validate that forked ACTIVE state. We proceed through 17103 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 17104 * are converging. But the problem is that we don't know that yet, as this 17105 * convergence has to happen at iter_next() call site only. So if nothing is 17106 * done, at 1: verifier will use bounded loop logic and declare infinite 17107 * looping (and would be *technically* correct, if not for iterator's 17108 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 17109 * don't want that. So what we do in process_iter_next_call() when we go on 17110 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 17111 * a different iteration. So when we suspect an infinite loop, we additionally 17112 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 17113 * pretend we are not looping and wait for next iter_next() call. 17114 * 17115 * This only applies to ACTIVE state. In DRAINED state we don't expect to 17116 * loop, because that would actually mean infinite loop, as DRAINED state is 17117 * "sticky", and so we'll keep returning into the same instruction with the 17118 * same state (at least in one of possible code paths). 17119 * 17120 * This approach allows to keep infinite loop heuristic even in the face of 17121 * active iterator. E.g., C snippet below is and will be detected as 17122 * inifintely looping: 17123 * 17124 * struct bpf_iter_num it; 17125 * int *p, x; 17126 * 17127 * bpf_iter_num_new(&it, 0, 10); 17128 * while ((p = bpf_iter_num_next(&t))) { 17129 * x = p; 17130 * while (x--) {} // <<-- infinite loop here 17131 * } 17132 * 17133 */ 17134 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 17135 { 17136 struct bpf_reg_state *slot, *cur_slot; 17137 struct bpf_func_state *state; 17138 int i, fr; 17139 17140 for (fr = old->curframe; fr >= 0; fr--) { 17141 state = old->frame[fr]; 17142 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 17143 if (state->stack[i].slot_type[0] != STACK_ITER) 17144 continue; 17145 17146 slot = &state->stack[i].spilled_ptr; 17147 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 17148 continue; 17149 17150 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 17151 if (cur_slot->iter.depth != slot->iter.depth) 17152 return true; 17153 } 17154 } 17155 return false; 17156 } 17157 17158 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 17159 { 17160 struct bpf_verifier_state_list *new_sl; 17161 struct bpf_verifier_state_list *sl, **pprev; 17162 struct bpf_verifier_state *cur = env->cur_state, *new, *loop_entry; 17163 int i, j, n, err, states_cnt = 0; 17164 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 17165 bool add_new_state = force_new_state; 17166 bool force_exact; 17167 17168 /* bpf progs typically have pruning point every 4 instructions 17169 * http://vger.kernel.org/bpfconf2019.html#session-1 17170 * Do not add new state for future pruning if the verifier hasn't seen 17171 * at least 2 jumps and at least 8 instructions. 17172 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 17173 * In tests that amounts to up to 50% reduction into total verifier 17174 * memory consumption and 20% verifier time speedup. 17175 */ 17176 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 17177 env->insn_processed - env->prev_insn_processed >= 8) 17178 add_new_state = true; 17179 17180 pprev = explored_state(env, insn_idx); 17181 sl = *pprev; 17182 17183 clean_live_states(env, insn_idx, cur); 17184 17185 while (sl) { 17186 states_cnt++; 17187 if (sl->state.insn_idx != insn_idx) 17188 goto next; 17189 17190 if (sl->state.branches) { 17191 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 17192 17193 if (frame->in_async_callback_fn && 17194 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 17195 /* Different async_entry_cnt means that the verifier is 17196 * processing another entry into async callback. 17197 * Seeing the same state is not an indication of infinite 17198 * loop or infinite recursion. 17199 * But finding the same state doesn't mean that it's safe 17200 * to stop processing the current state. The previous state 17201 * hasn't yet reached bpf_exit, since state.branches > 0. 17202 * Checking in_async_callback_fn alone is not enough either. 17203 * Since the verifier still needs to catch infinite loops 17204 * inside async callbacks. 17205 */ 17206 goto skip_inf_loop_check; 17207 } 17208 /* BPF open-coded iterators loop detection is special. 17209 * states_maybe_looping() logic is too simplistic in detecting 17210 * states that *might* be equivalent, because it doesn't know 17211 * about ID remapping, so don't even perform it. 17212 * See process_iter_next_call() and iter_active_depths_differ() 17213 * for overview of the logic. When current and one of parent 17214 * states are detected as equivalent, it's a good thing: we prove 17215 * convergence and can stop simulating further iterations. 17216 * It's safe to assume that iterator loop will finish, taking into 17217 * account iter_next() contract of eventually returning 17218 * sticky NULL result. 17219 * 17220 * Note, that states have to be compared exactly in this case because 17221 * read and precision marks might not be finalized inside the loop. 17222 * E.g. as in the program below: 17223 * 17224 * 1. r7 = -16 17225 * 2. r6 = bpf_get_prandom_u32() 17226 * 3. while (bpf_iter_num_next(&fp[-8])) { 17227 * 4. if (r6 != 42) { 17228 * 5. r7 = -32 17229 * 6. r6 = bpf_get_prandom_u32() 17230 * 7. continue 17231 * 8. } 17232 * 9. r0 = r10 17233 * 10. r0 += r7 17234 * 11. r8 = *(u64 *)(r0 + 0) 17235 * 12. r6 = bpf_get_prandom_u32() 17236 * 13. } 17237 * 17238 * Here verifier would first visit path 1-3, create a checkpoint at 3 17239 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 17240 * not have read or precision mark for r7 yet, thus inexact states 17241 * comparison would discard current state with r7=-32 17242 * => unsafe memory access at 11 would not be caught. 17243 */ 17244 if (is_iter_next_insn(env, insn_idx)) { 17245 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17246 struct bpf_func_state *cur_frame; 17247 struct bpf_reg_state *iter_state, *iter_reg; 17248 int spi; 17249 17250 cur_frame = cur->frame[cur->curframe]; 17251 /* btf_check_iter_kfuncs() enforces that 17252 * iter state pointer is always the first arg 17253 */ 17254 iter_reg = &cur_frame->regs[BPF_REG_1]; 17255 /* current state is valid due to states_equal(), 17256 * so we can assume valid iter and reg state, 17257 * no need for extra (re-)validations 17258 */ 17259 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 17260 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 17261 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) { 17262 update_loop_entry(cur, &sl->state); 17263 goto hit; 17264 } 17265 } 17266 goto skip_inf_loop_check; 17267 } 17268 if (is_may_goto_insn_at(env, insn_idx)) { 17269 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 17270 update_loop_entry(cur, &sl->state); 17271 goto hit; 17272 } 17273 goto skip_inf_loop_check; 17274 } 17275 if (calls_callback(env, insn_idx)) { 17276 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) 17277 goto hit; 17278 goto skip_inf_loop_check; 17279 } 17280 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 17281 if (states_maybe_looping(&sl->state, cur) && 17282 states_equal(env, &sl->state, cur, EXACT) && 17283 !iter_active_depths_differ(&sl->state, cur) && 17284 sl->state.may_goto_depth == cur->may_goto_depth && 17285 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 17286 verbose_linfo(env, insn_idx, "; "); 17287 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 17288 verbose(env, "cur state:"); 17289 print_verifier_state(env, cur->frame[cur->curframe], true); 17290 verbose(env, "old state:"); 17291 print_verifier_state(env, sl->state.frame[cur->curframe], true); 17292 return -EINVAL; 17293 } 17294 /* if the verifier is processing a loop, avoid adding new state 17295 * too often, since different loop iterations have distinct 17296 * states and may not help future pruning. 17297 * This threshold shouldn't be too low to make sure that 17298 * a loop with large bound will be rejected quickly. 17299 * The most abusive loop will be: 17300 * r1 += 1 17301 * if r1 < 1000000 goto pc-2 17302 * 1M insn_procssed limit / 100 == 10k peak states. 17303 * This threshold shouldn't be too high either, since states 17304 * at the end of the loop are likely to be useful in pruning. 17305 */ 17306 skip_inf_loop_check: 17307 if (!force_new_state && 17308 env->jmps_processed - env->prev_jmps_processed < 20 && 17309 env->insn_processed - env->prev_insn_processed < 100) 17310 add_new_state = false; 17311 goto miss; 17312 } 17313 /* If sl->state is a part of a loop and this loop's entry is a part of 17314 * current verification path then states have to be compared exactly. 17315 * 'force_exact' is needed to catch the following case: 17316 * 17317 * initial Here state 'succ' was processed first, 17318 * | it was eventually tracked to produce a 17319 * V state identical to 'hdr'. 17320 * .---------> hdr All branches from 'succ' had been explored 17321 * | | and thus 'succ' has its .branches == 0. 17322 * | V 17323 * | .------... Suppose states 'cur' and 'succ' correspond 17324 * | | | to the same instruction + callsites. 17325 * | V V In such case it is necessary to check 17326 * | ... ... if 'succ' and 'cur' are states_equal(). 17327 * | | | If 'succ' and 'cur' are a part of the 17328 * | V V same loop exact flag has to be set. 17329 * | succ <- cur To check if that is the case, verify 17330 * | | if loop entry of 'succ' is in current 17331 * | V DFS path. 17332 * | ... 17333 * | | 17334 * '----' 17335 * 17336 * Additional details are in the comment before get_loop_entry(). 17337 */ 17338 loop_entry = get_loop_entry(&sl->state); 17339 force_exact = loop_entry && loop_entry->branches > 0; 17340 if (states_equal(env, &sl->state, cur, force_exact ? RANGE_WITHIN : NOT_EXACT)) { 17341 if (force_exact) 17342 update_loop_entry(cur, loop_entry); 17343 hit: 17344 sl->hit_cnt++; 17345 /* reached equivalent register/stack state, 17346 * prune the search. 17347 * Registers read by the continuation are read by us. 17348 * If we have any write marks in env->cur_state, they 17349 * will prevent corresponding reads in the continuation 17350 * from reaching our parent (an explored_state). Our 17351 * own state will get the read marks recorded, but 17352 * they'll be immediately forgotten as we're pruning 17353 * this state and will pop a new one. 17354 */ 17355 err = propagate_liveness(env, &sl->state, cur); 17356 17357 /* if previous state reached the exit with precision and 17358 * current state is equivalent to it (except precsion marks) 17359 * the precision needs to be propagated back in 17360 * the current state. 17361 */ 17362 if (is_jmp_point(env, env->insn_idx)) 17363 err = err ? : push_jmp_history(env, cur, 0); 17364 err = err ? : propagate_precision(env, &sl->state); 17365 if (err) 17366 return err; 17367 return 1; 17368 } 17369 miss: 17370 /* when new state is not going to be added do not increase miss count. 17371 * Otherwise several loop iterations will remove the state 17372 * recorded earlier. The goal of these heuristics is to have 17373 * states from some iterations of the loop (some in the beginning 17374 * and some at the end) to help pruning. 17375 */ 17376 if (add_new_state) 17377 sl->miss_cnt++; 17378 /* heuristic to determine whether this state is beneficial 17379 * to keep checking from state equivalence point of view. 17380 * Higher numbers increase max_states_per_insn and verification time, 17381 * but do not meaningfully decrease insn_processed. 17382 * 'n' controls how many times state could miss before eviction. 17383 * Use bigger 'n' for checkpoints because evicting checkpoint states 17384 * too early would hinder iterator convergence. 17385 */ 17386 n = is_force_checkpoint(env, insn_idx) && sl->state.branches > 0 ? 64 : 3; 17387 if (sl->miss_cnt > sl->hit_cnt * n + n) { 17388 /* the state is unlikely to be useful. Remove it to 17389 * speed up verification 17390 */ 17391 *pprev = sl->next; 17392 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE && 17393 !sl->state.used_as_loop_entry) { 17394 u32 br = sl->state.branches; 17395 17396 WARN_ONCE(br, 17397 "BUG live_done but branches_to_explore %d\n", 17398 br); 17399 free_verifier_state(&sl->state, false); 17400 kfree(sl); 17401 env->peak_states--; 17402 } else { 17403 /* cannot free this state, since parentage chain may 17404 * walk it later. Add it for free_list instead to 17405 * be freed at the end of verification 17406 */ 17407 sl->next = env->free_list; 17408 env->free_list = sl; 17409 } 17410 sl = *pprev; 17411 continue; 17412 } 17413 next: 17414 pprev = &sl->next; 17415 sl = *pprev; 17416 } 17417 17418 if (env->max_states_per_insn < states_cnt) 17419 env->max_states_per_insn = states_cnt; 17420 17421 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 17422 return 0; 17423 17424 if (!add_new_state) 17425 return 0; 17426 17427 /* There were no equivalent states, remember the current one. 17428 * Technically the current state is not proven to be safe yet, 17429 * but it will either reach outer most bpf_exit (which means it's safe) 17430 * or it will be rejected. When there are no loops the verifier won't be 17431 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 17432 * again on the way to bpf_exit. 17433 * When looping the sl->state.branches will be > 0 and this state 17434 * will not be considered for equivalence until branches == 0. 17435 */ 17436 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 17437 if (!new_sl) 17438 return -ENOMEM; 17439 env->total_states++; 17440 env->peak_states++; 17441 env->prev_jmps_processed = env->jmps_processed; 17442 env->prev_insn_processed = env->insn_processed; 17443 17444 /* forget precise markings we inherited, see __mark_chain_precision */ 17445 if (env->bpf_capable) 17446 mark_all_scalars_imprecise(env, cur); 17447 17448 /* add new state to the head of linked list */ 17449 new = &new_sl->state; 17450 err = copy_verifier_state(new, cur); 17451 if (err) { 17452 free_verifier_state(new, false); 17453 kfree(new_sl); 17454 return err; 17455 } 17456 new->insn_idx = insn_idx; 17457 WARN_ONCE(new->branches != 1, 17458 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 17459 17460 cur->parent = new; 17461 cur->first_insn_idx = insn_idx; 17462 cur->dfs_depth = new->dfs_depth + 1; 17463 clear_jmp_history(cur); 17464 new_sl->next = *explored_state(env, insn_idx); 17465 *explored_state(env, insn_idx) = new_sl; 17466 /* connect new state to parentage chain. Current frame needs all 17467 * registers connected. Only r6 - r9 of the callers are alive (pushed 17468 * to the stack implicitly by JITs) so in callers' frames connect just 17469 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 17470 * the state of the call instruction (with WRITTEN set), and r0 comes 17471 * from callee with its full parentage chain, anyway. 17472 */ 17473 /* clear write marks in current state: the writes we did are not writes 17474 * our child did, so they don't screen off its reads from us. 17475 * (There are no read marks in current state, because reads always mark 17476 * their parent and current state never has children yet. Only 17477 * explored_states can get read marks.) 17478 */ 17479 for (j = 0; j <= cur->curframe; j++) { 17480 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 17481 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 17482 for (i = 0; i < BPF_REG_FP; i++) 17483 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 17484 } 17485 17486 /* all stack frames are accessible from callee, clear them all */ 17487 for (j = 0; j <= cur->curframe; j++) { 17488 struct bpf_func_state *frame = cur->frame[j]; 17489 struct bpf_func_state *newframe = new->frame[j]; 17490 17491 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 17492 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 17493 frame->stack[i].spilled_ptr.parent = 17494 &newframe->stack[i].spilled_ptr; 17495 } 17496 } 17497 return 0; 17498 } 17499 17500 /* Return true if it's OK to have the same insn return a different type. */ 17501 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 17502 { 17503 switch (base_type(type)) { 17504 case PTR_TO_CTX: 17505 case PTR_TO_SOCKET: 17506 case PTR_TO_SOCK_COMMON: 17507 case PTR_TO_TCP_SOCK: 17508 case PTR_TO_XDP_SOCK: 17509 case PTR_TO_BTF_ID: 17510 case PTR_TO_ARENA: 17511 return false; 17512 default: 17513 return true; 17514 } 17515 } 17516 17517 /* If an instruction was previously used with particular pointer types, then we 17518 * need to be careful to avoid cases such as the below, where it may be ok 17519 * for one branch accessing the pointer, but not ok for the other branch: 17520 * 17521 * R1 = sock_ptr 17522 * goto X; 17523 * ... 17524 * R1 = some_other_valid_ptr; 17525 * goto X; 17526 * ... 17527 * R2 = *(u32 *)(R1 + 0); 17528 */ 17529 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 17530 { 17531 return src != prev && (!reg_type_mismatch_ok(src) || 17532 !reg_type_mismatch_ok(prev)); 17533 } 17534 17535 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 17536 bool allow_trust_missmatch) 17537 { 17538 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 17539 17540 if (*prev_type == NOT_INIT) { 17541 /* Saw a valid insn 17542 * dst_reg = *(u32 *)(src_reg + off) 17543 * save type to validate intersecting paths 17544 */ 17545 *prev_type = type; 17546 } else if (reg_type_mismatch(type, *prev_type)) { 17547 /* Abuser program is trying to use the same insn 17548 * dst_reg = *(u32*) (src_reg + off) 17549 * with different pointer types: 17550 * src_reg == ctx in one branch and 17551 * src_reg == stack|map in some other branch. 17552 * Reject it. 17553 */ 17554 if (allow_trust_missmatch && 17555 base_type(type) == PTR_TO_BTF_ID && 17556 base_type(*prev_type) == PTR_TO_BTF_ID) { 17557 /* 17558 * Have to support a use case when one path through 17559 * the program yields TRUSTED pointer while another 17560 * is UNTRUSTED. Fallback to UNTRUSTED to generate 17561 * BPF_PROBE_MEM/BPF_PROBE_MEMSX. 17562 */ 17563 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 17564 } else { 17565 verbose(env, "same insn cannot be used with different pointers\n"); 17566 return -EINVAL; 17567 } 17568 } 17569 17570 return 0; 17571 } 17572 17573 static int do_check(struct bpf_verifier_env *env) 17574 { 17575 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17576 struct bpf_verifier_state *state = env->cur_state; 17577 struct bpf_insn *insns = env->prog->insnsi; 17578 struct bpf_reg_state *regs; 17579 int insn_cnt = env->prog->len; 17580 bool do_print_state = false; 17581 int prev_insn_idx = -1; 17582 17583 for (;;) { 17584 bool exception_exit = false; 17585 struct bpf_insn *insn; 17586 u8 class; 17587 int err; 17588 17589 /* reset current history entry on each new instruction */ 17590 env->cur_hist_ent = NULL; 17591 17592 env->prev_insn_idx = prev_insn_idx; 17593 if (env->insn_idx >= insn_cnt) { 17594 verbose(env, "invalid insn idx %d insn_cnt %d\n", 17595 env->insn_idx, insn_cnt); 17596 return -EFAULT; 17597 } 17598 17599 insn = &insns[env->insn_idx]; 17600 class = BPF_CLASS(insn->code); 17601 17602 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 17603 verbose(env, 17604 "BPF program is too large. Processed %d insn\n", 17605 env->insn_processed); 17606 return -E2BIG; 17607 } 17608 17609 state->last_insn_idx = env->prev_insn_idx; 17610 17611 if (is_prune_point(env, env->insn_idx)) { 17612 err = is_state_visited(env, env->insn_idx); 17613 if (err < 0) 17614 return err; 17615 if (err == 1) { 17616 /* found equivalent state, can prune the search */ 17617 if (env->log.level & BPF_LOG_LEVEL) { 17618 if (do_print_state) 17619 verbose(env, "\nfrom %d to %d%s: safe\n", 17620 env->prev_insn_idx, env->insn_idx, 17621 env->cur_state->speculative ? 17622 " (speculative execution)" : ""); 17623 else 17624 verbose(env, "%d: safe\n", env->insn_idx); 17625 } 17626 goto process_bpf_exit; 17627 } 17628 } 17629 17630 if (is_jmp_point(env, env->insn_idx)) { 17631 err = push_jmp_history(env, state, 0); 17632 if (err) 17633 return err; 17634 } 17635 17636 if (signal_pending(current)) 17637 return -EAGAIN; 17638 17639 if (need_resched()) 17640 cond_resched(); 17641 17642 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 17643 verbose(env, "\nfrom %d to %d%s:", 17644 env->prev_insn_idx, env->insn_idx, 17645 env->cur_state->speculative ? 17646 " (speculative execution)" : ""); 17647 print_verifier_state(env, state->frame[state->curframe], true); 17648 do_print_state = false; 17649 } 17650 17651 if (env->log.level & BPF_LOG_LEVEL) { 17652 const struct bpf_insn_cbs cbs = { 17653 .cb_call = disasm_kfunc_name, 17654 .cb_print = verbose, 17655 .private_data = env, 17656 }; 17657 17658 if (verifier_state_scratched(env)) 17659 print_insn_state(env, state->frame[state->curframe]); 17660 17661 verbose_linfo(env, env->insn_idx, "; "); 17662 env->prev_log_pos = env->log.end_pos; 17663 verbose(env, "%d: ", env->insn_idx); 17664 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 17665 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 17666 env->prev_log_pos = env->log.end_pos; 17667 } 17668 17669 if (bpf_prog_is_offloaded(env->prog->aux)) { 17670 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 17671 env->prev_insn_idx); 17672 if (err) 17673 return err; 17674 } 17675 17676 regs = cur_regs(env); 17677 sanitize_mark_insn_seen(env); 17678 prev_insn_idx = env->insn_idx; 17679 17680 if (class == BPF_ALU || class == BPF_ALU64) { 17681 err = check_alu_op(env, insn); 17682 if (err) 17683 return err; 17684 17685 } else if (class == BPF_LDX) { 17686 enum bpf_reg_type src_reg_type; 17687 17688 /* check for reserved fields is already done */ 17689 17690 /* check src operand */ 17691 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17692 if (err) 17693 return err; 17694 17695 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 17696 if (err) 17697 return err; 17698 17699 src_reg_type = regs[insn->src_reg].type; 17700 17701 /* check that memory (src_reg + off) is readable, 17702 * the state of dst_reg will be updated by this func 17703 */ 17704 err = check_mem_access(env, env->insn_idx, insn->src_reg, 17705 insn->off, BPF_SIZE(insn->code), 17706 BPF_READ, insn->dst_reg, false, 17707 BPF_MODE(insn->code) == BPF_MEMSX); 17708 err = err ?: save_aux_ptr_type(env, src_reg_type, true); 17709 err = err ?: reg_bounds_sanity_check(env, ®s[insn->dst_reg], "ldx"); 17710 if (err) 17711 return err; 17712 } else if (class == BPF_STX) { 17713 enum bpf_reg_type dst_reg_type; 17714 17715 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 17716 err = check_atomic(env, env->insn_idx, insn); 17717 if (err) 17718 return err; 17719 env->insn_idx++; 17720 continue; 17721 } 17722 17723 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 17724 verbose(env, "BPF_STX uses reserved fields\n"); 17725 return -EINVAL; 17726 } 17727 17728 /* check src1 operand */ 17729 err = check_reg_arg(env, insn->src_reg, SRC_OP); 17730 if (err) 17731 return err; 17732 /* check src2 operand */ 17733 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17734 if (err) 17735 return err; 17736 17737 dst_reg_type = regs[insn->dst_reg].type; 17738 17739 /* check that memory (dst_reg + off) is writeable */ 17740 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17741 insn->off, BPF_SIZE(insn->code), 17742 BPF_WRITE, insn->src_reg, false, false); 17743 if (err) 17744 return err; 17745 17746 err = save_aux_ptr_type(env, dst_reg_type, false); 17747 if (err) 17748 return err; 17749 } else if (class == BPF_ST) { 17750 enum bpf_reg_type dst_reg_type; 17751 17752 if (BPF_MODE(insn->code) != BPF_MEM || 17753 insn->src_reg != BPF_REG_0) { 17754 verbose(env, "BPF_ST uses reserved fields\n"); 17755 return -EINVAL; 17756 } 17757 /* check src operand */ 17758 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 17759 if (err) 17760 return err; 17761 17762 dst_reg_type = regs[insn->dst_reg].type; 17763 17764 /* check that memory (dst_reg + off) is writeable */ 17765 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 17766 insn->off, BPF_SIZE(insn->code), 17767 BPF_WRITE, -1, false, false); 17768 if (err) 17769 return err; 17770 17771 err = save_aux_ptr_type(env, dst_reg_type, false); 17772 if (err) 17773 return err; 17774 } else if (class == BPF_JMP || class == BPF_JMP32) { 17775 u8 opcode = BPF_OP(insn->code); 17776 17777 env->jmps_processed++; 17778 if (opcode == BPF_CALL) { 17779 if (BPF_SRC(insn->code) != BPF_K || 17780 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 17781 && insn->off != 0) || 17782 (insn->src_reg != BPF_REG_0 && 17783 insn->src_reg != BPF_PSEUDO_CALL && 17784 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 17785 insn->dst_reg != BPF_REG_0 || 17786 class == BPF_JMP32) { 17787 verbose(env, "BPF_CALL uses reserved fields\n"); 17788 return -EINVAL; 17789 } 17790 17791 if (env->cur_state->active_lock.ptr) { 17792 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 17793 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 17794 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 17795 verbose(env, "function calls are not allowed while holding a lock\n"); 17796 return -EINVAL; 17797 } 17798 } 17799 if (insn->src_reg == BPF_PSEUDO_CALL) { 17800 err = check_func_call(env, insn, &env->insn_idx); 17801 } else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17802 err = check_kfunc_call(env, insn, &env->insn_idx); 17803 if (!err && is_bpf_throw_kfunc(insn)) { 17804 exception_exit = true; 17805 goto process_bpf_exit_full; 17806 } 17807 } else { 17808 err = check_helper_call(env, insn, &env->insn_idx); 17809 } 17810 if (err) 17811 return err; 17812 17813 mark_reg_scratched(env, BPF_REG_0); 17814 } else if (opcode == BPF_JA) { 17815 if (BPF_SRC(insn->code) != BPF_K || 17816 insn->src_reg != BPF_REG_0 || 17817 insn->dst_reg != BPF_REG_0 || 17818 (class == BPF_JMP && insn->imm != 0) || 17819 (class == BPF_JMP32 && insn->off != 0)) { 17820 verbose(env, "BPF_JA uses reserved fields\n"); 17821 return -EINVAL; 17822 } 17823 17824 if (class == BPF_JMP) 17825 env->insn_idx += insn->off + 1; 17826 else 17827 env->insn_idx += insn->imm + 1; 17828 continue; 17829 17830 } else if (opcode == BPF_EXIT) { 17831 if (BPF_SRC(insn->code) != BPF_K || 17832 insn->imm != 0 || 17833 insn->src_reg != BPF_REG_0 || 17834 insn->dst_reg != BPF_REG_0 || 17835 class == BPF_JMP32) { 17836 verbose(env, "BPF_EXIT uses reserved fields\n"); 17837 return -EINVAL; 17838 } 17839 process_bpf_exit_full: 17840 if (env->cur_state->active_lock.ptr && !env->cur_state->curframe) { 17841 verbose(env, "bpf_spin_unlock is missing\n"); 17842 return -EINVAL; 17843 } 17844 17845 if (env->cur_state->active_rcu_lock && !env->cur_state->curframe) { 17846 verbose(env, "bpf_rcu_read_unlock is missing\n"); 17847 return -EINVAL; 17848 } 17849 17850 /* We must do check_reference_leak here before 17851 * prepare_func_exit to handle the case when 17852 * state->curframe > 0, it may be a callback 17853 * function, for which reference_state must 17854 * match caller reference state when it exits. 17855 */ 17856 err = check_reference_leak(env, exception_exit); 17857 if (err) 17858 return err; 17859 17860 /* The side effect of the prepare_func_exit 17861 * which is being skipped is that it frees 17862 * bpf_func_state. Typically, process_bpf_exit 17863 * will only be hit with outermost exit. 17864 * copy_verifier_state in pop_stack will handle 17865 * freeing of any extra bpf_func_state left over 17866 * from not processing all nested function 17867 * exits. We also skip return code checks as 17868 * they are not needed for exceptional exits. 17869 */ 17870 if (exception_exit) 17871 goto process_bpf_exit; 17872 17873 if (state->curframe) { 17874 /* exit from nested function */ 17875 err = prepare_func_exit(env, &env->insn_idx); 17876 if (err) 17877 return err; 17878 do_print_state = true; 17879 continue; 17880 } 17881 17882 err = check_return_code(env, BPF_REG_0, "R0"); 17883 if (err) 17884 return err; 17885 process_bpf_exit: 17886 mark_verifier_state_scratched(env); 17887 update_branch_counts(env, env->cur_state); 17888 err = pop_stack(env, &prev_insn_idx, 17889 &env->insn_idx, pop_log); 17890 if (err < 0) { 17891 if (err != -ENOENT) 17892 return err; 17893 break; 17894 } else { 17895 do_print_state = true; 17896 continue; 17897 } 17898 } else { 17899 err = check_cond_jmp_op(env, insn, &env->insn_idx); 17900 if (err) 17901 return err; 17902 } 17903 } else if (class == BPF_LD) { 17904 u8 mode = BPF_MODE(insn->code); 17905 17906 if (mode == BPF_ABS || mode == BPF_IND) { 17907 err = check_ld_abs(env, insn); 17908 if (err) 17909 return err; 17910 17911 } else if (mode == BPF_IMM) { 17912 err = check_ld_imm(env, insn); 17913 if (err) 17914 return err; 17915 17916 env->insn_idx++; 17917 sanitize_mark_insn_seen(env); 17918 } else { 17919 verbose(env, "invalid BPF_LD mode\n"); 17920 return -EINVAL; 17921 } 17922 } else { 17923 verbose(env, "unknown insn class %d\n", class); 17924 return -EINVAL; 17925 } 17926 17927 env->insn_idx++; 17928 } 17929 17930 return 0; 17931 } 17932 17933 static int find_btf_percpu_datasec(struct btf *btf) 17934 { 17935 const struct btf_type *t; 17936 const char *tname; 17937 int i, n; 17938 17939 /* 17940 * Both vmlinux and module each have their own ".data..percpu" 17941 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 17942 * types to look at only module's own BTF types. 17943 */ 17944 n = btf_nr_types(btf); 17945 if (btf_is_module(btf)) 17946 i = btf_nr_types(btf_vmlinux); 17947 else 17948 i = 1; 17949 17950 for(; i < n; i++) { 17951 t = btf_type_by_id(btf, i); 17952 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 17953 continue; 17954 17955 tname = btf_name_by_offset(btf, t->name_off); 17956 if (!strcmp(tname, ".data..percpu")) 17957 return i; 17958 } 17959 17960 return -ENOENT; 17961 } 17962 17963 /* replace pseudo btf_id with kernel symbol address */ 17964 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 17965 struct bpf_insn *insn, 17966 struct bpf_insn_aux_data *aux) 17967 { 17968 const struct btf_var_secinfo *vsi; 17969 const struct btf_type *datasec; 17970 struct btf_mod_pair *btf_mod; 17971 const struct btf_type *t; 17972 const char *sym_name; 17973 bool percpu = false; 17974 u32 type, id = insn->imm; 17975 struct btf *btf; 17976 s32 datasec_id; 17977 u64 addr; 17978 int i, btf_fd, err; 17979 17980 btf_fd = insn[1].imm; 17981 if (btf_fd) { 17982 btf = btf_get_by_fd(btf_fd); 17983 if (IS_ERR(btf)) { 17984 verbose(env, "invalid module BTF object FD specified.\n"); 17985 return -EINVAL; 17986 } 17987 } else { 17988 if (!btf_vmlinux) { 17989 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 17990 return -EINVAL; 17991 } 17992 btf = btf_vmlinux; 17993 btf_get(btf); 17994 } 17995 17996 t = btf_type_by_id(btf, id); 17997 if (!t) { 17998 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 17999 err = -ENOENT; 18000 goto err_put; 18001 } 18002 18003 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 18004 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 18005 err = -EINVAL; 18006 goto err_put; 18007 } 18008 18009 sym_name = btf_name_by_offset(btf, t->name_off); 18010 addr = kallsyms_lookup_name(sym_name); 18011 if (!addr) { 18012 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 18013 sym_name); 18014 err = -ENOENT; 18015 goto err_put; 18016 } 18017 insn[0].imm = (u32)addr; 18018 insn[1].imm = addr >> 32; 18019 18020 if (btf_type_is_func(t)) { 18021 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18022 aux->btf_var.mem_size = 0; 18023 goto check_btf; 18024 } 18025 18026 datasec_id = find_btf_percpu_datasec(btf); 18027 if (datasec_id > 0) { 18028 datasec = btf_type_by_id(btf, datasec_id); 18029 for_each_vsi(i, datasec, vsi) { 18030 if (vsi->type == id) { 18031 percpu = true; 18032 break; 18033 } 18034 } 18035 } 18036 18037 type = t->type; 18038 t = btf_type_skip_modifiers(btf, type, NULL); 18039 if (percpu) { 18040 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 18041 aux->btf_var.btf = btf; 18042 aux->btf_var.btf_id = type; 18043 } else if (!btf_type_is_struct(t)) { 18044 const struct btf_type *ret; 18045 const char *tname; 18046 u32 tsize; 18047 18048 /* resolve the type size of ksym. */ 18049 ret = btf_resolve_size(btf, t, &tsize); 18050 if (IS_ERR(ret)) { 18051 tname = btf_name_by_offset(btf, t->name_off); 18052 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 18053 tname, PTR_ERR(ret)); 18054 err = -EINVAL; 18055 goto err_put; 18056 } 18057 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 18058 aux->btf_var.mem_size = tsize; 18059 } else { 18060 aux->btf_var.reg_type = PTR_TO_BTF_ID; 18061 aux->btf_var.btf = btf; 18062 aux->btf_var.btf_id = type; 18063 } 18064 check_btf: 18065 /* check whether we recorded this BTF (and maybe module) already */ 18066 for (i = 0; i < env->used_btf_cnt; i++) { 18067 if (env->used_btfs[i].btf == btf) { 18068 btf_put(btf); 18069 return 0; 18070 } 18071 } 18072 18073 if (env->used_btf_cnt >= MAX_USED_BTFS) { 18074 err = -E2BIG; 18075 goto err_put; 18076 } 18077 18078 btf_mod = &env->used_btfs[env->used_btf_cnt]; 18079 btf_mod->btf = btf; 18080 btf_mod->module = NULL; 18081 18082 /* if we reference variables from kernel module, bump its refcount */ 18083 if (btf_is_module(btf)) { 18084 btf_mod->module = btf_try_get_module(btf); 18085 if (!btf_mod->module) { 18086 err = -ENXIO; 18087 goto err_put; 18088 } 18089 } 18090 18091 env->used_btf_cnt++; 18092 18093 return 0; 18094 err_put: 18095 btf_put(btf); 18096 return err; 18097 } 18098 18099 static bool is_tracing_prog_type(enum bpf_prog_type type) 18100 { 18101 switch (type) { 18102 case BPF_PROG_TYPE_KPROBE: 18103 case BPF_PROG_TYPE_TRACEPOINT: 18104 case BPF_PROG_TYPE_PERF_EVENT: 18105 case BPF_PROG_TYPE_RAW_TRACEPOINT: 18106 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 18107 return true; 18108 default: 18109 return false; 18110 } 18111 } 18112 18113 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 18114 struct bpf_map *map, 18115 struct bpf_prog *prog) 18116 18117 { 18118 enum bpf_prog_type prog_type = resolve_prog_type(prog); 18119 18120 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 18121 btf_record_has_field(map->record, BPF_RB_ROOT)) { 18122 if (is_tracing_prog_type(prog_type)) { 18123 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 18124 return -EINVAL; 18125 } 18126 } 18127 18128 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 18129 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 18130 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 18131 return -EINVAL; 18132 } 18133 18134 if (is_tracing_prog_type(prog_type)) { 18135 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 18136 return -EINVAL; 18137 } 18138 } 18139 18140 if (btf_record_has_field(map->record, BPF_TIMER)) { 18141 if (is_tracing_prog_type(prog_type)) { 18142 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 18143 return -EINVAL; 18144 } 18145 } 18146 18147 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 18148 !bpf_offload_prog_map_match(prog, map)) { 18149 verbose(env, "offload device mismatch between prog and map\n"); 18150 return -EINVAL; 18151 } 18152 18153 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 18154 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 18155 return -EINVAL; 18156 } 18157 18158 if (prog->sleepable) 18159 switch (map->map_type) { 18160 case BPF_MAP_TYPE_HASH: 18161 case BPF_MAP_TYPE_LRU_HASH: 18162 case BPF_MAP_TYPE_ARRAY: 18163 case BPF_MAP_TYPE_PERCPU_HASH: 18164 case BPF_MAP_TYPE_PERCPU_ARRAY: 18165 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 18166 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 18167 case BPF_MAP_TYPE_HASH_OF_MAPS: 18168 case BPF_MAP_TYPE_RINGBUF: 18169 case BPF_MAP_TYPE_USER_RINGBUF: 18170 case BPF_MAP_TYPE_INODE_STORAGE: 18171 case BPF_MAP_TYPE_SK_STORAGE: 18172 case BPF_MAP_TYPE_TASK_STORAGE: 18173 case BPF_MAP_TYPE_CGRP_STORAGE: 18174 case BPF_MAP_TYPE_QUEUE: 18175 case BPF_MAP_TYPE_STACK: 18176 case BPF_MAP_TYPE_ARENA: 18177 break; 18178 default: 18179 verbose(env, 18180 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 18181 return -EINVAL; 18182 } 18183 18184 return 0; 18185 } 18186 18187 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 18188 { 18189 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 18190 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 18191 } 18192 18193 /* find and rewrite pseudo imm in ld_imm64 instructions: 18194 * 18195 * 1. if it accesses map FD, replace it with actual map pointer. 18196 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 18197 * 18198 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 18199 */ 18200 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 18201 { 18202 struct bpf_insn *insn = env->prog->insnsi; 18203 int insn_cnt = env->prog->len; 18204 int i, j, err; 18205 18206 err = bpf_prog_calc_tag(env->prog); 18207 if (err) 18208 return err; 18209 18210 for (i = 0; i < insn_cnt; i++, insn++) { 18211 if (BPF_CLASS(insn->code) == BPF_LDX && 18212 ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_MEMSX) || 18213 insn->imm != 0)) { 18214 verbose(env, "BPF_LDX uses reserved fields\n"); 18215 return -EINVAL; 18216 } 18217 18218 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 18219 struct bpf_insn_aux_data *aux; 18220 struct bpf_map *map; 18221 struct fd f; 18222 u64 addr; 18223 u32 fd; 18224 18225 if (i == insn_cnt - 1 || insn[1].code != 0 || 18226 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 18227 insn[1].off != 0) { 18228 verbose(env, "invalid bpf_ld_imm64 insn\n"); 18229 return -EINVAL; 18230 } 18231 18232 if (insn[0].src_reg == 0) 18233 /* valid generic load 64-bit imm */ 18234 goto next_insn; 18235 18236 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 18237 aux = &env->insn_aux_data[i]; 18238 err = check_pseudo_btf_id(env, insn, aux); 18239 if (err) 18240 return err; 18241 goto next_insn; 18242 } 18243 18244 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 18245 aux = &env->insn_aux_data[i]; 18246 aux->ptr_type = PTR_TO_FUNC; 18247 goto next_insn; 18248 } 18249 18250 /* In final convert_pseudo_ld_imm64() step, this is 18251 * converted into regular 64-bit imm load insn. 18252 */ 18253 switch (insn[0].src_reg) { 18254 case BPF_PSEUDO_MAP_VALUE: 18255 case BPF_PSEUDO_MAP_IDX_VALUE: 18256 break; 18257 case BPF_PSEUDO_MAP_FD: 18258 case BPF_PSEUDO_MAP_IDX: 18259 if (insn[1].imm == 0) 18260 break; 18261 fallthrough; 18262 default: 18263 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 18264 return -EINVAL; 18265 } 18266 18267 switch (insn[0].src_reg) { 18268 case BPF_PSEUDO_MAP_IDX_VALUE: 18269 case BPF_PSEUDO_MAP_IDX: 18270 if (bpfptr_is_null(env->fd_array)) { 18271 verbose(env, "fd_idx without fd_array is invalid\n"); 18272 return -EPROTO; 18273 } 18274 if (copy_from_bpfptr_offset(&fd, env->fd_array, 18275 insn[0].imm * sizeof(fd), 18276 sizeof(fd))) 18277 return -EFAULT; 18278 break; 18279 default: 18280 fd = insn[0].imm; 18281 break; 18282 } 18283 18284 f = fdget(fd); 18285 map = __bpf_map_get(f); 18286 if (IS_ERR(map)) { 18287 verbose(env, "fd %d is not pointing to valid bpf_map\n", 18288 insn[0].imm); 18289 return PTR_ERR(map); 18290 } 18291 18292 err = check_map_prog_compatibility(env, map, env->prog); 18293 if (err) { 18294 fdput(f); 18295 return err; 18296 } 18297 18298 aux = &env->insn_aux_data[i]; 18299 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 18300 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 18301 addr = (unsigned long)map; 18302 } else { 18303 u32 off = insn[1].imm; 18304 18305 if (off >= BPF_MAX_VAR_OFF) { 18306 verbose(env, "direct value offset of %u is not allowed\n", off); 18307 fdput(f); 18308 return -EINVAL; 18309 } 18310 18311 if (!map->ops->map_direct_value_addr) { 18312 verbose(env, "no direct value access support for this map type\n"); 18313 fdput(f); 18314 return -EINVAL; 18315 } 18316 18317 err = map->ops->map_direct_value_addr(map, &addr, off); 18318 if (err) { 18319 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 18320 map->value_size, off); 18321 fdput(f); 18322 return err; 18323 } 18324 18325 aux->map_off = off; 18326 addr += off; 18327 } 18328 18329 insn[0].imm = (u32)addr; 18330 insn[1].imm = addr >> 32; 18331 18332 /* check whether we recorded this map already */ 18333 for (j = 0; j < env->used_map_cnt; j++) { 18334 if (env->used_maps[j] == map) { 18335 aux->map_index = j; 18336 fdput(f); 18337 goto next_insn; 18338 } 18339 } 18340 18341 if (env->used_map_cnt >= MAX_USED_MAPS) { 18342 fdput(f); 18343 return -E2BIG; 18344 } 18345 18346 if (env->prog->sleepable) 18347 atomic64_inc(&map->sleepable_refcnt); 18348 /* hold the map. If the program is rejected by verifier, 18349 * the map will be released by release_maps() or it 18350 * will be used by the valid program until it's unloaded 18351 * and all maps are released in bpf_free_used_maps() 18352 */ 18353 bpf_map_inc(map); 18354 18355 aux->map_index = env->used_map_cnt; 18356 env->used_maps[env->used_map_cnt++] = map; 18357 18358 if (bpf_map_is_cgroup_storage(map) && 18359 bpf_cgroup_storage_assign(env->prog->aux, map)) { 18360 verbose(env, "only one cgroup storage of each type is allowed\n"); 18361 fdput(f); 18362 return -EBUSY; 18363 } 18364 if (map->map_type == BPF_MAP_TYPE_ARENA) { 18365 if (env->prog->aux->arena) { 18366 verbose(env, "Only one arena per program\n"); 18367 fdput(f); 18368 return -EBUSY; 18369 } 18370 if (!env->allow_ptr_leaks || !env->bpf_capable) { 18371 verbose(env, "CAP_BPF and CAP_PERFMON are required to use arena\n"); 18372 fdput(f); 18373 return -EPERM; 18374 } 18375 if (!env->prog->jit_requested) { 18376 verbose(env, "JIT is required to use arena\n"); 18377 return -EOPNOTSUPP; 18378 } 18379 if (!bpf_jit_supports_arena()) { 18380 verbose(env, "JIT doesn't support arena\n"); 18381 return -EOPNOTSUPP; 18382 } 18383 env->prog->aux->arena = (void *)map; 18384 if (!bpf_arena_get_user_vm_start(env->prog->aux->arena)) { 18385 verbose(env, "arena's user address must be set via map_extra or mmap()\n"); 18386 return -EINVAL; 18387 } 18388 } 18389 18390 fdput(f); 18391 next_insn: 18392 insn++; 18393 i++; 18394 continue; 18395 } 18396 18397 /* Basic sanity check before we invest more work here. */ 18398 if (!bpf_opcode_in_insntable(insn->code)) { 18399 verbose(env, "unknown opcode %02x\n", insn->code); 18400 return -EINVAL; 18401 } 18402 } 18403 18404 /* now all pseudo BPF_LD_IMM64 instructions load valid 18405 * 'struct bpf_map *' into a register instead of user map_fd. 18406 * These pointers will be used later by verifier to validate map access. 18407 */ 18408 return 0; 18409 } 18410 18411 /* drop refcnt of maps used by the rejected program */ 18412 static void release_maps(struct bpf_verifier_env *env) 18413 { 18414 __bpf_free_used_maps(env->prog->aux, env->used_maps, 18415 env->used_map_cnt); 18416 } 18417 18418 /* drop refcnt of maps used by the rejected program */ 18419 static void release_btfs(struct bpf_verifier_env *env) 18420 { 18421 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 18422 env->used_btf_cnt); 18423 } 18424 18425 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 18426 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 18427 { 18428 struct bpf_insn *insn = env->prog->insnsi; 18429 int insn_cnt = env->prog->len; 18430 int i; 18431 18432 for (i = 0; i < insn_cnt; i++, insn++) { 18433 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 18434 continue; 18435 if (insn->src_reg == BPF_PSEUDO_FUNC) 18436 continue; 18437 insn->src_reg = 0; 18438 } 18439 } 18440 18441 /* single env->prog->insni[off] instruction was replaced with the range 18442 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 18443 * [0, off) and [off, end) to new locations, so the patched range stays zero 18444 */ 18445 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 18446 struct bpf_insn_aux_data *new_data, 18447 struct bpf_prog *new_prog, u32 off, u32 cnt) 18448 { 18449 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 18450 struct bpf_insn *insn = new_prog->insnsi; 18451 u32 old_seen = old_data[off].seen; 18452 u32 prog_len; 18453 int i; 18454 18455 /* aux info at OFF always needs adjustment, no matter fast path 18456 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 18457 * original insn at old prog. 18458 */ 18459 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 18460 18461 if (cnt == 1) 18462 return; 18463 prog_len = new_prog->len; 18464 18465 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 18466 memcpy(new_data + off + cnt - 1, old_data + off, 18467 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 18468 for (i = off; i < off + cnt - 1; i++) { 18469 /* Expand insni[off]'s seen count to the patched range. */ 18470 new_data[i].seen = old_seen; 18471 new_data[i].zext_dst = insn_has_def32(env, insn + i); 18472 } 18473 env->insn_aux_data = new_data; 18474 vfree(old_data); 18475 } 18476 18477 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 18478 { 18479 int i; 18480 18481 if (len == 1) 18482 return; 18483 /* NOTE: fake 'exit' subprog should be updated as well. */ 18484 for (i = 0; i <= env->subprog_cnt; i++) { 18485 if (env->subprog_info[i].start <= off) 18486 continue; 18487 env->subprog_info[i].start += len - 1; 18488 } 18489 } 18490 18491 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 18492 { 18493 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 18494 int i, sz = prog->aux->size_poke_tab; 18495 struct bpf_jit_poke_descriptor *desc; 18496 18497 for (i = 0; i < sz; i++) { 18498 desc = &tab[i]; 18499 if (desc->insn_idx <= off) 18500 continue; 18501 desc->insn_idx += len - 1; 18502 } 18503 } 18504 18505 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 18506 const struct bpf_insn *patch, u32 len) 18507 { 18508 struct bpf_prog *new_prog; 18509 struct bpf_insn_aux_data *new_data = NULL; 18510 18511 if (len > 1) { 18512 new_data = vzalloc(array_size(env->prog->len + len - 1, 18513 sizeof(struct bpf_insn_aux_data))); 18514 if (!new_data) 18515 return NULL; 18516 } 18517 18518 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 18519 if (IS_ERR(new_prog)) { 18520 if (PTR_ERR(new_prog) == -ERANGE) 18521 verbose(env, 18522 "insn %d cannot be patched due to 16-bit range\n", 18523 env->insn_aux_data[off].orig_idx); 18524 vfree(new_data); 18525 return NULL; 18526 } 18527 adjust_insn_aux_data(env, new_data, new_prog, off, len); 18528 adjust_subprog_starts(env, off, len); 18529 adjust_poke_descs(new_prog, off, len); 18530 return new_prog; 18531 } 18532 18533 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 18534 u32 off, u32 cnt) 18535 { 18536 int i, j; 18537 18538 /* find first prog starting at or after off (first to remove) */ 18539 for (i = 0; i < env->subprog_cnt; i++) 18540 if (env->subprog_info[i].start >= off) 18541 break; 18542 /* find first prog starting at or after off + cnt (first to stay) */ 18543 for (j = i; j < env->subprog_cnt; j++) 18544 if (env->subprog_info[j].start >= off + cnt) 18545 break; 18546 /* if j doesn't start exactly at off + cnt, we are just removing 18547 * the front of previous prog 18548 */ 18549 if (env->subprog_info[j].start != off + cnt) 18550 j--; 18551 18552 if (j > i) { 18553 struct bpf_prog_aux *aux = env->prog->aux; 18554 int move; 18555 18556 /* move fake 'exit' subprog as well */ 18557 move = env->subprog_cnt + 1 - j; 18558 18559 memmove(env->subprog_info + i, 18560 env->subprog_info + j, 18561 sizeof(*env->subprog_info) * move); 18562 env->subprog_cnt -= j - i; 18563 18564 /* remove func_info */ 18565 if (aux->func_info) { 18566 move = aux->func_info_cnt - j; 18567 18568 memmove(aux->func_info + i, 18569 aux->func_info + j, 18570 sizeof(*aux->func_info) * move); 18571 aux->func_info_cnt -= j - i; 18572 /* func_info->insn_off is set after all code rewrites, 18573 * in adjust_btf_func() - no need to adjust 18574 */ 18575 } 18576 } else { 18577 /* convert i from "first prog to remove" to "first to adjust" */ 18578 if (env->subprog_info[i].start == off) 18579 i++; 18580 } 18581 18582 /* update fake 'exit' subprog as well */ 18583 for (; i <= env->subprog_cnt; i++) 18584 env->subprog_info[i].start -= cnt; 18585 18586 return 0; 18587 } 18588 18589 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 18590 u32 cnt) 18591 { 18592 struct bpf_prog *prog = env->prog; 18593 u32 i, l_off, l_cnt, nr_linfo; 18594 struct bpf_line_info *linfo; 18595 18596 nr_linfo = prog->aux->nr_linfo; 18597 if (!nr_linfo) 18598 return 0; 18599 18600 linfo = prog->aux->linfo; 18601 18602 /* find first line info to remove, count lines to be removed */ 18603 for (i = 0; i < nr_linfo; i++) 18604 if (linfo[i].insn_off >= off) 18605 break; 18606 18607 l_off = i; 18608 l_cnt = 0; 18609 for (; i < nr_linfo; i++) 18610 if (linfo[i].insn_off < off + cnt) 18611 l_cnt++; 18612 else 18613 break; 18614 18615 /* First live insn doesn't match first live linfo, it needs to "inherit" 18616 * last removed linfo. prog is already modified, so prog->len == off 18617 * means no live instructions after (tail of the program was removed). 18618 */ 18619 if (prog->len != off && l_cnt && 18620 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 18621 l_cnt--; 18622 linfo[--i].insn_off = off + cnt; 18623 } 18624 18625 /* remove the line info which refer to the removed instructions */ 18626 if (l_cnt) { 18627 memmove(linfo + l_off, linfo + i, 18628 sizeof(*linfo) * (nr_linfo - i)); 18629 18630 prog->aux->nr_linfo -= l_cnt; 18631 nr_linfo = prog->aux->nr_linfo; 18632 } 18633 18634 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 18635 for (i = l_off; i < nr_linfo; i++) 18636 linfo[i].insn_off -= cnt; 18637 18638 /* fix up all subprogs (incl. 'exit') which start >= off */ 18639 for (i = 0; i <= env->subprog_cnt; i++) 18640 if (env->subprog_info[i].linfo_idx > l_off) { 18641 /* program may have started in the removed region but 18642 * may not be fully removed 18643 */ 18644 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 18645 env->subprog_info[i].linfo_idx -= l_cnt; 18646 else 18647 env->subprog_info[i].linfo_idx = l_off; 18648 } 18649 18650 return 0; 18651 } 18652 18653 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 18654 { 18655 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18656 unsigned int orig_prog_len = env->prog->len; 18657 int err; 18658 18659 if (bpf_prog_is_offloaded(env->prog->aux)) 18660 bpf_prog_offload_remove_insns(env, off, cnt); 18661 18662 err = bpf_remove_insns(env->prog, off, cnt); 18663 if (err) 18664 return err; 18665 18666 err = adjust_subprog_starts_after_remove(env, off, cnt); 18667 if (err) 18668 return err; 18669 18670 err = bpf_adj_linfo_after_remove(env, off, cnt); 18671 if (err) 18672 return err; 18673 18674 memmove(aux_data + off, aux_data + off + cnt, 18675 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 18676 18677 return 0; 18678 } 18679 18680 /* The verifier does more data flow analysis than llvm and will not 18681 * explore branches that are dead at run time. Malicious programs can 18682 * have dead code too. Therefore replace all dead at-run-time code 18683 * with 'ja -1'. 18684 * 18685 * Just nops are not optimal, e.g. if they would sit at the end of the 18686 * program and through another bug we would manage to jump there, then 18687 * we'd execute beyond program memory otherwise. Returning exception 18688 * code also wouldn't work since we can have subprogs where the dead 18689 * code could be located. 18690 */ 18691 static void sanitize_dead_code(struct bpf_verifier_env *env) 18692 { 18693 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18694 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 18695 struct bpf_insn *insn = env->prog->insnsi; 18696 const int insn_cnt = env->prog->len; 18697 int i; 18698 18699 for (i = 0; i < insn_cnt; i++) { 18700 if (aux_data[i].seen) 18701 continue; 18702 memcpy(insn + i, &trap, sizeof(trap)); 18703 aux_data[i].zext_dst = false; 18704 } 18705 } 18706 18707 static bool insn_is_cond_jump(u8 code) 18708 { 18709 u8 op; 18710 18711 op = BPF_OP(code); 18712 if (BPF_CLASS(code) == BPF_JMP32) 18713 return op != BPF_JA; 18714 18715 if (BPF_CLASS(code) != BPF_JMP) 18716 return false; 18717 18718 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 18719 } 18720 18721 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 18722 { 18723 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18724 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18725 struct bpf_insn *insn = env->prog->insnsi; 18726 const int insn_cnt = env->prog->len; 18727 int i; 18728 18729 for (i = 0; i < insn_cnt; i++, insn++) { 18730 if (!insn_is_cond_jump(insn->code)) 18731 continue; 18732 18733 if (!aux_data[i + 1].seen) 18734 ja.off = insn->off; 18735 else if (!aux_data[i + 1 + insn->off].seen) 18736 ja.off = 0; 18737 else 18738 continue; 18739 18740 if (bpf_prog_is_offloaded(env->prog->aux)) 18741 bpf_prog_offload_replace_insn(env, i, &ja); 18742 18743 memcpy(insn, &ja, sizeof(ja)); 18744 } 18745 } 18746 18747 static int opt_remove_dead_code(struct bpf_verifier_env *env) 18748 { 18749 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 18750 int insn_cnt = env->prog->len; 18751 int i, err; 18752 18753 for (i = 0; i < insn_cnt; i++) { 18754 int j; 18755 18756 j = 0; 18757 while (i + j < insn_cnt && !aux_data[i + j].seen) 18758 j++; 18759 if (!j) 18760 continue; 18761 18762 err = verifier_remove_insns(env, i, j); 18763 if (err) 18764 return err; 18765 insn_cnt = env->prog->len; 18766 } 18767 18768 return 0; 18769 } 18770 18771 static int opt_remove_nops(struct bpf_verifier_env *env) 18772 { 18773 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 18774 struct bpf_insn *insn = env->prog->insnsi; 18775 int insn_cnt = env->prog->len; 18776 int i, err; 18777 18778 for (i = 0; i < insn_cnt; i++) { 18779 if (memcmp(&insn[i], &ja, sizeof(ja))) 18780 continue; 18781 18782 err = verifier_remove_insns(env, i, 1); 18783 if (err) 18784 return err; 18785 insn_cnt--; 18786 i--; 18787 } 18788 18789 return 0; 18790 } 18791 18792 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 18793 const union bpf_attr *attr) 18794 { 18795 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 18796 struct bpf_insn_aux_data *aux = env->insn_aux_data; 18797 int i, patch_len, delta = 0, len = env->prog->len; 18798 struct bpf_insn *insns = env->prog->insnsi; 18799 struct bpf_prog *new_prog; 18800 bool rnd_hi32; 18801 18802 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 18803 zext_patch[1] = BPF_ZEXT_REG(0); 18804 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 18805 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 18806 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 18807 for (i = 0; i < len; i++) { 18808 int adj_idx = i + delta; 18809 struct bpf_insn insn; 18810 int load_reg; 18811 18812 insn = insns[adj_idx]; 18813 load_reg = insn_def_regno(&insn); 18814 if (!aux[adj_idx].zext_dst) { 18815 u8 code, class; 18816 u32 imm_rnd; 18817 18818 if (!rnd_hi32) 18819 continue; 18820 18821 code = insn.code; 18822 class = BPF_CLASS(code); 18823 if (load_reg == -1) 18824 continue; 18825 18826 /* NOTE: arg "reg" (the fourth one) is only used for 18827 * BPF_STX + SRC_OP, so it is safe to pass NULL 18828 * here. 18829 */ 18830 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 18831 if (class == BPF_LD && 18832 BPF_MODE(code) == BPF_IMM) 18833 i++; 18834 continue; 18835 } 18836 18837 /* ctx load could be transformed into wider load. */ 18838 if (class == BPF_LDX && 18839 aux[adj_idx].ptr_type == PTR_TO_CTX) 18840 continue; 18841 18842 imm_rnd = get_random_u32(); 18843 rnd_hi32_patch[0] = insn; 18844 rnd_hi32_patch[1].imm = imm_rnd; 18845 rnd_hi32_patch[3].dst_reg = load_reg; 18846 patch = rnd_hi32_patch; 18847 patch_len = 4; 18848 goto apply_patch_buffer; 18849 } 18850 18851 /* Add in an zero-extend instruction if a) the JIT has requested 18852 * it or b) it's a CMPXCHG. 18853 * 18854 * The latter is because: BPF_CMPXCHG always loads a value into 18855 * R0, therefore always zero-extends. However some archs' 18856 * equivalent instruction only does this load when the 18857 * comparison is successful. This detail of CMPXCHG is 18858 * orthogonal to the general zero-extension behaviour of the 18859 * CPU, so it's treated independently of bpf_jit_needs_zext. 18860 */ 18861 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 18862 continue; 18863 18864 /* Zero-extension is done by the caller. */ 18865 if (bpf_pseudo_kfunc_call(&insn)) 18866 continue; 18867 18868 if (WARN_ON(load_reg == -1)) { 18869 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 18870 return -EFAULT; 18871 } 18872 18873 zext_patch[0] = insn; 18874 zext_patch[1].dst_reg = load_reg; 18875 zext_patch[1].src_reg = load_reg; 18876 patch = zext_patch; 18877 patch_len = 2; 18878 apply_patch_buffer: 18879 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 18880 if (!new_prog) 18881 return -ENOMEM; 18882 env->prog = new_prog; 18883 insns = new_prog->insnsi; 18884 aux = env->insn_aux_data; 18885 delta += patch_len - 1; 18886 } 18887 18888 return 0; 18889 } 18890 18891 /* convert load instructions that access fields of a context type into a 18892 * sequence of instructions that access fields of the underlying structure: 18893 * struct __sk_buff -> struct sk_buff 18894 * struct bpf_sock_ops -> struct sock 18895 */ 18896 static int convert_ctx_accesses(struct bpf_verifier_env *env) 18897 { 18898 const struct bpf_verifier_ops *ops = env->ops; 18899 int i, cnt, size, ctx_field_size, delta = 0; 18900 const int insn_cnt = env->prog->len; 18901 struct bpf_insn insn_buf[16], *insn; 18902 u32 target_size, size_default, off; 18903 struct bpf_prog *new_prog; 18904 enum bpf_access_type type; 18905 bool is_narrower_load; 18906 18907 if (ops->gen_prologue || env->seen_direct_write) { 18908 if (!ops->gen_prologue) { 18909 verbose(env, "bpf verifier is misconfigured\n"); 18910 return -EINVAL; 18911 } 18912 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 18913 env->prog); 18914 if (cnt >= ARRAY_SIZE(insn_buf)) { 18915 verbose(env, "bpf verifier is misconfigured\n"); 18916 return -EINVAL; 18917 } else if (cnt) { 18918 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 18919 if (!new_prog) 18920 return -ENOMEM; 18921 18922 env->prog = new_prog; 18923 delta += cnt - 1; 18924 } 18925 } 18926 18927 if (bpf_prog_is_offloaded(env->prog->aux)) 18928 return 0; 18929 18930 insn = env->prog->insnsi + delta; 18931 18932 for (i = 0; i < insn_cnt; i++, insn++) { 18933 bpf_convert_ctx_access_t convert_ctx_access; 18934 u8 mode; 18935 18936 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 18937 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 18938 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 18939 insn->code == (BPF_LDX | BPF_MEM | BPF_DW) || 18940 insn->code == (BPF_LDX | BPF_MEMSX | BPF_B) || 18941 insn->code == (BPF_LDX | BPF_MEMSX | BPF_H) || 18942 insn->code == (BPF_LDX | BPF_MEMSX | BPF_W)) { 18943 type = BPF_READ; 18944 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 18945 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 18946 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 18947 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 18948 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 18949 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 18950 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 18951 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 18952 type = BPF_WRITE; 18953 } else { 18954 continue; 18955 } 18956 18957 if (type == BPF_WRITE && 18958 env->insn_aux_data[i + delta].sanitize_stack_spill) { 18959 struct bpf_insn patch[] = { 18960 *insn, 18961 BPF_ST_NOSPEC(), 18962 }; 18963 18964 cnt = ARRAY_SIZE(patch); 18965 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 18966 if (!new_prog) 18967 return -ENOMEM; 18968 18969 delta += cnt - 1; 18970 env->prog = new_prog; 18971 insn = new_prog->insnsi + i + delta; 18972 continue; 18973 } 18974 18975 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 18976 case PTR_TO_CTX: 18977 if (!ops->convert_ctx_access) 18978 continue; 18979 convert_ctx_access = ops->convert_ctx_access; 18980 break; 18981 case PTR_TO_SOCKET: 18982 case PTR_TO_SOCK_COMMON: 18983 convert_ctx_access = bpf_sock_convert_ctx_access; 18984 break; 18985 case PTR_TO_TCP_SOCK: 18986 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 18987 break; 18988 case PTR_TO_XDP_SOCK: 18989 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 18990 break; 18991 case PTR_TO_BTF_ID: 18992 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 18993 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 18994 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 18995 * be said once it is marked PTR_UNTRUSTED, hence we must handle 18996 * any faults for loads into such types. BPF_WRITE is disallowed 18997 * for this case. 18998 */ 18999 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 19000 if (type == BPF_READ) { 19001 if (BPF_MODE(insn->code) == BPF_MEM) 19002 insn->code = BPF_LDX | BPF_PROBE_MEM | 19003 BPF_SIZE((insn)->code); 19004 else 19005 insn->code = BPF_LDX | BPF_PROBE_MEMSX | 19006 BPF_SIZE((insn)->code); 19007 env->prog->aux->num_exentries++; 19008 } 19009 continue; 19010 case PTR_TO_ARENA: 19011 if (BPF_MODE(insn->code) == BPF_MEMSX) { 19012 verbose(env, "sign extending loads from arena are not supported yet\n"); 19013 return -EOPNOTSUPP; 19014 } 19015 insn->code = BPF_CLASS(insn->code) | BPF_PROBE_MEM32 | BPF_SIZE(insn->code); 19016 env->prog->aux->num_exentries++; 19017 continue; 19018 default: 19019 continue; 19020 } 19021 19022 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 19023 size = BPF_LDST_BYTES(insn); 19024 mode = BPF_MODE(insn->code); 19025 19026 /* If the read access is a narrower load of the field, 19027 * convert to a 4/8-byte load, to minimum program type specific 19028 * convert_ctx_access changes. If conversion is successful, 19029 * we will apply proper mask to the result. 19030 */ 19031 is_narrower_load = size < ctx_field_size; 19032 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 19033 off = insn->off; 19034 if (is_narrower_load) { 19035 u8 size_code; 19036 19037 if (type == BPF_WRITE) { 19038 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 19039 return -EINVAL; 19040 } 19041 19042 size_code = BPF_H; 19043 if (ctx_field_size == 4) 19044 size_code = BPF_W; 19045 else if (ctx_field_size == 8) 19046 size_code = BPF_DW; 19047 19048 insn->off = off & ~(size_default - 1); 19049 insn->code = BPF_LDX | BPF_MEM | size_code; 19050 } 19051 19052 target_size = 0; 19053 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 19054 &target_size); 19055 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 19056 (ctx_field_size && !target_size)) { 19057 verbose(env, "bpf verifier is misconfigured\n"); 19058 return -EINVAL; 19059 } 19060 19061 if (is_narrower_load && size < target_size) { 19062 u8 shift = bpf_ctx_narrow_access_offset( 19063 off, size, size_default) * 8; 19064 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 19065 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 19066 return -EINVAL; 19067 } 19068 if (ctx_field_size <= 4) { 19069 if (shift) 19070 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 19071 insn->dst_reg, 19072 shift); 19073 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19074 (1 << size * 8) - 1); 19075 } else { 19076 if (shift) 19077 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 19078 insn->dst_reg, 19079 shift); 19080 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 19081 (1ULL << size * 8) - 1); 19082 } 19083 } 19084 if (mode == BPF_MEMSX) 19085 insn_buf[cnt++] = BPF_RAW_INSN(BPF_ALU64 | BPF_MOV | BPF_X, 19086 insn->dst_reg, insn->dst_reg, 19087 size * 8, 0); 19088 19089 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19090 if (!new_prog) 19091 return -ENOMEM; 19092 19093 delta += cnt - 1; 19094 19095 /* keep walking new program and skip insns we just inserted */ 19096 env->prog = new_prog; 19097 insn = new_prog->insnsi + i + delta; 19098 } 19099 19100 return 0; 19101 } 19102 19103 static int jit_subprogs(struct bpf_verifier_env *env) 19104 { 19105 struct bpf_prog *prog = env->prog, **func, *tmp; 19106 int i, j, subprog_start, subprog_end = 0, len, subprog; 19107 struct bpf_map *map_ptr; 19108 struct bpf_insn *insn; 19109 void *old_bpf_func; 19110 int err, num_exentries; 19111 19112 if (env->subprog_cnt <= 1) 19113 return 0; 19114 19115 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19116 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 19117 continue; 19118 19119 /* Upon error here we cannot fall back to interpreter but 19120 * need a hard reject of the program. Thus -EFAULT is 19121 * propagated in any case. 19122 */ 19123 subprog = find_subprog(env, i + insn->imm + 1); 19124 if (subprog < 0) { 19125 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 19126 i + insn->imm + 1); 19127 return -EFAULT; 19128 } 19129 /* temporarily remember subprog id inside insn instead of 19130 * aux_data, since next loop will split up all insns into funcs 19131 */ 19132 insn->off = subprog; 19133 /* remember original imm in case JIT fails and fallback 19134 * to interpreter will be needed 19135 */ 19136 env->insn_aux_data[i].call_imm = insn->imm; 19137 /* point imm to __bpf_call_base+1 from JITs point of view */ 19138 insn->imm = 1; 19139 if (bpf_pseudo_func(insn)) 19140 /* jit (e.g. x86_64) may emit fewer instructions 19141 * if it learns a u32 imm is the same as a u64 imm. 19142 * Force a non zero here. 19143 */ 19144 insn[1].imm = 1; 19145 } 19146 19147 err = bpf_prog_alloc_jited_linfo(prog); 19148 if (err) 19149 goto out_undo_insn; 19150 19151 err = -ENOMEM; 19152 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 19153 if (!func) 19154 goto out_undo_insn; 19155 19156 for (i = 0; i < env->subprog_cnt; i++) { 19157 subprog_start = subprog_end; 19158 subprog_end = env->subprog_info[i + 1].start; 19159 19160 len = subprog_end - subprog_start; 19161 /* bpf_prog_run() doesn't call subprogs directly, 19162 * hence main prog stats include the runtime of subprogs. 19163 * subprogs don't have IDs and not reachable via prog_get_next_id 19164 * func[i]->stats will never be accessed and stays NULL 19165 */ 19166 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 19167 if (!func[i]) 19168 goto out_free; 19169 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 19170 len * sizeof(struct bpf_insn)); 19171 func[i]->type = prog->type; 19172 func[i]->len = len; 19173 if (bpf_prog_calc_tag(func[i])) 19174 goto out_free; 19175 func[i]->is_func = 1; 19176 func[i]->aux->func_idx = i; 19177 /* Below members will be freed only at prog->aux */ 19178 func[i]->aux->btf = prog->aux->btf; 19179 func[i]->aux->func_info = prog->aux->func_info; 19180 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 19181 func[i]->aux->poke_tab = prog->aux->poke_tab; 19182 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 19183 19184 for (j = 0; j < prog->aux->size_poke_tab; j++) { 19185 struct bpf_jit_poke_descriptor *poke; 19186 19187 poke = &prog->aux->poke_tab[j]; 19188 if (poke->insn_idx < subprog_end && 19189 poke->insn_idx >= subprog_start) 19190 poke->aux = func[i]->aux; 19191 } 19192 19193 func[i]->aux->name[0] = 'F'; 19194 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 19195 func[i]->jit_requested = 1; 19196 func[i]->blinding_requested = prog->blinding_requested; 19197 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 19198 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 19199 func[i]->aux->linfo = prog->aux->linfo; 19200 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 19201 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 19202 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 19203 func[i]->aux->arena = prog->aux->arena; 19204 num_exentries = 0; 19205 insn = func[i]->insnsi; 19206 for (j = 0; j < func[i]->len; j++, insn++) { 19207 if (BPF_CLASS(insn->code) == BPF_LDX && 19208 (BPF_MODE(insn->code) == BPF_PROBE_MEM || 19209 BPF_MODE(insn->code) == BPF_PROBE_MEM32 || 19210 BPF_MODE(insn->code) == BPF_PROBE_MEMSX)) 19211 num_exentries++; 19212 if ((BPF_CLASS(insn->code) == BPF_STX || 19213 BPF_CLASS(insn->code) == BPF_ST) && 19214 BPF_MODE(insn->code) == BPF_PROBE_MEM32) 19215 num_exentries++; 19216 } 19217 func[i]->aux->num_exentries = num_exentries; 19218 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 19219 func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb; 19220 if (!i) 19221 func[i]->aux->exception_boundary = env->seen_exception; 19222 func[i] = bpf_int_jit_compile(func[i]); 19223 if (!func[i]->jited) { 19224 err = -ENOTSUPP; 19225 goto out_free; 19226 } 19227 cond_resched(); 19228 } 19229 19230 /* at this point all bpf functions were successfully JITed 19231 * now populate all bpf_calls with correct addresses and 19232 * run last pass of JIT 19233 */ 19234 for (i = 0; i < env->subprog_cnt; i++) { 19235 insn = func[i]->insnsi; 19236 for (j = 0; j < func[i]->len; j++, insn++) { 19237 if (bpf_pseudo_func(insn)) { 19238 subprog = insn->off; 19239 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 19240 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 19241 continue; 19242 } 19243 if (!bpf_pseudo_call(insn)) 19244 continue; 19245 subprog = insn->off; 19246 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 19247 } 19248 19249 /* we use the aux data to keep a list of the start addresses 19250 * of the JITed images for each function in the program 19251 * 19252 * for some architectures, such as powerpc64, the imm field 19253 * might not be large enough to hold the offset of the start 19254 * address of the callee's JITed image from __bpf_call_base 19255 * 19256 * in such cases, we can lookup the start address of a callee 19257 * by using its subprog id, available from the off field of 19258 * the call instruction, as an index for this list 19259 */ 19260 func[i]->aux->func = func; 19261 func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19262 func[i]->aux->real_func_cnt = env->subprog_cnt; 19263 } 19264 for (i = 0; i < env->subprog_cnt; i++) { 19265 old_bpf_func = func[i]->bpf_func; 19266 tmp = bpf_int_jit_compile(func[i]); 19267 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 19268 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 19269 err = -ENOTSUPP; 19270 goto out_free; 19271 } 19272 cond_resched(); 19273 } 19274 19275 /* finally lock prog and jit images for all functions and 19276 * populate kallsysm. Begin at the first subprogram, since 19277 * bpf_prog_load will add the kallsyms for the main program. 19278 */ 19279 for (i = 1; i < env->subprog_cnt; i++) { 19280 bpf_prog_lock_ro(func[i]); 19281 bpf_prog_kallsyms_add(func[i]); 19282 } 19283 19284 /* Last step: make now unused interpreter insns from main 19285 * prog consistent for later dump requests, so they can 19286 * later look the same as if they were interpreted only. 19287 */ 19288 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19289 if (bpf_pseudo_func(insn)) { 19290 insn[0].imm = env->insn_aux_data[i].call_imm; 19291 insn[1].imm = insn->off; 19292 insn->off = 0; 19293 continue; 19294 } 19295 if (!bpf_pseudo_call(insn)) 19296 continue; 19297 insn->off = env->insn_aux_data[i].call_imm; 19298 subprog = find_subprog(env, i + insn->off + 1); 19299 insn->imm = subprog; 19300 } 19301 19302 prog->jited = 1; 19303 prog->bpf_func = func[0]->bpf_func; 19304 prog->jited_len = func[0]->jited_len; 19305 prog->aux->extable = func[0]->aux->extable; 19306 prog->aux->num_exentries = func[0]->aux->num_exentries; 19307 prog->aux->func = func; 19308 prog->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt; 19309 prog->aux->real_func_cnt = env->subprog_cnt; 19310 prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func; 19311 prog->aux->exception_boundary = func[0]->aux->exception_boundary; 19312 bpf_prog_jit_attempt_done(prog); 19313 return 0; 19314 out_free: 19315 /* We failed JIT'ing, so at this point we need to unregister poke 19316 * descriptors from subprogs, so that kernel is not attempting to 19317 * patch it anymore as we're freeing the subprog JIT memory. 19318 */ 19319 for (i = 0; i < prog->aux->size_poke_tab; i++) { 19320 map_ptr = prog->aux->poke_tab[i].tail_call.map; 19321 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 19322 } 19323 /* At this point we're guaranteed that poke descriptors are not 19324 * live anymore. We can just unlink its descriptor table as it's 19325 * released with the main prog. 19326 */ 19327 for (i = 0; i < env->subprog_cnt; i++) { 19328 if (!func[i]) 19329 continue; 19330 func[i]->aux->poke_tab = NULL; 19331 bpf_jit_free(func[i]); 19332 } 19333 kfree(func); 19334 out_undo_insn: 19335 /* cleanup main prog to be interpreted */ 19336 prog->jit_requested = 0; 19337 prog->blinding_requested = 0; 19338 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 19339 if (!bpf_pseudo_call(insn)) 19340 continue; 19341 insn->off = 0; 19342 insn->imm = env->insn_aux_data[i].call_imm; 19343 } 19344 bpf_prog_jit_attempt_done(prog); 19345 return err; 19346 } 19347 19348 static int fixup_call_args(struct bpf_verifier_env *env) 19349 { 19350 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19351 struct bpf_prog *prog = env->prog; 19352 struct bpf_insn *insn = prog->insnsi; 19353 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 19354 int i, depth; 19355 #endif 19356 int err = 0; 19357 19358 if (env->prog->jit_requested && 19359 !bpf_prog_is_offloaded(env->prog->aux)) { 19360 err = jit_subprogs(env); 19361 if (err == 0) 19362 return 0; 19363 if (err == -EFAULT) 19364 return err; 19365 } 19366 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 19367 if (has_kfunc_call) { 19368 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 19369 return -EINVAL; 19370 } 19371 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 19372 /* When JIT fails the progs with bpf2bpf calls and tail_calls 19373 * have to be rejected, since interpreter doesn't support them yet. 19374 */ 19375 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 19376 return -EINVAL; 19377 } 19378 for (i = 0; i < prog->len; i++, insn++) { 19379 if (bpf_pseudo_func(insn)) { 19380 /* When JIT fails the progs with callback calls 19381 * have to be rejected, since interpreter doesn't support them yet. 19382 */ 19383 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 19384 return -EINVAL; 19385 } 19386 19387 if (!bpf_pseudo_call(insn)) 19388 continue; 19389 depth = get_callee_stack_depth(env, insn, i); 19390 if (depth < 0) 19391 return depth; 19392 bpf_patch_call_args(insn, depth); 19393 } 19394 err = 0; 19395 #endif 19396 return err; 19397 } 19398 19399 /* replace a generic kfunc with a specialized version if necessary */ 19400 static void specialize_kfunc(struct bpf_verifier_env *env, 19401 u32 func_id, u16 offset, unsigned long *addr) 19402 { 19403 struct bpf_prog *prog = env->prog; 19404 bool seen_direct_write; 19405 void *xdp_kfunc; 19406 bool is_rdonly; 19407 19408 if (bpf_dev_bound_kfunc_id(func_id)) { 19409 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 19410 if (xdp_kfunc) { 19411 *addr = (unsigned long)xdp_kfunc; 19412 return; 19413 } 19414 /* fallback to default kfunc when not supported by netdev */ 19415 } 19416 19417 if (offset) 19418 return; 19419 19420 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 19421 seen_direct_write = env->seen_direct_write; 19422 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 19423 19424 if (is_rdonly) 19425 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 19426 19427 /* restore env->seen_direct_write to its original value, since 19428 * may_access_direct_pkt_data mutates it 19429 */ 19430 env->seen_direct_write = seen_direct_write; 19431 } 19432 } 19433 19434 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 19435 u16 struct_meta_reg, 19436 u16 node_offset_reg, 19437 struct bpf_insn *insn, 19438 struct bpf_insn *insn_buf, 19439 int *cnt) 19440 { 19441 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 19442 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 19443 19444 insn_buf[0] = addr[0]; 19445 insn_buf[1] = addr[1]; 19446 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 19447 insn_buf[3] = *insn; 19448 *cnt = 4; 19449 } 19450 19451 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 19452 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 19453 { 19454 const struct bpf_kfunc_desc *desc; 19455 19456 if (!insn->imm) { 19457 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 19458 return -EINVAL; 19459 } 19460 19461 *cnt = 0; 19462 19463 /* insn->imm has the btf func_id. Replace it with an offset relative to 19464 * __bpf_call_base, unless the JIT needs to call functions that are 19465 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 19466 */ 19467 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 19468 if (!desc) { 19469 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 19470 insn->imm); 19471 return -EFAULT; 19472 } 19473 19474 if (!bpf_jit_supports_far_kfunc_call()) 19475 insn->imm = BPF_CALL_IMM(desc->addr); 19476 if (insn->off) 19477 return 0; 19478 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl] || 19479 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl]) { 19480 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19481 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19482 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 19483 19484 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_new_impl] && kptr_struct_meta) { 19485 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19486 insn_idx); 19487 return -EFAULT; 19488 } 19489 19490 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 19491 insn_buf[1] = addr[0]; 19492 insn_buf[2] = addr[1]; 19493 insn_buf[3] = *insn; 19494 *cnt = 4; 19495 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 19496 desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] || 19497 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 19498 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19499 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 19500 19501 if (desc->func_id == special_kfunc_list[KF_bpf_percpu_obj_drop_impl] && kptr_struct_meta) { 19502 verbose(env, "verifier internal error: NULL kptr_struct_meta expected at insn_idx %d\n", 19503 insn_idx); 19504 return -EFAULT; 19505 } 19506 19507 if (desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl] && 19508 !kptr_struct_meta) { 19509 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19510 insn_idx); 19511 return -EFAULT; 19512 } 19513 19514 insn_buf[0] = addr[0]; 19515 insn_buf[1] = addr[1]; 19516 insn_buf[2] = *insn; 19517 *cnt = 3; 19518 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 19519 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 19520 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19521 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 19522 int struct_meta_reg = BPF_REG_3; 19523 int node_offset_reg = BPF_REG_4; 19524 19525 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 19526 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 19527 struct_meta_reg = BPF_REG_4; 19528 node_offset_reg = BPF_REG_5; 19529 } 19530 19531 if (!kptr_struct_meta) { 19532 verbose(env, "verifier internal error: kptr_struct_meta expected at insn_idx %d\n", 19533 insn_idx); 19534 return -EFAULT; 19535 } 19536 19537 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 19538 node_offset_reg, insn, insn_buf, cnt); 19539 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 19540 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 19541 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 19542 *cnt = 1; 19543 } 19544 return 0; 19545 } 19546 19547 /* The function requires that first instruction in 'patch' is insnsi[prog->len - 1] */ 19548 static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len) 19549 { 19550 struct bpf_subprog_info *info = env->subprog_info; 19551 int cnt = env->subprog_cnt; 19552 struct bpf_prog *prog; 19553 19554 /* We only reserve one slot for hidden subprogs in subprog_info. */ 19555 if (env->hidden_subprog_cnt) { 19556 verbose(env, "verifier internal error: only one hidden subprog supported\n"); 19557 return -EFAULT; 19558 } 19559 /* We're not patching any existing instruction, just appending the new 19560 * ones for the hidden subprog. Hence all of the adjustment operations 19561 * in bpf_patch_insn_data are no-ops. 19562 */ 19563 prog = bpf_patch_insn_data(env, env->prog->len - 1, patch, len); 19564 if (!prog) 19565 return -ENOMEM; 19566 env->prog = prog; 19567 info[cnt + 1].start = info[cnt].start; 19568 info[cnt].start = prog->len - len + 1; 19569 env->subprog_cnt++; 19570 env->hidden_subprog_cnt++; 19571 return 0; 19572 } 19573 19574 /* Do various post-verification rewrites in a single program pass. 19575 * These rewrites simplify JIT and interpreter implementations. 19576 */ 19577 static int do_misc_fixups(struct bpf_verifier_env *env) 19578 { 19579 struct bpf_prog *prog = env->prog; 19580 enum bpf_attach_type eatype = prog->expected_attach_type; 19581 enum bpf_prog_type prog_type = resolve_prog_type(prog); 19582 struct bpf_insn *insn = prog->insnsi; 19583 const struct bpf_func_proto *fn; 19584 const int insn_cnt = prog->len; 19585 const struct bpf_map_ops *ops; 19586 struct bpf_insn_aux_data *aux; 19587 struct bpf_insn insn_buf[16]; 19588 struct bpf_prog *new_prog; 19589 struct bpf_map *map_ptr; 19590 int i, ret, cnt, delta = 0, cur_subprog = 0; 19591 struct bpf_subprog_info *subprogs = env->subprog_info; 19592 u16 stack_depth = subprogs[cur_subprog].stack_depth; 19593 u16 stack_depth_extra = 0; 19594 19595 if (env->seen_exception && !env->exception_callback_subprog) { 19596 struct bpf_insn patch[] = { 19597 env->prog->insnsi[insn_cnt - 1], 19598 BPF_MOV64_REG(BPF_REG_0, BPF_REG_1), 19599 BPF_EXIT_INSN(), 19600 }; 19601 19602 ret = add_hidden_subprog(env, patch, ARRAY_SIZE(patch)); 19603 if (ret < 0) 19604 return ret; 19605 prog = env->prog; 19606 insn = prog->insnsi; 19607 19608 env->exception_callback_subprog = env->subprog_cnt - 1; 19609 /* Don't update insn_cnt, as add_hidden_subprog always appends insns */ 19610 mark_subprog_exc_cb(env, env->exception_callback_subprog); 19611 } 19612 19613 for (i = 0; i < insn_cnt;) { 19614 if (insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) && insn->imm) { 19615 if ((insn->off == BPF_ADDR_SPACE_CAST && insn->imm == 1) || 19616 (((struct bpf_map *)env->prog->aux->arena)->map_flags & BPF_F_NO_USER_CONV)) { 19617 /* convert to 32-bit mov that clears upper 32-bit */ 19618 insn->code = BPF_ALU | BPF_MOV | BPF_X; 19619 /* clear off and imm, so it's a normal 'wX = wY' from JIT pov */ 19620 insn->off = 0; 19621 insn->imm = 0; 19622 } /* cast from as(0) to as(1) should be handled by JIT */ 19623 goto next_insn; 19624 } 19625 19626 if (env->insn_aux_data[i + delta].needs_zext) 19627 /* Convert BPF_CLASS(insn->code) == BPF_ALU64 to 32-bit ALU */ 19628 insn->code = BPF_ALU | BPF_OP(insn->code) | BPF_SRC(insn->code); 19629 19630 /* Make divide-by-zero exceptions impossible. */ 19631 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 19632 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 19633 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 19634 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 19635 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 19636 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 19637 struct bpf_insn *patchlet; 19638 struct bpf_insn chk_and_div[] = { 19639 /* [R,W]x div 0 -> 0 */ 19640 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19641 BPF_JNE | BPF_K, insn->src_reg, 19642 0, 2, 0), 19643 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 19644 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19645 *insn, 19646 }; 19647 struct bpf_insn chk_and_mod[] = { 19648 /* [R,W]x mod 0 -> [R,W]x */ 19649 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 19650 BPF_JEQ | BPF_K, insn->src_reg, 19651 0, 1 + (is64 ? 0 : 1), 0), 19652 *insn, 19653 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 19654 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 19655 }; 19656 19657 patchlet = isdiv ? chk_and_div : chk_and_mod; 19658 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 19659 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 19660 19661 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 19662 if (!new_prog) 19663 return -ENOMEM; 19664 19665 delta += cnt - 1; 19666 env->prog = prog = new_prog; 19667 insn = new_prog->insnsi + i + delta; 19668 goto next_insn; 19669 } 19670 19671 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 19672 if (BPF_CLASS(insn->code) == BPF_LD && 19673 (BPF_MODE(insn->code) == BPF_ABS || 19674 BPF_MODE(insn->code) == BPF_IND)) { 19675 cnt = env->ops->gen_ld_abs(insn, insn_buf); 19676 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19677 verbose(env, "bpf verifier is misconfigured\n"); 19678 return -EINVAL; 19679 } 19680 19681 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19682 if (!new_prog) 19683 return -ENOMEM; 19684 19685 delta += cnt - 1; 19686 env->prog = prog = new_prog; 19687 insn = new_prog->insnsi + i + delta; 19688 goto next_insn; 19689 } 19690 19691 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 19692 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 19693 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 19694 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 19695 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 19696 struct bpf_insn *patch = &insn_buf[0]; 19697 bool issrc, isneg, isimm; 19698 u32 off_reg; 19699 19700 aux = &env->insn_aux_data[i + delta]; 19701 if (!aux->alu_state || 19702 aux->alu_state == BPF_ALU_NON_POINTER) 19703 goto next_insn; 19704 19705 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 19706 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 19707 BPF_ALU_SANITIZE_SRC; 19708 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 19709 19710 off_reg = issrc ? insn->src_reg : insn->dst_reg; 19711 if (isimm) { 19712 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19713 } else { 19714 if (isneg) 19715 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19716 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 19717 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 19718 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 19719 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 19720 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 19721 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 19722 } 19723 if (!issrc) 19724 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 19725 insn->src_reg = BPF_REG_AX; 19726 if (isneg) 19727 insn->code = insn->code == code_add ? 19728 code_sub : code_add; 19729 *patch++ = *insn; 19730 if (issrc && isneg && !isimm) 19731 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 19732 cnt = patch - insn_buf; 19733 19734 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19735 if (!new_prog) 19736 return -ENOMEM; 19737 19738 delta += cnt - 1; 19739 env->prog = prog = new_prog; 19740 insn = new_prog->insnsi + i + delta; 19741 goto next_insn; 19742 } 19743 19744 if (is_may_goto_insn(insn)) { 19745 int stack_off = -stack_depth - 8; 19746 19747 stack_depth_extra = 8; 19748 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_10, stack_off); 19749 insn_buf[1] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, insn->off + 2); 19750 insn_buf[2] = BPF_ALU64_IMM(BPF_SUB, BPF_REG_AX, 1); 19751 insn_buf[3] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_AX, stack_off); 19752 cnt = 4; 19753 19754 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19755 if (!new_prog) 19756 return -ENOMEM; 19757 19758 delta += cnt - 1; 19759 env->prog = prog = new_prog; 19760 insn = new_prog->insnsi + i + delta; 19761 goto next_insn; 19762 } 19763 19764 if (insn->code != (BPF_JMP | BPF_CALL)) 19765 goto next_insn; 19766 if (insn->src_reg == BPF_PSEUDO_CALL) 19767 goto next_insn; 19768 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 19769 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 19770 if (ret) 19771 return ret; 19772 if (cnt == 0) 19773 goto next_insn; 19774 19775 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19776 if (!new_prog) 19777 return -ENOMEM; 19778 19779 delta += cnt - 1; 19780 env->prog = prog = new_prog; 19781 insn = new_prog->insnsi + i + delta; 19782 goto next_insn; 19783 } 19784 19785 if (insn->imm == BPF_FUNC_get_route_realm) 19786 prog->dst_needed = 1; 19787 if (insn->imm == BPF_FUNC_get_prandom_u32) 19788 bpf_user_rnd_init_once(); 19789 if (insn->imm == BPF_FUNC_override_return) 19790 prog->kprobe_override = 1; 19791 if (insn->imm == BPF_FUNC_tail_call) { 19792 /* If we tail call into other programs, we 19793 * cannot make any assumptions since they can 19794 * be replaced dynamically during runtime in 19795 * the program array. 19796 */ 19797 prog->cb_access = 1; 19798 if (!allow_tail_call_in_subprogs(env)) 19799 prog->aux->stack_depth = MAX_BPF_STACK; 19800 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 19801 19802 /* mark bpf_tail_call as different opcode to avoid 19803 * conditional branch in the interpreter for every normal 19804 * call and to prevent accidental JITing by JIT compiler 19805 * that doesn't support bpf_tail_call yet 19806 */ 19807 insn->imm = 0; 19808 insn->code = BPF_JMP | BPF_TAIL_CALL; 19809 19810 aux = &env->insn_aux_data[i + delta]; 19811 if (env->bpf_capable && !prog->blinding_requested && 19812 prog->jit_requested && 19813 !bpf_map_key_poisoned(aux) && 19814 !bpf_map_ptr_poisoned(aux) && 19815 !bpf_map_ptr_unpriv(aux)) { 19816 struct bpf_jit_poke_descriptor desc = { 19817 .reason = BPF_POKE_REASON_TAIL_CALL, 19818 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 19819 .tail_call.key = bpf_map_key_immediate(aux), 19820 .insn_idx = i + delta, 19821 }; 19822 19823 ret = bpf_jit_add_poke_descriptor(prog, &desc); 19824 if (ret < 0) { 19825 verbose(env, "adding tail call poke descriptor failed\n"); 19826 return ret; 19827 } 19828 19829 insn->imm = ret + 1; 19830 goto next_insn; 19831 } 19832 19833 if (!bpf_map_ptr_unpriv(aux)) 19834 goto next_insn; 19835 19836 /* instead of changing every JIT dealing with tail_call 19837 * emit two extra insns: 19838 * if (index >= max_entries) goto out; 19839 * index &= array->index_mask; 19840 * to avoid out-of-bounds cpu speculation 19841 */ 19842 if (bpf_map_ptr_poisoned(aux)) { 19843 verbose(env, "tail_call abusing map_ptr\n"); 19844 return -EINVAL; 19845 } 19846 19847 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19848 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 19849 map_ptr->max_entries, 2); 19850 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 19851 container_of(map_ptr, 19852 struct bpf_array, 19853 map)->index_mask); 19854 insn_buf[2] = *insn; 19855 cnt = 3; 19856 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19857 if (!new_prog) 19858 return -ENOMEM; 19859 19860 delta += cnt - 1; 19861 env->prog = prog = new_prog; 19862 insn = new_prog->insnsi + i + delta; 19863 goto next_insn; 19864 } 19865 19866 if (insn->imm == BPF_FUNC_timer_set_callback) { 19867 /* The verifier will process callback_fn as many times as necessary 19868 * with different maps and the register states prepared by 19869 * set_timer_callback_state will be accurate. 19870 * 19871 * The following use case is valid: 19872 * map1 is shared by prog1, prog2, prog3. 19873 * prog1 calls bpf_timer_init for some map1 elements 19874 * prog2 calls bpf_timer_set_callback for some map1 elements. 19875 * Those that were not bpf_timer_init-ed will return -EINVAL. 19876 * prog3 calls bpf_timer_start for some map1 elements. 19877 * Those that were not both bpf_timer_init-ed and 19878 * bpf_timer_set_callback-ed will return -EINVAL. 19879 */ 19880 struct bpf_insn ld_addrs[2] = { 19881 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 19882 }; 19883 19884 insn_buf[0] = ld_addrs[0]; 19885 insn_buf[1] = ld_addrs[1]; 19886 insn_buf[2] = *insn; 19887 cnt = 3; 19888 19889 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19890 if (!new_prog) 19891 return -ENOMEM; 19892 19893 delta += cnt - 1; 19894 env->prog = prog = new_prog; 19895 insn = new_prog->insnsi + i + delta; 19896 goto patch_call_imm; 19897 } 19898 19899 if (is_storage_get_function(insn->imm)) { 19900 if (!in_sleepable(env) || 19901 env->insn_aux_data[i + delta].storage_get_func_atomic) 19902 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 19903 else 19904 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 19905 insn_buf[1] = *insn; 19906 cnt = 2; 19907 19908 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19909 if (!new_prog) 19910 return -ENOMEM; 19911 19912 delta += cnt - 1; 19913 env->prog = prog = new_prog; 19914 insn = new_prog->insnsi + i + delta; 19915 goto patch_call_imm; 19916 } 19917 19918 /* bpf_per_cpu_ptr() and bpf_this_cpu_ptr() */ 19919 if (env->insn_aux_data[i + delta].call_with_percpu_alloc_ptr) { 19920 /* patch with 'r1 = *(u64 *)(r1 + 0)' since for percpu data, 19921 * bpf_mem_alloc() returns a ptr to the percpu data ptr. 19922 */ 19923 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_1, 0); 19924 insn_buf[1] = *insn; 19925 cnt = 2; 19926 19927 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 19928 if (!new_prog) 19929 return -ENOMEM; 19930 19931 delta += cnt - 1; 19932 env->prog = prog = new_prog; 19933 insn = new_prog->insnsi + i + delta; 19934 goto patch_call_imm; 19935 } 19936 19937 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 19938 * and other inlining handlers are currently limited to 64 bit 19939 * only. 19940 */ 19941 if (prog->jit_requested && BITS_PER_LONG == 64 && 19942 (insn->imm == BPF_FUNC_map_lookup_elem || 19943 insn->imm == BPF_FUNC_map_update_elem || 19944 insn->imm == BPF_FUNC_map_delete_elem || 19945 insn->imm == BPF_FUNC_map_push_elem || 19946 insn->imm == BPF_FUNC_map_pop_elem || 19947 insn->imm == BPF_FUNC_map_peek_elem || 19948 insn->imm == BPF_FUNC_redirect_map || 19949 insn->imm == BPF_FUNC_for_each_map_elem || 19950 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 19951 aux = &env->insn_aux_data[i + delta]; 19952 if (bpf_map_ptr_poisoned(aux)) 19953 goto patch_call_imm; 19954 19955 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 19956 ops = map_ptr->ops; 19957 if (insn->imm == BPF_FUNC_map_lookup_elem && 19958 ops->map_gen_lookup) { 19959 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 19960 if (cnt == -EOPNOTSUPP) 19961 goto patch_map_ops_generic; 19962 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 19963 verbose(env, "bpf verifier is misconfigured\n"); 19964 return -EINVAL; 19965 } 19966 19967 new_prog = bpf_patch_insn_data(env, i + delta, 19968 insn_buf, cnt); 19969 if (!new_prog) 19970 return -ENOMEM; 19971 19972 delta += cnt - 1; 19973 env->prog = prog = new_prog; 19974 insn = new_prog->insnsi + i + delta; 19975 goto next_insn; 19976 } 19977 19978 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 19979 (void *(*)(struct bpf_map *map, void *key))NULL)); 19980 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 19981 (long (*)(struct bpf_map *map, void *key))NULL)); 19982 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 19983 (long (*)(struct bpf_map *map, void *key, void *value, 19984 u64 flags))NULL)); 19985 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 19986 (long (*)(struct bpf_map *map, void *value, 19987 u64 flags))NULL)); 19988 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 19989 (long (*)(struct bpf_map *map, void *value))NULL)); 19990 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 19991 (long (*)(struct bpf_map *map, void *value))NULL)); 19992 BUILD_BUG_ON(!__same_type(ops->map_redirect, 19993 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 19994 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 19995 (long (*)(struct bpf_map *map, 19996 bpf_callback_t callback_fn, 19997 void *callback_ctx, 19998 u64 flags))NULL)); 19999 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 20000 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 20001 20002 patch_map_ops_generic: 20003 switch (insn->imm) { 20004 case BPF_FUNC_map_lookup_elem: 20005 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 20006 goto next_insn; 20007 case BPF_FUNC_map_update_elem: 20008 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 20009 goto next_insn; 20010 case BPF_FUNC_map_delete_elem: 20011 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 20012 goto next_insn; 20013 case BPF_FUNC_map_push_elem: 20014 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 20015 goto next_insn; 20016 case BPF_FUNC_map_pop_elem: 20017 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 20018 goto next_insn; 20019 case BPF_FUNC_map_peek_elem: 20020 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 20021 goto next_insn; 20022 case BPF_FUNC_redirect_map: 20023 insn->imm = BPF_CALL_IMM(ops->map_redirect); 20024 goto next_insn; 20025 case BPF_FUNC_for_each_map_elem: 20026 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 20027 goto next_insn; 20028 case BPF_FUNC_map_lookup_percpu_elem: 20029 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 20030 goto next_insn; 20031 } 20032 20033 goto patch_call_imm; 20034 } 20035 20036 /* Implement bpf_jiffies64 inline. */ 20037 if (prog->jit_requested && BITS_PER_LONG == 64 && 20038 insn->imm == BPF_FUNC_jiffies64) { 20039 struct bpf_insn ld_jiffies_addr[2] = { 20040 BPF_LD_IMM64(BPF_REG_0, 20041 (unsigned long)&jiffies), 20042 }; 20043 20044 insn_buf[0] = ld_jiffies_addr[0]; 20045 insn_buf[1] = ld_jiffies_addr[1]; 20046 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 20047 BPF_REG_0, 0); 20048 cnt = 3; 20049 20050 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 20051 cnt); 20052 if (!new_prog) 20053 return -ENOMEM; 20054 20055 delta += cnt - 1; 20056 env->prog = prog = new_prog; 20057 insn = new_prog->insnsi + i + delta; 20058 goto next_insn; 20059 } 20060 20061 /* Implement bpf_get_func_arg inline. */ 20062 if (prog_type == BPF_PROG_TYPE_TRACING && 20063 insn->imm == BPF_FUNC_get_func_arg) { 20064 /* Load nr_args from ctx - 8 */ 20065 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20066 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 20067 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 20068 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 20069 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 20070 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 20071 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 20072 insn_buf[7] = BPF_JMP_A(1); 20073 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 20074 cnt = 9; 20075 20076 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20077 if (!new_prog) 20078 return -ENOMEM; 20079 20080 delta += cnt - 1; 20081 env->prog = prog = new_prog; 20082 insn = new_prog->insnsi + i + delta; 20083 goto next_insn; 20084 } 20085 20086 /* Implement bpf_get_func_ret inline. */ 20087 if (prog_type == BPF_PROG_TYPE_TRACING && 20088 insn->imm == BPF_FUNC_get_func_ret) { 20089 if (eatype == BPF_TRACE_FEXIT || 20090 eatype == BPF_MODIFY_RETURN) { 20091 /* Load nr_args from ctx - 8 */ 20092 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20093 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 20094 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 20095 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 20096 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 20097 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 20098 cnt = 6; 20099 } else { 20100 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 20101 cnt = 1; 20102 } 20103 20104 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20105 if (!new_prog) 20106 return -ENOMEM; 20107 20108 delta += cnt - 1; 20109 env->prog = prog = new_prog; 20110 insn = new_prog->insnsi + i + delta; 20111 goto next_insn; 20112 } 20113 20114 /* Implement get_func_arg_cnt inline. */ 20115 if (prog_type == BPF_PROG_TYPE_TRACING && 20116 insn->imm == BPF_FUNC_get_func_arg_cnt) { 20117 /* Load nr_args from ctx - 8 */ 20118 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 20119 20120 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 20121 if (!new_prog) 20122 return -ENOMEM; 20123 20124 env->prog = prog = new_prog; 20125 insn = new_prog->insnsi + i + delta; 20126 goto next_insn; 20127 } 20128 20129 /* Implement bpf_get_func_ip inline. */ 20130 if (prog_type == BPF_PROG_TYPE_TRACING && 20131 insn->imm == BPF_FUNC_get_func_ip) { 20132 /* Load IP address from ctx - 16 */ 20133 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 20134 20135 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 20136 if (!new_prog) 20137 return -ENOMEM; 20138 20139 env->prog = prog = new_prog; 20140 insn = new_prog->insnsi + i + delta; 20141 goto next_insn; 20142 } 20143 20144 /* Implement bpf_kptr_xchg inline */ 20145 if (prog->jit_requested && BITS_PER_LONG == 64 && 20146 insn->imm == BPF_FUNC_kptr_xchg && 20147 bpf_jit_supports_ptr_xchg()) { 20148 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_2); 20149 insn_buf[1] = BPF_ATOMIC_OP(BPF_DW, BPF_XCHG, BPF_REG_1, BPF_REG_0, 0); 20150 cnt = 2; 20151 20152 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 20153 if (!new_prog) 20154 return -ENOMEM; 20155 20156 delta += cnt - 1; 20157 env->prog = prog = new_prog; 20158 insn = new_prog->insnsi + i + delta; 20159 goto next_insn; 20160 } 20161 patch_call_imm: 20162 fn = env->ops->get_func_proto(insn->imm, env->prog); 20163 /* all functions that have prototype and verifier allowed 20164 * programs to call them, must be real in-kernel functions 20165 */ 20166 if (!fn->func) { 20167 verbose(env, 20168 "kernel subsystem misconfigured func %s#%d\n", 20169 func_id_name(insn->imm), insn->imm); 20170 return -EFAULT; 20171 } 20172 insn->imm = fn->func - __bpf_call_base; 20173 next_insn: 20174 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 20175 subprogs[cur_subprog].stack_depth += stack_depth_extra; 20176 subprogs[cur_subprog].stack_extra = stack_depth_extra; 20177 cur_subprog++; 20178 stack_depth = subprogs[cur_subprog].stack_depth; 20179 stack_depth_extra = 0; 20180 } 20181 i++; 20182 insn++; 20183 } 20184 20185 env->prog->aux->stack_depth = subprogs[0].stack_depth; 20186 for (i = 0; i < env->subprog_cnt; i++) { 20187 int subprog_start = subprogs[i].start; 20188 int stack_slots = subprogs[i].stack_extra / 8; 20189 20190 if (!stack_slots) 20191 continue; 20192 if (stack_slots > 1) { 20193 verbose(env, "verifier bug: stack_slots supports may_goto only\n"); 20194 return -EFAULT; 20195 } 20196 20197 /* Add ST insn to subprog prologue to init extra stack */ 20198 insn_buf[0] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, 20199 -subprogs[i].stack_depth, BPF_MAX_LOOPS); 20200 /* Copy first actual insn to preserve it */ 20201 insn_buf[1] = env->prog->insnsi[subprog_start]; 20202 20203 new_prog = bpf_patch_insn_data(env, subprog_start, insn_buf, 2); 20204 if (!new_prog) 20205 return -ENOMEM; 20206 env->prog = prog = new_prog; 20207 } 20208 20209 /* Since poke tab is now finalized, publish aux to tracker. */ 20210 for (i = 0; i < prog->aux->size_poke_tab; i++) { 20211 map_ptr = prog->aux->poke_tab[i].tail_call.map; 20212 if (!map_ptr->ops->map_poke_track || 20213 !map_ptr->ops->map_poke_untrack || 20214 !map_ptr->ops->map_poke_run) { 20215 verbose(env, "bpf verifier is misconfigured\n"); 20216 return -EINVAL; 20217 } 20218 20219 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 20220 if (ret < 0) { 20221 verbose(env, "tracking tail call prog failed\n"); 20222 return ret; 20223 } 20224 } 20225 20226 sort_kfunc_descs_by_imm_off(env->prog); 20227 20228 return 0; 20229 } 20230 20231 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 20232 int position, 20233 s32 stack_base, 20234 u32 callback_subprogno, 20235 u32 *cnt) 20236 { 20237 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 20238 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 20239 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 20240 int reg_loop_max = BPF_REG_6; 20241 int reg_loop_cnt = BPF_REG_7; 20242 int reg_loop_ctx = BPF_REG_8; 20243 20244 struct bpf_prog *new_prog; 20245 u32 callback_start; 20246 u32 call_insn_offset; 20247 s32 callback_offset; 20248 20249 /* This represents an inlined version of bpf_iter.c:bpf_loop, 20250 * be careful to modify this code in sync. 20251 */ 20252 struct bpf_insn insn_buf[] = { 20253 /* Return error and jump to the end of the patch if 20254 * expected number of iterations is too big. 20255 */ 20256 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 20257 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 20258 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 20259 /* spill R6, R7, R8 to use these as loop vars */ 20260 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 20261 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 20262 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 20263 /* initialize loop vars */ 20264 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 20265 BPF_MOV32_IMM(reg_loop_cnt, 0), 20266 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 20267 /* loop header, 20268 * if reg_loop_cnt >= reg_loop_max skip the loop body 20269 */ 20270 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 20271 /* callback call, 20272 * correct callback offset would be set after patching 20273 */ 20274 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 20275 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 20276 BPF_CALL_REL(0), 20277 /* increment loop counter */ 20278 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 20279 /* jump to loop header if callback returned 0 */ 20280 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 20281 /* return value of bpf_loop, 20282 * set R0 to the number of iterations 20283 */ 20284 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 20285 /* restore original values of R6, R7, R8 */ 20286 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 20287 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 20288 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 20289 }; 20290 20291 *cnt = ARRAY_SIZE(insn_buf); 20292 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 20293 if (!new_prog) 20294 return new_prog; 20295 20296 /* callback start is known only after patching */ 20297 callback_start = env->subprog_info[callback_subprogno].start; 20298 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 20299 call_insn_offset = position + 12; 20300 callback_offset = callback_start - call_insn_offset - 1; 20301 new_prog->insnsi[call_insn_offset].imm = callback_offset; 20302 20303 return new_prog; 20304 } 20305 20306 static bool is_bpf_loop_call(struct bpf_insn *insn) 20307 { 20308 return insn->code == (BPF_JMP | BPF_CALL) && 20309 insn->src_reg == 0 && 20310 insn->imm == BPF_FUNC_loop; 20311 } 20312 20313 /* For all sub-programs in the program (including main) check 20314 * insn_aux_data to see if there are bpf_loop calls that require 20315 * inlining. If such calls are found the calls are replaced with a 20316 * sequence of instructions produced by `inline_bpf_loop` function and 20317 * subprog stack_depth is increased by the size of 3 registers. 20318 * This stack space is used to spill values of the R6, R7, R8. These 20319 * registers are used to store the loop bound, counter and context 20320 * variables. 20321 */ 20322 static int optimize_bpf_loop(struct bpf_verifier_env *env) 20323 { 20324 struct bpf_subprog_info *subprogs = env->subprog_info; 20325 int i, cur_subprog = 0, cnt, delta = 0; 20326 struct bpf_insn *insn = env->prog->insnsi; 20327 int insn_cnt = env->prog->len; 20328 u16 stack_depth = subprogs[cur_subprog].stack_depth; 20329 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20330 u16 stack_depth_extra = 0; 20331 20332 for (i = 0; i < insn_cnt; i++, insn++) { 20333 struct bpf_loop_inline_state *inline_state = 20334 &env->insn_aux_data[i + delta].loop_inline_state; 20335 20336 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 20337 struct bpf_prog *new_prog; 20338 20339 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 20340 new_prog = inline_bpf_loop(env, 20341 i + delta, 20342 -(stack_depth + stack_depth_extra), 20343 inline_state->callback_subprogno, 20344 &cnt); 20345 if (!new_prog) 20346 return -ENOMEM; 20347 20348 delta += cnt - 1; 20349 env->prog = new_prog; 20350 insn = new_prog->insnsi + i + delta; 20351 } 20352 20353 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 20354 subprogs[cur_subprog].stack_depth += stack_depth_extra; 20355 cur_subprog++; 20356 stack_depth = subprogs[cur_subprog].stack_depth; 20357 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 20358 stack_depth_extra = 0; 20359 } 20360 } 20361 20362 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20363 20364 return 0; 20365 } 20366 20367 static void free_states(struct bpf_verifier_env *env) 20368 { 20369 struct bpf_verifier_state_list *sl, *sln; 20370 int i; 20371 20372 sl = env->free_list; 20373 while (sl) { 20374 sln = sl->next; 20375 free_verifier_state(&sl->state, false); 20376 kfree(sl); 20377 sl = sln; 20378 } 20379 env->free_list = NULL; 20380 20381 if (!env->explored_states) 20382 return; 20383 20384 for (i = 0; i < state_htab_size(env); i++) { 20385 sl = env->explored_states[i]; 20386 20387 while (sl) { 20388 sln = sl->next; 20389 free_verifier_state(&sl->state, false); 20390 kfree(sl); 20391 sl = sln; 20392 } 20393 env->explored_states[i] = NULL; 20394 } 20395 } 20396 20397 static int do_check_common(struct bpf_verifier_env *env, int subprog) 20398 { 20399 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 20400 struct bpf_subprog_info *sub = subprog_info(env, subprog); 20401 struct bpf_verifier_state *state; 20402 struct bpf_reg_state *regs; 20403 int ret, i; 20404 20405 env->prev_linfo = NULL; 20406 env->pass_cnt++; 20407 20408 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 20409 if (!state) 20410 return -ENOMEM; 20411 state->curframe = 0; 20412 state->speculative = false; 20413 state->branches = 1; 20414 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 20415 if (!state->frame[0]) { 20416 kfree(state); 20417 return -ENOMEM; 20418 } 20419 env->cur_state = state; 20420 init_func_state(env, state->frame[0], 20421 BPF_MAIN_FUNC /* callsite */, 20422 0 /* frameno */, 20423 subprog); 20424 state->first_insn_idx = env->subprog_info[subprog].start; 20425 state->last_insn_idx = -1; 20426 20427 regs = state->frame[state->curframe]->regs; 20428 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 20429 const char *sub_name = subprog_name(env, subprog); 20430 struct bpf_subprog_arg_info *arg; 20431 struct bpf_reg_state *reg; 20432 20433 verbose(env, "Validating %s() func#%d...\n", sub_name, subprog); 20434 ret = btf_prepare_func_args(env, subprog); 20435 if (ret) 20436 goto out; 20437 20438 if (subprog_is_exc_cb(env, subprog)) { 20439 state->frame[0]->in_exception_callback_fn = true; 20440 /* We have already ensured that the callback returns an integer, just 20441 * like all global subprogs. We need to determine it only has a single 20442 * scalar argument. 20443 */ 20444 if (sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_ANYTHING) { 20445 verbose(env, "exception cb only supports single integer argument\n"); 20446 ret = -EINVAL; 20447 goto out; 20448 } 20449 } 20450 for (i = BPF_REG_1; i <= sub->arg_cnt; i++) { 20451 arg = &sub->args[i - BPF_REG_1]; 20452 reg = ®s[i]; 20453 20454 if (arg->arg_type == ARG_PTR_TO_CTX) { 20455 reg->type = PTR_TO_CTX; 20456 mark_reg_known_zero(env, regs, i); 20457 } else if (arg->arg_type == ARG_ANYTHING) { 20458 reg->type = SCALAR_VALUE; 20459 mark_reg_unknown(env, regs, i); 20460 } else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) { 20461 /* assume unspecial LOCAL dynptr type */ 20462 __mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen); 20463 } else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) { 20464 reg->type = PTR_TO_MEM; 20465 if (arg->arg_type & PTR_MAYBE_NULL) 20466 reg->type |= PTR_MAYBE_NULL; 20467 mark_reg_known_zero(env, regs, i); 20468 reg->mem_size = arg->mem_size; 20469 reg->id = ++env->id_gen; 20470 } else if (base_type(arg->arg_type) == ARG_PTR_TO_BTF_ID) { 20471 reg->type = PTR_TO_BTF_ID; 20472 if (arg->arg_type & PTR_MAYBE_NULL) 20473 reg->type |= PTR_MAYBE_NULL; 20474 if (arg->arg_type & PTR_UNTRUSTED) 20475 reg->type |= PTR_UNTRUSTED; 20476 if (arg->arg_type & PTR_TRUSTED) 20477 reg->type |= PTR_TRUSTED; 20478 mark_reg_known_zero(env, regs, i); 20479 reg->btf = bpf_get_btf_vmlinux(); /* can't fail at this point */ 20480 reg->btf_id = arg->btf_id; 20481 reg->id = ++env->id_gen; 20482 } else if (base_type(arg->arg_type) == ARG_PTR_TO_ARENA) { 20483 /* caller can pass either PTR_TO_ARENA or SCALAR */ 20484 mark_reg_unknown(env, regs, i); 20485 } else { 20486 WARN_ONCE(1, "BUG: unhandled arg#%d type %d\n", 20487 i - BPF_REG_1, arg->arg_type); 20488 ret = -EFAULT; 20489 goto out; 20490 } 20491 } 20492 } else { 20493 /* if main BPF program has associated BTF info, validate that 20494 * it's matching expected signature, and otherwise mark BTF 20495 * info for main program as unreliable 20496 */ 20497 if (env->prog->aux->func_info_aux) { 20498 ret = btf_prepare_func_args(env, 0); 20499 if (ret || sub->arg_cnt != 1 || sub->args[0].arg_type != ARG_PTR_TO_CTX) 20500 env->prog->aux->func_info_aux[0].unreliable = true; 20501 } 20502 20503 /* 1st arg to a function */ 20504 regs[BPF_REG_1].type = PTR_TO_CTX; 20505 mark_reg_known_zero(env, regs, BPF_REG_1); 20506 } 20507 20508 ret = do_check(env); 20509 out: 20510 /* check for NULL is necessary, since cur_state can be freed inside 20511 * do_check() under memory pressure. 20512 */ 20513 if (env->cur_state) { 20514 free_verifier_state(env->cur_state, true); 20515 env->cur_state = NULL; 20516 } 20517 while (!pop_stack(env, NULL, NULL, false)); 20518 if (!ret && pop_log) 20519 bpf_vlog_reset(&env->log, 0); 20520 free_states(env); 20521 return ret; 20522 } 20523 20524 /* Lazily verify all global functions based on their BTF, if they are called 20525 * from main BPF program or any of subprograms transitively. 20526 * BPF global subprogs called from dead code are not validated. 20527 * All callable global functions must pass verification. 20528 * Otherwise the whole program is rejected. 20529 * Consider: 20530 * int bar(int); 20531 * int foo(int f) 20532 * { 20533 * return bar(f); 20534 * } 20535 * int bar(int b) 20536 * { 20537 * ... 20538 * } 20539 * foo() will be verified first for R1=any_scalar_value. During verification it 20540 * will be assumed that bar() already verified successfully and call to bar() 20541 * from foo() will be checked for type match only. Later bar() will be verified 20542 * independently to check that it's safe for R1=any_scalar_value. 20543 */ 20544 static int do_check_subprogs(struct bpf_verifier_env *env) 20545 { 20546 struct bpf_prog_aux *aux = env->prog->aux; 20547 struct bpf_func_info_aux *sub_aux; 20548 int i, ret, new_cnt; 20549 20550 if (!aux->func_info) 20551 return 0; 20552 20553 /* exception callback is presumed to be always called */ 20554 if (env->exception_callback_subprog) 20555 subprog_aux(env, env->exception_callback_subprog)->called = true; 20556 20557 again: 20558 new_cnt = 0; 20559 for (i = 1; i < env->subprog_cnt; i++) { 20560 if (!subprog_is_global(env, i)) 20561 continue; 20562 20563 sub_aux = subprog_aux(env, i); 20564 if (!sub_aux->called || sub_aux->verified) 20565 continue; 20566 20567 env->insn_idx = env->subprog_info[i].start; 20568 WARN_ON_ONCE(env->insn_idx == 0); 20569 ret = do_check_common(env, i); 20570 if (ret) { 20571 return ret; 20572 } else if (env->log.level & BPF_LOG_LEVEL) { 20573 verbose(env, "Func#%d ('%s') is safe for any args that match its prototype\n", 20574 i, subprog_name(env, i)); 20575 } 20576 20577 /* We verified new global subprog, it might have called some 20578 * more global subprogs that we haven't verified yet, so we 20579 * need to do another pass over subprogs to verify those. 20580 */ 20581 sub_aux->verified = true; 20582 new_cnt++; 20583 } 20584 20585 /* We can't loop forever as we verify at least one global subprog on 20586 * each pass. 20587 */ 20588 if (new_cnt) 20589 goto again; 20590 20591 return 0; 20592 } 20593 20594 static int do_check_main(struct bpf_verifier_env *env) 20595 { 20596 int ret; 20597 20598 env->insn_idx = 0; 20599 ret = do_check_common(env, 0); 20600 if (!ret) 20601 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 20602 return ret; 20603 } 20604 20605 20606 static void print_verification_stats(struct bpf_verifier_env *env) 20607 { 20608 int i; 20609 20610 if (env->log.level & BPF_LOG_STATS) { 20611 verbose(env, "verification time %lld usec\n", 20612 div_u64(env->verification_time, 1000)); 20613 verbose(env, "stack depth "); 20614 for (i = 0; i < env->subprog_cnt; i++) { 20615 u32 depth = env->subprog_info[i].stack_depth; 20616 20617 verbose(env, "%d", depth); 20618 if (i + 1 < env->subprog_cnt) 20619 verbose(env, "+"); 20620 } 20621 verbose(env, "\n"); 20622 } 20623 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 20624 "total_states %d peak_states %d mark_read %d\n", 20625 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 20626 env->max_states_per_insn, env->total_states, 20627 env->peak_states, env->longest_mark_read_walk); 20628 } 20629 20630 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 20631 { 20632 const struct btf_type *t, *func_proto; 20633 const struct bpf_struct_ops_desc *st_ops_desc; 20634 const struct bpf_struct_ops *st_ops; 20635 const struct btf_member *member; 20636 struct bpf_prog *prog = env->prog; 20637 u32 btf_id, member_idx; 20638 struct btf *btf; 20639 const char *mname; 20640 20641 if (!prog->gpl_compatible) { 20642 verbose(env, "struct ops programs must have a GPL compatible license\n"); 20643 return -EINVAL; 20644 } 20645 20646 if (!prog->aux->attach_btf_id) 20647 return -ENOTSUPP; 20648 20649 btf = prog->aux->attach_btf; 20650 if (btf_is_module(btf)) { 20651 /* Make sure st_ops is valid through the lifetime of env */ 20652 env->attach_btf_mod = btf_try_get_module(btf); 20653 if (!env->attach_btf_mod) { 20654 verbose(env, "struct_ops module %s is not found\n", 20655 btf_get_name(btf)); 20656 return -ENOTSUPP; 20657 } 20658 } 20659 20660 btf_id = prog->aux->attach_btf_id; 20661 st_ops_desc = bpf_struct_ops_find(btf, btf_id); 20662 if (!st_ops_desc) { 20663 verbose(env, "attach_btf_id %u is not a supported struct\n", 20664 btf_id); 20665 return -ENOTSUPP; 20666 } 20667 st_ops = st_ops_desc->st_ops; 20668 20669 t = st_ops_desc->type; 20670 member_idx = prog->expected_attach_type; 20671 if (member_idx >= btf_type_vlen(t)) { 20672 verbose(env, "attach to invalid member idx %u of struct %s\n", 20673 member_idx, st_ops->name); 20674 return -EINVAL; 20675 } 20676 20677 member = &btf_type_member(t)[member_idx]; 20678 mname = btf_name_by_offset(btf, member->name_off); 20679 func_proto = btf_type_resolve_func_ptr(btf, member->type, 20680 NULL); 20681 if (!func_proto) { 20682 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 20683 mname, member_idx, st_ops->name); 20684 return -EINVAL; 20685 } 20686 20687 if (st_ops->check_member) { 20688 int err = st_ops->check_member(t, member, prog); 20689 20690 if (err) { 20691 verbose(env, "attach to unsupported member %s of struct %s\n", 20692 mname, st_ops->name); 20693 return err; 20694 } 20695 } 20696 20697 /* btf_ctx_access() used this to provide argument type info */ 20698 prog->aux->ctx_arg_info = 20699 st_ops_desc->arg_info[member_idx].info; 20700 prog->aux->ctx_arg_info_size = 20701 st_ops_desc->arg_info[member_idx].cnt; 20702 20703 prog->aux->attach_func_proto = func_proto; 20704 prog->aux->attach_func_name = mname; 20705 env->ops = st_ops->verifier_ops; 20706 20707 return 0; 20708 } 20709 #define SECURITY_PREFIX "security_" 20710 20711 static int check_attach_modify_return(unsigned long addr, const char *func_name) 20712 { 20713 if (within_error_injection_list(addr) || 20714 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 20715 return 0; 20716 20717 return -EINVAL; 20718 } 20719 20720 /* list of non-sleepable functions that are otherwise on 20721 * ALLOW_ERROR_INJECTION list 20722 */ 20723 BTF_SET_START(btf_non_sleepable_error_inject) 20724 /* Three functions below can be called from sleepable and non-sleepable context. 20725 * Assume non-sleepable from bpf safety point of view. 20726 */ 20727 BTF_ID(func, __filemap_add_folio) 20728 BTF_ID(func, should_fail_alloc_page) 20729 BTF_ID(func, should_failslab) 20730 BTF_SET_END(btf_non_sleepable_error_inject) 20731 20732 static int check_non_sleepable_error_inject(u32 btf_id) 20733 { 20734 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 20735 } 20736 20737 int bpf_check_attach_target(struct bpf_verifier_log *log, 20738 const struct bpf_prog *prog, 20739 const struct bpf_prog *tgt_prog, 20740 u32 btf_id, 20741 struct bpf_attach_target_info *tgt_info) 20742 { 20743 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 20744 bool prog_tracing = prog->type == BPF_PROG_TYPE_TRACING; 20745 const char prefix[] = "btf_trace_"; 20746 int ret = 0, subprog = -1, i; 20747 const struct btf_type *t; 20748 bool conservative = true; 20749 const char *tname; 20750 struct btf *btf; 20751 long addr = 0; 20752 struct module *mod = NULL; 20753 20754 if (!btf_id) { 20755 bpf_log(log, "Tracing programs must provide btf_id\n"); 20756 return -EINVAL; 20757 } 20758 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 20759 if (!btf) { 20760 bpf_log(log, 20761 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 20762 return -EINVAL; 20763 } 20764 t = btf_type_by_id(btf, btf_id); 20765 if (!t) { 20766 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 20767 return -EINVAL; 20768 } 20769 tname = btf_name_by_offset(btf, t->name_off); 20770 if (!tname) { 20771 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 20772 return -EINVAL; 20773 } 20774 if (tgt_prog) { 20775 struct bpf_prog_aux *aux = tgt_prog->aux; 20776 20777 if (bpf_prog_is_dev_bound(prog->aux) && 20778 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 20779 bpf_log(log, "Target program bound device mismatch"); 20780 return -EINVAL; 20781 } 20782 20783 for (i = 0; i < aux->func_info_cnt; i++) 20784 if (aux->func_info[i].type_id == btf_id) { 20785 subprog = i; 20786 break; 20787 } 20788 if (subprog == -1) { 20789 bpf_log(log, "Subprog %s doesn't exist\n", tname); 20790 return -EINVAL; 20791 } 20792 if (aux->func && aux->func[subprog]->aux->exception_cb) { 20793 bpf_log(log, 20794 "%s programs cannot attach to exception callback\n", 20795 prog_extension ? "Extension" : "FENTRY/FEXIT"); 20796 return -EINVAL; 20797 } 20798 conservative = aux->func_info_aux[subprog].unreliable; 20799 if (prog_extension) { 20800 if (conservative) { 20801 bpf_log(log, 20802 "Cannot replace static functions\n"); 20803 return -EINVAL; 20804 } 20805 if (!prog->jit_requested) { 20806 bpf_log(log, 20807 "Extension programs should be JITed\n"); 20808 return -EINVAL; 20809 } 20810 } 20811 if (!tgt_prog->jited) { 20812 bpf_log(log, "Can attach to only JITed progs\n"); 20813 return -EINVAL; 20814 } 20815 if (prog_tracing) { 20816 if (aux->attach_tracing_prog) { 20817 /* 20818 * Target program is an fentry/fexit which is already attached 20819 * to another tracing program. More levels of nesting 20820 * attachment are not allowed. 20821 */ 20822 bpf_log(log, "Cannot nest tracing program attach more than once\n"); 20823 return -EINVAL; 20824 } 20825 } else if (tgt_prog->type == prog->type) { 20826 /* 20827 * To avoid potential call chain cycles, prevent attaching of a 20828 * program extension to another extension. It's ok to attach 20829 * fentry/fexit to extension program. 20830 */ 20831 bpf_log(log, "Cannot recursively attach\n"); 20832 return -EINVAL; 20833 } 20834 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 20835 prog_extension && 20836 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 20837 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 20838 /* Program extensions can extend all program types 20839 * except fentry/fexit. The reason is the following. 20840 * The fentry/fexit programs are used for performance 20841 * analysis, stats and can be attached to any program 20842 * type. When extension program is replacing XDP function 20843 * it is necessary to allow performance analysis of all 20844 * functions. Both original XDP program and its program 20845 * extension. Hence attaching fentry/fexit to 20846 * BPF_PROG_TYPE_EXT is allowed. If extending of 20847 * fentry/fexit was allowed it would be possible to create 20848 * long call chain fentry->extension->fentry->extension 20849 * beyond reasonable stack size. Hence extending fentry 20850 * is not allowed. 20851 */ 20852 bpf_log(log, "Cannot extend fentry/fexit\n"); 20853 return -EINVAL; 20854 } 20855 } else { 20856 if (prog_extension) { 20857 bpf_log(log, "Cannot replace kernel functions\n"); 20858 return -EINVAL; 20859 } 20860 } 20861 20862 switch (prog->expected_attach_type) { 20863 case BPF_TRACE_RAW_TP: 20864 if (tgt_prog) { 20865 bpf_log(log, 20866 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 20867 return -EINVAL; 20868 } 20869 if (!btf_type_is_typedef(t)) { 20870 bpf_log(log, "attach_btf_id %u is not a typedef\n", 20871 btf_id); 20872 return -EINVAL; 20873 } 20874 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 20875 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 20876 btf_id, tname); 20877 return -EINVAL; 20878 } 20879 tname += sizeof(prefix) - 1; 20880 t = btf_type_by_id(btf, t->type); 20881 if (!btf_type_is_ptr(t)) 20882 /* should never happen in valid vmlinux build */ 20883 return -EINVAL; 20884 t = btf_type_by_id(btf, t->type); 20885 if (!btf_type_is_func_proto(t)) 20886 /* should never happen in valid vmlinux build */ 20887 return -EINVAL; 20888 20889 break; 20890 case BPF_TRACE_ITER: 20891 if (!btf_type_is_func(t)) { 20892 bpf_log(log, "attach_btf_id %u is not a function\n", 20893 btf_id); 20894 return -EINVAL; 20895 } 20896 t = btf_type_by_id(btf, t->type); 20897 if (!btf_type_is_func_proto(t)) 20898 return -EINVAL; 20899 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20900 if (ret) 20901 return ret; 20902 break; 20903 default: 20904 if (!prog_extension) 20905 return -EINVAL; 20906 fallthrough; 20907 case BPF_MODIFY_RETURN: 20908 case BPF_LSM_MAC: 20909 case BPF_LSM_CGROUP: 20910 case BPF_TRACE_FENTRY: 20911 case BPF_TRACE_FEXIT: 20912 if (!btf_type_is_func(t)) { 20913 bpf_log(log, "attach_btf_id %u is not a function\n", 20914 btf_id); 20915 return -EINVAL; 20916 } 20917 if (prog_extension && 20918 btf_check_type_match(log, prog, btf, t)) 20919 return -EINVAL; 20920 t = btf_type_by_id(btf, t->type); 20921 if (!btf_type_is_func_proto(t)) 20922 return -EINVAL; 20923 20924 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 20925 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 20926 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 20927 return -EINVAL; 20928 20929 if (tgt_prog && conservative) 20930 t = NULL; 20931 20932 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 20933 if (ret < 0) 20934 return ret; 20935 20936 if (tgt_prog) { 20937 if (subprog == 0) 20938 addr = (long) tgt_prog->bpf_func; 20939 else 20940 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 20941 } else { 20942 if (btf_is_module(btf)) { 20943 mod = btf_try_get_module(btf); 20944 if (mod) 20945 addr = find_kallsyms_symbol_value(mod, tname); 20946 else 20947 addr = 0; 20948 } else { 20949 addr = kallsyms_lookup_name(tname); 20950 } 20951 if (!addr) { 20952 module_put(mod); 20953 bpf_log(log, 20954 "The address of function %s cannot be found\n", 20955 tname); 20956 return -ENOENT; 20957 } 20958 } 20959 20960 if (prog->sleepable) { 20961 ret = -EINVAL; 20962 switch (prog->type) { 20963 case BPF_PROG_TYPE_TRACING: 20964 20965 /* fentry/fexit/fmod_ret progs can be sleepable if they are 20966 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 20967 */ 20968 if (!check_non_sleepable_error_inject(btf_id) && 20969 within_error_injection_list(addr)) 20970 ret = 0; 20971 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 20972 * in the fmodret id set with the KF_SLEEPABLE flag. 20973 */ 20974 else { 20975 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id, 20976 prog); 20977 20978 if (flags && (*flags & KF_SLEEPABLE)) 20979 ret = 0; 20980 } 20981 break; 20982 case BPF_PROG_TYPE_LSM: 20983 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 20984 * Only some of them are sleepable. 20985 */ 20986 if (bpf_lsm_is_sleepable_hook(btf_id)) 20987 ret = 0; 20988 break; 20989 default: 20990 break; 20991 } 20992 if (ret) { 20993 module_put(mod); 20994 bpf_log(log, "%s is not sleepable\n", tname); 20995 return ret; 20996 } 20997 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 20998 if (tgt_prog) { 20999 module_put(mod); 21000 bpf_log(log, "can't modify return codes of BPF programs\n"); 21001 return -EINVAL; 21002 } 21003 ret = -EINVAL; 21004 if (btf_kfunc_is_modify_return(btf, btf_id, prog) || 21005 !check_attach_modify_return(addr, tname)) 21006 ret = 0; 21007 if (ret) { 21008 module_put(mod); 21009 bpf_log(log, "%s() is not modifiable\n", tname); 21010 return ret; 21011 } 21012 } 21013 21014 break; 21015 } 21016 tgt_info->tgt_addr = addr; 21017 tgt_info->tgt_name = tname; 21018 tgt_info->tgt_type = t; 21019 tgt_info->tgt_mod = mod; 21020 return 0; 21021 } 21022 21023 BTF_SET_START(btf_id_deny) 21024 BTF_ID_UNUSED 21025 #ifdef CONFIG_SMP 21026 BTF_ID(func, migrate_disable) 21027 BTF_ID(func, migrate_enable) 21028 #endif 21029 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 21030 BTF_ID(func, rcu_read_unlock_strict) 21031 #endif 21032 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 21033 BTF_ID(func, preempt_count_add) 21034 BTF_ID(func, preempt_count_sub) 21035 #endif 21036 #ifdef CONFIG_PREEMPT_RCU 21037 BTF_ID(func, __rcu_read_lock) 21038 BTF_ID(func, __rcu_read_unlock) 21039 #endif 21040 BTF_SET_END(btf_id_deny) 21041 21042 static bool can_be_sleepable(struct bpf_prog *prog) 21043 { 21044 if (prog->type == BPF_PROG_TYPE_TRACING) { 21045 switch (prog->expected_attach_type) { 21046 case BPF_TRACE_FENTRY: 21047 case BPF_TRACE_FEXIT: 21048 case BPF_MODIFY_RETURN: 21049 case BPF_TRACE_ITER: 21050 return true; 21051 default: 21052 return false; 21053 } 21054 } 21055 return prog->type == BPF_PROG_TYPE_LSM || 21056 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 21057 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 21058 } 21059 21060 static int check_attach_btf_id(struct bpf_verifier_env *env) 21061 { 21062 struct bpf_prog *prog = env->prog; 21063 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 21064 struct bpf_attach_target_info tgt_info = {}; 21065 u32 btf_id = prog->aux->attach_btf_id; 21066 struct bpf_trampoline *tr; 21067 int ret; 21068 u64 key; 21069 21070 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 21071 if (prog->sleepable) 21072 /* attach_btf_id checked to be zero already */ 21073 return 0; 21074 verbose(env, "Syscall programs can only be sleepable\n"); 21075 return -EINVAL; 21076 } 21077 21078 if (prog->sleepable && !can_be_sleepable(prog)) { 21079 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 21080 return -EINVAL; 21081 } 21082 21083 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 21084 return check_struct_ops_btf_id(env); 21085 21086 if (prog->type != BPF_PROG_TYPE_TRACING && 21087 prog->type != BPF_PROG_TYPE_LSM && 21088 prog->type != BPF_PROG_TYPE_EXT) 21089 return 0; 21090 21091 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 21092 if (ret) 21093 return ret; 21094 21095 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 21096 /* to make freplace equivalent to their targets, they need to 21097 * inherit env->ops and expected_attach_type for the rest of the 21098 * verification 21099 */ 21100 env->ops = bpf_verifier_ops[tgt_prog->type]; 21101 prog->expected_attach_type = tgt_prog->expected_attach_type; 21102 } 21103 21104 /* store info about the attachment target that will be used later */ 21105 prog->aux->attach_func_proto = tgt_info.tgt_type; 21106 prog->aux->attach_func_name = tgt_info.tgt_name; 21107 prog->aux->mod = tgt_info.tgt_mod; 21108 21109 if (tgt_prog) { 21110 prog->aux->saved_dst_prog_type = tgt_prog->type; 21111 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 21112 } 21113 21114 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 21115 prog->aux->attach_btf_trace = true; 21116 return 0; 21117 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 21118 if (!bpf_iter_prog_supported(prog)) 21119 return -EINVAL; 21120 return 0; 21121 } 21122 21123 if (prog->type == BPF_PROG_TYPE_LSM) { 21124 ret = bpf_lsm_verify_prog(&env->log, prog); 21125 if (ret < 0) 21126 return ret; 21127 } else if (prog->type == BPF_PROG_TYPE_TRACING && 21128 btf_id_set_contains(&btf_id_deny, btf_id)) { 21129 return -EINVAL; 21130 } 21131 21132 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 21133 tr = bpf_trampoline_get(key, &tgt_info); 21134 if (!tr) 21135 return -ENOMEM; 21136 21137 if (tgt_prog && tgt_prog->aux->tail_call_reachable) 21138 tr->flags = BPF_TRAMP_F_TAIL_CALL_CTX; 21139 21140 prog->aux->dst_trampoline = tr; 21141 return 0; 21142 } 21143 21144 struct btf *bpf_get_btf_vmlinux(void) 21145 { 21146 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 21147 mutex_lock(&bpf_verifier_lock); 21148 if (!btf_vmlinux) 21149 btf_vmlinux = btf_parse_vmlinux(); 21150 mutex_unlock(&bpf_verifier_lock); 21151 } 21152 return btf_vmlinux; 21153 } 21154 21155 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 21156 { 21157 u64 start_time = ktime_get_ns(); 21158 struct bpf_verifier_env *env; 21159 int i, len, ret = -EINVAL, err; 21160 u32 log_true_size; 21161 bool is_priv; 21162 21163 /* no program is valid */ 21164 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 21165 return -EINVAL; 21166 21167 /* 'struct bpf_verifier_env' can be global, but since it's not small, 21168 * allocate/free it every time bpf_check() is called 21169 */ 21170 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 21171 if (!env) 21172 return -ENOMEM; 21173 21174 env->bt.env = env; 21175 21176 len = (*prog)->len; 21177 env->insn_aux_data = 21178 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 21179 ret = -ENOMEM; 21180 if (!env->insn_aux_data) 21181 goto err_free_env; 21182 for (i = 0; i < len; i++) 21183 env->insn_aux_data[i].orig_idx = i; 21184 env->prog = *prog; 21185 env->ops = bpf_verifier_ops[env->prog->type]; 21186 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 21187 21188 env->allow_ptr_leaks = bpf_allow_ptr_leaks(env->prog->aux->token); 21189 env->allow_uninit_stack = bpf_allow_uninit_stack(env->prog->aux->token); 21190 env->bypass_spec_v1 = bpf_bypass_spec_v1(env->prog->aux->token); 21191 env->bypass_spec_v4 = bpf_bypass_spec_v4(env->prog->aux->token); 21192 env->bpf_capable = is_priv = bpf_token_capable(env->prog->aux->token, CAP_BPF); 21193 21194 bpf_get_btf_vmlinux(); 21195 21196 /* grab the mutex to protect few globals used by verifier */ 21197 if (!is_priv) 21198 mutex_lock(&bpf_verifier_lock); 21199 21200 /* user could have requested verbose verifier output 21201 * and supplied buffer to store the verification trace 21202 */ 21203 ret = bpf_vlog_init(&env->log, attr->log_level, 21204 (char __user *) (unsigned long) attr->log_buf, 21205 attr->log_size); 21206 if (ret) 21207 goto err_unlock; 21208 21209 mark_verifier_state_clean(env); 21210 21211 if (IS_ERR(btf_vmlinux)) { 21212 /* Either gcc or pahole or kernel are broken. */ 21213 verbose(env, "in-kernel BTF is malformed\n"); 21214 ret = PTR_ERR(btf_vmlinux); 21215 goto skip_full_check; 21216 } 21217 21218 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 21219 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 21220 env->strict_alignment = true; 21221 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 21222 env->strict_alignment = false; 21223 21224 if (is_priv) 21225 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 21226 env->test_reg_invariants = attr->prog_flags & BPF_F_TEST_REG_INVARIANTS; 21227 21228 env->explored_states = kvcalloc(state_htab_size(env), 21229 sizeof(struct bpf_verifier_state_list *), 21230 GFP_USER); 21231 ret = -ENOMEM; 21232 if (!env->explored_states) 21233 goto skip_full_check; 21234 21235 ret = check_btf_info_early(env, attr, uattr); 21236 if (ret < 0) 21237 goto skip_full_check; 21238 21239 ret = add_subprog_and_kfunc(env); 21240 if (ret < 0) 21241 goto skip_full_check; 21242 21243 ret = check_subprogs(env); 21244 if (ret < 0) 21245 goto skip_full_check; 21246 21247 ret = check_btf_info(env, attr, uattr); 21248 if (ret < 0) 21249 goto skip_full_check; 21250 21251 ret = check_attach_btf_id(env); 21252 if (ret) 21253 goto skip_full_check; 21254 21255 ret = resolve_pseudo_ldimm64(env); 21256 if (ret < 0) 21257 goto skip_full_check; 21258 21259 if (bpf_prog_is_offloaded(env->prog->aux)) { 21260 ret = bpf_prog_offload_verifier_prep(env->prog); 21261 if (ret) 21262 goto skip_full_check; 21263 } 21264 21265 ret = check_cfg(env); 21266 if (ret < 0) 21267 goto skip_full_check; 21268 21269 ret = do_check_main(env); 21270 ret = ret ?: do_check_subprogs(env); 21271 21272 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 21273 ret = bpf_prog_offload_finalize(env); 21274 21275 skip_full_check: 21276 kvfree(env->explored_states); 21277 21278 if (ret == 0) 21279 ret = check_max_stack_depth(env); 21280 21281 /* instruction rewrites happen after this point */ 21282 if (ret == 0) 21283 ret = optimize_bpf_loop(env); 21284 21285 if (is_priv) { 21286 if (ret == 0) 21287 opt_hard_wire_dead_code_branches(env); 21288 if (ret == 0) 21289 ret = opt_remove_dead_code(env); 21290 if (ret == 0) 21291 ret = opt_remove_nops(env); 21292 } else { 21293 if (ret == 0) 21294 sanitize_dead_code(env); 21295 } 21296 21297 if (ret == 0) 21298 /* program is valid, convert *(u32*)(ctx + off) accesses */ 21299 ret = convert_ctx_accesses(env); 21300 21301 if (ret == 0) 21302 ret = do_misc_fixups(env); 21303 21304 /* do 32-bit optimization after insn patching has done so those patched 21305 * insns could be handled correctly. 21306 */ 21307 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 21308 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 21309 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 21310 : false; 21311 } 21312 21313 if (ret == 0) 21314 ret = fixup_call_args(env); 21315 21316 env->verification_time = ktime_get_ns() - start_time; 21317 print_verification_stats(env); 21318 env->prog->aux->verified_insns = env->insn_processed; 21319 21320 /* preserve original error even if log finalization is successful */ 21321 err = bpf_vlog_finalize(&env->log, &log_true_size); 21322 if (err) 21323 ret = err; 21324 21325 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 21326 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 21327 &log_true_size, sizeof(log_true_size))) { 21328 ret = -EFAULT; 21329 goto err_release_maps; 21330 } 21331 21332 if (ret) 21333 goto err_release_maps; 21334 21335 if (env->used_map_cnt) { 21336 /* if program passed verifier, update used_maps in bpf_prog_info */ 21337 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 21338 sizeof(env->used_maps[0]), 21339 GFP_KERNEL); 21340 21341 if (!env->prog->aux->used_maps) { 21342 ret = -ENOMEM; 21343 goto err_release_maps; 21344 } 21345 21346 memcpy(env->prog->aux->used_maps, env->used_maps, 21347 sizeof(env->used_maps[0]) * env->used_map_cnt); 21348 env->prog->aux->used_map_cnt = env->used_map_cnt; 21349 } 21350 if (env->used_btf_cnt) { 21351 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 21352 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 21353 sizeof(env->used_btfs[0]), 21354 GFP_KERNEL); 21355 if (!env->prog->aux->used_btfs) { 21356 ret = -ENOMEM; 21357 goto err_release_maps; 21358 } 21359 21360 memcpy(env->prog->aux->used_btfs, env->used_btfs, 21361 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 21362 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 21363 } 21364 if (env->used_map_cnt || env->used_btf_cnt) { 21365 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 21366 * bpf_ld_imm64 instructions 21367 */ 21368 convert_pseudo_ld_imm64(env); 21369 } 21370 21371 adjust_btf_func(env); 21372 21373 err_release_maps: 21374 if (!env->prog->aux->used_maps) 21375 /* if we didn't copy map pointers into bpf_prog_info, release 21376 * them now. Otherwise free_used_maps() will release them. 21377 */ 21378 release_maps(env); 21379 if (!env->prog->aux->used_btfs) 21380 release_btfs(env); 21381 21382 /* extension progs temporarily inherit the attach_type of their targets 21383 for verification purposes, so set it back to zero before returning 21384 */ 21385 if (env->prog->type == BPF_PROG_TYPE_EXT) 21386 env->prog->expected_attach_type = 0; 21387 21388 *prog = env->prog; 21389 21390 module_put(env->attach_btf_mod); 21391 err_unlock: 21392 if (!is_priv) 21393 mutex_unlock(&bpf_verifier_lock); 21394 vfree(env->insn_aux_data); 21395 err_free_env: 21396 kfree(env); 21397 return ret; 21398 } 21399