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 29 #include "disasm.h" 30 31 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 32 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 33 [_id] = & _name ## _verifier_ops, 34 #define BPF_MAP_TYPE(_id, _ops) 35 #define BPF_LINK_TYPE(_id, _name) 36 #include <linux/bpf_types.h> 37 #undef BPF_PROG_TYPE 38 #undef BPF_MAP_TYPE 39 #undef BPF_LINK_TYPE 40 }; 41 42 /* bpf_check() is a static code analyzer that walks eBPF program 43 * instruction by instruction and updates register/stack state. 44 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 45 * 46 * The first pass is depth-first-search to check that the program is a DAG. 47 * It rejects the following programs: 48 * - larger than BPF_MAXINSNS insns 49 * - if loop is present (detected via back-edge) 50 * - unreachable insns exist (shouldn't be a forest. program = one function) 51 * - out of bounds or malformed jumps 52 * The second pass is all possible path descent from the 1st insn. 53 * Since it's analyzing all paths through the program, the length of the 54 * analysis is limited to 64k insn, which may be hit even if total number of 55 * insn is less then 4K, but there are too many branches that change stack/regs. 56 * Number of 'branches to be analyzed' is limited to 1k 57 * 58 * On entry to each instruction, each register has a type, and the instruction 59 * changes the types of the registers depending on instruction semantics. 60 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 61 * copied to R1. 62 * 63 * All registers are 64-bit. 64 * R0 - return register 65 * R1-R5 argument passing registers 66 * R6-R9 callee saved registers 67 * R10 - frame pointer read-only 68 * 69 * At the start of BPF program the register R1 contains a pointer to bpf_context 70 * and has type PTR_TO_CTX. 71 * 72 * Verifier tracks arithmetic operations on pointers in case: 73 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 74 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 75 * 1st insn copies R10 (which has FRAME_PTR) type into R1 76 * and 2nd arithmetic instruction is pattern matched to recognize 77 * that it wants to construct a pointer to some element within stack. 78 * So after 2nd insn, the register R1 has type PTR_TO_STACK 79 * (and -20 constant is saved for further stack bounds checking). 80 * Meaning that this reg is a pointer to stack plus known immediate constant. 81 * 82 * Most of the time the registers have SCALAR_VALUE type, which 83 * means the register has some value, but it's not a valid pointer. 84 * (like pointer plus pointer becomes SCALAR_VALUE type) 85 * 86 * When verifier sees load or store instructions the type of base register 87 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 88 * four pointer types recognized by check_mem_access() function. 89 * 90 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 91 * and the range of [ptr, ptr + map's value_size) is accessible. 92 * 93 * registers used to pass values to function calls are checked against 94 * function argument constraints. 95 * 96 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 97 * It means that the register type passed to this function must be 98 * PTR_TO_STACK and it will be used inside the function as 99 * 'pointer to map element key' 100 * 101 * For example the argument constraints for bpf_map_lookup_elem(): 102 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 103 * .arg1_type = ARG_CONST_MAP_PTR, 104 * .arg2_type = ARG_PTR_TO_MAP_KEY, 105 * 106 * ret_type says that this function returns 'pointer to map elem value or null' 107 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 108 * 2nd argument should be a pointer to stack, which will be used inside 109 * the helper function as a pointer to map element key. 110 * 111 * On the kernel side the helper function looks like: 112 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 113 * { 114 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 115 * void *key = (void *) (unsigned long) r2; 116 * void *value; 117 * 118 * here kernel can access 'key' and 'map' pointers safely, knowing that 119 * [key, key + map->key_size) bytes are valid and were initialized on 120 * the stack of eBPF program. 121 * } 122 * 123 * Corresponding eBPF program may look like: 124 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 125 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 126 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 127 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 128 * here verifier looks at prototype of map_lookup_elem() and sees: 129 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 130 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 131 * 132 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 133 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 134 * and were initialized prior to this call. 135 * If it's ok, then verifier allows this BPF_CALL insn and looks at 136 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 137 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 138 * returns either pointer to map value or NULL. 139 * 140 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 141 * insn, the register holding that pointer in the true branch changes state to 142 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 143 * branch. See check_cond_jmp_op(). 144 * 145 * After the call R0 is set to return type of the function and registers R1-R5 146 * are set to NOT_INIT to indicate that they are no longer readable. 147 * 148 * The following reference types represent a potential reference to a kernel 149 * resource which, after first being allocated, must be checked and freed by 150 * the BPF program: 151 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 152 * 153 * When the verifier sees a helper call return a reference type, it allocates a 154 * pointer id for the reference and stores it in the current function state. 155 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 156 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 157 * passes through a NULL-check conditional. For the branch wherein the state is 158 * changed to CONST_IMM, the verifier releases the reference. 159 * 160 * For each helper function that allocates a reference, such as 161 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 162 * bpf_sk_release(). When a reference type passes into the release function, 163 * the verifier also releases the reference. If any unchecked or unreleased 164 * reference remains at the end of the program, the verifier rejects it. 165 */ 166 167 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 168 struct bpf_verifier_stack_elem { 169 /* verifer state is 'st' 170 * before processing instruction 'insn_idx' 171 * and after processing instruction 'prev_insn_idx' 172 */ 173 struct bpf_verifier_state st; 174 int insn_idx; 175 int prev_insn_idx; 176 struct bpf_verifier_stack_elem *next; 177 /* length of verifier log at the time this state was pushed on stack */ 178 u32 log_pos; 179 }; 180 181 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 182 #define BPF_COMPLEXITY_LIMIT_STATES 64 183 184 #define BPF_MAP_KEY_POISON (1ULL << 63) 185 #define BPF_MAP_KEY_SEEN (1ULL << 62) 186 187 #define BPF_MAP_PTR_UNPRIV 1UL 188 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 189 POISON_POINTER_DELTA)) 190 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 191 192 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 193 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 194 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 195 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 196 static int ref_set_non_owning(struct bpf_verifier_env *env, 197 struct bpf_reg_state *reg); 198 static void specialize_kfunc(struct bpf_verifier_env *env, 199 u32 func_id, u16 offset, unsigned long *addr); 200 201 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 202 { 203 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 204 } 205 206 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 207 { 208 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 209 } 210 211 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 212 const struct bpf_map *map, bool unpriv) 213 { 214 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 215 unpriv |= bpf_map_ptr_unpriv(aux); 216 aux->map_ptr_state = (unsigned long)map | 217 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 218 } 219 220 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 221 { 222 return aux->map_key_state & BPF_MAP_KEY_POISON; 223 } 224 225 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 226 { 227 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 228 } 229 230 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 231 { 232 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 233 } 234 235 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 236 { 237 bool poisoned = bpf_map_key_poisoned(aux); 238 239 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 240 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 241 } 242 243 static bool bpf_pseudo_call(const struct bpf_insn *insn) 244 { 245 return insn->code == (BPF_JMP | BPF_CALL) && 246 insn->src_reg == BPF_PSEUDO_CALL; 247 } 248 249 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 250 { 251 return insn->code == (BPF_JMP | BPF_CALL) && 252 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 253 } 254 255 struct bpf_call_arg_meta { 256 struct bpf_map *map_ptr; 257 bool raw_mode; 258 bool pkt_access; 259 u8 release_regno; 260 int regno; 261 int access_size; 262 int mem_size; 263 u64 msize_max_value; 264 int ref_obj_id; 265 int dynptr_id; 266 int map_uid; 267 int func_id; 268 struct btf *btf; 269 u32 btf_id; 270 struct btf *ret_btf; 271 u32 ret_btf_id; 272 u32 subprogno; 273 struct btf_field *kptr_field; 274 }; 275 276 struct btf_and_id { 277 struct btf *btf; 278 u32 btf_id; 279 }; 280 281 struct bpf_kfunc_call_arg_meta { 282 /* In parameters */ 283 struct btf *btf; 284 u32 func_id; 285 u32 kfunc_flags; 286 const struct btf_type *func_proto; 287 const char *func_name; 288 /* Out parameters */ 289 u32 ref_obj_id; 290 u8 release_regno; 291 bool r0_rdonly; 292 u32 ret_btf_id; 293 u64 r0_size; 294 u32 subprogno; 295 struct { 296 u64 value; 297 bool found; 298 } arg_constant; 299 union { 300 struct btf_and_id arg_obj_drop; 301 struct btf_and_id arg_refcount_acquire; 302 }; 303 struct { 304 struct btf_field *field; 305 } arg_list_head; 306 struct { 307 struct btf_field *field; 308 } arg_rbtree_root; 309 struct { 310 enum bpf_dynptr_type type; 311 u32 id; 312 u32 ref_obj_id; 313 } initialized_dynptr; 314 struct { 315 u8 spi; 316 u8 frameno; 317 } iter; 318 u64 mem_size; 319 }; 320 321 struct btf *btf_vmlinux; 322 323 static DEFINE_MUTEX(bpf_verifier_lock); 324 325 static const struct bpf_line_info * 326 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 327 { 328 const struct bpf_line_info *linfo; 329 const struct bpf_prog *prog; 330 u32 i, nr_linfo; 331 332 prog = env->prog; 333 nr_linfo = prog->aux->nr_linfo; 334 335 if (!nr_linfo || insn_off >= prog->len) 336 return NULL; 337 338 linfo = prog->aux->linfo; 339 for (i = 1; i < nr_linfo; i++) 340 if (insn_off < linfo[i].insn_off) 341 break; 342 343 return &linfo[i - 1]; 344 } 345 346 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 347 { 348 struct bpf_verifier_env *env = private_data; 349 va_list args; 350 351 if (!bpf_verifier_log_needed(&env->log)) 352 return; 353 354 va_start(args, fmt); 355 bpf_verifier_vlog(&env->log, fmt, args); 356 va_end(args); 357 } 358 359 static const char *ltrim(const char *s) 360 { 361 while (isspace(*s)) 362 s++; 363 364 return s; 365 } 366 367 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 368 u32 insn_off, 369 const char *prefix_fmt, ...) 370 { 371 const struct bpf_line_info *linfo; 372 373 if (!bpf_verifier_log_needed(&env->log)) 374 return; 375 376 linfo = find_linfo(env, insn_off); 377 if (!linfo || linfo == env->prev_linfo) 378 return; 379 380 if (prefix_fmt) { 381 va_list args; 382 383 va_start(args, prefix_fmt); 384 bpf_verifier_vlog(&env->log, prefix_fmt, args); 385 va_end(args); 386 } 387 388 verbose(env, "%s\n", 389 ltrim(btf_name_by_offset(env->prog->aux->btf, 390 linfo->line_off))); 391 392 env->prev_linfo = linfo; 393 } 394 395 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 396 struct bpf_reg_state *reg, 397 struct tnum *range, const char *ctx, 398 const char *reg_name) 399 { 400 char tn_buf[48]; 401 402 verbose(env, "At %s the register %s ", ctx, reg_name); 403 if (!tnum_is_unknown(reg->var_off)) { 404 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 405 verbose(env, "has value %s", tn_buf); 406 } else { 407 verbose(env, "has unknown scalar value"); 408 } 409 tnum_strn(tn_buf, sizeof(tn_buf), *range); 410 verbose(env, " should have been in %s\n", tn_buf); 411 } 412 413 static bool type_is_pkt_pointer(enum bpf_reg_type type) 414 { 415 type = base_type(type); 416 return type == PTR_TO_PACKET || 417 type == PTR_TO_PACKET_META; 418 } 419 420 static bool type_is_sk_pointer(enum bpf_reg_type type) 421 { 422 return type == PTR_TO_SOCKET || 423 type == PTR_TO_SOCK_COMMON || 424 type == PTR_TO_TCP_SOCK || 425 type == PTR_TO_XDP_SOCK; 426 } 427 428 static bool type_may_be_null(u32 type) 429 { 430 return type & PTR_MAYBE_NULL; 431 } 432 433 static bool reg_type_not_null(enum bpf_reg_type type) 434 { 435 if (type_may_be_null(type)) 436 return false; 437 438 type = base_type(type); 439 return type == PTR_TO_SOCKET || 440 type == PTR_TO_TCP_SOCK || 441 type == PTR_TO_MAP_VALUE || 442 type == PTR_TO_MAP_KEY || 443 type == PTR_TO_SOCK_COMMON || 444 type == PTR_TO_MEM; 445 } 446 447 static bool type_is_ptr_alloc_obj(u32 type) 448 { 449 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 450 } 451 452 static bool type_is_non_owning_ref(u32 type) 453 { 454 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF; 455 } 456 457 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 458 { 459 struct btf_record *rec = NULL; 460 struct btf_struct_meta *meta; 461 462 if (reg->type == PTR_TO_MAP_VALUE) { 463 rec = reg->map_ptr->record; 464 } else if (type_is_ptr_alloc_obj(reg->type)) { 465 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 466 if (meta) 467 rec = meta->record; 468 } 469 return rec; 470 } 471 472 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 473 { 474 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 475 } 476 477 static bool type_is_rdonly_mem(u32 type) 478 { 479 return type & MEM_RDONLY; 480 } 481 482 static bool is_acquire_function(enum bpf_func_id func_id, 483 const struct bpf_map *map) 484 { 485 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 486 487 if (func_id == BPF_FUNC_sk_lookup_tcp || 488 func_id == BPF_FUNC_sk_lookup_udp || 489 func_id == BPF_FUNC_skc_lookup_tcp || 490 func_id == BPF_FUNC_ringbuf_reserve || 491 func_id == BPF_FUNC_kptr_xchg) 492 return true; 493 494 if (func_id == BPF_FUNC_map_lookup_elem && 495 (map_type == BPF_MAP_TYPE_SOCKMAP || 496 map_type == BPF_MAP_TYPE_SOCKHASH)) 497 return true; 498 499 return false; 500 } 501 502 static bool is_ptr_cast_function(enum bpf_func_id func_id) 503 { 504 return func_id == BPF_FUNC_tcp_sock || 505 func_id == BPF_FUNC_sk_fullsock || 506 func_id == BPF_FUNC_skc_to_tcp_sock || 507 func_id == BPF_FUNC_skc_to_tcp6_sock || 508 func_id == BPF_FUNC_skc_to_udp6_sock || 509 func_id == BPF_FUNC_skc_to_mptcp_sock || 510 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 511 func_id == BPF_FUNC_skc_to_tcp_request_sock; 512 } 513 514 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 515 { 516 return func_id == BPF_FUNC_dynptr_data; 517 } 518 519 static bool is_callback_calling_function(enum bpf_func_id func_id) 520 { 521 return func_id == BPF_FUNC_for_each_map_elem || 522 func_id == BPF_FUNC_timer_set_callback || 523 func_id == BPF_FUNC_find_vma || 524 func_id == BPF_FUNC_loop || 525 func_id == BPF_FUNC_user_ringbuf_drain; 526 } 527 528 static bool is_storage_get_function(enum bpf_func_id func_id) 529 { 530 return func_id == BPF_FUNC_sk_storage_get || 531 func_id == BPF_FUNC_inode_storage_get || 532 func_id == BPF_FUNC_task_storage_get || 533 func_id == BPF_FUNC_cgrp_storage_get; 534 } 535 536 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 537 const struct bpf_map *map) 538 { 539 int ref_obj_uses = 0; 540 541 if (is_ptr_cast_function(func_id)) 542 ref_obj_uses++; 543 if (is_acquire_function(func_id, map)) 544 ref_obj_uses++; 545 if (is_dynptr_ref_function(func_id)) 546 ref_obj_uses++; 547 548 return ref_obj_uses > 1; 549 } 550 551 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 552 { 553 return BPF_CLASS(insn->code) == BPF_STX && 554 BPF_MODE(insn->code) == BPF_ATOMIC && 555 insn->imm == BPF_CMPXCHG; 556 } 557 558 /* string representation of 'enum bpf_reg_type' 559 * 560 * Note that reg_type_str() can not appear more than once in a single verbose() 561 * statement. 562 */ 563 static const char *reg_type_str(struct bpf_verifier_env *env, 564 enum bpf_reg_type type) 565 { 566 char postfix[16] = {0}, prefix[64] = {0}; 567 static const char * const str[] = { 568 [NOT_INIT] = "?", 569 [SCALAR_VALUE] = "scalar", 570 [PTR_TO_CTX] = "ctx", 571 [CONST_PTR_TO_MAP] = "map_ptr", 572 [PTR_TO_MAP_VALUE] = "map_value", 573 [PTR_TO_STACK] = "fp", 574 [PTR_TO_PACKET] = "pkt", 575 [PTR_TO_PACKET_META] = "pkt_meta", 576 [PTR_TO_PACKET_END] = "pkt_end", 577 [PTR_TO_FLOW_KEYS] = "flow_keys", 578 [PTR_TO_SOCKET] = "sock", 579 [PTR_TO_SOCK_COMMON] = "sock_common", 580 [PTR_TO_TCP_SOCK] = "tcp_sock", 581 [PTR_TO_TP_BUFFER] = "tp_buffer", 582 [PTR_TO_XDP_SOCK] = "xdp_sock", 583 [PTR_TO_BTF_ID] = "ptr_", 584 [PTR_TO_MEM] = "mem", 585 [PTR_TO_BUF] = "buf", 586 [PTR_TO_FUNC] = "func", 587 [PTR_TO_MAP_KEY] = "map_key", 588 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 589 }; 590 591 if (type & PTR_MAYBE_NULL) { 592 if (base_type(type) == PTR_TO_BTF_ID) 593 strncpy(postfix, "or_null_", 16); 594 else 595 strncpy(postfix, "_or_null", 16); 596 } 597 598 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 599 type & MEM_RDONLY ? "rdonly_" : "", 600 type & MEM_RINGBUF ? "ringbuf_" : "", 601 type & MEM_USER ? "user_" : "", 602 type & MEM_PERCPU ? "percpu_" : "", 603 type & MEM_RCU ? "rcu_" : "", 604 type & PTR_UNTRUSTED ? "untrusted_" : "", 605 type & PTR_TRUSTED ? "trusted_" : "" 606 ); 607 608 snprintf(env->tmp_str_buf, TMP_STR_BUF_LEN, "%s%s%s", 609 prefix, str[base_type(type)], postfix); 610 return env->tmp_str_buf; 611 } 612 613 static char slot_type_char[] = { 614 [STACK_INVALID] = '?', 615 [STACK_SPILL] = 'r', 616 [STACK_MISC] = 'm', 617 [STACK_ZERO] = '0', 618 [STACK_DYNPTR] = 'd', 619 [STACK_ITER] = 'i', 620 }; 621 622 static void print_liveness(struct bpf_verifier_env *env, 623 enum bpf_reg_liveness live) 624 { 625 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 626 verbose(env, "_"); 627 if (live & REG_LIVE_READ) 628 verbose(env, "r"); 629 if (live & REG_LIVE_WRITTEN) 630 verbose(env, "w"); 631 if (live & REG_LIVE_DONE) 632 verbose(env, "D"); 633 } 634 635 static int __get_spi(s32 off) 636 { 637 return (-off - 1) / BPF_REG_SIZE; 638 } 639 640 static struct bpf_func_state *func(struct bpf_verifier_env *env, 641 const struct bpf_reg_state *reg) 642 { 643 struct bpf_verifier_state *cur = env->cur_state; 644 645 return cur->frame[reg->frameno]; 646 } 647 648 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 649 { 650 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 651 652 /* We need to check that slots between [spi - nr_slots + 1, spi] are 653 * within [0, allocated_stack). 654 * 655 * Please note that the spi grows downwards. For example, a dynptr 656 * takes the size of two stack slots; the first slot will be at 657 * spi and the second slot will be at spi - 1. 658 */ 659 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 660 } 661 662 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 663 const char *obj_kind, int nr_slots) 664 { 665 int off, spi; 666 667 if (!tnum_is_const(reg->var_off)) { 668 verbose(env, "%s has to be at a constant offset\n", obj_kind); 669 return -EINVAL; 670 } 671 672 off = reg->off + reg->var_off.value; 673 if (off % BPF_REG_SIZE) { 674 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 675 return -EINVAL; 676 } 677 678 spi = __get_spi(off); 679 if (spi + 1 < nr_slots) { 680 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 681 return -EINVAL; 682 } 683 684 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 685 return -ERANGE; 686 return spi; 687 } 688 689 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 690 { 691 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 692 } 693 694 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 695 { 696 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 697 } 698 699 static const char *btf_type_name(const struct btf *btf, u32 id) 700 { 701 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 702 } 703 704 static const char *dynptr_type_str(enum bpf_dynptr_type type) 705 { 706 switch (type) { 707 case BPF_DYNPTR_TYPE_LOCAL: 708 return "local"; 709 case BPF_DYNPTR_TYPE_RINGBUF: 710 return "ringbuf"; 711 case BPF_DYNPTR_TYPE_SKB: 712 return "skb"; 713 case BPF_DYNPTR_TYPE_XDP: 714 return "xdp"; 715 case BPF_DYNPTR_TYPE_INVALID: 716 return "<invalid>"; 717 default: 718 WARN_ONCE(1, "unknown dynptr type %d\n", type); 719 return "<unknown>"; 720 } 721 } 722 723 static const char *iter_type_str(const struct btf *btf, u32 btf_id) 724 { 725 if (!btf || btf_id == 0) 726 return "<invalid>"; 727 728 /* we already validated that type is valid and has conforming name */ 729 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1; 730 } 731 732 static const char *iter_state_str(enum bpf_iter_state state) 733 { 734 switch (state) { 735 case BPF_ITER_STATE_ACTIVE: 736 return "active"; 737 case BPF_ITER_STATE_DRAINED: 738 return "drained"; 739 case BPF_ITER_STATE_INVALID: 740 return "<invalid>"; 741 default: 742 WARN_ONCE(1, "unknown iter state %d\n", state); 743 return "<unknown>"; 744 } 745 } 746 747 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 748 { 749 env->scratched_regs |= 1U << regno; 750 } 751 752 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 753 { 754 env->scratched_stack_slots |= 1ULL << spi; 755 } 756 757 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 758 { 759 return (env->scratched_regs >> regno) & 1; 760 } 761 762 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 763 { 764 return (env->scratched_stack_slots >> regno) & 1; 765 } 766 767 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 768 { 769 return env->scratched_regs || env->scratched_stack_slots; 770 } 771 772 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 773 { 774 env->scratched_regs = 0U; 775 env->scratched_stack_slots = 0ULL; 776 } 777 778 /* Used for printing the entire verifier state. */ 779 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 780 { 781 env->scratched_regs = ~0U; 782 env->scratched_stack_slots = ~0ULL; 783 } 784 785 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 786 { 787 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 788 case DYNPTR_TYPE_LOCAL: 789 return BPF_DYNPTR_TYPE_LOCAL; 790 case DYNPTR_TYPE_RINGBUF: 791 return BPF_DYNPTR_TYPE_RINGBUF; 792 case DYNPTR_TYPE_SKB: 793 return BPF_DYNPTR_TYPE_SKB; 794 case DYNPTR_TYPE_XDP: 795 return BPF_DYNPTR_TYPE_XDP; 796 default: 797 return BPF_DYNPTR_TYPE_INVALID; 798 } 799 } 800 801 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 802 { 803 switch (type) { 804 case BPF_DYNPTR_TYPE_LOCAL: 805 return DYNPTR_TYPE_LOCAL; 806 case BPF_DYNPTR_TYPE_RINGBUF: 807 return DYNPTR_TYPE_RINGBUF; 808 case BPF_DYNPTR_TYPE_SKB: 809 return DYNPTR_TYPE_SKB; 810 case BPF_DYNPTR_TYPE_XDP: 811 return DYNPTR_TYPE_XDP; 812 default: 813 return 0; 814 } 815 } 816 817 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 818 { 819 return type == BPF_DYNPTR_TYPE_RINGBUF; 820 } 821 822 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 823 enum bpf_dynptr_type type, 824 bool first_slot, int dynptr_id); 825 826 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 827 struct bpf_reg_state *reg); 828 829 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 830 struct bpf_reg_state *sreg1, 831 struct bpf_reg_state *sreg2, 832 enum bpf_dynptr_type type) 833 { 834 int id = ++env->id_gen; 835 836 __mark_dynptr_reg(sreg1, type, true, id); 837 __mark_dynptr_reg(sreg2, type, false, id); 838 } 839 840 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 841 struct bpf_reg_state *reg, 842 enum bpf_dynptr_type type) 843 { 844 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 845 } 846 847 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 848 struct bpf_func_state *state, int spi); 849 850 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 851 enum bpf_arg_type arg_type, int insn_idx, int clone_ref_obj_id) 852 { 853 struct bpf_func_state *state = func(env, reg); 854 enum bpf_dynptr_type type; 855 int spi, i, err; 856 857 spi = dynptr_get_spi(env, reg); 858 if (spi < 0) 859 return spi; 860 861 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 862 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 863 * to ensure that for the following example: 864 * [d1][d1][d2][d2] 865 * spi 3 2 1 0 866 * So marking spi = 2 should lead to destruction of both d1 and d2. In 867 * case they do belong to same dynptr, second call won't see slot_type 868 * as STACK_DYNPTR and will simply skip destruction. 869 */ 870 err = destroy_if_dynptr_stack_slot(env, state, spi); 871 if (err) 872 return err; 873 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 874 if (err) 875 return err; 876 877 for (i = 0; i < BPF_REG_SIZE; i++) { 878 state->stack[spi].slot_type[i] = STACK_DYNPTR; 879 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 880 } 881 882 type = arg_to_dynptr_type(arg_type); 883 if (type == BPF_DYNPTR_TYPE_INVALID) 884 return -EINVAL; 885 886 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 887 &state->stack[spi - 1].spilled_ptr, type); 888 889 if (dynptr_type_refcounted(type)) { 890 /* The id is used to track proper releasing */ 891 int id; 892 893 if (clone_ref_obj_id) 894 id = clone_ref_obj_id; 895 else 896 id = acquire_reference_state(env, insn_idx); 897 898 if (id < 0) 899 return id; 900 901 state->stack[spi].spilled_ptr.ref_obj_id = id; 902 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 903 } 904 905 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 906 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 907 908 return 0; 909 } 910 911 static void invalidate_dynptr(struct bpf_verifier_env *env, struct bpf_func_state *state, int spi) 912 { 913 int i; 914 915 for (i = 0; i < BPF_REG_SIZE; i++) { 916 state->stack[spi].slot_type[i] = STACK_INVALID; 917 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 918 } 919 920 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 921 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 922 923 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 924 * 925 * While we don't allow reading STACK_INVALID, it is still possible to 926 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 927 * helpers or insns can do partial read of that part without failing, 928 * but check_stack_range_initialized, check_stack_read_var_off, and 929 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 930 * the slot conservatively. Hence we need to prevent those liveness 931 * marking walks. 932 * 933 * This was not a problem before because STACK_INVALID is only set by 934 * default (where the default reg state has its reg->parent as NULL), or 935 * in clean_live_states after REG_LIVE_DONE (at which point 936 * mark_reg_read won't walk reg->parent chain), but not randomly during 937 * verifier state exploration (like we did above). Hence, for our case 938 * parentage chain will still be live (i.e. reg->parent may be 939 * non-NULL), while earlier reg->parent was NULL, so we need 940 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 941 * done later on reads or by mark_dynptr_read as well to unnecessary 942 * mark registers in verifier state. 943 */ 944 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 945 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 946 } 947 948 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 949 { 950 struct bpf_func_state *state = func(env, reg); 951 int spi, ref_obj_id, i; 952 953 spi = dynptr_get_spi(env, reg); 954 if (spi < 0) 955 return spi; 956 957 if (!dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 958 invalidate_dynptr(env, state, spi); 959 return 0; 960 } 961 962 ref_obj_id = state->stack[spi].spilled_ptr.ref_obj_id; 963 964 /* If the dynptr has a ref_obj_id, then we need to invalidate 965 * two things: 966 * 967 * 1) Any dynptrs with a matching ref_obj_id (clones) 968 * 2) Any slices derived from this dynptr. 969 */ 970 971 /* Invalidate any slices associated with this dynptr */ 972 WARN_ON_ONCE(release_reference(env, ref_obj_id)); 973 974 /* Invalidate any dynptr clones */ 975 for (i = 1; i < state->allocated_stack / BPF_REG_SIZE; i++) { 976 if (state->stack[i].spilled_ptr.ref_obj_id != ref_obj_id) 977 continue; 978 979 /* it should always be the case that if the ref obj id 980 * matches then the stack slot also belongs to a 981 * dynptr 982 */ 983 if (state->stack[i].slot_type[0] != STACK_DYNPTR) { 984 verbose(env, "verifier internal error: misconfigured ref_obj_id\n"); 985 return -EFAULT; 986 } 987 if (state->stack[i].spilled_ptr.dynptr.first_slot) 988 invalidate_dynptr(env, state, i); 989 } 990 991 return 0; 992 } 993 994 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 995 struct bpf_reg_state *reg); 996 997 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 998 { 999 if (!env->allow_ptr_leaks) 1000 __mark_reg_not_init(env, reg); 1001 else 1002 __mark_reg_unknown(env, reg); 1003 } 1004 1005 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 1006 struct bpf_func_state *state, int spi) 1007 { 1008 struct bpf_func_state *fstate; 1009 struct bpf_reg_state *dreg; 1010 int i, dynptr_id; 1011 1012 /* We always ensure that STACK_DYNPTR is never set partially, 1013 * hence just checking for slot_type[0] is enough. This is 1014 * different for STACK_SPILL, where it may be only set for 1015 * 1 byte, so code has to use is_spilled_reg. 1016 */ 1017 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 1018 return 0; 1019 1020 /* Reposition spi to first slot */ 1021 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1022 spi = spi + 1; 1023 1024 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 1025 verbose(env, "cannot overwrite referenced dynptr\n"); 1026 return -EINVAL; 1027 } 1028 1029 mark_stack_slot_scratched(env, spi); 1030 mark_stack_slot_scratched(env, spi - 1); 1031 1032 /* Writing partially to one dynptr stack slot destroys both. */ 1033 for (i = 0; i < BPF_REG_SIZE; i++) { 1034 state->stack[spi].slot_type[i] = STACK_INVALID; 1035 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 1036 } 1037 1038 dynptr_id = state->stack[spi].spilled_ptr.id; 1039 /* Invalidate any slices associated with this dynptr */ 1040 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 1041 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 1042 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 1043 continue; 1044 if (dreg->dynptr_id == dynptr_id) 1045 mark_reg_invalid(env, dreg); 1046 })); 1047 1048 /* Do not release reference state, we are destroying dynptr on stack, 1049 * not using some helper to release it. Just reset register. 1050 */ 1051 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 1052 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 1053 1054 /* Same reason as unmark_stack_slots_dynptr above */ 1055 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1056 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 1057 1058 return 0; 1059 } 1060 1061 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1062 { 1063 int spi; 1064 1065 if (reg->type == CONST_PTR_TO_DYNPTR) 1066 return false; 1067 1068 spi = dynptr_get_spi(env, reg); 1069 1070 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 1071 * error because this just means the stack state hasn't been updated yet. 1072 * We will do check_mem_access to check and update stack bounds later. 1073 */ 1074 if (spi < 0 && spi != -ERANGE) 1075 return false; 1076 1077 /* We don't need to check if the stack slots are marked by previous 1078 * dynptr initializations because we allow overwriting existing unreferenced 1079 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 1080 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 1081 * touching are completely destructed before we reinitialize them for a new 1082 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 1083 * instead of delaying it until the end where the user will get "Unreleased 1084 * reference" error. 1085 */ 1086 return true; 1087 } 1088 1089 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1090 { 1091 struct bpf_func_state *state = func(env, reg); 1092 int i, spi; 1093 1094 /* This already represents first slot of initialized bpf_dynptr. 1095 * 1096 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 1097 * check_func_arg_reg_off's logic, so we don't need to check its 1098 * offset and alignment. 1099 */ 1100 if (reg->type == CONST_PTR_TO_DYNPTR) 1101 return true; 1102 1103 spi = dynptr_get_spi(env, reg); 1104 if (spi < 0) 1105 return false; 1106 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1107 return false; 1108 1109 for (i = 0; i < BPF_REG_SIZE; i++) { 1110 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 1111 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 1112 return false; 1113 } 1114 1115 return true; 1116 } 1117 1118 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1119 enum bpf_arg_type arg_type) 1120 { 1121 struct bpf_func_state *state = func(env, reg); 1122 enum bpf_dynptr_type dynptr_type; 1123 int spi; 1124 1125 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1126 if (arg_type == ARG_PTR_TO_DYNPTR) 1127 return true; 1128 1129 dynptr_type = arg_to_dynptr_type(arg_type); 1130 if (reg->type == CONST_PTR_TO_DYNPTR) { 1131 return reg->dynptr.type == dynptr_type; 1132 } else { 1133 spi = dynptr_get_spi(env, reg); 1134 if (spi < 0) 1135 return false; 1136 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1137 } 1138 } 1139 1140 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1141 1142 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1143 struct bpf_reg_state *reg, int insn_idx, 1144 struct btf *btf, u32 btf_id, int nr_slots) 1145 { 1146 struct bpf_func_state *state = func(env, reg); 1147 int spi, i, j, id; 1148 1149 spi = iter_get_spi(env, reg, nr_slots); 1150 if (spi < 0) 1151 return spi; 1152 1153 id = acquire_reference_state(env, insn_idx); 1154 if (id < 0) 1155 return id; 1156 1157 for (i = 0; i < nr_slots; i++) { 1158 struct bpf_stack_state *slot = &state->stack[spi - i]; 1159 struct bpf_reg_state *st = &slot->spilled_ptr; 1160 1161 __mark_reg_known_zero(st); 1162 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1163 st->live |= REG_LIVE_WRITTEN; 1164 st->ref_obj_id = i == 0 ? id : 0; 1165 st->iter.btf = btf; 1166 st->iter.btf_id = btf_id; 1167 st->iter.state = BPF_ITER_STATE_ACTIVE; 1168 st->iter.depth = 0; 1169 1170 for (j = 0; j < BPF_REG_SIZE; j++) 1171 slot->slot_type[j] = STACK_ITER; 1172 1173 mark_stack_slot_scratched(env, spi - i); 1174 } 1175 1176 return 0; 1177 } 1178 1179 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1180 struct bpf_reg_state *reg, int nr_slots) 1181 { 1182 struct bpf_func_state *state = func(env, reg); 1183 int spi, i, j; 1184 1185 spi = iter_get_spi(env, reg, nr_slots); 1186 if (spi < 0) 1187 return spi; 1188 1189 for (i = 0; i < nr_slots; i++) { 1190 struct bpf_stack_state *slot = &state->stack[spi - i]; 1191 struct bpf_reg_state *st = &slot->spilled_ptr; 1192 1193 if (i == 0) 1194 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1195 1196 __mark_reg_not_init(env, st); 1197 1198 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1199 st->live |= REG_LIVE_WRITTEN; 1200 1201 for (j = 0; j < BPF_REG_SIZE; j++) 1202 slot->slot_type[j] = STACK_INVALID; 1203 1204 mark_stack_slot_scratched(env, spi - i); 1205 } 1206 1207 return 0; 1208 } 1209 1210 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1211 struct bpf_reg_state *reg, int nr_slots) 1212 { 1213 struct bpf_func_state *state = func(env, reg); 1214 int spi, i, j; 1215 1216 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1217 * will do check_mem_access to check and update stack bounds later, so 1218 * return true for that case. 1219 */ 1220 spi = iter_get_spi(env, reg, nr_slots); 1221 if (spi == -ERANGE) 1222 return true; 1223 if (spi < 0) 1224 return false; 1225 1226 for (i = 0; i < nr_slots; i++) { 1227 struct bpf_stack_state *slot = &state->stack[spi - i]; 1228 1229 for (j = 0; j < BPF_REG_SIZE; j++) 1230 if (slot->slot_type[j] == STACK_ITER) 1231 return false; 1232 } 1233 1234 return true; 1235 } 1236 1237 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1238 struct btf *btf, u32 btf_id, int nr_slots) 1239 { 1240 struct bpf_func_state *state = func(env, reg); 1241 int spi, i, j; 1242 1243 spi = iter_get_spi(env, reg, nr_slots); 1244 if (spi < 0) 1245 return false; 1246 1247 for (i = 0; i < nr_slots; i++) { 1248 struct bpf_stack_state *slot = &state->stack[spi - i]; 1249 struct bpf_reg_state *st = &slot->spilled_ptr; 1250 1251 /* only main (first) slot has ref_obj_id set */ 1252 if (i == 0 && !st->ref_obj_id) 1253 return false; 1254 if (i != 0 && st->ref_obj_id) 1255 return false; 1256 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1257 return false; 1258 1259 for (j = 0; j < BPF_REG_SIZE; j++) 1260 if (slot->slot_type[j] != STACK_ITER) 1261 return false; 1262 } 1263 1264 return true; 1265 } 1266 1267 /* Check if given stack slot is "special": 1268 * - spilled register state (STACK_SPILL); 1269 * - dynptr state (STACK_DYNPTR); 1270 * - iter state (STACK_ITER). 1271 */ 1272 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1273 { 1274 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1275 1276 switch (type) { 1277 case STACK_SPILL: 1278 case STACK_DYNPTR: 1279 case STACK_ITER: 1280 return true; 1281 case STACK_INVALID: 1282 case STACK_MISC: 1283 case STACK_ZERO: 1284 return false; 1285 default: 1286 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1287 return true; 1288 } 1289 } 1290 1291 /* The reg state of a pointer or a bounded scalar was saved when 1292 * it was spilled to the stack. 1293 */ 1294 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1295 { 1296 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1297 } 1298 1299 static bool is_spilled_scalar_reg(const struct bpf_stack_state *stack) 1300 { 1301 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL && 1302 stack->spilled_ptr.type == SCALAR_VALUE; 1303 } 1304 1305 static void scrub_spilled_slot(u8 *stype) 1306 { 1307 if (*stype != STACK_INVALID) 1308 *stype = STACK_MISC; 1309 } 1310 1311 static void print_verifier_state(struct bpf_verifier_env *env, 1312 const struct bpf_func_state *state, 1313 bool print_all) 1314 { 1315 const struct bpf_reg_state *reg; 1316 enum bpf_reg_type t; 1317 int i; 1318 1319 if (state->frameno) 1320 verbose(env, " frame%d:", state->frameno); 1321 for (i = 0; i < MAX_BPF_REG; i++) { 1322 reg = &state->regs[i]; 1323 t = reg->type; 1324 if (t == NOT_INIT) 1325 continue; 1326 if (!print_all && !reg_scratched(env, i)) 1327 continue; 1328 verbose(env, " R%d", i); 1329 print_liveness(env, reg->live); 1330 verbose(env, "="); 1331 if (t == SCALAR_VALUE && reg->precise) 1332 verbose(env, "P"); 1333 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1334 tnum_is_const(reg->var_off)) { 1335 /* reg->off should be 0 for SCALAR_VALUE */ 1336 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1337 verbose(env, "%lld", reg->var_off.value + reg->off); 1338 } else { 1339 const char *sep = ""; 1340 1341 verbose(env, "%s", reg_type_str(env, t)); 1342 if (base_type(t) == PTR_TO_BTF_ID) 1343 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id)); 1344 verbose(env, "("); 1345 /* 1346 * _a stands for append, was shortened to avoid multiline statements below. 1347 * This macro is used to output a comma separated list of attributes. 1348 */ 1349 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1350 1351 if (reg->id) 1352 verbose_a("id=%d", reg->id); 1353 if (reg->ref_obj_id) 1354 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1355 if (type_is_non_owning_ref(reg->type)) 1356 verbose_a("%s", "non_own_ref"); 1357 if (t != SCALAR_VALUE) 1358 verbose_a("off=%d", reg->off); 1359 if (type_is_pkt_pointer(t)) 1360 verbose_a("r=%d", reg->range); 1361 else if (base_type(t) == CONST_PTR_TO_MAP || 1362 base_type(t) == PTR_TO_MAP_KEY || 1363 base_type(t) == PTR_TO_MAP_VALUE) 1364 verbose_a("ks=%d,vs=%d", 1365 reg->map_ptr->key_size, 1366 reg->map_ptr->value_size); 1367 if (tnum_is_const(reg->var_off)) { 1368 /* Typically an immediate SCALAR_VALUE, but 1369 * could be a pointer whose offset is too big 1370 * for reg->off 1371 */ 1372 verbose_a("imm=%llx", reg->var_off.value); 1373 } else { 1374 if (reg->smin_value != reg->umin_value && 1375 reg->smin_value != S64_MIN) 1376 verbose_a("smin=%lld", (long long)reg->smin_value); 1377 if (reg->smax_value != reg->umax_value && 1378 reg->smax_value != S64_MAX) 1379 verbose_a("smax=%lld", (long long)reg->smax_value); 1380 if (reg->umin_value != 0) 1381 verbose_a("umin=%llu", (unsigned long long)reg->umin_value); 1382 if (reg->umax_value != U64_MAX) 1383 verbose_a("umax=%llu", (unsigned long long)reg->umax_value); 1384 if (!tnum_is_unknown(reg->var_off)) { 1385 char tn_buf[48]; 1386 1387 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1388 verbose_a("var_off=%s", tn_buf); 1389 } 1390 if (reg->s32_min_value != reg->smin_value && 1391 reg->s32_min_value != S32_MIN) 1392 verbose_a("s32_min=%d", (int)(reg->s32_min_value)); 1393 if (reg->s32_max_value != reg->smax_value && 1394 reg->s32_max_value != S32_MAX) 1395 verbose_a("s32_max=%d", (int)(reg->s32_max_value)); 1396 if (reg->u32_min_value != reg->umin_value && 1397 reg->u32_min_value != U32_MIN) 1398 verbose_a("u32_min=%d", (int)(reg->u32_min_value)); 1399 if (reg->u32_max_value != reg->umax_value && 1400 reg->u32_max_value != U32_MAX) 1401 verbose_a("u32_max=%d", (int)(reg->u32_max_value)); 1402 } 1403 #undef verbose_a 1404 1405 verbose(env, ")"); 1406 } 1407 } 1408 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1409 char types_buf[BPF_REG_SIZE + 1]; 1410 bool valid = false; 1411 int j; 1412 1413 for (j = 0; j < BPF_REG_SIZE; j++) { 1414 if (state->stack[i].slot_type[j] != STACK_INVALID) 1415 valid = true; 1416 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1417 } 1418 types_buf[BPF_REG_SIZE] = 0; 1419 if (!valid) 1420 continue; 1421 if (!print_all && !stack_slot_scratched(env, i)) 1422 continue; 1423 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) { 1424 case STACK_SPILL: 1425 reg = &state->stack[i].spilled_ptr; 1426 t = reg->type; 1427 1428 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1429 print_liveness(env, reg->live); 1430 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1431 if (t == SCALAR_VALUE && reg->precise) 1432 verbose(env, "P"); 1433 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1434 verbose(env, "%lld", reg->var_off.value + reg->off); 1435 break; 1436 case STACK_DYNPTR: 1437 i += BPF_DYNPTR_NR_SLOTS - 1; 1438 reg = &state->stack[i].spilled_ptr; 1439 1440 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1441 print_liveness(env, reg->live); 1442 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type)); 1443 if (reg->ref_obj_id) 1444 verbose(env, "(ref_id=%d)", reg->ref_obj_id); 1445 break; 1446 case STACK_ITER: 1447 /* only main slot has ref_obj_id set; skip others */ 1448 reg = &state->stack[i].spilled_ptr; 1449 if (!reg->ref_obj_id) 1450 continue; 1451 1452 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1453 print_liveness(env, reg->live); 1454 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)", 1455 iter_type_str(reg->iter.btf, reg->iter.btf_id), 1456 reg->ref_obj_id, iter_state_str(reg->iter.state), 1457 reg->iter.depth); 1458 break; 1459 case STACK_MISC: 1460 case STACK_ZERO: 1461 default: 1462 reg = &state->stack[i].spilled_ptr; 1463 1464 for (j = 0; j < BPF_REG_SIZE; j++) 1465 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1466 types_buf[BPF_REG_SIZE] = 0; 1467 1468 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1469 print_liveness(env, reg->live); 1470 verbose(env, "=%s", types_buf); 1471 break; 1472 } 1473 } 1474 if (state->acquired_refs && state->refs[0].id) { 1475 verbose(env, " refs=%d", state->refs[0].id); 1476 for (i = 1; i < state->acquired_refs; i++) 1477 if (state->refs[i].id) 1478 verbose(env, ",%d", state->refs[i].id); 1479 } 1480 if (state->in_callback_fn) 1481 verbose(env, " cb"); 1482 if (state->in_async_callback_fn) 1483 verbose(env, " async_cb"); 1484 verbose(env, "\n"); 1485 mark_verifier_state_clean(env); 1486 } 1487 1488 static inline u32 vlog_alignment(u32 pos) 1489 { 1490 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1491 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1492 } 1493 1494 static void print_insn_state(struct bpf_verifier_env *env, 1495 const struct bpf_func_state *state) 1496 { 1497 if (env->prev_log_pos && env->prev_log_pos == env->log.end_pos) { 1498 /* remove new line character */ 1499 bpf_vlog_reset(&env->log, env->prev_log_pos - 1); 1500 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_pos), ' '); 1501 } else { 1502 verbose(env, "%d:", env->insn_idx); 1503 } 1504 print_verifier_state(env, state, false); 1505 } 1506 1507 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1508 * small to hold src. This is different from krealloc since we don't want to preserve 1509 * the contents of dst. 1510 * 1511 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1512 * not be allocated. 1513 */ 1514 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1515 { 1516 size_t alloc_bytes; 1517 void *orig = dst; 1518 size_t bytes; 1519 1520 if (ZERO_OR_NULL_PTR(src)) 1521 goto out; 1522 1523 if (unlikely(check_mul_overflow(n, size, &bytes))) 1524 return NULL; 1525 1526 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1527 dst = krealloc(orig, alloc_bytes, flags); 1528 if (!dst) { 1529 kfree(orig); 1530 return NULL; 1531 } 1532 1533 memcpy(dst, src, bytes); 1534 out: 1535 return dst ? dst : ZERO_SIZE_PTR; 1536 } 1537 1538 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1539 * small to hold new_n items. new items are zeroed out if the array grows. 1540 * 1541 * Contrary to krealloc_array, does not free arr if new_n is zero. 1542 */ 1543 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1544 { 1545 size_t alloc_size; 1546 void *new_arr; 1547 1548 if (!new_n || old_n == new_n) 1549 goto out; 1550 1551 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1552 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1553 if (!new_arr) { 1554 kfree(arr); 1555 return NULL; 1556 } 1557 arr = new_arr; 1558 1559 if (new_n > old_n) 1560 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1561 1562 out: 1563 return arr ? arr : ZERO_SIZE_PTR; 1564 } 1565 1566 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1567 { 1568 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1569 sizeof(struct bpf_reference_state), GFP_KERNEL); 1570 if (!dst->refs) 1571 return -ENOMEM; 1572 1573 dst->acquired_refs = src->acquired_refs; 1574 return 0; 1575 } 1576 1577 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1578 { 1579 size_t n = src->allocated_stack / BPF_REG_SIZE; 1580 1581 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1582 GFP_KERNEL); 1583 if (!dst->stack) 1584 return -ENOMEM; 1585 1586 dst->allocated_stack = src->allocated_stack; 1587 return 0; 1588 } 1589 1590 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1591 { 1592 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1593 sizeof(struct bpf_reference_state)); 1594 if (!state->refs) 1595 return -ENOMEM; 1596 1597 state->acquired_refs = n; 1598 return 0; 1599 } 1600 1601 static int grow_stack_state(struct bpf_func_state *state, int size) 1602 { 1603 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1604 1605 if (old_n >= n) 1606 return 0; 1607 1608 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1609 if (!state->stack) 1610 return -ENOMEM; 1611 1612 state->allocated_stack = size; 1613 return 0; 1614 } 1615 1616 /* Acquire a pointer id from the env and update the state->refs to include 1617 * this new pointer reference. 1618 * On success, returns a valid pointer id to associate with the register 1619 * On failure, returns a negative errno. 1620 */ 1621 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1622 { 1623 struct bpf_func_state *state = cur_func(env); 1624 int new_ofs = state->acquired_refs; 1625 int id, err; 1626 1627 err = resize_reference_state(state, state->acquired_refs + 1); 1628 if (err) 1629 return err; 1630 id = ++env->id_gen; 1631 state->refs[new_ofs].id = id; 1632 state->refs[new_ofs].insn_idx = insn_idx; 1633 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1634 1635 return id; 1636 } 1637 1638 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1639 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1640 { 1641 int i, last_idx; 1642 1643 last_idx = state->acquired_refs - 1; 1644 for (i = 0; i < state->acquired_refs; i++) { 1645 if (state->refs[i].id == ptr_id) { 1646 /* Cannot release caller references in callbacks */ 1647 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1648 return -EINVAL; 1649 if (last_idx && i != last_idx) 1650 memcpy(&state->refs[i], &state->refs[last_idx], 1651 sizeof(*state->refs)); 1652 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1653 state->acquired_refs--; 1654 return 0; 1655 } 1656 } 1657 return -EINVAL; 1658 } 1659 1660 static void free_func_state(struct bpf_func_state *state) 1661 { 1662 if (!state) 1663 return; 1664 kfree(state->refs); 1665 kfree(state->stack); 1666 kfree(state); 1667 } 1668 1669 static void clear_jmp_history(struct bpf_verifier_state *state) 1670 { 1671 kfree(state->jmp_history); 1672 state->jmp_history = NULL; 1673 state->jmp_history_cnt = 0; 1674 } 1675 1676 static void free_verifier_state(struct bpf_verifier_state *state, 1677 bool free_self) 1678 { 1679 int i; 1680 1681 for (i = 0; i <= state->curframe; i++) { 1682 free_func_state(state->frame[i]); 1683 state->frame[i] = NULL; 1684 } 1685 clear_jmp_history(state); 1686 if (free_self) 1687 kfree(state); 1688 } 1689 1690 /* copy verifier state from src to dst growing dst stack space 1691 * when necessary to accommodate larger src stack 1692 */ 1693 static int copy_func_state(struct bpf_func_state *dst, 1694 const struct bpf_func_state *src) 1695 { 1696 int err; 1697 1698 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1699 err = copy_reference_state(dst, src); 1700 if (err) 1701 return err; 1702 return copy_stack_state(dst, src); 1703 } 1704 1705 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1706 const struct bpf_verifier_state *src) 1707 { 1708 struct bpf_func_state *dst; 1709 int i, err; 1710 1711 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1712 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1713 GFP_USER); 1714 if (!dst_state->jmp_history) 1715 return -ENOMEM; 1716 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1717 1718 /* if dst has more stack frames then src frame, free them */ 1719 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1720 free_func_state(dst_state->frame[i]); 1721 dst_state->frame[i] = NULL; 1722 } 1723 dst_state->speculative = src->speculative; 1724 dst_state->active_rcu_lock = src->active_rcu_lock; 1725 dst_state->curframe = src->curframe; 1726 dst_state->active_lock.ptr = src->active_lock.ptr; 1727 dst_state->active_lock.id = src->active_lock.id; 1728 dst_state->branches = src->branches; 1729 dst_state->parent = src->parent; 1730 dst_state->first_insn_idx = src->first_insn_idx; 1731 dst_state->last_insn_idx = src->last_insn_idx; 1732 for (i = 0; i <= src->curframe; i++) { 1733 dst = dst_state->frame[i]; 1734 if (!dst) { 1735 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1736 if (!dst) 1737 return -ENOMEM; 1738 dst_state->frame[i] = dst; 1739 } 1740 err = copy_func_state(dst, src->frame[i]); 1741 if (err) 1742 return err; 1743 } 1744 return 0; 1745 } 1746 1747 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1748 { 1749 while (st) { 1750 u32 br = --st->branches; 1751 1752 /* WARN_ON(br > 1) technically makes sense here, 1753 * but see comment in push_stack(), hence: 1754 */ 1755 WARN_ONCE((int)br < 0, 1756 "BUG update_branch_counts:branches_to_explore=%d\n", 1757 br); 1758 if (br) 1759 break; 1760 st = st->parent; 1761 } 1762 } 1763 1764 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1765 int *insn_idx, bool pop_log) 1766 { 1767 struct bpf_verifier_state *cur = env->cur_state; 1768 struct bpf_verifier_stack_elem *elem, *head = env->head; 1769 int err; 1770 1771 if (env->head == NULL) 1772 return -ENOENT; 1773 1774 if (cur) { 1775 err = copy_verifier_state(cur, &head->st); 1776 if (err) 1777 return err; 1778 } 1779 if (pop_log) 1780 bpf_vlog_reset(&env->log, head->log_pos); 1781 if (insn_idx) 1782 *insn_idx = head->insn_idx; 1783 if (prev_insn_idx) 1784 *prev_insn_idx = head->prev_insn_idx; 1785 elem = head->next; 1786 free_verifier_state(&head->st, false); 1787 kfree(head); 1788 env->head = elem; 1789 env->stack_size--; 1790 return 0; 1791 } 1792 1793 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1794 int insn_idx, int prev_insn_idx, 1795 bool speculative) 1796 { 1797 struct bpf_verifier_state *cur = env->cur_state; 1798 struct bpf_verifier_stack_elem *elem; 1799 int err; 1800 1801 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1802 if (!elem) 1803 goto err; 1804 1805 elem->insn_idx = insn_idx; 1806 elem->prev_insn_idx = prev_insn_idx; 1807 elem->next = env->head; 1808 elem->log_pos = env->log.end_pos; 1809 env->head = elem; 1810 env->stack_size++; 1811 err = copy_verifier_state(&elem->st, cur); 1812 if (err) 1813 goto err; 1814 elem->st.speculative |= speculative; 1815 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1816 verbose(env, "The sequence of %d jumps is too complex.\n", 1817 env->stack_size); 1818 goto err; 1819 } 1820 if (elem->st.parent) { 1821 ++elem->st.parent->branches; 1822 /* WARN_ON(branches > 2) technically makes sense here, 1823 * but 1824 * 1. speculative states will bump 'branches' for non-branch 1825 * instructions 1826 * 2. is_state_visited() heuristics may decide not to create 1827 * a new state for a sequence of branches and all such current 1828 * and cloned states will be pointing to a single parent state 1829 * which might have large 'branches' count. 1830 */ 1831 } 1832 return &elem->st; 1833 err: 1834 free_verifier_state(env->cur_state, true); 1835 env->cur_state = NULL; 1836 /* pop all elements and return */ 1837 while (!pop_stack(env, NULL, NULL, false)); 1838 return NULL; 1839 } 1840 1841 #define CALLER_SAVED_REGS 6 1842 static const int caller_saved[CALLER_SAVED_REGS] = { 1843 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1844 }; 1845 1846 /* This helper doesn't clear reg->id */ 1847 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1848 { 1849 reg->var_off = tnum_const(imm); 1850 reg->smin_value = (s64)imm; 1851 reg->smax_value = (s64)imm; 1852 reg->umin_value = imm; 1853 reg->umax_value = imm; 1854 1855 reg->s32_min_value = (s32)imm; 1856 reg->s32_max_value = (s32)imm; 1857 reg->u32_min_value = (u32)imm; 1858 reg->u32_max_value = (u32)imm; 1859 } 1860 1861 /* Mark the unknown part of a register (variable offset or scalar value) as 1862 * known to have the value @imm. 1863 */ 1864 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1865 { 1866 /* Clear off and union(map_ptr, range) */ 1867 memset(((u8 *)reg) + sizeof(reg->type), 0, 1868 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1869 reg->id = 0; 1870 reg->ref_obj_id = 0; 1871 ___mark_reg_known(reg, imm); 1872 } 1873 1874 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1875 { 1876 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1877 reg->s32_min_value = (s32)imm; 1878 reg->s32_max_value = (s32)imm; 1879 reg->u32_min_value = (u32)imm; 1880 reg->u32_max_value = (u32)imm; 1881 } 1882 1883 /* Mark the 'variable offset' part of a register as zero. This should be 1884 * used only on registers holding a pointer type. 1885 */ 1886 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1887 { 1888 __mark_reg_known(reg, 0); 1889 } 1890 1891 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1892 { 1893 __mark_reg_known(reg, 0); 1894 reg->type = SCALAR_VALUE; 1895 } 1896 1897 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1898 struct bpf_reg_state *regs, u32 regno) 1899 { 1900 if (WARN_ON(regno >= MAX_BPF_REG)) { 1901 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1902 /* Something bad happened, let's kill all regs */ 1903 for (regno = 0; regno < MAX_BPF_REG; regno++) 1904 __mark_reg_not_init(env, regs + regno); 1905 return; 1906 } 1907 __mark_reg_known_zero(regs + regno); 1908 } 1909 1910 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1911 bool first_slot, int dynptr_id) 1912 { 1913 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1914 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1915 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1916 */ 1917 __mark_reg_known_zero(reg); 1918 reg->type = CONST_PTR_TO_DYNPTR; 1919 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1920 reg->id = dynptr_id; 1921 reg->dynptr.type = type; 1922 reg->dynptr.first_slot = first_slot; 1923 } 1924 1925 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1926 { 1927 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1928 const struct bpf_map *map = reg->map_ptr; 1929 1930 if (map->inner_map_meta) { 1931 reg->type = CONST_PTR_TO_MAP; 1932 reg->map_ptr = map->inner_map_meta; 1933 /* transfer reg's id which is unique for every map_lookup_elem 1934 * as UID of the inner map. 1935 */ 1936 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1937 reg->map_uid = reg->id; 1938 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1939 reg->type = PTR_TO_XDP_SOCK; 1940 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1941 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1942 reg->type = PTR_TO_SOCKET; 1943 } else { 1944 reg->type = PTR_TO_MAP_VALUE; 1945 } 1946 return; 1947 } 1948 1949 reg->type &= ~PTR_MAYBE_NULL; 1950 } 1951 1952 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1953 struct btf_field_graph_root *ds_head) 1954 { 1955 __mark_reg_known_zero(®s[regno]); 1956 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1957 regs[regno].btf = ds_head->btf; 1958 regs[regno].btf_id = ds_head->value_btf_id; 1959 regs[regno].off = ds_head->node_offset; 1960 } 1961 1962 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1963 { 1964 return type_is_pkt_pointer(reg->type); 1965 } 1966 1967 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1968 { 1969 return reg_is_pkt_pointer(reg) || 1970 reg->type == PTR_TO_PACKET_END; 1971 } 1972 1973 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1974 { 1975 return base_type(reg->type) == PTR_TO_MEM && 1976 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1977 } 1978 1979 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1980 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1981 enum bpf_reg_type which) 1982 { 1983 /* The register can already have a range from prior markings. 1984 * This is fine as long as it hasn't been advanced from its 1985 * origin. 1986 */ 1987 return reg->type == which && 1988 reg->id == 0 && 1989 reg->off == 0 && 1990 tnum_equals_const(reg->var_off, 0); 1991 } 1992 1993 /* Reset the min/max bounds of a register */ 1994 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1995 { 1996 reg->smin_value = S64_MIN; 1997 reg->smax_value = S64_MAX; 1998 reg->umin_value = 0; 1999 reg->umax_value = U64_MAX; 2000 2001 reg->s32_min_value = S32_MIN; 2002 reg->s32_max_value = S32_MAX; 2003 reg->u32_min_value = 0; 2004 reg->u32_max_value = U32_MAX; 2005 } 2006 2007 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2008 { 2009 reg->smin_value = S64_MIN; 2010 reg->smax_value = S64_MAX; 2011 reg->umin_value = 0; 2012 reg->umax_value = U64_MAX; 2013 } 2014 2015 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2016 { 2017 reg->s32_min_value = S32_MIN; 2018 reg->s32_max_value = S32_MAX; 2019 reg->u32_min_value = 0; 2020 reg->u32_max_value = U32_MAX; 2021 } 2022 2023 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2024 { 2025 struct tnum var32_off = tnum_subreg(reg->var_off); 2026 2027 /* min signed is max(sign bit) | min(other bits) */ 2028 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2029 var32_off.value | (var32_off.mask & S32_MIN)); 2030 /* max signed is min(sign bit) | max(other bits) */ 2031 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2032 var32_off.value | (var32_off.mask & S32_MAX)); 2033 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2034 reg->u32_max_value = min(reg->u32_max_value, 2035 (u32)(var32_off.value | var32_off.mask)); 2036 } 2037 2038 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2039 { 2040 /* min signed is max(sign bit) | min(other bits) */ 2041 reg->smin_value = max_t(s64, reg->smin_value, 2042 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2043 /* max signed is min(sign bit) | max(other bits) */ 2044 reg->smax_value = min_t(s64, reg->smax_value, 2045 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2046 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2047 reg->umax_value = min(reg->umax_value, 2048 reg->var_off.value | reg->var_off.mask); 2049 } 2050 2051 static void __update_reg_bounds(struct bpf_reg_state *reg) 2052 { 2053 __update_reg32_bounds(reg); 2054 __update_reg64_bounds(reg); 2055 } 2056 2057 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2058 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2059 { 2060 /* Learn sign from signed bounds. 2061 * If we cannot cross the sign boundary, then signed and unsigned bounds 2062 * are the same, so combine. This works even in the negative case, e.g. 2063 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2064 */ 2065 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 2066 reg->s32_min_value = reg->u32_min_value = 2067 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2068 reg->s32_max_value = reg->u32_max_value = 2069 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2070 return; 2071 } 2072 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2073 * boundary, so we must be careful. 2074 */ 2075 if ((s32)reg->u32_max_value >= 0) { 2076 /* Positive. We can't learn anything from the smin, but smax 2077 * is positive, hence safe. 2078 */ 2079 reg->s32_min_value = reg->u32_min_value; 2080 reg->s32_max_value = reg->u32_max_value = 2081 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2082 } else if ((s32)reg->u32_min_value < 0) { 2083 /* Negative. We can't learn anything from the smax, but smin 2084 * is negative, hence safe. 2085 */ 2086 reg->s32_min_value = reg->u32_min_value = 2087 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2088 reg->s32_max_value = reg->u32_max_value; 2089 } 2090 } 2091 2092 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2093 { 2094 /* Learn sign from signed bounds. 2095 * If we cannot cross the sign boundary, then signed and unsigned bounds 2096 * are the same, so combine. This works even in the negative case, e.g. 2097 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2098 */ 2099 if (reg->smin_value >= 0 || reg->smax_value < 0) { 2100 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2101 reg->umin_value); 2102 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2103 reg->umax_value); 2104 return; 2105 } 2106 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2107 * boundary, so we must be careful. 2108 */ 2109 if ((s64)reg->umax_value >= 0) { 2110 /* Positive. We can't learn anything from the smin, but smax 2111 * is positive, hence safe. 2112 */ 2113 reg->smin_value = reg->umin_value; 2114 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2115 reg->umax_value); 2116 } else if ((s64)reg->umin_value < 0) { 2117 /* Negative. We can't learn anything from the smax, but smin 2118 * is negative, hence safe. 2119 */ 2120 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2121 reg->umin_value); 2122 reg->smax_value = reg->umax_value; 2123 } 2124 } 2125 2126 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2127 { 2128 __reg32_deduce_bounds(reg); 2129 __reg64_deduce_bounds(reg); 2130 } 2131 2132 /* Attempts to improve var_off based on unsigned min/max information */ 2133 static void __reg_bound_offset(struct bpf_reg_state *reg) 2134 { 2135 struct tnum var64_off = tnum_intersect(reg->var_off, 2136 tnum_range(reg->umin_value, 2137 reg->umax_value)); 2138 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2139 tnum_range(reg->u32_min_value, 2140 reg->u32_max_value)); 2141 2142 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2143 } 2144 2145 static void reg_bounds_sync(struct bpf_reg_state *reg) 2146 { 2147 /* We might have learned new bounds from the var_off. */ 2148 __update_reg_bounds(reg); 2149 /* We might have learned something about the sign bit. */ 2150 __reg_deduce_bounds(reg); 2151 /* We might have learned some bits from the bounds. */ 2152 __reg_bound_offset(reg); 2153 /* Intersecting with the old var_off might have improved our bounds 2154 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2155 * then new var_off is (0; 0x7f...fc) which improves our umax. 2156 */ 2157 __update_reg_bounds(reg); 2158 } 2159 2160 static bool __reg32_bound_s64(s32 a) 2161 { 2162 return a >= 0 && a <= S32_MAX; 2163 } 2164 2165 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2166 { 2167 reg->umin_value = reg->u32_min_value; 2168 reg->umax_value = reg->u32_max_value; 2169 2170 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2171 * be positive otherwise set to worse case bounds and refine later 2172 * from tnum. 2173 */ 2174 if (__reg32_bound_s64(reg->s32_min_value) && 2175 __reg32_bound_s64(reg->s32_max_value)) { 2176 reg->smin_value = reg->s32_min_value; 2177 reg->smax_value = reg->s32_max_value; 2178 } else { 2179 reg->smin_value = 0; 2180 reg->smax_value = U32_MAX; 2181 } 2182 } 2183 2184 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 2185 { 2186 /* special case when 64-bit register has upper 32-bit register 2187 * zeroed. Typically happens after zext or <<32, >>32 sequence 2188 * allowing us to use 32-bit bounds directly, 2189 */ 2190 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 2191 __reg_assign_32_into_64(reg); 2192 } else { 2193 /* Otherwise the best we can do is push lower 32bit known and 2194 * unknown bits into register (var_off set from jmp logic) 2195 * then learn as much as possible from the 64-bit tnum 2196 * known and unknown bits. The previous smin/smax bounds are 2197 * invalid here because of jmp32 compare so mark them unknown 2198 * so they do not impact tnum bounds calculation. 2199 */ 2200 __mark_reg64_unbounded(reg); 2201 } 2202 reg_bounds_sync(reg); 2203 } 2204 2205 static bool __reg64_bound_s32(s64 a) 2206 { 2207 return a >= S32_MIN && a <= S32_MAX; 2208 } 2209 2210 static bool __reg64_bound_u32(u64 a) 2211 { 2212 return a >= U32_MIN && a <= U32_MAX; 2213 } 2214 2215 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 2216 { 2217 __mark_reg32_unbounded(reg); 2218 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 2219 reg->s32_min_value = (s32)reg->smin_value; 2220 reg->s32_max_value = (s32)reg->smax_value; 2221 } 2222 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 2223 reg->u32_min_value = (u32)reg->umin_value; 2224 reg->u32_max_value = (u32)reg->umax_value; 2225 } 2226 reg_bounds_sync(reg); 2227 } 2228 2229 /* Mark a register as having a completely unknown (scalar) value. */ 2230 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2231 struct bpf_reg_state *reg) 2232 { 2233 /* 2234 * Clear type, off, and union(map_ptr, range) and 2235 * padding between 'type' and union 2236 */ 2237 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2238 reg->type = SCALAR_VALUE; 2239 reg->id = 0; 2240 reg->ref_obj_id = 0; 2241 reg->var_off = tnum_unknown; 2242 reg->frameno = 0; 2243 reg->precise = !env->bpf_capable; 2244 __mark_reg_unbounded(reg); 2245 } 2246 2247 static void mark_reg_unknown(struct bpf_verifier_env *env, 2248 struct bpf_reg_state *regs, u32 regno) 2249 { 2250 if (WARN_ON(regno >= MAX_BPF_REG)) { 2251 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2252 /* Something bad happened, let's kill all regs except FP */ 2253 for (regno = 0; regno < BPF_REG_FP; regno++) 2254 __mark_reg_not_init(env, regs + regno); 2255 return; 2256 } 2257 __mark_reg_unknown(env, regs + regno); 2258 } 2259 2260 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2261 struct bpf_reg_state *reg) 2262 { 2263 __mark_reg_unknown(env, reg); 2264 reg->type = NOT_INIT; 2265 } 2266 2267 static void mark_reg_not_init(struct bpf_verifier_env *env, 2268 struct bpf_reg_state *regs, u32 regno) 2269 { 2270 if (WARN_ON(regno >= MAX_BPF_REG)) { 2271 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2272 /* Something bad happened, let's kill all regs except FP */ 2273 for (regno = 0; regno < BPF_REG_FP; regno++) 2274 __mark_reg_not_init(env, regs + regno); 2275 return; 2276 } 2277 __mark_reg_not_init(env, regs + regno); 2278 } 2279 2280 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2281 struct bpf_reg_state *regs, u32 regno, 2282 enum bpf_reg_type reg_type, 2283 struct btf *btf, u32 btf_id, 2284 enum bpf_type_flag flag) 2285 { 2286 if (reg_type == SCALAR_VALUE) { 2287 mark_reg_unknown(env, regs, regno); 2288 return; 2289 } 2290 mark_reg_known_zero(env, regs, regno); 2291 regs[regno].type = PTR_TO_BTF_ID | flag; 2292 regs[regno].btf = btf; 2293 regs[regno].btf_id = btf_id; 2294 } 2295 2296 #define DEF_NOT_SUBREG (0) 2297 static void init_reg_state(struct bpf_verifier_env *env, 2298 struct bpf_func_state *state) 2299 { 2300 struct bpf_reg_state *regs = state->regs; 2301 int i; 2302 2303 for (i = 0; i < MAX_BPF_REG; i++) { 2304 mark_reg_not_init(env, regs, i); 2305 regs[i].live = REG_LIVE_NONE; 2306 regs[i].parent = NULL; 2307 regs[i].subreg_def = DEF_NOT_SUBREG; 2308 } 2309 2310 /* frame pointer */ 2311 regs[BPF_REG_FP].type = PTR_TO_STACK; 2312 mark_reg_known_zero(env, regs, BPF_REG_FP); 2313 regs[BPF_REG_FP].frameno = state->frameno; 2314 } 2315 2316 #define BPF_MAIN_FUNC (-1) 2317 static void init_func_state(struct bpf_verifier_env *env, 2318 struct bpf_func_state *state, 2319 int callsite, int frameno, int subprogno) 2320 { 2321 state->callsite = callsite; 2322 state->frameno = frameno; 2323 state->subprogno = subprogno; 2324 state->callback_ret_range = tnum_range(0, 0); 2325 init_reg_state(env, state); 2326 mark_verifier_state_scratched(env); 2327 } 2328 2329 /* Similar to push_stack(), but for async callbacks */ 2330 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2331 int insn_idx, int prev_insn_idx, 2332 int subprog) 2333 { 2334 struct bpf_verifier_stack_elem *elem; 2335 struct bpf_func_state *frame; 2336 2337 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2338 if (!elem) 2339 goto err; 2340 2341 elem->insn_idx = insn_idx; 2342 elem->prev_insn_idx = prev_insn_idx; 2343 elem->next = env->head; 2344 elem->log_pos = env->log.end_pos; 2345 env->head = elem; 2346 env->stack_size++; 2347 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2348 verbose(env, 2349 "The sequence of %d jumps is too complex for async cb.\n", 2350 env->stack_size); 2351 goto err; 2352 } 2353 /* Unlike push_stack() do not copy_verifier_state(). 2354 * The caller state doesn't matter. 2355 * This is async callback. It starts in a fresh stack. 2356 * Initialize it similar to do_check_common(). 2357 */ 2358 elem->st.branches = 1; 2359 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2360 if (!frame) 2361 goto err; 2362 init_func_state(env, frame, 2363 BPF_MAIN_FUNC /* callsite */, 2364 0 /* frameno within this callchain */, 2365 subprog /* subprog number within this prog */); 2366 elem->st.frame[0] = frame; 2367 return &elem->st; 2368 err: 2369 free_verifier_state(env->cur_state, true); 2370 env->cur_state = NULL; 2371 /* pop all elements and return */ 2372 while (!pop_stack(env, NULL, NULL, false)); 2373 return NULL; 2374 } 2375 2376 2377 enum reg_arg_type { 2378 SRC_OP, /* register is used as source operand */ 2379 DST_OP, /* register is used as destination operand */ 2380 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2381 }; 2382 2383 static int cmp_subprogs(const void *a, const void *b) 2384 { 2385 return ((struct bpf_subprog_info *)a)->start - 2386 ((struct bpf_subprog_info *)b)->start; 2387 } 2388 2389 static int find_subprog(struct bpf_verifier_env *env, int off) 2390 { 2391 struct bpf_subprog_info *p; 2392 2393 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2394 sizeof(env->subprog_info[0]), cmp_subprogs); 2395 if (!p) 2396 return -ENOENT; 2397 return p - env->subprog_info; 2398 2399 } 2400 2401 static int add_subprog(struct bpf_verifier_env *env, int off) 2402 { 2403 int insn_cnt = env->prog->len; 2404 int ret; 2405 2406 if (off >= insn_cnt || off < 0) { 2407 verbose(env, "call to invalid destination\n"); 2408 return -EINVAL; 2409 } 2410 ret = find_subprog(env, off); 2411 if (ret >= 0) 2412 return ret; 2413 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2414 verbose(env, "too many subprograms\n"); 2415 return -E2BIG; 2416 } 2417 /* determine subprog starts. The end is one before the next starts */ 2418 env->subprog_info[env->subprog_cnt++].start = off; 2419 sort(env->subprog_info, env->subprog_cnt, 2420 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2421 return env->subprog_cnt - 1; 2422 } 2423 2424 #define MAX_KFUNC_DESCS 256 2425 #define MAX_KFUNC_BTFS 256 2426 2427 struct bpf_kfunc_desc { 2428 struct btf_func_model func_model; 2429 u32 func_id; 2430 s32 imm; 2431 u16 offset; 2432 unsigned long addr; 2433 }; 2434 2435 struct bpf_kfunc_btf { 2436 struct btf *btf; 2437 struct module *module; 2438 u16 offset; 2439 }; 2440 2441 struct bpf_kfunc_desc_tab { 2442 /* Sorted by func_id (BTF ID) and offset (fd_array offset) during 2443 * verification. JITs do lookups by bpf_insn, where func_id may not be 2444 * available, therefore at the end of verification do_misc_fixups() 2445 * sorts this by imm and offset. 2446 */ 2447 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2448 u32 nr_descs; 2449 }; 2450 2451 struct bpf_kfunc_btf_tab { 2452 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2453 u32 nr_descs; 2454 }; 2455 2456 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2457 { 2458 const struct bpf_kfunc_desc *d0 = a; 2459 const struct bpf_kfunc_desc *d1 = b; 2460 2461 /* func_id is not greater than BTF_MAX_TYPE */ 2462 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2463 } 2464 2465 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2466 { 2467 const struct bpf_kfunc_btf *d0 = a; 2468 const struct bpf_kfunc_btf *d1 = b; 2469 2470 return d0->offset - d1->offset; 2471 } 2472 2473 static const struct bpf_kfunc_desc * 2474 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2475 { 2476 struct bpf_kfunc_desc desc = { 2477 .func_id = func_id, 2478 .offset = offset, 2479 }; 2480 struct bpf_kfunc_desc_tab *tab; 2481 2482 tab = prog->aux->kfunc_tab; 2483 return bsearch(&desc, tab->descs, tab->nr_descs, 2484 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2485 } 2486 2487 int bpf_get_kfunc_addr(const struct bpf_prog *prog, u32 func_id, 2488 u16 btf_fd_idx, u8 **func_addr) 2489 { 2490 const struct bpf_kfunc_desc *desc; 2491 2492 desc = find_kfunc_desc(prog, func_id, btf_fd_idx); 2493 if (!desc) 2494 return -EFAULT; 2495 2496 *func_addr = (u8 *)desc->addr; 2497 return 0; 2498 } 2499 2500 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2501 s16 offset) 2502 { 2503 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2504 struct bpf_kfunc_btf_tab *tab; 2505 struct bpf_kfunc_btf *b; 2506 struct module *mod; 2507 struct btf *btf; 2508 int btf_fd; 2509 2510 tab = env->prog->aux->kfunc_btf_tab; 2511 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2512 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2513 if (!b) { 2514 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2515 verbose(env, "too many different module BTFs\n"); 2516 return ERR_PTR(-E2BIG); 2517 } 2518 2519 if (bpfptr_is_null(env->fd_array)) { 2520 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2521 return ERR_PTR(-EPROTO); 2522 } 2523 2524 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2525 offset * sizeof(btf_fd), 2526 sizeof(btf_fd))) 2527 return ERR_PTR(-EFAULT); 2528 2529 btf = btf_get_by_fd(btf_fd); 2530 if (IS_ERR(btf)) { 2531 verbose(env, "invalid module BTF fd specified\n"); 2532 return btf; 2533 } 2534 2535 if (!btf_is_module(btf)) { 2536 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2537 btf_put(btf); 2538 return ERR_PTR(-EINVAL); 2539 } 2540 2541 mod = btf_try_get_module(btf); 2542 if (!mod) { 2543 btf_put(btf); 2544 return ERR_PTR(-ENXIO); 2545 } 2546 2547 b = &tab->descs[tab->nr_descs++]; 2548 b->btf = btf; 2549 b->module = mod; 2550 b->offset = offset; 2551 2552 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2553 kfunc_btf_cmp_by_off, NULL); 2554 } 2555 return b->btf; 2556 } 2557 2558 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2559 { 2560 if (!tab) 2561 return; 2562 2563 while (tab->nr_descs--) { 2564 module_put(tab->descs[tab->nr_descs].module); 2565 btf_put(tab->descs[tab->nr_descs].btf); 2566 } 2567 kfree(tab); 2568 } 2569 2570 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2571 { 2572 if (offset) { 2573 if (offset < 0) { 2574 /* In the future, this can be allowed to increase limit 2575 * of fd index into fd_array, interpreted as u16. 2576 */ 2577 verbose(env, "negative offset disallowed for kernel module function call\n"); 2578 return ERR_PTR(-EINVAL); 2579 } 2580 2581 return __find_kfunc_desc_btf(env, offset); 2582 } 2583 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2584 } 2585 2586 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2587 { 2588 const struct btf_type *func, *func_proto; 2589 struct bpf_kfunc_btf_tab *btf_tab; 2590 struct bpf_kfunc_desc_tab *tab; 2591 struct bpf_prog_aux *prog_aux; 2592 struct bpf_kfunc_desc *desc; 2593 const char *func_name; 2594 struct btf *desc_btf; 2595 unsigned long call_imm; 2596 unsigned long addr; 2597 int err; 2598 2599 prog_aux = env->prog->aux; 2600 tab = prog_aux->kfunc_tab; 2601 btf_tab = prog_aux->kfunc_btf_tab; 2602 if (!tab) { 2603 if (!btf_vmlinux) { 2604 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2605 return -ENOTSUPP; 2606 } 2607 2608 if (!env->prog->jit_requested) { 2609 verbose(env, "JIT is required for calling kernel function\n"); 2610 return -ENOTSUPP; 2611 } 2612 2613 if (!bpf_jit_supports_kfunc_call()) { 2614 verbose(env, "JIT does not support calling kernel function\n"); 2615 return -ENOTSUPP; 2616 } 2617 2618 if (!env->prog->gpl_compatible) { 2619 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2620 return -EINVAL; 2621 } 2622 2623 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2624 if (!tab) 2625 return -ENOMEM; 2626 prog_aux->kfunc_tab = tab; 2627 } 2628 2629 /* func_id == 0 is always invalid, but instead of returning an error, be 2630 * conservative and wait until the code elimination pass before returning 2631 * error, so that invalid calls that get pruned out can be in BPF programs 2632 * loaded from userspace. It is also required that offset be untouched 2633 * for such calls. 2634 */ 2635 if (!func_id && !offset) 2636 return 0; 2637 2638 if (!btf_tab && offset) { 2639 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2640 if (!btf_tab) 2641 return -ENOMEM; 2642 prog_aux->kfunc_btf_tab = btf_tab; 2643 } 2644 2645 desc_btf = find_kfunc_desc_btf(env, offset); 2646 if (IS_ERR(desc_btf)) { 2647 verbose(env, "failed to find BTF for kernel function\n"); 2648 return PTR_ERR(desc_btf); 2649 } 2650 2651 if (find_kfunc_desc(env->prog, func_id, offset)) 2652 return 0; 2653 2654 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2655 verbose(env, "too many different kernel function calls\n"); 2656 return -E2BIG; 2657 } 2658 2659 func = btf_type_by_id(desc_btf, func_id); 2660 if (!func || !btf_type_is_func(func)) { 2661 verbose(env, "kernel btf_id %u is not a function\n", 2662 func_id); 2663 return -EINVAL; 2664 } 2665 func_proto = btf_type_by_id(desc_btf, func->type); 2666 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2667 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2668 func_id); 2669 return -EINVAL; 2670 } 2671 2672 func_name = btf_name_by_offset(desc_btf, func->name_off); 2673 addr = kallsyms_lookup_name(func_name); 2674 if (!addr) { 2675 verbose(env, "cannot find address for kernel function %s\n", 2676 func_name); 2677 return -EINVAL; 2678 } 2679 specialize_kfunc(env, func_id, offset, &addr); 2680 2681 if (bpf_jit_supports_far_kfunc_call()) { 2682 call_imm = func_id; 2683 } else { 2684 call_imm = BPF_CALL_IMM(addr); 2685 /* Check whether the relative offset overflows desc->imm */ 2686 if ((unsigned long)(s32)call_imm != call_imm) { 2687 verbose(env, "address of kernel function %s is out of range\n", 2688 func_name); 2689 return -EINVAL; 2690 } 2691 } 2692 2693 if (bpf_dev_bound_kfunc_id(func_id)) { 2694 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2695 if (err) 2696 return err; 2697 } 2698 2699 desc = &tab->descs[tab->nr_descs++]; 2700 desc->func_id = func_id; 2701 desc->imm = call_imm; 2702 desc->offset = offset; 2703 desc->addr = addr; 2704 err = btf_distill_func_proto(&env->log, desc_btf, 2705 func_proto, func_name, 2706 &desc->func_model); 2707 if (!err) 2708 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2709 kfunc_desc_cmp_by_id_off, NULL); 2710 return err; 2711 } 2712 2713 static int kfunc_desc_cmp_by_imm_off(const void *a, const void *b) 2714 { 2715 const struct bpf_kfunc_desc *d0 = a; 2716 const struct bpf_kfunc_desc *d1 = b; 2717 2718 if (d0->imm != d1->imm) 2719 return d0->imm < d1->imm ? -1 : 1; 2720 if (d0->offset != d1->offset) 2721 return d0->offset < d1->offset ? -1 : 1; 2722 return 0; 2723 } 2724 2725 static void sort_kfunc_descs_by_imm_off(struct bpf_prog *prog) 2726 { 2727 struct bpf_kfunc_desc_tab *tab; 2728 2729 tab = prog->aux->kfunc_tab; 2730 if (!tab) 2731 return; 2732 2733 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2734 kfunc_desc_cmp_by_imm_off, NULL); 2735 } 2736 2737 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2738 { 2739 return !!prog->aux->kfunc_tab; 2740 } 2741 2742 const struct btf_func_model * 2743 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2744 const struct bpf_insn *insn) 2745 { 2746 const struct bpf_kfunc_desc desc = { 2747 .imm = insn->imm, 2748 .offset = insn->off, 2749 }; 2750 const struct bpf_kfunc_desc *res; 2751 struct bpf_kfunc_desc_tab *tab; 2752 2753 tab = prog->aux->kfunc_tab; 2754 res = bsearch(&desc, tab->descs, tab->nr_descs, 2755 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm_off); 2756 2757 return res ? &res->func_model : NULL; 2758 } 2759 2760 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2761 { 2762 struct bpf_subprog_info *subprog = env->subprog_info; 2763 struct bpf_insn *insn = env->prog->insnsi; 2764 int i, ret, insn_cnt = env->prog->len; 2765 2766 /* Add entry function. */ 2767 ret = add_subprog(env, 0); 2768 if (ret) 2769 return ret; 2770 2771 for (i = 0; i < insn_cnt; i++, insn++) { 2772 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2773 !bpf_pseudo_kfunc_call(insn)) 2774 continue; 2775 2776 if (!env->bpf_capable) { 2777 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2778 return -EPERM; 2779 } 2780 2781 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2782 ret = add_subprog(env, i + insn->imm + 1); 2783 else 2784 ret = add_kfunc_call(env, insn->imm, insn->off); 2785 2786 if (ret < 0) 2787 return ret; 2788 } 2789 2790 /* Add a fake 'exit' subprog which could simplify subprog iteration 2791 * logic. 'subprog_cnt' should not be increased. 2792 */ 2793 subprog[env->subprog_cnt].start = insn_cnt; 2794 2795 if (env->log.level & BPF_LOG_LEVEL2) 2796 for (i = 0; i < env->subprog_cnt; i++) 2797 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2798 2799 return 0; 2800 } 2801 2802 static int check_subprogs(struct bpf_verifier_env *env) 2803 { 2804 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2805 struct bpf_subprog_info *subprog = env->subprog_info; 2806 struct bpf_insn *insn = env->prog->insnsi; 2807 int insn_cnt = env->prog->len; 2808 2809 /* now check that all jumps are within the same subprog */ 2810 subprog_start = subprog[cur_subprog].start; 2811 subprog_end = subprog[cur_subprog + 1].start; 2812 for (i = 0; i < insn_cnt; i++) { 2813 u8 code = insn[i].code; 2814 2815 if (code == (BPF_JMP | BPF_CALL) && 2816 insn[i].src_reg == 0 && 2817 insn[i].imm == BPF_FUNC_tail_call) 2818 subprog[cur_subprog].has_tail_call = true; 2819 if (BPF_CLASS(code) == BPF_LD && 2820 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2821 subprog[cur_subprog].has_ld_abs = true; 2822 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2823 goto next; 2824 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2825 goto next; 2826 off = i + insn[i].off + 1; 2827 if (off < subprog_start || off >= subprog_end) { 2828 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2829 return -EINVAL; 2830 } 2831 next: 2832 if (i == subprog_end - 1) { 2833 /* to avoid fall-through from one subprog into another 2834 * the last insn of the subprog should be either exit 2835 * or unconditional jump back 2836 */ 2837 if (code != (BPF_JMP | BPF_EXIT) && 2838 code != (BPF_JMP | BPF_JA)) { 2839 verbose(env, "last insn is not an exit or jmp\n"); 2840 return -EINVAL; 2841 } 2842 subprog_start = subprog_end; 2843 cur_subprog++; 2844 if (cur_subprog < env->subprog_cnt) 2845 subprog_end = subprog[cur_subprog + 1].start; 2846 } 2847 } 2848 return 0; 2849 } 2850 2851 /* Parentage chain of this register (or stack slot) should take care of all 2852 * issues like callee-saved registers, stack slot allocation time, etc. 2853 */ 2854 static int mark_reg_read(struct bpf_verifier_env *env, 2855 const struct bpf_reg_state *state, 2856 struct bpf_reg_state *parent, u8 flag) 2857 { 2858 bool writes = parent == state->parent; /* Observe write marks */ 2859 int cnt = 0; 2860 2861 while (parent) { 2862 /* if read wasn't screened by an earlier write ... */ 2863 if (writes && state->live & REG_LIVE_WRITTEN) 2864 break; 2865 if (parent->live & REG_LIVE_DONE) { 2866 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2867 reg_type_str(env, parent->type), 2868 parent->var_off.value, parent->off); 2869 return -EFAULT; 2870 } 2871 /* The first condition is more likely to be true than the 2872 * second, checked it first. 2873 */ 2874 if ((parent->live & REG_LIVE_READ) == flag || 2875 parent->live & REG_LIVE_READ64) 2876 /* The parentage chain never changes and 2877 * this parent was already marked as LIVE_READ. 2878 * There is no need to keep walking the chain again and 2879 * keep re-marking all parents as LIVE_READ. 2880 * This case happens when the same register is read 2881 * multiple times without writes into it in-between. 2882 * Also, if parent has the stronger REG_LIVE_READ64 set, 2883 * then no need to set the weak REG_LIVE_READ32. 2884 */ 2885 break; 2886 /* ... then we depend on parent's value */ 2887 parent->live |= flag; 2888 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 2889 if (flag == REG_LIVE_READ64) 2890 parent->live &= ~REG_LIVE_READ32; 2891 state = parent; 2892 parent = state->parent; 2893 writes = true; 2894 cnt++; 2895 } 2896 2897 if (env->longest_mark_read_walk < cnt) 2898 env->longest_mark_read_walk = cnt; 2899 return 0; 2900 } 2901 2902 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 2903 { 2904 struct bpf_func_state *state = func(env, reg); 2905 int spi, ret; 2906 2907 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 2908 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 2909 * check_kfunc_call. 2910 */ 2911 if (reg->type == CONST_PTR_TO_DYNPTR) 2912 return 0; 2913 spi = dynptr_get_spi(env, reg); 2914 if (spi < 0) 2915 return spi; 2916 /* Caller ensures dynptr is valid and initialized, which means spi is in 2917 * bounds and spi is the first dynptr slot. Simply mark stack slot as 2918 * read. 2919 */ 2920 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 2921 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 2922 if (ret) 2923 return ret; 2924 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 2925 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 2926 } 2927 2928 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 2929 int spi, int nr_slots) 2930 { 2931 struct bpf_func_state *state = func(env, reg); 2932 int err, i; 2933 2934 for (i = 0; i < nr_slots; i++) { 2935 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 2936 2937 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 2938 if (err) 2939 return err; 2940 2941 mark_stack_slot_scratched(env, spi - i); 2942 } 2943 2944 return 0; 2945 } 2946 2947 /* This function is supposed to be used by the following 32-bit optimization 2948 * code only. It returns TRUE if the source or destination register operates 2949 * on 64-bit, otherwise return FALSE. 2950 */ 2951 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 2952 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 2953 { 2954 u8 code, class, op; 2955 2956 code = insn->code; 2957 class = BPF_CLASS(code); 2958 op = BPF_OP(code); 2959 if (class == BPF_JMP) { 2960 /* BPF_EXIT for "main" will reach here. Return TRUE 2961 * conservatively. 2962 */ 2963 if (op == BPF_EXIT) 2964 return true; 2965 if (op == BPF_CALL) { 2966 /* BPF to BPF call will reach here because of marking 2967 * caller saved clobber with DST_OP_NO_MARK for which we 2968 * don't care the register def because they are anyway 2969 * marked as NOT_INIT already. 2970 */ 2971 if (insn->src_reg == BPF_PSEUDO_CALL) 2972 return false; 2973 /* Helper call will reach here because of arg type 2974 * check, conservatively return TRUE. 2975 */ 2976 if (t == SRC_OP) 2977 return true; 2978 2979 return false; 2980 } 2981 } 2982 2983 if (class == BPF_ALU64 || class == BPF_JMP || 2984 /* BPF_END always use BPF_ALU class. */ 2985 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 2986 return true; 2987 2988 if (class == BPF_ALU || class == BPF_JMP32) 2989 return false; 2990 2991 if (class == BPF_LDX) { 2992 if (t != SRC_OP) 2993 return BPF_SIZE(code) == BPF_DW; 2994 /* LDX source must be ptr. */ 2995 return true; 2996 } 2997 2998 if (class == BPF_STX) { 2999 /* BPF_STX (including atomic variants) has multiple source 3000 * operands, one of which is a ptr. Check whether the caller is 3001 * asking about it. 3002 */ 3003 if (t == SRC_OP && reg->type != SCALAR_VALUE) 3004 return true; 3005 return BPF_SIZE(code) == BPF_DW; 3006 } 3007 3008 if (class == BPF_LD) { 3009 u8 mode = BPF_MODE(code); 3010 3011 /* LD_IMM64 */ 3012 if (mode == BPF_IMM) 3013 return true; 3014 3015 /* Both LD_IND and LD_ABS return 32-bit data. */ 3016 if (t != SRC_OP) 3017 return false; 3018 3019 /* Implicit ctx ptr. */ 3020 if (regno == BPF_REG_6) 3021 return true; 3022 3023 /* Explicit source could be any width. */ 3024 return true; 3025 } 3026 3027 if (class == BPF_ST) 3028 /* The only source register for BPF_ST is a ptr. */ 3029 return true; 3030 3031 /* Conservatively return true at default. */ 3032 return true; 3033 } 3034 3035 /* Return the regno defined by the insn, or -1. */ 3036 static int insn_def_regno(const struct bpf_insn *insn) 3037 { 3038 switch (BPF_CLASS(insn->code)) { 3039 case BPF_JMP: 3040 case BPF_JMP32: 3041 case BPF_ST: 3042 return -1; 3043 case BPF_STX: 3044 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3045 (insn->imm & BPF_FETCH)) { 3046 if (insn->imm == BPF_CMPXCHG) 3047 return BPF_REG_0; 3048 else 3049 return insn->src_reg; 3050 } else { 3051 return -1; 3052 } 3053 default: 3054 return insn->dst_reg; 3055 } 3056 } 3057 3058 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3059 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3060 { 3061 int dst_reg = insn_def_regno(insn); 3062 3063 if (dst_reg == -1) 3064 return false; 3065 3066 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3067 } 3068 3069 static void mark_insn_zext(struct bpf_verifier_env *env, 3070 struct bpf_reg_state *reg) 3071 { 3072 s32 def_idx = reg->subreg_def; 3073 3074 if (def_idx == DEF_NOT_SUBREG) 3075 return; 3076 3077 env->insn_aux_data[def_idx - 1].zext_dst = true; 3078 /* The dst will be zero extended, so won't be sub-register anymore. */ 3079 reg->subreg_def = DEF_NOT_SUBREG; 3080 } 3081 3082 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3083 enum reg_arg_type t) 3084 { 3085 struct bpf_verifier_state *vstate = env->cur_state; 3086 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3087 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3088 struct bpf_reg_state *reg, *regs = state->regs; 3089 bool rw64; 3090 3091 if (regno >= MAX_BPF_REG) { 3092 verbose(env, "R%d is invalid\n", regno); 3093 return -EINVAL; 3094 } 3095 3096 mark_reg_scratched(env, regno); 3097 3098 reg = ®s[regno]; 3099 rw64 = is_reg64(env, insn, regno, reg, t); 3100 if (t == SRC_OP) { 3101 /* check whether register used as source operand can be read */ 3102 if (reg->type == NOT_INIT) { 3103 verbose(env, "R%d !read_ok\n", regno); 3104 return -EACCES; 3105 } 3106 /* We don't need to worry about FP liveness because it's read-only */ 3107 if (regno == BPF_REG_FP) 3108 return 0; 3109 3110 if (rw64) 3111 mark_insn_zext(env, reg); 3112 3113 return mark_reg_read(env, reg, reg->parent, 3114 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3115 } else { 3116 /* check whether register used as dest operand can be written to */ 3117 if (regno == BPF_REG_FP) { 3118 verbose(env, "frame pointer is read only\n"); 3119 return -EACCES; 3120 } 3121 reg->live |= REG_LIVE_WRITTEN; 3122 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3123 if (t == DST_OP) 3124 mark_reg_unknown(env, regs, regno); 3125 } 3126 return 0; 3127 } 3128 3129 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3130 { 3131 env->insn_aux_data[idx].jmp_point = true; 3132 } 3133 3134 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3135 { 3136 return env->insn_aux_data[insn_idx].jmp_point; 3137 } 3138 3139 /* for any branch, call, exit record the history of jmps in the given state */ 3140 static int push_jmp_history(struct bpf_verifier_env *env, 3141 struct bpf_verifier_state *cur) 3142 { 3143 u32 cnt = cur->jmp_history_cnt; 3144 struct bpf_idx_pair *p; 3145 size_t alloc_size; 3146 3147 if (!is_jmp_point(env, env->insn_idx)) 3148 return 0; 3149 3150 cnt++; 3151 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3152 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3153 if (!p) 3154 return -ENOMEM; 3155 p[cnt - 1].idx = env->insn_idx; 3156 p[cnt - 1].prev_idx = env->prev_insn_idx; 3157 cur->jmp_history = p; 3158 cur->jmp_history_cnt = cnt; 3159 return 0; 3160 } 3161 3162 /* Backtrack one insn at a time. If idx is not at the top of recorded 3163 * history then previous instruction came from straight line execution. 3164 */ 3165 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3166 u32 *history) 3167 { 3168 u32 cnt = *history; 3169 3170 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3171 i = st->jmp_history[cnt - 1].prev_idx; 3172 (*history)--; 3173 } else { 3174 i--; 3175 } 3176 return i; 3177 } 3178 3179 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3180 { 3181 const struct btf_type *func; 3182 struct btf *desc_btf; 3183 3184 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3185 return NULL; 3186 3187 desc_btf = find_kfunc_desc_btf(data, insn->off); 3188 if (IS_ERR(desc_btf)) 3189 return "<error>"; 3190 3191 func = btf_type_by_id(desc_btf, insn->imm); 3192 return btf_name_by_offset(desc_btf, func->name_off); 3193 } 3194 3195 static inline void bt_init(struct backtrack_state *bt, u32 frame) 3196 { 3197 bt->frame = frame; 3198 } 3199 3200 static inline void bt_reset(struct backtrack_state *bt) 3201 { 3202 struct bpf_verifier_env *env = bt->env; 3203 3204 memset(bt, 0, sizeof(*bt)); 3205 bt->env = env; 3206 } 3207 3208 static inline u32 bt_empty(struct backtrack_state *bt) 3209 { 3210 u64 mask = 0; 3211 int i; 3212 3213 for (i = 0; i <= bt->frame; i++) 3214 mask |= bt->reg_masks[i] | bt->stack_masks[i]; 3215 3216 return mask == 0; 3217 } 3218 3219 static inline int bt_subprog_enter(struct backtrack_state *bt) 3220 { 3221 if (bt->frame == MAX_CALL_FRAMES - 1) { 3222 verbose(bt->env, "BUG subprog enter from frame %d\n", bt->frame); 3223 WARN_ONCE(1, "verifier backtracking bug"); 3224 return -EFAULT; 3225 } 3226 bt->frame++; 3227 return 0; 3228 } 3229 3230 static inline int bt_subprog_exit(struct backtrack_state *bt) 3231 { 3232 if (bt->frame == 0) { 3233 verbose(bt->env, "BUG subprog exit from frame 0\n"); 3234 WARN_ONCE(1, "verifier backtracking bug"); 3235 return -EFAULT; 3236 } 3237 bt->frame--; 3238 return 0; 3239 } 3240 3241 static inline void bt_set_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3242 { 3243 bt->reg_masks[frame] |= 1 << reg; 3244 } 3245 3246 static inline void bt_clear_frame_reg(struct backtrack_state *bt, u32 frame, u32 reg) 3247 { 3248 bt->reg_masks[frame] &= ~(1 << reg); 3249 } 3250 3251 static inline void bt_set_reg(struct backtrack_state *bt, u32 reg) 3252 { 3253 bt_set_frame_reg(bt, bt->frame, reg); 3254 } 3255 3256 static inline void bt_clear_reg(struct backtrack_state *bt, u32 reg) 3257 { 3258 bt_clear_frame_reg(bt, bt->frame, reg); 3259 } 3260 3261 static inline void bt_set_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3262 { 3263 bt->stack_masks[frame] |= 1ull << slot; 3264 } 3265 3266 static inline void bt_clear_frame_slot(struct backtrack_state *bt, u32 frame, u32 slot) 3267 { 3268 bt->stack_masks[frame] &= ~(1ull << slot); 3269 } 3270 3271 static inline void bt_set_slot(struct backtrack_state *bt, u32 slot) 3272 { 3273 bt_set_frame_slot(bt, bt->frame, slot); 3274 } 3275 3276 static inline void bt_clear_slot(struct backtrack_state *bt, u32 slot) 3277 { 3278 bt_clear_frame_slot(bt, bt->frame, slot); 3279 } 3280 3281 static inline u32 bt_frame_reg_mask(struct backtrack_state *bt, u32 frame) 3282 { 3283 return bt->reg_masks[frame]; 3284 } 3285 3286 static inline u32 bt_reg_mask(struct backtrack_state *bt) 3287 { 3288 return bt->reg_masks[bt->frame]; 3289 } 3290 3291 static inline u64 bt_frame_stack_mask(struct backtrack_state *bt, u32 frame) 3292 { 3293 return bt->stack_masks[frame]; 3294 } 3295 3296 static inline u64 bt_stack_mask(struct backtrack_state *bt) 3297 { 3298 return bt->stack_masks[bt->frame]; 3299 } 3300 3301 static inline bool bt_is_reg_set(struct backtrack_state *bt, u32 reg) 3302 { 3303 return bt->reg_masks[bt->frame] & (1 << reg); 3304 } 3305 3306 static inline bool bt_is_slot_set(struct backtrack_state *bt, u32 slot) 3307 { 3308 return bt->stack_masks[bt->frame] & (1ull << slot); 3309 } 3310 3311 /* format registers bitmask, e.g., "r0,r2,r4" for 0x15 mask */ 3312 static void fmt_reg_mask(char *buf, ssize_t buf_sz, u32 reg_mask) 3313 { 3314 DECLARE_BITMAP(mask, 64); 3315 bool first = true; 3316 int i, n; 3317 3318 buf[0] = '\0'; 3319 3320 bitmap_from_u64(mask, reg_mask); 3321 for_each_set_bit(i, mask, 32) { 3322 n = snprintf(buf, buf_sz, "%sr%d", first ? "" : ",", i); 3323 first = false; 3324 buf += n; 3325 buf_sz -= n; 3326 if (buf_sz < 0) 3327 break; 3328 } 3329 } 3330 /* format stack slots bitmask, e.g., "-8,-24,-40" for 0x15 mask */ 3331 static void fmt_stack_mask(char *buf, ssize_t buf_sz, u64 stack_mask) 3332 { 3333 DECLARE_BITMAP(mask, 64); 3334 bool first = true; 3335 int i, n; 3336 3337 buf[0] = '\0'; 3338 3339 bitmap_from_u64(mask, stack_mask); 3340 for_each_set_bit(i, mask, 64) { 3341 n = snprintf(buf, buf_sz, "%s%d", first ? "" : ",", -(i + 1) * 8); 3342 first = false; 3343 buf += n; 3344 buf_sz -= n; 3345 if (buf_sz < 0) 3346 break; 3347 } 3348 } 3349 3350 /* For given verifier state backtrack_insn() is called from the last insn to 3351 * the first insn. Its purpose is to compute a bitmask of registers and 3352 * stack slots that needs precision in the parent verifier state. 3353 */ 3354 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 3355 struct backtrack_state *bt) 3356 { 3357 const struct bpf_insn_cbs cbs = { 3358 .cb_call = disasm_kfunc_name, 3359 .cb_print = verbose, 3360 .private_data = env, 3361 }; 3362 struct bpf_insn *insn = env->prog->insnsi + idx; 3363 u8 class = BPF_CLASS(insn->code); 3364 u8 opcode = BPF_OP(insn->code); 3365 u8 mode = BPF_MODE(insn->code); 3366 u32 dreg = insn->dst_reg; 3367 u32 sreg = insn->src_reg; 3368 u32 spi; 3369 3370 if (insn->code == 0) 3371 return 0; 3372 if (env->log.level & BPF_LOG_LEVEL2) { 3373 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_reg_mask(bt)); 3374 verbose(env, "mark_precise: frame%d: regs=%s ", 3375 bt->frame, env->tmp_str_buf); 3376 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, bt_stack_mask(bt)); 3377 verbose(env, "stack=%s before ", env->tmp_str_buf); 3378 verbose(env, "%d: ", idx); 3379 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3380 } 3381 3382 if (class == BPF_ALU || class == BPF_ALU64) { 3383 if (!bt_is_reg_set(bt, dreg)) 3384 return 0; 3385 if (opcode == BPF_MOV) { 3386 if (BPF_SRC(insn->code) == BPF_X) { 3387 /* dreg = sreg 3388 * dreg needs precision after this insn 3389 * sreg needs precision before this insn 3390 */ 3391 bt_clear_reg(bt, dreg); 3392 bt_set_reg(bt, sreg); 3393 } else { 3394 /* dreg = K 3395 * dreg needs precision after this insn. 3396 * Corresponding register is already marked 3397 * as precise=true in this verifier state. 3398 * No further markings in parent are necessary 3399 */ 3400 bt_clear_reg(bt, dreg); 3401 } 3402 } else { 3403 if (BPF_SRC(insn->code) == BPF_X) { 3404 /* dreg += sreg 3405 * both dreg and sreg need precision 3406 * before this insn 3407 */ 3408 bt_set_reg(bt, sreg); 3409 } /* else dreg += K 3410 * dreg still needs precision before this insn 3411 */ 3412 } 3413 } else if (class == BPF_LDX) { 3414 if (!bt_is_reg_set(bt, dreg)) 3415 return 0; 3416 bt_clear_reg(bt, dreg); 3417 3418 /* scalars can only be spilled into stack w/o losing precision. 3419 * Load from any other memory can be zero extended. 3420 * The desire to keep that precision is already indicated 3421 * by 'precise' mark in corresponding register of this state. 3422 * No further tracking necessary. 3423 */ 3424 if (insn->src_reg != BPF_REG_FP) 3425 return 0; 3426 3427 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3428 * that [fp - off] slot contains scalar that needs to be 3429 * tracked with precision 3430 */ 3431 spi = (-insn->off - 1) / BPF_REG_SIZE; 3432 if (spi >= 64) { 3433 verbose(env, "BUG spi %d\n", spi); 3434 WARN_ONCE(1, "verifier backtracking bug"); 3435 return -EFAULT; 3436 } 3437 bt_set_slot(bt, spi); 3438 } else if (class == BPF_STX || class == BPF_ST) { 3439 if (bt_is_reg_set(bt, dreg)) 3440 /* stx & st shouldn't be using _scalar_ dst_reg 3441 * to access memory. It means backtracking 3442 * encountered a case of pointer subtraction. 3443 */ 3444 return -ENOTSUPP; 3445 /* scalars can only be spilled into stack */ 3446 if (insn->dst_reg != BPF_REG_FP) 3447 return 0; 3448 spi = (-insn->off - 1) / BPF_REG_SIZE; 3449 if (spi >= 64) { 3450 verbose(env, "BUG spi %d\n", spi); 3451 WARN_ONCE(1, "verifier backtracking bug"); 3452 return -EFAULT; 3453 } 3454 if (!bt_is_slot_set(bt, spi)) 3455 return 0; 3456 bt_clear_slot(bt, spi); 3457 if (class == BPF_STX) 3458 bt_set_reg(bt, sreg); 3459 } else if (class == BPF_JMP || class == BPF_JMP32) { 3460 if (opcode == BPF_CALL) { 3461 if (insn->src_reg == BPF_PSEUDO_CALL) 3462 return -ENOTSUPP; 3463 /* BPF helpers that invoke callback subprogs are 3464 * equivalent to BPF_PSEUDO_CALL above 3465 */ 3466 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm)) 3467 return -ENOTSUPP; 3468 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3469 * catch this error later. Make backtracking conservative 3470 * with ENOTSUPP. 3471 */ 3472 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3473 return -ENOTSUPP; 3474 /* regular helper call sets R0 */ 3475 bt_clear_reg(bt, BPF_REG_0); 3476 if (bt_reg_mask(bt) & BPF_REGMASK_ARGS) { 3477 /* if backtracing was looking for registers R1-R5 3478 * they should have been found already. 3479 */ 3480 verbose(env, "BUG regs %x\n", bt_reg_mask(bt)); 3481 WARN_ONCE(1, "verifier backtracking bug"); 3482 return -EFAULT; 3483 } 3484 } else if (opcode == BPF_EXIT) { 3485 return -ENOTSUPP; 3486 } else if (BPF_SRC(insn->code) == BPF_X) { 3487 if (!bt_is_reg_set(bt, dreg) && !bt_is_reg_set(bt, sreg)) 3488 return 0; 3489 /* dreg <cond> sreg 3490 * Both dreg and sreg need precision before 3491 * this insn. If only sreg was marked precise 3492 * before it would be equally necessary to 3493 * propagate it to dreg. 3494 */ 3495 bt_set_reg(bt, dreg); 3496 bt_set_reg(bt, sreg); 3497 /* else dreg <cond> K 3498 * Only dreg still needs precision before 3499 * this insn, so for the K-based conditional 3500 * there is nothing new to be marked. 3501 */ 3502 } 3503 } else if (class == BPF_LD) { 3504 if (!bt_is_reg_set(bt, dreg)) 3505 return 0; 3506 bt_clear_reg(bt, dreg); 3507 /* It's ld_imm64 or ld_abs or ld_ind. 3508 * For ld_imm64 no further tracking of precision 3509 * into parent is necessary 3510 */ 3511 if (mode == BPF_IND || mode == BPF_ABS) 3512 /* to be analyzed */ 3513 return -ENOTSUPP; 3514 } 3515 return 0; 3516 } 3517 3518 /* the scalar precision tracking algorithm: 3519 * . at the start all registers have precise=false. 3520 * . scalar ranges are tracked as normal through alu and jmp insns. 3521 * . once precise value of the scalar register is used in: 3522 * . ptr + scalar alu 3523 * . if (scalar cond K|scalar) 3524 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3525 * backtrack through the verifier states and mark all registers and 3526 * stack slots with spilled constants that these scalar regisers 3527 * should be precise. 3528 * . during state pruning two registers (or spilled stack slots) 3529 * are equivalent if both are not precise. 3530 * 3531 * Note the verifier cannot simply walk register parentage chain, 3532 * since many different registers and stack slots could have been 3533 * used to compute single precise scalar. 3534 * 3535 * The approach of starting with precise=true for all registers and then 3536 * backtrack to mark a register as not precise when the verifier detects 3537 * that program doesn't care about specific value (e.g., when helper 3538 * takes register as ARG_ANYTHING parameter) is not safe. 3539 * 3540 * It's ok to walk single parentage chain of the verifier states. 3541 * It's possible that this backtracking will go all the way till 1st insn. 3542 * All other branches will be explored for needing precision later. 3543 * 3544 * The backtracking needs to deal with cases like: 3545 * 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) 3546 * r9 -= r8 3547 * r5 = r9 3548 * if r5 > 0x79f goto pc+7 3549 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3550 * r5 += 1 3551 * ... 3552 * call bpf_perf_event_output#25 3553 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3554 * 3555 * and this case: 3556 * r6 = 1 3557 * call foo // uses callee's r6 inside to compute r0 3558 * r0 += r6 3559 * if r0 == 0 goto 3560 * 3561 * to track above reg_mask/stack_mask needs to be independent for each frame. 3562 * 3563 * Also if parent's curframe > frame where backtracking started, 3564 * the verifier need to mark registers in both frames, otherwise callees 3565 * may incorrectly prune callers. This is similar to 3566 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3567 * 3568 * For now backtracking falls back into conservative marking. 3569 */ 3570 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3571 struct bpf_verifier_state *st) 3572 { 3573 struct bpf_func_state *func; 3574 struct bpf_reg_state *reg; 3575 int i, j; 3576 3577 if (env->log.level & BPF_LOG_LEVEL2) { 3578 verbose(env, "mark_precise: frame%d: falling back to forcing all scalars precise\n", 3579 st->curframe); 3580 } 3581 3582 /* big hammer: mark all scalars precise in this path. 3583 * pop_stack may still get !precise scalars. 3584 * We also skip current state and go straight to first parent state, 3585 * because precision markings in current non-checkpointed state are 3586 * not needed. See why in the comment in __mark_chain_precision below. 3587 */ 3588 for (st = st->parent; st; st = st->parent) { 3589 for (i = 0; i <= st->curframe; i++) { 3590 func = st->frame[i]; 3591 for (j = 0; j < BPF_REG_FP; j++) { 3592 reg = &func->regs[j]; 3593 if (reg->type != SCALAR_VALUE || reg->precise) 3594 continue; 3595 reg->precise = true; 3596 if (env->log.level & BPF_LOG_LEVEL2) { 3597 verbose(env, "force_precise: frame%d: forcing r%d to be precise\n", 3598 i, j); 3599 } 3600 } 3601 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3602 if (!is_spilled_reg(&func->stack[j])) 3603 continue; 3604 reg = &func->stack[j].spilled_ptr; 3605 if (reg->type != SCALAR_VALUE || reg->precise) 3606 continue; 3607 reg->precise = true; 3608 if (env->log.level & BPF_LOG_LEVEL2) { 3609 verbose(env, "force_precise: frame%d: forcing fp%d to be precise\n", 3610 i, -(j + 1) * 8); 3611 } 3612 } 3613 } 3614 } 3615 } 3616 3617 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3618 { 3619 struct bpf_func_state *func; 3620 struct bpf_reg_state *reg; 3621 int i, j; 3622 3623 for (i = 0; i <= st->curframe; i++) { 3624 func = st->frame[i]; 3625 for (j = 0; j < BPF_REG_FP; j++) { 3626 reg = &func->regs[j]; 3627 if (reg->type != SCALAR_VALUE) 3628 continue; 3629 reg->precise = false; 3630 } 3631 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3632 if (!is_spilled_reg(&func->stack[j])) 3633 continue; 3634 reg = &func->stack[j].spilled_ptr; 3635 if (reg->type != SCALAR_VALUE) 3636 continue; 3637 reg->precise = false; 3638 } 3639 } 3640 } 3641 3642 /* 3643 * __mark_chain_precision() backtracks BPF program instruction sequence and 3644 * chain of verifier states making sure that register *regno* (if regno >= 0) 3645 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 3646 * SCALARS, as well as any other registers and slots that contribute to 3647 * a tracked state of given registers/stack slots, depending on specific BPF 3648 * assembly instructions (see backtrack_insns() for exact instruction handling 3649 * logic). This backtracking relies on recorded jmp_history and is able to 3650 * traverse entire chain of parent states. This process ends only when all the 3651 * necessary registers/slots and their transitive dependencies are marked as 3652 * precise. 3653 * 3654 * One important and subtle aspect is that precise marks *do not matter* in 3655 * the currently verified state (current state). It is important to understand 3656 * why this is the case. 3657 * 3658 * First, note that current state is the state that is not yet "checkpointed", 3659 * i.e., it is not yet put into env->explored_states, and it has no children 3660 * states as well. It's ephemeral, and can end up either a) being discarded if 3661 * compatible explored state is found at some point or BPF_EXIT instruction is 3662 * reached or b) checkpointed and put into env->explored_states, branching out 3663 * into one or more children states. 3664 * 3665 * In the former case, precise markings in current state are completely 3666 * ignored by state comparison code (see regsafe() for details). Only 3667 * checkpointed ("old") state precise markings are important, and if old 3668 * state's register/slot is precise, regsafe() assumes current state's 3669 * register/slot as precise and checks value ranges exactly and precisely. If 3670 * states turn out to be compatible, current state's necessary precise 3671 * markings and any required parent states' precise markings are enforced 3672 * after the fact with propagate_precision() logic, after the fact. But it's 3673 * important to realize that in this case, even after marking current state 3674 * registers/slots as precise, we immediately discard current state. So what 3675 * actually matters is any of the precise markings propagated into current 3676 * state's parent states, which are always checkpointed (due to b) case above). 3677 * As such, for scenario a) it doesn't matter if current state has precise 3678 * markings set or not. 3679 * 3680 * Now, for the scenario b), checkpointing and forking into child(ren) 3681 * state(s). Note that before current state gets to checkpointing step, any 3682 * processed instruction always assumes precise SCALAR register/slot 3683 * knowledge: if precise value or range is useful to prune jump branch, BPF 3684 * verifier takes this opportunity enthusiastically. Similarly, when 3685 * register's value is used to calculate offset or memory address, exact 3686 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 3687 * what we mentioned above about state comparison ignoring precise markings 3688 * during state comparison, BPF verifier ignores and also assumes precise 3689 * markings *at will* during instruction verification process. But as verifier 3690 * assumes precision, it also propagates any precision dependencies across 3691 * parent states, which are not yet finalized, so can be further restricted 3692 * based on new knowledge gained from restrictions enforced by their children 3693 * states. This is so that once those parent states are finalized, i.e., when 3694 * they have no more active children state, state comparison logic in 3695 * is_state_visited() would enforce strict and precise SCALAR ranges, if 3696 * required for correctness. 3697 * 3698 * To build a bit more intuition, note also that once a state is checkpointed, 3699 * the path we took to get to that state is not important. This is crucial 3700 * property for state pruning. When state is checkpointed and finalized at 3701 * some instruction index, it can be correctly and safely used to "short 3702 * circuit" any *compatible* state that reaches exactly the same instruction 3703 * index. I.e., if we jumped to that instruction from a completely different 3704 * code path than original finalized state was derived from, it doesn't 3705 * matter, current state can be discarded because from that instruction 3706 * forward having a compatible state will ensure we will safely reach the 3707 * exit. States describe preconditions for further exploration, but completely 3708 * forget the history of how we got here. 3709 * 3710 * This also means that even if we needed precise SCALAR range to get to 3711 * finalized state, but from that point forward *that same* SCALAR register is 3712 * never used in a precise context (i.e., it's precise value is not needed for 3713 * correctness), it's correct and safe to mark such register as "imprecise" 3714 * (i.e., precise marking set to false). This is what we rely on when we do 3715 * not set precise marking in current state. If no child state requires 3716 * precision for any given SCALAR register, it's safe to dictate that it can 3717 * be imprecise. If any child state does require this register to be precise, 3718 * we'll mark it precise later retroactively during precise markings 3719 * propagation from child state to parent states. 3720 * 3721 * Skipping precise marking setting in current state is a mild version of 3722 * relying on the above observation. But we can utilize this property even 3723 * more aggressively by proactively forgetting any precise marking in the 3724 * current state (which we inherited from the parent state), right before we 3725 * checkpoint it and branch off into new child state. This is done by 3726 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 3727 * finalized states which help in short circuiting more future states. 3728 */ 3729 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno, 3730 int spi) 3731 { 3732 struct backtrack_state *bt = &env->bt; 3733 struct bpf_verifier_state *st = env->cur_state; 3734 int first_idx = st->first_insn_idx; 3735 int last_idx = env->insn_idx; 3736 struct bpf_func_state *func; 3737 struct bpf_reg_state *reg; 3738 bool skip_first = true; 3739 int i, fr, err; 3740 3741 if (!env->bpf_capable) 3742 return 0; 3743 3744 /* set frame number from which we are starting to backtrack */ 3745 bt_init(bt, frame); 3746 3747 /* Do sanity checks against current state of register and/or stack 3748 * slot, but don't set precise flag in current state, as precision 3749 * tracking in the current state is unnecessary. 3750 */ 3751 func = st->frame[frame]; 3752 if (regno >= 0) { 3753 reg = &func->regs[regno]; 3754 if (reg->type != SCALAR_VALUE) { 3755 WARN_ONCE(1, "backtracing misuse"); 3756 return -EFAULT; 3757 } 3758 bt_set_reg(bt, regno); 3759 } 3760 3761 while (spi >= 0) { 3762 if (!is_spilled_scalar_reg(&func->stack[spi])) 3763 break; 3764 bt_set_slot(bt, spi); 3765 break; 3766 } 3767 3768 if (bt_empty(bt)) 3769 return 0; 3770 3771 for (;;) { 3772 DECLARE_BITMAP(mask, 64); 3773 u32 history = st->jmp_history_cnt; 3774 3775 if (env->log.level & BPF_LOG_LEVEL2) { 3776 verbose(env, "mark_precise: frame%d: last_idx %d first_idx %d\n", 3777 bt->frame, last_idx, first_idx); 3778 } 3779 3780 if (last_idx < 0) { 3781 /* we are at the entry into subprog, which 3782 * is expected for global funcs, but only if 3783 * requested precise registers are R1-R5 3784 * (which are global func's input arguments) 3785 */ 3786 if (st->curframe == 0 && 3787 st->frame[0]->subprogno > 0 && 3788 st->frame[0]->callsite == BPF_MAIN_FUNC && 3789 bt_stack_mask(bt) == 0 && 3790 (bt_reg_mask(bt) & ~BPF_REGMASK_ARGS) == 0) { 3791 bitmap_from_u64(mask, bt_reg_mask(bt)); 3792 for_each_set_bit(i, mask, 32) { 3793 reg = &st->frame[0]->regs[i]; 3794 if (reg->type != SCALAR_VALUE) { 3795 bt_clear_reg(bt, i); 3796 continue; 3797 } 3798 reg->precise = true; 3799 } 3800 return 0; 3801 } 3802 3803 verbose(env, "BUG backtracking func entry subprog %d reg_mask %x stack_mask %llx\n", 3804 st->frame[0]->subprogno, bt_reg_mask(bt), bt_stack_mask(bt)); 3805 WARN_ONCE(1, "verifier backtracking bug"); 3806 return -EFAULT; 3807 } 3808 3809 for (i = last_idx;;) { 3810 if (skip_first) { 3811 err = 0; 3812 skip_first = false; 3813 } else { 3814 err = backtrack_insn(env, i, bt); 3815 } 3816 if (err == -ENOTSUPP) { 3817 mark_all_scalars_precise(env, st); 3818 bt_reset(bt); 3819 return 0; 3820 } else if (err) { 3821 return err; 3822 } 3823 if (bt_empty(bt)) 3824 /* Found assignment(s) into tracked register in this state. 3825 * Since this state is already marked, just return. 3826 * Nothing to be tracked further in the parent state. 3827 */ 3828 return 0; 3829 if (i == first_idx) 3830 break; 3831 i = get_prev_insn_idx(st, i, &history); 3832 if (i >= env->prog->len) { 3833 /* This can happen if backtracking reached insn 0 3834 * and there are still reg_mask or stack_mask 3835 * to backtrack. 3836 * It means the backtracking missed the spot where 3837 * particular register was initialized with a constant. 3838 */ 3839 verbose(env, "BUG backtracking idx %d\n", i); 3840 WARN_ONCE(1, "verifier backtracking bug"); 3841 return -EFAULT; 3842 } 3843 } 3844 st = st->parent; 3845 if (!st) 3846 break; 3847 3848 for (fr = bt->frame; fr >= 0; fr--) { 3849 func = st->frame[fr]; 3850 bitmap_from_u64(mask, bt_frame_reg_mask(bt, fr)); 3851 for_each_set_bit(i, mask, 32) { 3852 reg = &func->regs[i]; 3853 if (reg->type != SCALAR_VALUE) { 3854 bt_clear_frame_reg(bt, fr, i); 3855 continue; 3856 } 3857 if (reg->precise) 3858 bt_clear_frame_reg(bt, fr, i); 3859 else 3860 reg->precise = true; 3861 } 3862 3863 bitmap_from_u64(mask, bt_frame_stack_mask(bt, fr)); 3864 for_each_set_bit(i, mask, 64) { 3865 if (i >= func->allocated_stack / BPF_REG_SIZE) { 3866 /* the sequence of instructions: 3867 * 2: (bf) r3 = r10 3868 * 3: (7b) *(u64 *)(r3 -8) = r0 3869 * 4: (79) r4 = *(u64 *)(r10 -8) 3870 * doesn't contain jmps. It's backtracked 3871 * as a single block. 3872 * During backtracking insn 3 is not recognized as 3873 * stack access, so at the end of backtracking 3874 * stack slot fp-8 is still marked in stack_mask. 3875 * However the parent state may not have accessed 3876 * fp-8 and it's "unallocated" stack space. 3877 * In such case fallback to conservative. 3878 */ 3879 mark_all_scalars_precise(env, st); 3880 bt_reset(bt); 3881 return 0; 3882 } 3883 3884 if (!is_spilled_scalar_reg(&func->stack[i])) { 3885 bt_clear_frame_slot(bt, fr, i); 3886 continue; 3887 } 3888 reg = &func->stack[i].spilled_ptr; 3889 if (reg->precise) 3890 bt_clear_frame_slot(bt, fr, i); 3891 else 3892 reg->precise = true; 3893 } 3894 if (env->log.level & BPF_LOG_LEVEL2) { 3895 fmt_reg_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 3896 bt_frame_reg_mask(bt, fr)); 3897 verbose(env, "mark_precise: frame%d: parent state regs=%s ", 3898 fr, env->tmp_str_buf); 3899 fmt_stack_mask(env->tmp_str_buf, TMP_STR_BUF_LEN, 3900 bt_frame_stack_mask(bt, fr)); 3901 verbose(env, "stack=%s: ", env->tmp_str_buf); 3902 print_verifier_state(env, func, true); 3903 } 3904 } 3905 3906 if (bt_empty(bt)) 3907 break; 3908 3909 last_idx = st->last_insn_idx; 3910 first_idx = st->first_insn_idx; 3911 } 3912 return 0; 3913 } 3914 3915 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3916 { 3917 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1); 3918 } 3919 3920 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno) 3921 { 3922 return __mark_chain_precision(env, frame, regno, -1); 3923 } 3924 3925 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi) 3926 { 3927 return __mark_chain_precision(env, frame, -1, spi); 3928 } 3929 3930 static bool is_spillable_regtype(enum bpf_reg_type type) 3931 { 3932 switch (base_type(type)) { 3933 case PTR_TO_MAP_VALUE: 3934 case PTR_TO_STACK: 3935 case PTR_TO_CTX: 3936 case PTR_TO_PACKET: 3937 case PTR_TO_PACKET_META: 3938 case PTR_TO_PACKET_END: 3939 case PTR_TO_FLOW_KEYS: 3940 case CONST_PTR_TO_MAP: 3941 case PTR_TO_SOCKET: 3942 case PTR_TO_SOCK_COMMON: 3943 case PTR_TO_TCP_SOCK: 3944 case PTR_TO_XDP_SOCK: 3945 case PTR_TO_BTF_ID: 3946 case PTR_TO_BUF: 3947 case PTR_TO_MEM: 3948 case PTR_TO_FUNC: 3949 case PTR_TO_MAP_KEY: 3950 return true; 3951 default: 3952 return false; 3953 } 3954 } 3955 3956 /* Does this register contain a constant zero? */ 3957 static bool register_is_null(struct bpf_reg_state *reg) 3958 { 3959 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 3960 } 3961 3962 static bool register_is_const(struct bpf_reg_state *reg) 3963 { 3964 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 3965 } 3966 3967 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 3968 { 3969 return tnum_is_unknown(reg->var_off) && 3970 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 3971 reg->umin_value == 0 && reg->umax_value == U64_MAX && 3972 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 3973 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 3974 } 3975 3976 static bool register_is_bounded(struct bpf_reg_state *reg) 3977 { 3978 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 3979 } 3980 3981 static bool __is_pointer_value(bool allow_ptr_leaks, 3982 const struct bpf_reg_state *reg) 3983 { 3984 if (allow_ptr_leaks) 3985 return false; 3986 3987 return reg->type != SCALAR_VALUE; 3988 } 3989 3990 /* Copy src state preserving dst->parent and dst->live fields */ 3991 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 3992 { 3993 struct bpf_reg_state *parent = dst->parent; 3994 enum bpf_reg_liveness live = dst->live; 3995 3996 *dst = *src; 3997 dst->parent = parent; 3998 dst->live = live; 3999 } 4000 4001 static void save_register_state(struct bpf_func_state *state, 4002 int spi, struct bpf_reg_state *reg, 4003 int size) 4004 { 4005 int i; 4006 4007 copy_register_state(&state->stack[spi].spilled_ptr, reg); 4008 if (size == BPF_REG_SIZE) 4009 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4010 4011 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 4012 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 4013 4014 /* size < 8 bytes spill */ 4015 for (; i; i--) 4016 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 4017 } 4018 4019 static bool is_bpf_st_mem(struct bpf_insn *insn) 4020 { 4021 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 4022 } 4023 4024 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 4025 * stack boundary and alignment are checked in check_mem_access() 4026 */ 4027 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 4028 /* stack frame we're writing to */ 4029 struct bpf_func_state *state, 4030 int off, int size, int value_regno, 4031 int insn_idx) 4032 { 4033 struct bpf_func_state *cur; /* state of the current function */ 4034 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 4035 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4036 struct bpf_reg_state *reg = NULL; 4037 u32 dst_reg = insn->dst_reg; 4038 4039 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 4040 if (err) 4041 return err; 4042 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 4043 * so it's aligned access and [off, off + size) are within stack limits 4044 */ 4045 if (!env->allow_ptr_leaks && 4046 state->stack[spi].slot_type[0] == STACK_SPILL && 4047 size != BPF_REG_SIZE) { 4048 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 4049 return -EACCES; 4050 } 4051 4052 cur = env->cur_state->frame[env->cur_state->curframe]; 4053 if (value_regno >= 0) 4054 reg = &cur->regs[value_regno]; 4055 if (!env->bypass_spec_v4) { 4056 bool sanitize = reg && is_spillable_regtype(reg->type); 4057 4058 for (i = 0; i < size; i++) { 4059 u8 type = state->stack[spi].slot_type[i]; 4060 4061 if (type != STACK_MISC && type != STACK_ZERO) { 4062 sanitize = true; 4063 break; 4064 } 4065 } 4066 4067 if (sanitize) 4068 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 4069 } 4070 4071 err = destroy_if_dynptr_stack_slot(env, state, spi); 4072 if (err) 4073 return err; 4074 4075 mark_stack_slot_scratched(env, spi); 4076 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 4077 !register_is_null(reg) && env->bpf_capable) { 4078 if (dst_reg != BPF_REG_FP) { 4079 /* The backtracking logic can only recognize explicit 4080 * stack slot address like [fp - 8]. Other spill of 4081 * scalar via different register has to be conservative. 4082 * Backtrack from here and mark all registers as precise 4083 * that contributed into 'reg' being a constant. 4084 */ 4085 err = mark_chain_precision(env, value_regno); 4086 if (err) 4087 return err; 4088 } 4089 save_register_state(state, spi, reg, size); 4090 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 4091 insn->imm != 0 && env->bpf_capable) { 4092 struct bpf_reg_state fake_reg = {}; 4093 4094 __mark_reg_known(&fake_reg, (u32)insn->imm); 4095 fake_reg.type = SCALAR_VALUE; 4096 save_register_state(state, spi, &fake_reg, size); 4097 } else if (reg && is_spillable_regtype(reg->type)) { 4098 /* register containing pointer is being spilled into stack */ 4099 if (size != BPF_REG_SIZE) { 4100 verbose_linfo(env, insn_idx, "; "); 4101 verbose(env, "invalid size of register spill\n"); 4102 return -EACCES; 4103 } 4104 if (state != cur && reg->type == PTR_TO_STACK) { 4105 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 4106 return -EINVAL; 4107 } 4108 save_register_state(state, spi, reg, size); 4109 } else { 4110 u8 type = STACK_MISC; 4111 4112 /* regular write of data into stack destroys any spilled ptr */ 4113 state->stack[spi].spilled_ptr.type = NOT_INIT; 4114 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 4115 if (is_stack_slot_special(&state->stack[spi])) 4116 for (i = 0; i < BPF_REG_SIZE; i++) 4117 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 4118 4119 /* only mark the slot as written if all 8 bytes were written 4120 * otherwise read propagation may incorrectly stop too soon 4121 * when stack slots are partially written. 4122 * This heuristic means that read propagation will be 4123 * conservative, since it will add reg_live_read marks 4124 * to stack slots all the way to first state when programs 4125 * writes+reads less than 8 bytes 4126 */ 4127 if (size == BPF_REG_SIZE) 4128 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 4129 4130 /* when we zero initialize stack slots mark them as such */ 4131 if ((reg && register_is_null(reg)) || 4132 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 4133 /* backtracking doesn't work for STACK_ZERO yet. */ 4134 err = mark_chain_precision(env, value_regno); 4135 if (err) 4136 return err; 4137 type = STACK_ZERO; 4138 } 4139 4140 /* Mark slots affected by this stack write. */ 4141 for (i = 0; i < size; i++) 4142 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 4143 type; 4144 } 4145 return 0; 4146 } 4147 4148 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 4149 * known to contain a variable offset. 4150 * This function checks whether the write is permitted and conservatively 4151 * tracks the effects of the write, considering that each stack slot in the 4152 * dynamic range is potentially written to. 4153 * 4154 * 'off' includes 'regno->off'. 4155 * 'value_regno' can be -1, meaning that an unknown value is being written to 4156 * the stack. 4157 * 4158 * Spilled pointers in range are not marked as written because we don't know 4159 * what's going to be actually written. This means that read propagation for 4160 * future reads cannot be terminated by this write. 4161 * 4162 * For privileged programs, uninitialized stack slots are considered 4163 * initialized by this write (even though we don't know exactly what offsets 4164 * are going to be written to). The idea is that we don't want the verifier to 4165 * reject future reads that access slots written to through variable offsets. 4166 */ 4167 static int check_stack_write_var_off(struct bpf_verifier_env *env, 4168 /* func where register points to */ 4169 struct bpf_func_state *state, 4170 int ptr_regno, int off, int size, 4171 int value_regno, int insn_idx) 4172 { 4173 struct bpf_func_state *cur; /* state of the current function */ 4174 int min_off, max_off; 4175 int i, err; 4176 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 4177 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4178 bool writing_zero = false; 4179 /* set if the fact that we're writing a zero is used to let any 4180 * stack slots remain STACK_ZERO 4181 */ 4182 bool zero_used = false; 4183 4184 cur = env->cur_state->frame[env->cur_state->curframe]; 4185 ptr_reg = &cur->regs[ptr_regno]; 4186 min_off = ptr_reg->smin_value + off; 4187 max_off = ptr_reg->smax_value + off + size; 4188 if (value_regno >= 0) 4189 value_reg = &cur->regs[value_regno]; 4190 if ((value_reg && register_is_null(value_reg)) || 4191 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 4192 writing_zero = true; 4193 4194 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 4195 if (err) 4196 return err; 4197 4198 for (i = min_off; i < max_off; i++) { 4199 int spi; 4200 4201 spi = __get_spi(i); 4202 err = destroy_if_dynptr_stack_slot(env, state, spi); 4203 if (err) 4204 return err; 4205 } 4206 4207 /* Variable offset writes destroy any spilled pointers in range. */ 4208 for (i = min_off; i < max_off; i++) { 4209 u8 new_type, *stype; 4210 int slot, spi; 4211 4212 slot = -i - 1; 4213 spi = slot / BPF_REG_SIZE; 4214 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4215 mark_stack_slot_scratched(env, spi); 4216 4217 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4218 /* Reject the write if range we may write to has not 4219 * been initialized beforehand. If we didn't reject 4220 * here, the ptr status would be erased below (even 4221 * though not all slots are actually overwritten), 4222 * possibly opening the door to leaks. 4223 * 4224 * We do however catch STACK_INVALID case below, and 4225 * only allow reading possibly uninitialized memory 4226 * later for CAP_PERFMON, as the write may not happen to 4227 * that slot. 4228 */ 4229 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4230 insn_idx, i); 4231 return -EINVAL; 4232 } 4233 4234 /* Erase all spilled pointers. */ 4235 state->stack[spi].spilled_ptr.type = NOT_INIT; 4236 4237 /* Update the slot type. */ 4238 new_type = STACK_MISC; 4239 if (writing_zero && *stype == STACK_ZERO) { 4240 new_type = STACK_ZERO; 4241 zero_used = true; 4242 } 4243 /* If the slot is STACK_INVALID, we check whether it's OK to 4244 * pretend that it will be initialized by this write. The slot 4245 * might not actually be written to, and so if we mark it as 4246 * initialized future reads might leak uninitialized memory. 4247 * For privileged programs, we will accept such reads to slots 4248 * that may or may not be written because, if we're reject 4249 * them, the error would be too confusing. 4250 */ 4251 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4252 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4253 insn_idx, i); 4254 return -EINVAL; 4255 } 4256 *stype = new_type; 4257 } 4258 if (zero_used) { 4259 /* backtracking doesn't work for STACK_ZERO yet. */ 4260 err = mark_chain_precision(env, value_regno); 4261 if (err) 4262 return err; 4263 } 4264 return 0; 4265 } 4266 4267 /* When register 'dst_regno' is assigned some values from stack[min_off, 4268 * max_off), we set the register's type according to the types of the 4269 * respective stack slots. If all the stack values are known to be zeros, then 4270 * so is the destination reg. Otherwise, the register is considered to be 4271 * SCALAR. This function does not deal with register filling; the caller must 4272 * ensure that all spilled registers in the stack range have been marked as 4273 * read. 4274 */ 4275 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4276 /* func where src register points to */ 4277 struct bpf_func_state *ptr_state, 4278 int min_off, int max_off, int dst_regno) 4279 { 4280 struct bpf_verifier_state *vstate = env->cur_state; 4281 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4282 int i, slot, spi; 4283 u8 *stype; 4284 int zeros = 0; 4285 4286 for (i = min_off; i < max_off; i++) { 4287 slot = -i - 1; 4288 spi = slot / BPF_REG_SIZE; 4289 mark_stack_slot_scratched(env, spi); 4290 stype = ptr_state->stack[spi].slot_type; 4291 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4292 break; 4293 zeros++; 4294 } 4295 if (zeros == max_off - min_off) { 4296 /* any access_size read into register is zero extended, 4297 * so the whole register == const_zero 4298 */ 4299 __mark_reg_const_zero(&state->regs[dst_regno]); 4300 /* backtracking doesn't support STACK_ZERO yet, 4301 * so mark it precise here, so that later 4302 * backtracking can stop here. 4303 * Backtracking may not need this if this register 4304 * doesn't participate in pointer adjustment. 4305 * Forward propagation of precise flag is not 4306 * necessary either. This mark is only to stop 4307 * backtracking. Any register that contributed 4308 * to const 0 was marked precise before spill. 4309 */ 4310 state->regs[dst_regno].precise = true; 4311 } else { 4312 /* have read misc data from the stack */ 4313 mark_reg_unknown(env, state->regs, dst_regno); 4314 } 4315 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4316 } 4317 4318 /* Read the stack at 'off' and put the results into the register indicated by 4319 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4320 * spilled reg. 4321 * 4322 * 'dst_regno' can be -1, meaning that the read value is not going to a 4323 * register. 4324 * 4325 * The access is assumed to be within the current stack bounds. 4326 */ 4327 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4328 /* func where src register points to */ 4329 struct bpf_func_state *reg_state, 4330 int off, int size, int dst_regno) 4331 { 4332 struct bpf_verifier_state *vstate = env->cur_state; 4333 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4334 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4335 struct bpf_reg_state *reg; 4336 u8 *stype, type; 4337 4338 stype = reg_state->stack[spi].slot_type; 4339 reg = ®_state->stack[spi].spilled_ptr; 4340 4341 mark_stack_slot_scratched(env, spi); 4342 4343 if (is_spilled_reg(®_state->stack[spi])) { 4344 u8 spill_size = 1; 4345 4346 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4347 spill_size++; 4348 4349 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4350 if (reg->type != SCALAR_VALUE) { 4351 verbose_linfo(env, env->insn_idx, "; "); 4352 verbose(env, "invalid size of register fill\n"); 4353 return -EACCES; 4354 } 4355 4356 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4357 if (dst_regno < 0) 4358 return 0; 4359 4360 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4361 /* The earlier check_reg_arg() has decided the 4362 * subreg_def for this insn. Save it first. 4363 */ 4364 s32 subreg_def = state->regs[dst_regno].subreg_def; 4365 4366 copy_register_state(&state->regs[dst_regno], reg); 4367 state->regs[dst_regno].subreg_def = subreg_def; 4368 } else { 4369 for (i = 0; i < size; i++) { 4370 type = stype[(slot - i) % BPF_REG_SIZE]; 4371 if (type == STACK_SPILL) 4372 continue; 4373 if (type == STACK_MISC) 4374 continue; 4375 if (type == STACK_INVALID && env->allow_uninit_stack) 4376 continue; 4377 verbose(env, "invalid read from stack off %d+%d size %d\n", 4378 off, i, size); 4379 return -EACCES; 4380 } 4381 mark_reg_unknown(env, state->regs, dst_regno); 4382 } 4383 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4384 return 0; 4385 } 4386 4387 if (dst_regno >= 0) { 4388 /* restore register state from stack */ 4389 copy_register_state(&state->regs[dst_regno], reg); 4390 /* mark reg as written since spilled pointer state likely 4391 * has its liveness marks cleared by is_state_visited() 4392 * which resets stack/reg liveness for state transitions 4393 */ 4394 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4395 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4396 /* If dst_regno==-1, the caller is asking us whether 4397 * it is acceptable to use this value as a SCALAR_VALUE 4398 * (e.g. for XADD). 4399 * We must not allow unprivileged callers to do that 4400 * with spilled pointers. 4401 */ 4402 verbose(env, "leaking pointer from stack off %d\n", 4403 off); 4404 return -EACCES; 4405 } 4406 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4407 } else { 4408 for (i = 0; i < size; i++) { 4409 type = stype[(slot - i) % BPF_REG_SIZE]; 4410 if (type == STACK_MISC) 4411 continue; 4412 if (type == STACK_ZERO) 4413 continue; 4414 if (type == STACK_INVALID && env->allow_uninit_stack) 4415 continue; 4416 verbose(env, "invalid read from stack off %d+%d size %d\n", 4417 off, i, size); 4418 return -EACCES; 4419 } 4420 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4421 if (dst_regno >= 0) 4422 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4423 } 4424 return 0; 4425 } 4426 4427 enum bpf_access_src { 4428 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4429 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4430 }; 4431 4432 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4433 int regno, int off, int access_size, 4434 bool zero_size_allowed, 4435 enum bpf_access_src type, 4436 struct bpf_call_arg_meta *meta); 4437 4438 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4439 { 4440 return cur_regs(env) + regno; 4441 } 4442 4443 /* Read the stack at 'ptr_regno + off' and put the result into the register 4444 * 'dst_regno'. 4445 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4446 * but not its variable offset. 4447 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4448 * 4449 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4450 * filling registers (i.e. reads of spilled register cannot be detected when 4451 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4452 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4453 * offset; for a fixed offset check_stack_read_fixed_off should be used 4454 * instead. 4455 */ 4456 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4457 int ptr_regno, int off, int size, int dst_regno) 4458 { 4459 /* The state of the source register. */ 4460 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4461 struct bpf_func_state *ptr_state = func(env, reg); 4462 int err; 4463 int min_off, max_off; 4464 4465 /* Note that we pass a NULL meta, so raw access will not be permitted. 4466 */ 4467 err = check_stack_range_initialized(env, ptr_regno, off, size, 4468 false, ACCESS_DIRECT, NULL); 4469 if (err) 4470 return err; 4471 4472 min_off = reg->smin_value + off; 4473 max_off = reg->smax_value + off; 4474 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4475 return 0; 4476 } 4477 4478 /* check_stack_read dispatches to check_stack_read_fixed_off or 4479 * check_stack_read_var_off. 4480 * 4481 * The caller must ensure that the offset falls within the allocated stack 4482 * bounds. 4483 * 4484 * 'dst_regno' is a register which will receive the value from the stack. It 4485 * can be -1, meaning that the read value is not going to a register. 4486 */ 4487 static int check_stack_read(struct bpf_verifier_env *env, 4488 int ptr_regno, int off, int size, 4489 int dst_regno) 4490 { 4491 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4492 struct bpf_func_state *state = func(env, reg); 4493 int err; 4494 /* Some accesses are only permitted with a static offset. */ 4495 bool var_off = !tnum_is_const(reg->var_off); 4496 4497 /* The offset is required to be static when reads don't go to a 4498 * register, in order to not leak pointers (see 4499 * check_stack_read_fixed_off). 4500 */ 4501 if (dst_regno < 0 && var_off) { 4502 char tn_buf[48]; 4503 4504 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4505 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4506 tn_buf, off, size); 4507 return -EACCES; 4508 } 4509 /* Variable offset is prohibited for unprivileged mode for simplicity 4510 * since it requires corresponding support in Spectre masking for stack 4511 * ALU. See also retrieve_ptr_limit(). The check in 4512 * check_stack_access_for_ptr_arithmetic() called by 4513 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4514 * with variable offsets, therefore no check is required here. Further, 4515 * just checking it here would be insufficient as speculative stack 4516 * writes could still lead to unsafe speculative behaviour. 4517 */ 4518 if (!var_off) { 4519 off += reg->var_off.value; 4520 err = check_stack_read_fixed_off(env, state, off, size, 4521 dst_regno); 4522 } else { 4523 /* Variable offset stack reads need more conservative handling 4524 * than fixed offset ones. Note that dst_regno >= 0 on this 4525 * branch. 4526 */ 4527 err = check_stack_read_var_off(env, ptr_regno, off, size, 4528 dst_regno); 4529 } 4530 return err; 4531 } 4532 4533 4534 /* check_stack_write dispatches to check_stack_write_fixed_off or 4535 * check_stack_write_var_off. 4536 * 4537 * 'ptr_regno' is the register used as a pointer into the stack. 4538 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4539 * 'value_regno' is the register whose value we're writing to the stack. It can 4540 * be -1, meaning that we're not writing from a register. 4541 * 4542 * The caller must ensure that the offset falls within the maximum stack size. 4543 */ 4544 static int check_stack_write(struct bpf_verifier_env *env, 4545 int ptr_regno, int off, int size, 4546 int value_regno, int insn_idx) 4547 { 4548 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4549 struct bpf_func_state *state = func(env, reg); 4550 int err; 4551 4552 if (tnum_is_const(reg->var_off)) { 4553 off += reg->var_off.value; 4554 err = check_stack_write_fixed_off(env, state, off, size, 4555 value_regno, insn_idx); 4556 } else { 4557 /* Variable offset stack reads need more conservative handling 4558 * than fixed offset ones. 4559 */ 4560 err = check_stack_write_var_off(env, state, 4561 ptr_regno, off, size, 4562 value_regno, insn_idx); 4563 } 4564 return err; 4565 } 4566 4567 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4568 int off, int size, enum bpf_access_type type) 4569 { 4570 struct bpf_reg_state *regs = cur_regs(env); 4571 struct bpf_map *map = regs[regno].map_ptr; 4572 u32 cap = bpf_map_flags_to_cap(map); 4573 4574 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4575 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 4576 map->value_size, off, size); 4577 return -EACCES; 4578 } 4579 4580 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4581 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 4582 map->value_size, off, size); 4583 return -EACCES; 4584 } 4585 4586 return 0; 4587 } 4588 4589 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4590 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 4591 int off, int size, u32 mem_size, 4592 bool zero_size_allowed) 4593 { 4594 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4595 struct bpf_reg_state *reg; 4596 4597 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4598 return 0; 4599 4600 reg = &cur_regs(env)[regno]; 4601 switch (reg->type) { 4602 case PTR_TO_MAP_KEY: 4603 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4604 mem_size, off, size); 4605 break; 4606 case PTR_TO_MAP_VALUE: 4607 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4608 mem_size, off, size); 4609 break; 4610 case PTR_TO_PACKET: 4611 case PTR_TO_PACKET_META: 4612 case PTR_TO_PACKET_END: 4613 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 4614 off, size, regno, reg->id, off, mem_size); 4615 break; 4616 case PTR_TO_MEM: 4617 default: 4618 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4619 mem_size, off, size); 4620 } 4621 4622 return -EACCES; 4623 } 4624 4625 /* check read/write into a memory region with possible variable offset */ 4626 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 4627 int off, int size, u32 mem_size, 4628 bool zero_size_allowed) 4629 { 4630 struct bpf_verifier_state *vstate = env->cur_state; 4631 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4632 struct bpf_reg_state *reg = &state->regs[regno]; 4633 int err; 4634 4635 /* We may have adjusted the register pointing to memory region, so we 4636 * need to try adding each of min_value and max_value to off 4637 * to make sure our theoretical access will be safe. 4638 * 4639 * The minimum value is only important with signed 4640 * comparisons where we can't assume the floor of a 4641 * value is 0. If we are using signed variables for our 4642 * index'es we need to make sure that whatever we use 4643 * will have a set floor within our range. 4644 */ 4645 if (reg->smin_value < 0 && 4646 (reg->smin_value == S64_MIN || 4647 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 4648 reg->smin_value + off < 0)) { 4649 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4650 regno); 4651 return -EACCES; 4652 } 4653 err = __check_mem_access(env, regno, reg->smin_value + off, size, 4654 mem_size, zero_size_allowed); 4655 if (err) { 4656 verbose(env, "R%d min value is outside of the allowed memory range\n", 4657 regno); 4658 return err; 4659 } 4660 4661 /* If we haven't set a max value then we need to bail since we can't be 4662 * sure we won't do bad things. 4663 * If reg->umax_value + off could overflow, treat that as unbounded too. 4664 */ 4665 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 4666 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 4667 regno); 4668 return -EACCES; 4669 } 4670 err = __check_mem_access(env, regno, reg->umax_value + off, size, 4671 mem_size, zero_size_allowed); 4672 if (err) { 4673 verbose(env, "R%d max value is outside of the allowed memory range\n", 4674 regno); 4675 return err; 4676 } 4677 4678 return 0; 4679 } 4680 4681 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4682 const struct bpf_reg_state *reg, int regno, 4683 bool fixed_off_ok) 4684 { 4685 /* Access to this pointer-typed register or passing it to a helper 4686 * is only allowed in its original, unmodified form. 4687 */ 4688 4689 if (reg->off < 0) { 4690 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 4691 reg_type_str(env, reg->type), regno, reg->off); 4692 return -EACCES; 4693 } 4694 4695 if (!fixed_off_ok && reg->off) { 4696 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 4697 reg_type_str(env, reg->type), regno, reg->off); 4698 return -EACCES; 4699 } 4700 4701 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4702 char tn_buf[48]; 4703 4704 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4705 verbose(env, "variable %s access var_off=%s disallowed\n", 4706 reg_type_str(env, reg->type), tn_buf); 4707 return -EACCES; 4708 } 4709 4710 return 0; 4711 } 4712 4713 int check_ptr_off_reg(struct bpf_verifier_env *env, 4714 const struct bpf_reg_state *reg, int regno) 4715 { 4716 return __check_ptr_off_reg(env, reg, regno, false); 4717 } 4718 4719 static int map_kptr_match_type(struct bpf_verifier_env *env, 4720 struct btf_field *kptr_field, 4721 struct bpf_reg_state *reg, u32 regno) 4722 { 4723 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4724 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4725 const char *reg_name = ""; 4726 4727 /* Only unreferenced case accepts untrusted pointers */ 4728 if (kptr_field->type == BPF_KPTR_UNREF) 4729 perm_flags |= PTR_UNTRUSTED; 4730 4731 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 4732 goto bad_type; 4733 4734 if (!btf_is_kernel(reg->btf)) { 4735 verbose(env, "R%d must point to kernel BTF\n", regno); 4736 return -EINVAL; 4737 } 4738 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4739 reg_name = btf_type_name(reg->btf, reg->btf_id); 4740 4741 /* For ref_ptr case, release function check should ensure we get one 4742 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4743 * normal store of unreferenced kptr, we must ensure var_off is zero. 4744 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 4745 * reg->off and reg->ref_obj_id are not needed here. 4746 */ 4747 if (__check_ptr_off_reg(env, reg, regno, true)) 4748 return -EACCES; 4749 4750 /* A full type match is needed, as BTF can be vmlinux or module BTF, and 4751 * we also need to take into account the reg->off. 4752 * 4753 * We want to support cases like: 4754 * 4755 * struct foo { 4756 * struct bar br; 4757 * struct baz bz; 4758 * }; 4759 * 4760 * struct foo *v; 4761 * v = func(); // PTR_TO_BTF_ID 4762 * val->foo = v; // reg->off is zero, btf and btf_id match type 4763 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 4764 * // first member type of struct after comparison fails 4765 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 4766 * // to match type 4767 * 4768 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 4769 * is zero. We must also ensure that btf_struct_ids_match does not walk 4770 * the struct to match type against first member of struct, i.e. reject 4771 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4772 * strict mode to true for type match. 4773 */ 4774 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 4775 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4776 kptr_field->type == BPF_KPTR_REF)) 4777 goto bad_type; 4778 return 0; 4779 bad_type: 4780 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4781 reg_type_str(env, reg->type), reg_name); 4782 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4783 if (kptr_field->type == BPF_KPTR_UNREF) 4784 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4785 targ_name); 4786 else 4787 verbose(env, "\n"); 4788 return -EINVAL; 4789 } 4790 4791 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 4792 * can dereference RCU protected pointers and result is PTR_TRUSTED. 4793 */ 4794 static bool in_rcu_cs(struct bpf_verifier_env *env) 4795 { 4796 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable; 4797 } 4798 4799 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 4800 BTF_SET_START(rcu_protected_types) 4801 BTF_ID(struct, prog_test_ref_kfunc) 4802 BTF_ID(struct, cgroup) 4803 BTF_ID(struct, bpf_cpumask) 4804 BTF_ID(struct, task_struct) 4805 BTF_SET_END(rcu_protected_types) 4806 4807 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 4808 { 4809 if (!btf_is_kernel(btf)) 4810 return false; 4811 return btf_id_set_contains(&rcu_protected_types, btf_id); 4812 } 4813 4814 static bool rcu_safe_kptr(const struct btf_field *field) 4815 { 4816 const struct btf_field_kptr *kptr = &field->kptr; 4817 4818 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id); 4819 } 4820 4821 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 4822 int value_regno, int insn_idx, 4823 struct btf_field *kptr_field) 4824 { 4825 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4826 int class = BPF_CLASS(insn->code); 4827 struct bpf_reg_state *val_reg; 4828 4829 /* Things we already checked for in check_map_access and caller: 4830 * - Reject cases where variable offset may touch kptr 4831 * - size of access (must be BPF_DW) 4832 * - tnum_is_const(reg->var_off) 4833 * - kptr_field->offset == off + reg->var_off.value 4834 */ 4835 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4836 if (BPF_MODE(insn->code) != BPF_MEM) { 4837 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4838 return -EACCES; 4839 } 4840 4841 /* We only allow loading referenced kptr, since it will be marked as 4842 * untrusted, similar to unreferenced kptr. 4843 */ 4844 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) { 4845 verbose(env, "store to referenced kptr disallowed\n"); 4846 return -EACCES; 4847 } 4848 4849 if (class == BPF_LDX) { 4850 val_reg = reg_state(env, value_regno); 4851 /* We can simply mark the value_regno receiving the pointer 4852 * value from map as PTR_TO_BTF_ID, with the correct type. 4853 */ 4854 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 4855 kptr_field->kptr.btf_id, 4856 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ? 4857 PTR_MAYBE_NULL | MEM_RCU : 4858 PTR_MAYBE_NULL | PTR_UNTRUSTED); 4859 /* For mark_ptr_or_null_reg */ 4860 val_reg->id = ++env->id_gen; 4861 } else if (class == BPF_STX) { 4862 val_reg = reg_state(env, value_regno); 4863 if (!register_is_null(val_reg) && 4864 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4865 return -EACCES; 4866 } else if (class == BPF_ST) { 4867 if (insn->imm) { 4868 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4869 kptr_field->offset); 4870 return -EACCES; 4871 } 4872 } else { 4873 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4874 return -EACCES; 4875 } 4876 return 0; 4877 } 4878 4879 /* check read/write into a map element with possible variable offset */ 4880 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 4881 int off, int size, bool zero_size_allowed, 4882 enum bpf_access_src src) 4883 { 4884 struct bpf_verifier_state *vstate = env->cur_state; 4885 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4886 struct bpf_reg_state *reg = &state->regs[regno]; 4887 struct bpf_map *map = reg->map_ptr; 4888 struct btf_record *rec; 4889 int err, i; 4890 4891 err = check_mem_region_access(env, regno, off, size, map->value_size, 4892 zero_size_allowed); 4893 if (err) 4894 return err; 4895 4896 if (IS_ERR_OR_NULL(map->record)) 4897 return 0; 4898 rec = map->record; 4899 for (i = 0; i < rec->cnt; i++) { 4900 struct btf_field *field = &rec->fields[i]; 4901 u32 p = field->offset; 4902 4903 /* If any part of a field can be touched by load/store, reject 4904 * this program. To check that [x1, x2) overlaps with [y1, y2), 4905 * it is sufficient to check x1 < y2 && y1 < x2. 4906 */ 4907 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 4908 p < reg->umax_value + off + size) { 4909 switch (field->type) { 4910 case BPF_KPTR_UNREF: 4911 case BPF_KPTR_REF: 4912 if (src != ACCESS_DIRECT) { 4913 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 4914 return -EACCES; 4915 } 4916 if (!tnum_is_const(reg->var_off)) { 4917 verbose(env, "kptr access cannot have variable offset\n"); 4918 return -EACCES; 4919 } 4920 if (p != off + reg->var_off.value) { 4921 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 4922 p, off + reg->var_off.value); 4923 return -EACCES; 4924 } 4925 if (size != bpf_size_to_bytes(BPF_DW)) { 4926 verbose(env, "kptr access size must be BPF_DW\n"); 4927 return -EACCES; 4928 } 4929 break; 4930 default: 4931 verbose(env, "%s cannot be accessed directly by load/store\n", 4932 btf_field_type_name(field->type)); 4933 return -EACCES; 4934 } 4935 } 4936 } 4937 return 0; 4938 } 4939 4940 #define MAX_PACKET_OFF 0xffff 4941 4942 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4943 const struct bpf_call_arg_meta *meta, 4944 enum bpf_access_type t) 4945 { 4946 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4947 4948 switch (prog_type) { 4949 /* Program types only with direct read access go here! */ 4950 case BPF_PROG_TYPE_LWT_IN: 4951 case BPF_PROG_TYPE_LWT_OUT: 4952 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4953 case BPF_PROG_TYPE_SK_REUSEPORT: 4954 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4955 case BPF_PROG_TYPE_CGROUP_SKB: 4956 if (t == BPF_WRITE) 4957 return false; 4958 fallthrough; 4959 4960 /* Program types with direct read + write access go here! */ 4961 case BPF_PROG_TYPE_SCHED_CLS: 4962 case BPF_PROG_TYPE_SCHED_ACT: 4963 case BPF_PROG_TYPE_XDP: 4964 case BPF_PROG_TYPE_LWT_XMIT: 4965 case BPF_PROG_TYPE_SK_SKB: 4966 case BPF_PROG_TYPE_SK_MSG: 4967 if (meta) 4968 return meta->pkt_access; 4969 4970 env->seen_direct_write = true; 4971 return true; 4972 4973 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4974 if (t == BPF_WRITE) 4975 env->seen_direct_write = true; 4976 4977 return true; 4978 4979 default: 4980 return false; 4981 } 4982 } 4983 4984 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 4985 int size, bool zero_size_allowed) 4986 { 4987 struct bpf_reg_state *regs = cur_regs(env); 4988 struct bpf_reg_state *reg = ®s[regno]; 4989 int err; 4990 4991 /* We may have added a variable offset to the packet pointer; but any 4992 * reg->range we have comes after that. We are only checking the fixed 4993 * offset. 4994 */ 4995 4996 /* We don't allow negative numbers, because we aren't tracking enough 4997 * detail to prove they're safe. 4998 */ 4999 if (reg->smin_value < 0) { 5000 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5001 regno); 5002 return -EACCES; 5003 } 5004 5005 err = reg->range < 0 ? -EINVAL : 5006 __check_mem_access(env, regno, off, size, reg->range, 5007 zero_size_allowed); 5008 if (err) { 5009 verbose(env, "R%d offset is outside of the packet\n", regno); 5010 return err; 5011 } 5012 5013 /* __check_mem_access has made sure "off + size - 1" is within u16. 5014 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 5015 * otherwise find_good_pkt_pointers would have refused to set range info 5016 * that __check_mem_access would have rejected this pkt access. 5017 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 5018 */ 5019 env->prog->aux->max_pkt_offset = 5020 max_t(u32, env->prog->aux->max_pkt_offset, 5021 off + reg->umax_value + size - 1); 5022 5023 return err; 5024 } 5025 5026 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 5027 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 5028 enum bpf_access_type t, enum bpf_reg_type *reg_type, 5029 struct btf **btf, u32 *btf_id) 5030 { 5031 struct bpf_insn_access_aux info = { 5032 .reg_type = *reg_type, 5033 .log = &env->log, 5034 }; 5035 5036 if (env->ops->is_valid_access && 5037 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 5038 /* A non zero info.ctx_field_size indicates that this field is a 5039 * candidate for later verifier transformation to load the whole 5040 * field and then apply a mask when accessed with a narrower 5041 * access than actual ctx access size. A zero info.ctx_field_size 5042 * will only allow for whole field access and rejects any other 5043 * type of narrower access. 5044 */ 5045 *reg_type = info.reg_type; 5046 5047 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 5048 *btf = info.btf; 5049 *btf_id = info.btf_id; 5050 } else { 5051 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 5052 } 5053 /* remember the offset of last byte accessed in ctx */ 5054 if (env->prog->aux->max_ctx_offset < off + size) 5055 env->prog->aux->max_ctx_offset = off + size; 5056 return 0; 5057 } 5058 5059 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 5060 return -EACCES; 5061 } 5062 5063 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 5064 int size) 5065 { 5066 if (size < 0 || off < 0 || 5067 (u64)off + size > sizeof(struct bpf_flow_keys)) { 5068 verbose(env, "invalid access to flow keys off=%d size=%d\n", 5069 off, size); 5070 return -EACCES; 5071 } 5072 return 0; 5073 } 5074 5075 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 5076 u32 regno, int off, int size, 5077 enum bpf_access_type t) 5078 { 5079 struct bpf_reg_state *regs = cur_regs(env); 5080 struct bpf_reg_state *reg = ®s[regno]; 5081 struct bpf_insn_access_aux info = {}; 5082 bool valid; 5083 5084 if (reg->smin_value < 0) { 5085 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 5086 regno); 5087 return -EACCES; 5088 } 5089 5090 switch (reg->type) { 5091 case PTR_TO_SOCK_COMMON: 5092 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 5093 break; 5094 case PTR_TO_SOCKET: 5095 valid = bpf_sock_is_valid_access(off, size, t, &info); 5096 break; 5097 case PTR_TO_TCP_SOCK: 5098 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 5099 break; 5100 case PTR_TO_XDP_SOCK: 5101 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 5102 break; 5103 default: 5104 valid = false; 5105 } 5106 5107 5108 if (valid) { 5109 env->insn_aux_data[insn_idx].ctx_field_size = 5110 info.ctx_field_size; 5111 return 0; 5112 } 5113 5114 verbose(env, "R%d invalid %s access off=%d size=%d\n", 5115 regno, reg_type_str(env, reg->type), off, size); 5116 5117 return -EACCES; 5118 } 5119 5120 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 5121 { 5122 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 5123 } 5124 5125 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 5126 { 5127 const struct bpf_reg_state *reg = reg_state(env, regno); 5128 5129 return reg->type == PTR_TO_CTX; 5130 } 5131 5132 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 5133 { 5134 const struct bpf_reg_state *reg = reg_state(env, regno); 5135 5136 return type_is_sk_pointer(reg->type); 5137 } 5138 5139 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 5140 { 5141 const struct bpf_reg_state *reg = reg_state(env, regno); 5142 5143 return type_is_pkt_pointer(reg->type); 5144 } 5145 5146 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 5147 { 5148 const struct bpf_reg_state *reg = reg_state(env, regno); 5149 5150 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 5151 return reg->type == PTR_TO_FLOW_KEYS; 5152 } 5153 5154 static bool is_trusted_reg(const struct bpf_reg_state *reg) 5155 { 5156 /* A referenced register is always trusted. */ 5157 if (reg->ref_obj_id) 5158 return true; 5159 5160 /* If a register is not referenced, it is trusted if it has the 5161 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 5162 * other type modifiers may be safe, but we elect to take an opt-in 5163 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 5164 * not. 5165 * 5166 * Eventually, we should make PTR_TRUSTED the single source of truth 5167 * for whether a register is trusted. 5168 */ 5169 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 5170 !bpf_type_has_unsafe_modifiers(reg->type); 5171 } 5172 5173 static bool is_rcu_reg(const struct bpf_reg_state *reg) 5174 { 5175 return reg->type & MEM_RCU; 5176 } 5177 5178 static void clear_trusted_flags(enum bpf_type_flag *flag) 5179 { 5180 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 5181 } 5182 5183 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 5184 const struct bpf_reg_state *reg, 5185 int off, int size, bool strict) 5186 { 5187 struct tnum reg_off; 5188 int ip_align; 5189 5190 /* Byte size accesses are always allowed. */ 5191 if (!strict || size == 1) 5192 return 0; 5193 5194 /* For platforms that do not have a Kconfig enabling 5195 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 5196 * NET_IP_ALIGN is universally set to '2'. And on platforms 5197 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 5198 * to this code only in strict mode where we want to emulate 5199 * the NET_IP_ALIGN==2 checking. Therefore use an 5200 * unconditional IP align value of '2'. 5201 */ 5202 ip_align = 2; 5203 5204 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5205 if (!tnum_is_aligned(reg_off, size)) { 5206 char tn_buf[48]; 5207 5208 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5209 verbose(env, 5210 "misaligned packet access off %d+%s+%d+%d size %d\n", 5211 ip_align, tn_buf, reg->off, off, size); 5212 return -EACCES; 5213 } 5214 5215 return 0; 5216 } 5217 5218 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5219 const struct bpf_reg_state *reg, 5220 const char *pointer_desc, 5221 int off, int size, bool strict) 5222 { 5223 struct tnum reg_off; 5224 5225 /* Byte size accesses are always allowed. */ 5226 if (!strict || size == 1) 5227 return 0; 5228 5229 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5230 if (!tnum_is_aligned(reg_off, size)) { 5231 char tn_buf[48]; 5232 5233 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5234 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5235 pointer_desc, tn_buf, reg->off, off, size); 5236 return -EACCES; 5237 } 5238 5239 return 0; 5240 } 5241 5242 static int check_ptr_alignment(struct bpf_verifier_env *env, 5243 const struct bpf_reg_state *reg, int off, 5244 int size, bool strict_alignment_once) 5245 { 5246 bool strict = env->strict_alignment || strict_alignment_once; 5247 const char *pointer_desc = ""; 5248 5249 switch (reg->type) { 5250 case PTR_TO_PACKET: 5251 case PTR_TO_PACKET_META: 5252 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5253 * right in front, treat it the very same way. 5254 */ 5255 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5256 case PTR_TO_FLOW_KEYS: 5257 pointer_desc = "flow keys "; 5258 break; 5259 case PTR_TO_MAP_KEY: 5260 pointer_desc = "key "; 5261 break; 5262 case PTR_TO_MAP_VALUE: 5263 pointer_desc = "value "; 5264 break; 5265 case PTR_TO_CTX: 5266 pointer_desc = "context "; 5267 break; 5268 case PTR_TO_STACK: 5269 pointer_desc = "stack "; 5270 /* The stack spill tracking logic in check_stack_write_fixed_off() 5271 * and check_stack_read_fixed_off() relies on stack accesses being 5272 * aligned. 5273 */ 5274 strict = true; 5275 break; 5276 case PTR_TO_SOCKET: 5277 pointer_desc = "sock "; 5278 break; 5279 case PTR_TO_SOCK_COMMON: 5280 pointer_desc = "sock_common "; 5281 break; 5282 case PTR_TO_TCP_SOCK: 5283 pointer_desc = "tcp_sock "; 5284 break; 5285 case PTR_TO_XDP_SOCK: 5286 pointer_desc = "xdp_sock "; 5287 break; 5288 default: 5289 break; 5290 } 5291 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5292 strict); 5293 } 5294 5295 static int update_stack_depth(struct bpf_verifier_env *env, 5296 const struct bpf_func_state *func, 5297 int off) 5298 { 5299 u16 stack = env->subprog_info[func->subprogno].stack_depth; 5300 5301 if (stack >= -off) 5302 return 0; 5303 5304 /* update known max for given subprogram */ 5305 env->subprog_info[func->subprogno].stack_depth = -off; 5306 return 0; 5307 } 5308 5309 /* starting from main bpf function walk all instructions of the function 5310 * and recursively walk all callees that given function can call. 5311 * Ignore jump and exit insns. 5312 * Since recursion is prevented by check_cfg() this algorithm 5313 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5314 */ 5315 static int check_max_stack_depth(struct bpf_verifier_env *env) 5316 { 5317 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 5318 struct bpf_subprog_info *subprog = env->subprog_info; 5319 struct bpf_insn *insn = env->prog->insnsi; 5320 bool tail_call_reachable = false; 5321 int ret_insn[MAX_CALL_FRAMES]; 5322 int ret_prog[MAX_CALL_FRAMES]; 5323 int j; 5324 5325 process_func: 5326 /* protect against potential stack overflow that might happen when 5327 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5328 * depth for such case down to 256 so that the worst case scenario 5329 * would result in 8k stack size (32 which is tailcall limit * 256 = 5330 * 8k). 5331 * 5332 * To get the idea what might happen, see an example: 5333 * func1 -> sub rsp, 128 5334 * subfunc1 -> sub rsp, 256 5335 * tailcall1 -> add rsp, 256 5336 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5337 * subfunc2 -> sub rsp, 64 5338 * subfunc22 -> sub rsp, 128 5339 * tailcall2 -> add rsp, 128 5340 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5341 * 5342 * tailcall will unwind the current stack frame but it will not get rid 5343 * of caller's stack as shown on the example above. 5344 */ 5345 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5346 verbose(env, 5347 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5348 depth); 5349 return -EACCES; 5350 } 5351 /* round up to 32-bytes, since this is granularity 5352 * of interpreter stack size 5353 */ 5354 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5355 if (depth > MAX_BPF_STACK) { 5356 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5357 frame + 1, depth); 5358 return -EACCES; 5359 } 5360 continue_func: 5361 subprog_end = subprog[idx + 1].start; 5362 for (; i < subprog_end; i++) { 5363 int next_insn; 5364 5365 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5366 continue; 5367 /* remember insn and function to return to */ 5368 ret_insn[frame] = i + 1; 5369 ret_prog[frame] = idx; 5370 5371 /* find the callee */ 5372 next_insn = i + insn[i].imm + 1; 5373 idx = find_subprog(env, next_insn); 5374 if (idx < 0) { 5375 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5376 next_insn); 5377 return -EFAULT; 5378 } 5379 if (subprog[idx].is_async_cb) { 5380 if (subprog[idx].has_tail_call) { 5381 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5382 return -EFAULT; 5383 } 5384 /* async callbacks don't increase bpf prog stack size */ 5385 continue; 5386 } 5387 i = next_insn; 5388 5389 if (subprog[idx].has_tail_call) 5390 tail_call_reachable = true; 5391 5392 frame++; 5393 if (frame >= MAX_CALL_FRAMES) { 5394 verbose(env, "the call stack of %d frames is too deep !\n", 5395 frame); 5396 return -E2BIG; 5397 } 5398 goto process_func; 5399 } 5400 /* if tail call got detected across bpf2bpf calls then mark each of the 5401 * currently present subprog frames as tail call reachable subprogs; 5402 * this info will be utilized by JIT so that we will be preserving the 5403 * tail call counter throughout bpf2bpf calls combined with tailcalls 5404 */ 5405 if (tail_call_reachable) 5406 for (j = 0; j < frame; j++) 5407 subprog[ret_prog[j]].tail_call_reachable = true; 5408 if (subprog[0].tail_call_reachable) 5409 env->prog->aux->tail_call_reachable = true; 5410 5411 /* end of for() loop means the last insn of the 'subprog' 5412 * was reached. Doesn't matter whether it was JA or EXIT 5413 */ 5414 if (frame == 0) 5415 return 0; 5416 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5417 frame--; 5418 i = ret_insn[frame]; 5419 idx = ret_prog[frame]; 5420 goto continue_func; 5421 } 5422 5423 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5424 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5425 const struct bpf_insn *insn, int idx) 5426 { 5427 int start = idx + insn->imm + 1, subprog; 5428 5429 subprog = find_subprog(env, start); 5430 if (subprog < 0) { 5431 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5432 start); 5433 return -EFAULT; 5434 } 5435 return env->subprog_info[subprog].stack_depth; 5436 } 5437 #endif 5438 5439 static int __check_buffer_access(struct bpf_verifier_env *env, 5440 const char *buf_info, 5441 const struct bpf_reg_state *reg, 5442 int regno, int off, int size) 5443 { 5444 if (off < 0) { 5445 verbose(env, 5446 "R%d invalid %s buffer access: off=%d, size=%d\n", 5447 regno, buf_info, off, size); 5448 return -EACCES; 5449 } 5450 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5451 char tn_buf[48]; 5452 5453 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5454 verbose(env, 5455 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5456 regno, off, tn_buf); 5457 return -EACCES; 5458 } 5459 5460 return 0; 5461 } 5462 5463 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5464 const struct bpf_reg_state *reg, 5465 int regno, int off, int size) 5466 { 5467 int err; 5468 5469 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5470 if (err) 5471 return err; 5472 5473 if (off + size > env->prog->aux->max_tp_access) 5474 env->prog->aux->max_tp_access = off + size; 5475 5476 return 0; 5477 } 5478 5479 static int check_buffer_access(struct bpf_verifier_env *env, 5480 const struct bpf_reg_state *reg, 5481 int regno, int off, int size, 5482 bool zero_size_allowed, 5483 u32 *max_access) 5484 { 5485 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5486 int err; 5487 5488 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 5489 if (err) 5490 return err; 5491 5492 if (off + size > *max_access) 5493 *max_access = off + size; 5494 5495 return 0; 5496 } 5497 5498 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5499 static void zext_32_to_64(struct bpf_reg_state *reg) 5500 { 5501 reg->var_off = tnum_subreg(reg->var_off); 5502 __reg_assign_32_into_64(reg); 5503 } 5504 5505 /* truncate register to smaller size (in bytes) 5506 * must be called with size < BPF_REG_SIZE 5507 */ 5508 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5509 { 5510 u64 mask; 5511 5512 /* clear high bits in bit representation */ 5513 reg->var_off = tnum_cast(reg->var_off, size); 5514 5515 /* fix arithmetic bounds */ 5516 mask = ((u64)1 << (size * 8)) - 1; 5517 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 5518 reg->umin_value &= mask; 5519 reg->umax_value &= mask; 5520 } else { 5521 reg->umin_value = 0; 5522 reg->umax_value = mask; 5523 } 5524 reg->smin_value = reg->umin_value; 5525 reg->smax_value = reg->umax_value; 5526 5527 /* If size is smaller than 32bit register the 32bit register 5528 * values are also truncated so we push 64-bit bounds into 5529 * 32-bit bounds. Above were truncated < 32-bits already. 5530 */ 5531 if (size >= 4) 5532 return; 5533 __reg_combine_64_into_32(reg); 5534 } 5535 5536 static bool bpf_map_is_rdonly(const struct bpf_map *map) 5537 { 5538 /* A map is considered read-only if the following condition are true: 5539 * 5540 * 1) BPF program side cannot change any of the map content. The 5541 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5542 * and was set at map creation time. 5543 * 2) The map value(s) have been initialized from user space by a 5544 * loader and then "frozen", such that no new map update/delete 5545 * operations from syscall side are possible for the rest of 5546 * the map's lifetime from that point onwards. 5547 * 3) Any parallel/pending map update/delete operations from syscall 5548 * side have been completed. Only after that point, it's safe to 5549 * assume that map value(s) are immutable. 5550 */ 5551 return (map->map_flags & BPF_F_RDONLY_PROG) && 5552 READ_ONCE(map->frozen) && 5553 !bpf_map_write_active(map); 5554 } 5555 5556 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 5557 { 5558 void *ptr; 5559 u64 addr; 5560 int err; 5561 5562 err = map->ops->map_direct_value_addr(map, &addr, off); 5563 if (err) 5564 return err; 5565 ptr = (void *)(long)addr + off; 5566 5567 switch (size) { 5568 case sizeof(u8): 5569 *val = (u64)*(u8 *)ptr; 5570 break; 5571 case sizeof(u16): 5572 *val = (u64)*(u16 *)ptr; 5573 break; 5574 case sizeof(u32): 5575 *val = (u64)*(u32 *)ptr; 5576 break; 5577 case sizeof(u64): 5578 *val = *(u64 *)ptr; 5579 break; 5580 default: 5581 return -EINVAL; 5582 } 5583 return 0; 5584 } 5585 5586 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 5587 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 5588 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 5589 5590 /* 5591 * Allow list few fields as RCU trusted or full trusted. 5592 * This logic doesn't allow mix tagging and will be removed once GCC supports 5593 * btf_type_tag. 5594 */ 5595 5596 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 5597 BTF_TYPE_SAFE_RCU(struct task_struct) { 5598 const cpumask_t *cpus_ptr; 5599 struct css_set __rcu *cgroups; 5600 struct task_struct __rcu *real_parent; 5601 struct task_struct *group_leader; 5602 }; 5603 5604 BTF_TYPE_SAFE_RCU(struct cgroup) { 5605 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 5606 struct kernfs_node *kn; 5607 }; 5608 5609 BTF_TYPE_SAFE_RCU(struct css_set) { 5610 struct cgroup *dfl_cgrp; 5611 }; 5612 5613 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 5614 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 5615 struct file __rcu *exe_file; 5616 }; 5617 5618 /* skb->sk, req->sk are not RCU protected, but we mark them as such 5619 * because bpf prog accessible sockets are SOCK_RCU_FREE. 5620 */ 5621 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 5622 struct sock *sk; 5623 }; 5624 5625 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 5626 struct sock *sk; 5627 }; 5628 5629 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 5630 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 5631 struct seq_file *seq; 5632 }; 5633 5634 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 5635 struct bpf_iter_meta *meta; 5636 struct task_struct *task; 5637 }; 5638 5639 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 5640 struct file *file; 5641 }; 5642 5643 BTF_TYPE_SAFE_TRUSTED(struct file) { 5644 struct inode *f_inode; 5645 }; 5646 5647 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 5648 /* no negative dentry-s in places where bpf can see it */ 5649 struct inode *d_inode; 5650 }; 5651 5652 BTF_TYPE_SAFE_TRUSTED(struct socket) { 5653 struct sock *sk; 5654 }; 5655 5656 static bool type_is_rcu(struct bpf_verifier_env *env, 5657 struct bpf_reg_state *reg, 5658 const char *field_name, u32 btf_id) 5659 { 5660 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 5661 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 5662 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 5663 5664 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 5665 } 5666 5667 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 5668 struct bpf_reg_state *reg, 5669 const char *field_name, u32 btf_id) 5670 { 5671 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 5672 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 5673 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 5674 5675 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 5676 } 5677 5678 static bool type_is_trusted(struct bpf_verifier_env *env, 5679 struct bpf_reg_state *reg, 5680 const char *field_name, u32 btf_id) 5681 { 5682 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 5683 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 5684 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 5685 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 5686 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 5687 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 5688 5689 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 5690 } 5691 5692 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5693 struct bpf_reg_state *regs, 5694 int regno, int off, int size, 5695 enum bpf_access_type atype, 5696 int value_regno) 5697 { 5698 struct bpf_reg_state *reg = regs + regno; 5699 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5700 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5701 const char *field_name = NULL; 5702 enum bpf_type_flag flag = 0; 5703 u32 btf_id = 0; 5704 int ret; 5705 5706 if (!env->allow_ptr_leaks) { 5707 verbose(env, 5708 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5709 tname); 5710 return -EPERM; 5711 } 5712 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5713 verbose(env, 5714 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 5715 tname); 5716 return -EINVAL; 5717 } 5718 if (off < 0) { 5719 verbose(env, 5720 "R%d is ptr_%s invalid negative access: off=%d\n", 5721 regno, tname, off); 5722 return -EACCES; 5723 } 5724 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5725 char tn_buf[48]; 5726 5727 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5728 verbose(env, 5729 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5730 regno, tname, off, tn_buf); 5731 return -EACCES; 5732 } 5733 5734 if (reg->type & MEM_USER) { 5735 verbose(env, 5736 "R%d is ptr_%s access user memory: off=%d\n", 5737 regno, tname, off); 5738 return -EACCES; 5739 } 5740 5741 if (reg->type & MEM_PERCPU) { 5742 verbose(env, 5743 "R%d is ptr_%s access percpu memory: off=%d\n", 5744 regno, tname, off); 5745 return -EACCES; 5746 } 5747 5748 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 5749 if (!btf_is_kernel(reg->btf)) { 5750 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 5751 return -EFAULT; 5752 } 5753 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 5754 } else { 5755 /* Writes are permitted with default btf_struct_access for 5756 * program allocated objects (which always have ref_obj_id > 0), 5757 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 5758 */ 5759 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 5760 verbose(env, "only read is supported\n"); 5761 return -EACCES; 5762 } 5763 5764 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 5765 !reg->ref_obj_id) { 5766 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 5767 return -EFAULT; 5768 } 5769 5770 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 5771 } 5772 5773 if (ret < 0) 5774 return ret; 5775 5776 if (ret != PTR_TO_BTF_ID) { 5777 /* just mark; */ 5778 5779 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 5780 /* If this is an untrusted pointer, all pointers formed by walking it 5781 * also inherit the untrusted flag. 5782 */ 5783 flag = PTR_UNTRUSTED; 5784 5785 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 5786 /* By default any pointer obtained from walking a trusted pointer is no 5787 * longer trusted, unless the field being accessed has explicitly been 5788 * marked as inheriting its parent's state of trust (either full or RCU). 5789 * For example: 5790 * 'cgroups' pointer is untrusted if task->cgroups dereference 5791 * happened in a sleepable program outside of bpf_rcu_read_lock() 5792 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 5793 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 5794 * 5795 * A regular RCU-protected pointer with __rcu tag can also be deemed 5796 * trusted if we are in an RCU CS. Such pointer can be NULL. 5797 */ 5798 if (type_is_trusted(env, reg, field_name, btf_id)) { 5799 flag |= PTR_TRUSTED; 5800 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 5801 if (type_is_rcu(env, reg, field_name, btf_id)) { 5802 /* ignore __rcu tag and mark it MEM_RCU */ 5803 flag |= MEM_RCU; 5804 } else if (flag & MEM_RCU || 5805 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 5806 /* __rcu tagged pointers can be NULL */ 5807 flag |= MEM_RCU | PTR_MAYBE_NULL; 5808 } else if (flag & (MEM_PERCPU | MEM_USER)) { 5809 /* keep as-is */ 5810 } else { 5811 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 5812 clear_trusted_flags(&flag); 5813 } 5814 } else { 5815 /* 5816 * If not in RCU CS or MEM_RCU pointer can be NULL then 5817 * aggressively mark as untrusted otherwise such 5818 * pointers will be plain PTR_TO_BTF_ID without flags 5819 * and will be allowed to be passed into helpers for 5820 * compat reasons. 5821 */ 5822 flag = PTR_UNTRUSTED; 5823 } 5824 } else { 5825 /* Old compat. Deprecated */ 5826 clear_trusted_flags(&flag); 5827 } 5828 5829 if (atype == BPF_READ && value_regno >= 0) 5830 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5831 5832 return 0; 5833 } 5834 5835 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5836 struct bpf_reg_state *regs, 5837 int regno, int off, int size, 5838 enum bpf_access_type atype, 5839 int value_regno) 5840 { 5841 struct bpf_reg_state *reg = regs + regno; 5842 struct bpf_map *map = reg->map_ptr; 5843 struct bpf_reg_state map_reg; 5844 enum bpf_type_flag flag = 0; 5845 const struct btf_type *t; 5846 const char *tname; 5847 u32 btf_id; 5848 int ret; 5849 5850 if (!btf_vmlinux) { 5851 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5852 return -ENOTSUPP; 5853 } 5854 5855 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5856 verbose(env, "map_ptr access not supported for map type %d\n", 5857 map->map_type); 5858 return -ENOTSUPP; 5859 } 5860 5861 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5862 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5863 5864 if (!env->allow_ptr_leaks) { 5865 verbose(env, 5866 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5867 tname); 5868 return -EPERM; 5869 } 5870 5871 if (off < 0) { 5872 verbose(env, "R%d is %s invalid negative access: off=%d\n", 5873 regno, tname, off); 5874 return -EACCES; 5875 } 5876 5877 if (atype != BPF_READ) { 5878 verbose(env, "only read from %s is supported\n", tname); 5879 return -EACCES; 5880 } 5881 5882 /* Simulate access to a PTR_TO_BTF_ID */ 5883 memset(&map_reg, 0, sizeof(map_reg)); 5884 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 5885 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 5886 if (ret < 0) 5887 return ret; 5888 5889 if (value_regno >= 0) 5890 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 5891 5892 return 0; 5893 } 5894 5895 /* Check that the stack access at the given offset is within bounds. The 5896 * maximum valid offset is -1. 5897 * 5898 * The minimum valid offset is -MAX_BPF_STACK for writes, and 5899 * -state->allocated_stack for reads. 5900 */ 5901 static int check_stack_slot_within_bounds(int off, 5902 struct bpf_func_state *state, 5903 enum bpf_access_type t) 5904 { 5905 int min_valid_off; 5906 5907 if (t == BPF_WRITE) 5908 min_valid_off = -MAX_BPF_STACK; 5909 else 5910 min_valid_off = -state->allocated_stack; 5911 5912 if (off < min_valid_off || off > -1) 5913 return -EACCES; 5914 return 0; 5915 } 5916 5917 /* Check that the stack access at 'regno + off' falls within the maximum stack 5918 * bounds. 5919 * 5920 * 'off' includes `regno->offset`, but not its dynamic part (if any). 5921 */ 5922 static int check_stack_access_within_bounds( 5923 struct bpf_verifier_env *env, 5924 int regno, int off, int access_size, 5925 enum bpf_access_src src, enum bpf_access_type type) 5926 { 5927 struct bpf_reg_state *regs = cur_regs(env); 5928 struct bpf_reg_state *reg = regs + regno; 5929 struct bpf_func_state *state = func(env, reg); 5930 int min_off, max_off; 5931 int err; 5932 char *err_extra; 5933 5934 if (src == ACCESS_HELPER) 5935 /* We don't know if helpers are reading or writing (or both). */ 5936 err_extra = " indirect access to"; 5937 else if (type == BPF_READ) 5938 err_extra = " read from"; 5939 else 5940 err_extra = " write to"; 5941 5942 if (tnum_is_const(reg->var_off)) { 5943 min_off = reg->var_off.value + off; 5944 if (access_size > 0) 5945 max_off = min_off + access_size - 1; 5946 else 5947 max_off = min_off; 5948 } else { 5949 if (reg->smax_value >= BPF_MAX_VAR_OFF || 5950 reg->smin_value <= -BPF_MAX_VAR_OFF) { 5951 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 5952 err_extra, regno); 5953 return -EACCES; 5954 } 5955 min_off = reg->smin_value + off; 5956 if (access_size > 0) 5957 max_off = reg->smax_value + off + access_size - 1; 5958 else 5959 max_off = min_off; 5960 } 5961 5962 err = check_stack_slot_within_bounds(min_off, state, type); 5963 if (!err) 5964 err = check_stack_slot_within_bounds(max_off, state, type); 5965 5966 if (err) { 5967 if (tnum_is_const(reg->var_off)) { 5968 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 5969 err_extra, regno, off, access_size); 5970 } else { 5971 char tn_buf[48]; 5972 5973 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5974 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 5975 err_extra, regno, tn_buf, access_size); 5976 } 5977 } 5978 return err; 5979 } 5980 5981 /* check whether memory at (regno + off) is accessible for t = (read | write) 5982 * if t==write, value_regno is a register which value is stored into memory 5983 * if t==read, value_regno is a register which will receive the value from memory 5984 * if t==write && value_regno==-1, some unknown value is stored into memory 5985 * if t==read && value_regno==-1, don't care what we read from memory 5986 */ 5987 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 5988 int off, int bpf_size, enum bpf_access_type t, 5989 int value_regno, bool strict_alignment_once) 5990 { 5991 struct bpf_reg_state *regs = cur_regs(env); 5992 struct bpf_reg_state *reg = regs + regno; 5993 struct bpf_func_state *state; 5994 int size, err = 0; 5995 5996 size = bpf_size_to_bytes(bpf_size); 5997 if (size < 0) 5998 return size; 5999 6000 /* alignment checks will add in reg->off themselves */ 6001 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 6002 if (err) 6003 return err; 6004 6005 /* for access checks, reg->off is just part of off */ 6006 off += reg->off; 6007 6008 if (reg->type == PTR_TO_MAP_KEY) { 6009 if (t == BPF_WRITE) { 6010 verbose(env, "write to change key R%d not allowed\n", regno); 6011 return -EACCES; 6012 } 6013 6014 err = check_mem_region_access(env, regno, off, size, 6015 reg->map_ptr->key_size, false); 6016 if (err) 6017 return err; 6018 if (value_regno >= 0) 6019 mark_reg_unknown(env, regs, value_regno); 6020 } else if (reg->type == PTR_TO_MAP_VALUE) { 6021 struct btf_field *kptr_field = NULL; 6022 6023 if (t == BPF_WRITE && value_regno >= 0 && 6024 is_pointer_value(env, value_regno)) { 6025 verbose(env, "R%d leaks addr into map\n", value_regno); 6026 return -EACCES; 6027 } 6028 err = check_map_access_type(env, regno, off, size, t); 6029 if (err) 6030 return err; 6031 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 6032 if (err) 6033 return err; 6034 if (tnum_is_const(reg->var_off)) 6035 kptr_field = btf_record_find(reg->map_ptr->record, 6036 off + reg->var_off.value, BPF_KPTR); 6037 if (kptr_field) { 6038 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 6039 } else if (t == BPF_READ && value_regno >= 0) { 6040 struct bpf_map *map = reg->map_ptr; 6041 6042 /* if map is read-only, track its contents as scalars */ 6043 if (tnum_is_const(reg->var_off) && 6044 bpf_map_is_rdonly(map) && 6045 map->ops->map_direct_value_addr) { 6046 int map_off = off + reg->var_off.value; 6047 u64 val = 0; 6048 6049 err = bpf_map_direct_read(map, map_off, size, 6050 &val); 6051 if (err) 6052 return err; 6053 6054 regs[value_regno].type = SCALAR_VALUE; 6055 __mark_reg_known(®s[value_regno], val); 6056 } else { 6057 mark_reg_unknown(env, regs, value_regno); 6058 } 6059 } 6060 } else if (base_type(reg->type) == PTR_TO_MEM) { 6061 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6062 6063 if (type_may_be_null(reg->type)) { 6064 verbose(env, "R%d invalid mem access '%s'\n", regno, 6065 reg_type_str(env, reg->type)); 6066 return -EACCES; 6067 } 6068 6069 if (t == BPF_WRITE && rdonly_mem) { 6070 verbose(env, "R%d cannot write into %s\n", 6071 regno, reg_type_str(env, reg->type)); 6072 return -EACCES; 6073 } 6074 6075 if (t == BPF_WRITE && value_regno >= 0 && 6076 is_pointer_value(env, value_regno)) { 6077 verbose(env, "R%d leaks addr into mem\n", value_regno); 6078 return -EACCES; 6079 } 6080 6081 err = check_mem_region_access(env, regno, off, size, 6082 reg->mem_size, false); 6083 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 6084 mark_reg_unknown(env, regs, value_regno); 6085 } else if (reg->type == PTR_TO_CTX) { 6086 enum bpf_reg_type reg_type = SCALAR_VALUE; 6087 struct btf *btf = NULL; 6088 u32 btf_id = 0; 6089 6090 if (t == BPF_WRITE && value_regno >= 0 && 6091 is_pointer_value(env, value_regno)) { 6092 verbose(env, "R%d leaks addr into ctx\n", value_regno); 6093 return -EACCES; 6094 } 6095 6096 err = check_ptr_off_reg(env, reg, regno); 6097 if (err < 0) 6098 return err; 6099 6100 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 6101 &btf_id); 6102 if (err) 6103 verbose_linfo(env, insn_idx, "; "); 6104 if (!err && t == BPF_READ && value_regno >= 0) { 6105 /* ctx access returns either a scalar, or a 6106 * PTR_TO_PACKET[_META,_END]. In the latter 6107 * case, we know the offset is zero. 6108 */ 6109 if (reg_type == SCALAR_VALUE) { 6110 mark_reg_unknown(env, regs, value_regno); 6111 } else { 6112 mark_reg_known_zero(env, regs, 6113 value_regno); 6114 if (type_may_be_null(reg_type)) 6115 regs[value_regno].id = ++env->id_gen; 6116 /* A load of ctx field could have different 6117 * actual load size with the one encoded in the 6118 * insn. When the dst is PTR, it is for sure not 6119 * a sub-register. 6120 */ 6121 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 6122 if (base_type(reg_type) == PTR_TO_BTF_ID) { 6123 regs[value_regno].btf = btf; 6124 regs[value_regno].btf_id = btf_id; 6125 } 6126 } 6127 regs[value_regno].type = reg_type; 6128 } 6129 6130 } else if (reg->type == PTR_TO_STACK) { 6131 /* Basic bounds checks. */ 6132 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 6133 if (err) 6134 return err; 6135 6136 state = func(env, reg); 6137 err = update_stack_depth(env, state, off); 6138 if (err) 6139 return err; 6140 6141 if (t == BPF_READ) 6142 err = check_stack_read(env, regno, off, size, 6143 value_regno); 6144 else 6145 err = check_stack_write(env, regno, off, size, 6146 value_regno, insn_idx); 6147 } else if (reg_is_pkt_pointer(reg)) { 6148 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 6149 verbose(env, "cannot write into packet\n"); 6150 return -EACCES; 6151 } 6152 if (t == BPF_WRITE && value_regno >= 0 && 6153 is_pointer_value(env, value_regno)) { 6154 verbose(env, "R%d leaks addr into packet\n", 6155 value_regno); 6156 return -EACCES; 6157 } 6158 err = check_packet_access(env, regno, off, size, false); 6159 if (!err && t == BPF_READ && value_regno >= 0) 6160 mark_reg_unknown(env, regs, value_regno); 6161 } else if (reg->type == PTR_TO_FLOW_KEYS) { 6162 if (t == BPF_WRITE && value_regno >= 0 && 6163 is_pointer_value(env, value_regno)) { 6164 verbose(env, "R%d leaks addr into flow keys\n", 6165 value_regno); 6166 return -EACCES; 6167 } 6168 6169 err = check_flow_keys_access(env, off, size); 6170 if (!err && t == BPF_READ && value_regno >= 0) 6171 mark_reg_unknown(env, regs, value_regno); 6172 } else if (type_is_sk_pointer(reg->type)) { 6173 if (t == BPF_WRITE) { 6174 verbose(env, "R%d cannot write into %s\n", 6175 regno, reg_type_str(env, reg->type)); 6176 return -EACCES; 6177 } 6178 err = check_sock_access(env, insn_idx, regno, off, size, t); 6179 if (!err && value_regno >= 0) 6180 mark_reg_unknown(env, regs, value_regno); 6181 } else if (reg->type == PTR_TO_TP_BUFFER) { 6182 err = check_tp_buffer_access(env, reg, regno, off, size); 6183 if (!err && t == BPF_READ && value_regno >= 0) 6184 mark_reg_unknown(env, regs, value_regno); 6185 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 6186 !type_may_be_null(reg->type)) { 6187 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 6188 value_regno); 6189 } else if (reg->type == CONST_PTR_TO_MAP) { 6190 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 6191 value_regno); 6192 } else if (base_type(reg->type) == PTR_TO_BUF) { 6193 bool rdonly_mem = type_is_rdonly_mem(reg->type); 6194 u32 *max_access; 6195 6196 if (rdonly_mem) { 6197 if (t == BPF_WRITE) { 6198 verbose(env, "R%d cannot write into %s\n", 6199 regno, reg_type_str(env, reg->type)); 6200 return -EACCES; 6201 } 6202 max_access = &env->prog->aux->max_rdonly_access; 6203 } else { 6204 max_access = &env->prog->aux->max_rdwr_access; 6205 } 6206 6207 err = check_buffer_access(env, reg, regno, off, size, false, 6208 max_access); 6209 6210 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6211 mark_reg_unknown(env, regs, value_regno); 6212 } else { 6213 verbose(env, "R%d invalid mem access '%s'\n", regno, 6214 reg_type_str(env, reg->type)); 6215 return -EACCES; 6216 } 6217 6218 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6219 regs[value_regno].type == SCALAR_VALUE) { 6220 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6221 coerce_reg_to_size(®s[value_regno], size); 6222 } 6223 return err; 6224 } 6225 6226 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6227 { 6228 int load_reg; 6229 int err; 6230 6231 switch (insn->imm) { 6232 case BPF_ADD: 6233 case BPF_ADD | BPF_FETCH: 6234 case BPF_AND: 6235 case BPF_AND | BPF_FETCH: 6236 case BPF_OR: 6237 case BPF_OR | BPF_FETCH: 6238 case BPF_XOR: 6239 case BPF_XOR | BPF_FETCH: 6240 case BPF_XCHG: 6241 case BPF_CMPXCHG: 6242 break; 6243 default: 6244 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6245 return -EINVAL; 6246 } 6247 6248 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6249 verbose(env, "invalid atomic operand size\n"); 6250 return -EINVAL; 6251 } 6252 6253 /* check src1 operand */ 6254 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6255 if (err) 6256 return err; 6257 6258 /* check src2 operand */ 6259 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6260 if (err) 6261 return err; 6262 6263 if (insn->imm == BPF_CMPXCHG) { 6264 /* Check comparison of R0 with memory location */ 6265 const u32 aux_reg = BPF_REG_0; 6266 6267 err = check_reg_arg(env, aux_reg, SRC_OP); 6268 if (err) 6269 return err; 6270 6271 if (is_pointer_value(env, aux_reg)) { 6272 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6273 return -EACCES; 6274 } 6275 } 6276 6277 if (is_pointer_value(env, insn->src_reg)) { 6278 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6279 return -EACCES; 6280 } 6281 6282 if (is_ctx_reg(env, insn->dst_reg) || 6283 is_pkt_reg(env, insn->dst_reg) || 6284 is_flow_key_reg(env, insn->dst_reg) || 6285 is_sk_reg(env, insn->dst_reg)) { 6286 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6287 insn->dst_reg, 6288 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6289 return -EACCES; 6290 } 6291 6292 if (insn->imm & BPF_FETCH) { 6293 if (insn->imm == BPF_CMPXCHG) 6294 load_reg = BPF_REG_0; 6295 else 6296 load_reg = insn->src_reg; 6297 6298 /* check and record load of old value */ 6299 err = check_reg_arg(env, load_reg, DST_OP); 6300 if (err) 6301 return err; 6302 } else { 6303 /* This instruction accesses a memory location but doesn't 6304 * actually load it into a register. 6305 */ 6306 load_reg = -1; 6307 } 6308 6309 /* Check whether we can read the memory, with second call for fetch 6310 * case to simulate the register fill. 6311 */ 6312 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6313 BPF_SIZE(insn->code), BPF_READ, -1, true); 6314 if (!err && load_reg >= 0) 6315 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6316 BPF_SIZE(insn->code), BPF_READ, load_reg, 6317 true); 6318 if (err) 6319 return err; 6320 6321 /* Check whether we can write into the same memory. */ 6322 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6323 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 6324 if (err) 6325 return err; 6326 6327 return 0; 6328 } 6329 6330 /* When register 'regno' is used to read the stack (either directly or through 6331 * a helper function) make sure that it's within stack boundary and, depending 6332 * on the access type, that all elements of the stack are initialized. 6333 * 6334 * 'off' includes 'regno->off', but not its dynamic part (if any). 6335 * 6336 * All registers that have been spilled on the stack in the slots within the 6337 * read offsets are marked as read. 6338 */ 6339 static int check_stack_range_initialized( 6340 struct bpf_verifier_env *env, int regno, int off, 6341 int access_size, bool zero_size_allowed, 6342 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 6343 { 6344 struct bpf_reg_state *reg = reg_state(env, regno); 6345 struct bpf_func_state *state = func(env, reg); 6346 int err, min_off, max_off, i, j, slot, spi; 6347 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 6348 enum bpf_access_type bounds_check_type; 6349 /* Some accesses can write anything into the stack, others are 6350 * read-only. 6351 */ 6352 bool clobber = false; 6353 6354 if (access_size == 0 && !zero_size_allowed) { 6355 verbose(env, "invalid zero-sized read\n"); 6356 return -EACCES; 6357 } 6358 6359 if (type == ACCESS_HELPER) { 6360 /* The bounds checks for writes are more permissive than for 6361 * reads. However, if raw_mode is not set, we'll do extra 6362 * checks below. 6363 */ 6364 bounds_check_type = BPF_WRITE; 6365 clobber = true; 6366 } else { 6367 bounds_check_type = BPF_READ; 6368 } 6369 err = check_stack_access_within_bounds(env, regno, off, access_size, 6370 type, bounds_check_type); 6371 if (err) 6372 return err; 6373 6374 6375 if (tnum_is_const(reg->var_off)) { 6376 min_off = max_off = reg->var_off.value + off; 6377 } else { 6378 /* Variable offset is prohibited for unprivileged mode for 6379 * simplicity since it requires corresponding support in 6380 * Spectre masking for stack ALU. 6381 * See also retrieve_ptr_limit(). 6382 */ 6383 if (!env->bypass_spec_v1) { 6384 char tn_buf[48]; 6385 6386 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6387 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 6388 regno, err_extra, tn_buf); 6389 return -EACCES; 6390 } 6391 /* Only initialized buffer on stack is allowed to be accessed 6392 * with variable offset. With uninitialized buffer it's hard to 6393 * guarantee that whole memory is marked as initialized on 6394 * helper return since specific bounds are unknown what may 6395 * cause uninitialized stack leaking. 6396 */ 6397 if (meta && meta->raw_mode) 6398 meta = NULL; 6399 6400 min_off = reg->smin_value + off; 6401 max_off = reg->smax_value + off; 6402 } 6403 6404 if (meta && meta->raw_mode) { 6405 /* Ensure we won't be overwriting dynptrs when simulating byte 6406 * by byte access in check_helper_call using meta.access_size. 6407 * This would be a problem if we have a helper in the future 6408 * which takes: 6409 * 6410 * helper(uninit_mem, len, dynptr) 6411 * 6412 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6413 * may end up writing to dynptr itself when touching memory from 6414 * arg 1. This can be relaxed on a case by case basis for known 6415 * safe cases, but reject due to the possibilitiy of aliasing by 6416 * default. 6417 */ 6418 for (i = min_off; i < max_off + access_size; i++) { 6419 int stack_off = -i - 1; 6420 6421 spi = __get_spi(i); 6422 /* raw_mode may write past allocated_stack */ 6423 if (state->allocated_stack <= stack_off) 6424 continue; 6425 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 6426 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 6427 return -EACCES; 6428 } 6429 } 6430 meta->access_size = access_size; 6431 meta->regno = regno; 6432 return 0; 6433 } 6434 6435 for (i = min_off; i < max_off + access_size; i++) { 6436 u8 *stype; 6437 6438 slot = -i - 1; 6439 spi = slot / BPF_REG_SIZE; 6440 if (state->allocated_stack <= slot) 6441 goto err; 6442 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6443 if (*stype == STACK_MISC) 6444 goto mark; 6445 if ((*stype == STACK_ZERO) || 6446 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6447 if (clobber) { 6448 /* helper can write anything into the stack */ 6449 *stype = STACK_MISC; 6450 } 6451 goto mark; 6452 } 6453 6454 if (is_spilled_reg(&state->stack[spi]) && 6455 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6456 env->allow_ptr_leaks)) { 6457 if (clobber) { 6458 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6459 for (j = 0; j < BPF_REG_SIZE; j++) 6460 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6461 } 6462 goto mark; 6463 } 6464 6465 err: 6466 if (tnum_is_const(reg->var_off)) { 6467 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 6468 err_extra, regno, min_off, i - min_off, access_size); 6469 } else { 6470 char tn_buf[48]; 6471 6472 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6473 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 6474 err_extra, regno, tn_buf, i - min_off, access_size); 6475 } 6476 return -EACCES; 6477 mark: 6478 /* reading any byte out of 8-byte 'spill_slot' will cause 6479 * the whole slot to be marked as 'read' 6480 */ 6481 mark_reg_read(env, &state->stack[spi].spilled_ptr, 6482 state->stack[spi].spilled_ptr.parent, 6483 REG_LIVE_READ64); 6484 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 6485 * be sure that whether stack slot is written to or not. Hence, 6486 * we must still conservatively propagate reads upwards even if 6487 * helper may write to the entire memory range. 6488 */ 6489 } 6490 return update_stack_depth(env, state, min_off); 6491 } 6492 6493 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 6494 int access_size, bool zero_size_allowed, 6495 struct bpf_call_arg_meta *meta) 6496 { 6497 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6498 u32 *max_access; 6499 6500 switch (base_type(reg->type)) { 6501 case PTR_TO_PACKET: 6502 case PTR_TO_PACKET_META: 6503 return check_packet_access(env, regno, reg->off, access_size, 6504 zero_size_allowed); 6505 case PTR_TO_MAP_KEY: 6506 if (meta && meta->raw_mode) { 6507 verbose(env, "R%d cannot write into %s\n", regno, 6508 reg_type_str(env, reg->type)); 6509 return -EACCES; 6510 } 6511 return check_mem_region_access(env, regno, reg->off, access_size, 6512 reg->map_ptr->key_size, false); 6513 case PTR_TO_MAP_VALUE: 6514 if (check_map_access_type(env, regno, reg->off, access_size, 6515 meta && meta->raw_mode ? BPF_WRITE : 6516 BPF_READ)) 6517 return -EACCES; 6518 return check_map_access(env, regno, reg->off, access_size, 6519 zero_size_allowed, ACCESS_HELPER); 6520 case PTR_TO_MEM: 6521 if (type_is_rdonly_mem(reg->type)) { 6522 if (meta && meta->raw_mode) { 6523 verbose(env, "R%d cannot write into %s\n", regno, 6524 reg_type_str(env, reg->type)); 6525 return -EACCES; 6526 } 6527 } 6528 return check_mem_region_access(env, regno, reg->off, 6529 access_size, reg->mem_size, 6530 zero_size_allowed); 6531 case PTR_TO_BUF: 6532 if (type_is_rdonly_mem(reg->type)) { 6533 if (meta && meta->raw_mode) { 6534 verbose(env, "R%d cannot write into %s\n", regno, 6535 reg_type_str(env, reg->type)); 6536 return -EACCES; 6537 } 6538 6539 max_access = &env->prog->aux->max_rdonly_access; 6540 } else { 6541 max_access = &env->prog->aux->max_rdwr_access; 6542 } 6543 return check_buffer_access(env, reg, regno, reg->off, 6544 access_size, zero_size_allowed, 6545 max_access); 6546 case PTR_TO_STACK: 6547 return check_stack_range_initialized( 6548 env, 6549 regno, reg->off, access_size, 6550 zero_size_allowed, ACCESS_HELPER, meta); 6551 case PTR_TO_BTF_ID: 6552 return check_ptr_to_btf_access(env, regs, regno, reg->off, 6553 access_size, BPF_READ, -1); 6554 case PTR_TO_CTX: 6555 /* in case the function doesn't know how to access the context, 6556 * (because we are in a program of type SYSCALL for example), we 6557 * can not statically check its size. 6558 * Dynamically check it now. 6559 */ 6560 if (!env->ops->convert_ctx_access) { 6561 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 6562 int offset = access_size - 1; 6563 6564 /* Allow zero-byte read from PTR_TO_CTX */ 6565 if (access_size == 0) 6566 return zero_size_allowed ? 0 : -EACCES; 6567 6568 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 6569 atype, -1, false); 6570 } 6571 6572 fallthrough; 6573 default: /* scalar_value or invalid ptr */ 6574 /* Allow zero-byte read from NULL, regardless of pointer type */ 6575 if (zero_size_allowed && access_size == 0 && 6576 register_is_null(reg)) 6577 return 0; 6578 6579 verbose(env, "R%d type=%s ", regno, 6580 reg_type_str(env, reg->type)); 6581 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 6582 return -EACCES; 6583 } 6584 } 6585 6586 static int check_mem_size_reg(struct bpf_verifier_env *env, 6587 struct bpf_reg_state *reg, u32 regno, 6588 bool zero_size_allowed, 6589 struct bpf_call_arg_meta *meta) 6590 { 6591 int err; 6592 6593 /* This is used to refine r0 return value bounds for helpers 6594 * that enforce this value as an upper bound on return values. 6595 * See do_refine_retval_range() for helpers that can refine 6596 * the return value. C type of helper is u32 so we pull register 6597 * bound from umax_value however, if negative verifier errors 6598 * out. Only upper bounds can be learned because retval is an 6599 * int type and negative retvals are allowed. 6600 */ 6601 meta->msize_max_value = reg->umax_value; 6602 6603 /* The register is SCALAR_VALUE; the access check 6604 * happens using its boundaries. 6605 */ 6606 if (!tnum_is_const(reg->var_off)) 6607 /* For unprivileged variable accesses, disable raw 6608 * mode so that the program is required to 6609 * initialize all the memory that the helper could 6610 * just partially fill up. 6611 */ 6612 meta = NULL; 6613 6614 if (reg->smin_value < 0) { 6615 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 6616 regno); 6617 return -EACCES; 6618 } 6619 6620 if (reg->umin_value == 0) { 6621 err = check_helper_mem_access(env, regno - 1, 0, 6622 zero_size_allowed, 6623 meta); 6624 if (err) 6625 return err; 6626 } 6627 6628 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 6629 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 6630 regno); 6631 return -EACCES; 6632 } 6633 err = check_helper_mem_access(env, regno - 1, 6634 reg->umax_value, 6635 zero_size_allowed, meta); 6636 if (!err) 6637 err = mark_chain_precision(env, regno); 6638 return err; 6639 } 6640 6641 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6642 u32 regno, u32 mem_size) 6643 { 6644 bool may_be_null = type_may_be_null(reg->type); 6645 struct bpf_reg_state saved_reg; 6646 struct bpf_call_arg_meta meta; 6647 int err; 6648 6649 if (register_is_null(reg)) 6650 return 0; 6651 6652 memset(&meta, 0, sizeof(meta)); 6653 /* Assuming that the register contains a value check if the memory 6654 * access is safe. Temporarily save and restore the register's state as 6655 * the conversion shouldn't be visible to a caller. 6656 */ 6657 if (may_be_null) { 6658 saved_reg = *reg; 6659 mark_ptr_not_null_reg(reg); 6660 } 6661 6662 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 6663 /* Check access for BPF_WRITE */ 6664 meta.raw_mode = true; 6665 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 6666 6667 if (may_be_null) 6668 *reg = saved_reg; 6669 6670 return err; 6671 } 6672 6673 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6674 u32 regno) 6675 { 6676 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 6677 bool may_be_null = type_may_be_null(mem_reg->type); 6678 struct bpf_reg_state saved_reg; 6679 struct bpf_call_arg_meta meta; 6680 int err; 6681 6682 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 6683 6684 memset(&meta, 0, sizeof(meta)); 6685 6686 if (may_be_null) { 6687 saved_reg = *mem_reg; 6688 mark_ptr_not_null_reg(mem_reg); 6689 } 6690 6691 err = check_mem_size_reg(env, reg, regno, true, &meta); 6692 /* Check access for BPF_WRITE */ 6693 meta.raw_mode = true; 6694 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 6695 6696 if (may_be_null) 6697 *mem_reg = saved_reg; 6698 return err; 6699 } 6700 6701 /* Implementation details: 6702 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 6703 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 6704 * Two bpf_map_lookups (even with the same key) will have different reg->id. 6705 * Two separate bpf_obj_new will also have different reg->id. 6706 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 6707 * clears reg->id after value_or_null->value transition, since the verifier only 6708 * cares about the range of access to valid map value pointer and doesn't care 6709 * about actual address of the map element. 6710 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 6711 * reg->id > 0 after value_or_null->value transition. By doing so 6712 * two bpf_map_lookups will be considered two different pointers that 6713 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 6714 * returned from bpf_obj_new. 6715 * The verifier allows taking only one bpf_spin_lock at a time to avoid 6716 * dead-locks. 6717 * Since only one bpf_spin_lock is allowed the checks are simpler than 6718 * reg_is_refcounted() logic. The verifier needs to remember only 6719 * one spin_lock instead of array of acquired_refs. 6720 * cur_state->active_lock remembers which map value element or allocated 6721 * object got locked and clears it after bpf_spin_unlock. 6722 */ 6723 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 6724 bool is_lock) 6725 { 6726 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6727 struct bpf_verifier_state *cur = env->cur_state; 6728 bool is_const = tnum_is_const(reg->var_off); 6729 u64 val = reg->var_off.value; 6730 struct bpf_map *map = NULL; 6731 struct btf *btf = NULL; 6732 struct btf_record *rec; 6733 6734 if (!is_const) { 6735 verbose(env, 6736 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 6737 regno); 6738 return -EINVAL; 6739 } 6740 if (reg->type == PTR_TO_MAP_VALUE) { 6741 map = reg->map_ptr; 6742 if (!map->btf) { 6743 verbose(env, 6744 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 6745 map->name); 6746 return -EINVAL; 6747 } 6748 } else { 6749 btf = reg->btf; 6750 } 6751 6752 rec = reg_btf_record(reg); 6753 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 6754 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 6755 map ? map->name : "kptr"); 6756 return -EINVAL; 6757 } 6758 if (rec->spin_lock_off != val + reg->off) { 6759 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 6760 val + reg->off, rec->spin_lock_off); 6761 return -EINVAL; 6762 } 6763 if (is_lock) { 6764 if (cur->active_lock.ptr) { 6765 verbose(env, 6766 "Locking two bpf_spin_locks are not allowed\n"); 6767 return -EINVAL; 6768 } 6769 if (map) 6770 cur->active_lock.ptr = map; 6771 else 6772 cur->active_lock.ptr = btf; 6773 cur->active_lock.id = reg->id; 6774 } else { 6775 void *ptr; 6776 6777 if (map) 6778 ptr = map; 6779 else 6780 ptr = btf; 6781 6782 if (!cur->active_lock.ptr) { 6783 verbose(env, "bpf_spin_unlock without taking a lock\n"); 6784 return -EINVAL; 6785 } 6786 if (cur->active_lock.ptr != ptr || 6787 cur->active_lock.id != reg->id) { 6788 verbose(env, "bpf_spin_unlock of different lock\n"); 6789 return -EINVAL; 6790 } 6791 6792 invalidate_non_owning_refs(env); 6793 6794 cur->active_lock.ptr = NULL; 6795 cur->active_lock.id = 0; 6796 } 6797 return 0; 6798 } 6799 6800 static int process_timer_func(struct bpf_verifier_env *env, int regno, 6801 struct bpf_call_arg_meta *meta) 6802 { 6803 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6804 bool is_const = tnum_is_const(reg->var_off); 6805 struct bpf_map *map = reg->map_ptr; 6806 u64 val = reg->var_off.value; 6807 6808 if (!is_const) { 6809 verbose(env, 6810 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 6811 regno); 6812 return -EINVAL; 6813 } 6814 if (!map->btf) { 6815 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 6816 map->name); 6817 return -EINVAL; 6818 } 6819 if (!btf_record_has_field(map->record, BPF_TIMER)) { 6820 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 6821 return -EINVAL; 6822 } 6823 if (map->record->timer_off != val + reg->off) { 6824 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 6825 val + reg->off, map->record->timer_off); 6826 return -EINVAL; 6827 } 6828 if (meta->map_ptr) { 6829 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 6830 return -EFAULT; 6831 } 6832 meta->map_uid = reg->map_uid; 6833 meta->map_ptr = map; 6834 return 0; 6835 } 6836 6837 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 6838 struct bpf_call_arg_meta *meta) 6839 { 6840 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6841 struct bpf_map *map_ptr = reg->map_ptr; 6842 struct btf_field *kptr_field; 6843 u32 kptr_off; 6844 6845 if (!tnum_is_const(reg->var_off)) { 6846 verbose(env, 6847 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 6848 regno); 6849 return -EINVAL; 6850 } 6851 if (!map_ptr->btf) { 6852 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 6853 map_ptr->name); 6854 return -EINVAL; 6855 } 6856 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 6857 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 6858 return -EINVAL; 6859 } 6860 6861 meta->map_ptr = map_ptr; 6862 kptr_off = reg->off + reg->var_off.value; 6863 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 6864 if (!kptr_field) { 6865 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 6866 return -EACCES; 6867 } 6868 if (kptr_field->type != BPF_KPTR_REF) { 6869 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 6870 return -EACCES; 6871 } 6872 meta->kptr_field = kptr_field; 6873 return 0; 6874 } 6875 6876 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 6877 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 6878 * 6879 * In both cases we deal with the first 8 bytes, but need to mark the next 8 6880 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 6881 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 6882 * 6883 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 6884 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 6885 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 6886 * mutate the view of the dynptr and also possibly destroy it. In the latter 6887 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 6888 * memory that dynptr points to. 6889 * 6890 * The verifier will keep track both levels of mutation (bpf_dynptr's in 6891 * reg->type and the memory's in reg->dynptr.type), but there is no support for 6892 * readonly dynptr view yet, hence only the first case is tracked and checked. 6893 * 6894 * This is consistent with how C applies the const modifier to a struct object, 6895 * where the pointer itself inside bpf_dynptr becomes const but not what it 6896 * points to. 6897 * 6898 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 6899 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 6900 */ 6901 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 6902 enum bpf_arg_type arg_type, int clone_ref_obj_id) 6903 { 6904 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6905 int err; 6906 6907 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 6908 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 6909 */ 6910 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 6911 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 6912 return -EFAULT; 6913 } 6914 6915 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 6916 * constructing a mutable bpf_dynptr object. 6917 * 6918 * Currently, this is only possible with PTR_TO_STACK 6919 * pointing to a region of at least 16 bytes which doesn't 6920 * contain an existing bpf_dynptr. 6921 * 6922 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 6923 * mutated or destroyed. However, the memory it points to 6924 * may be mutated. 6925 * 6926 * None - Points to a initialized dynptr that can be mutated and 6927 * destroyed, including mutation of the memory it points 6928 * to. 6929 */ 6930 if (arg_type & MEM_UNINIT) { 6931 int i; 6932 6933 if (!is_dynptr_reg_valid_uninit(env, reg)) { 6934 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 6935 return -EINVAL; 6936 } 6937 6938 /* we write BPF_DW bits (8 bytes) at a time */ 6939 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 6940 err = check_mem_access(env, insn_idx, regno, 6941 i, BPF_DW, BPF_WRITE, -1, false); 6942 if (err) 6943 return err; 6944 } 6945 6946 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx, clone_ref_obj_id); 6947 } else /* MEM_RDONLY and None case from above */ { 6948 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 6949 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 6950 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 6951 return -EINVAL; 6952 } 6953 6954 if (!is_dynptr_reg_valid_init(env, reg)) { 6955 verbose(env, 6956 "Expected an initialized dynptr as arg #%d\n", 6957 regno); 6958 return -EINVAL; 6959 } 6960 6961 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 6962 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 6963 verbose(env, 6964 "Expected a dynptr of type %s as arg #%d\n", 6965 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 6966 return -EINVAL; 6967 } 6968 6969 err = mark_dynptr_read(env, reg); 6970 } 6971 return err; 6972 } 6973 6974 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 6975 { 6976 struct bpf_func_state *state = func(env, reg); 6977 6978 return state->stack[spi].spilled_ptr.ref_obj_id; 6979 } 6980 6981 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 6982 { 6983 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 6984 } 6985 6986 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 6987 { 6988 return meta->kfunc_flags & KF_ITER_NEW; 6989 } 6990 6991 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 6992 { 6993 return meta->kfunc_flags & KF_ITER_NEXT; 6994 } 6995 6996 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 6997 { 6998 return meta->kfunc_flags & KF_ITER_DESTROY; 6999 } 7000 7001 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 7002 { 7003 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 7004 * kfunc is iter state pointer 7005 */ 7006 return arg == 0 && is_iter_kfunc(meta); 7007 } 7008 7009 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 7010 struct bpf_kfunc_call_arg_meta *meta) 7011 { 7012 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7013 const struct btf_type *t; 7014 const struct btf_param *arg; 7015 int spi, err, i, nr_slots; 7016 u32 btf_id; 7017 7018 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 7019 arg = &btf_params(meta->func_proto)[0]; 7020 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 7021 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 7022 nr_slots = t->size / BPF_REG_SIZE; 7023 7024 if (is_iter_new_kfunc(meta)) { 7025 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 7026 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 7027 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 7028 iter_type_str(meta->btf, btf_id), regno); 7029 return -EINVAL; 7030 } 7031 7032 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 7033 err = check_mem_access(env, insn_idx, regno, 7034 i, BPF_DW, BPF_WRITE, -1, false); 7035 if (err) 7036 return err; 7037 } 7038 7039 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots); 7040 if (err) 7041 return err; 7042 } else { 7043 /* iter_next() or iter_destroy() expect initialized iter state*/ 7044 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) { 7045 verbose(env, "expected an initialized iter_%s as arg #%d\n", 7046 iter_type_str(meta->btf, btf_id), regno); 7047 return -EINVAL; 7048 } 7049 7050 spi = iter_get_spi(env, reg, nr_slots); 7051 if (spi < 0) 7052 return spi; 7053 7054 err = mark_iter_read(env, reg, spi, nr_slots); 7055 if (err) 7056 return err; 7057 7058 /* remember meta->iter info for process_iter_next_call() */ 7059 meta->iter.spi = spi; 7060 meta->iter.frameno = reg->frameno; 7061 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 7062 7063 if (is_iter_destroy_kfunc(meta)) { 7064 err = unmark_stack_slots_iter(env, reg, nr_slots); 7065 if (err) 7066 return err; 7067 } 7068 } 7069 7070 return 0; 7071 } 7072 7073 /* process_iter_next_call() is called when verifier gets to iterator's next 7074 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 7075 * to it as just "iter_next()" in comments below. 7076 * 7077 * BPF verifier relies on a crucial contract for any iter_next() 7078 * implementation: it should *eventually* return NULL, and once that happens 7079 * it should keep returning NULL. That is, once iterator exhausts elements to 7080 * iterate, it should never reset or spuriously return new elements. 7081 * 7082 * With the assumption of such contract, process_iter_next_call() simulates 7083 * a fork in the verifier state to validate loop logic correctness and safety 7084 * without having to simulate infinite amount of iterations. 7085 * 7086 * In current state, we first assume that iter_next() returned NULL and 7087 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 7088 * conditions we should not form an infinite loop and should eventually reach 7089 * exit. 7090 * 7091 * Besides that, we also fork current state and enqueue it for later 7092 * verification. In a forked state we keep iterator state as ACTIVE 7093 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 7094 * also bump iteration depth to prevent erroneous infinite loop detection 7095 * later on (see iter_active_depths_differ() comment for details). In this 7096 * state we assume that we'll eventually loop back to another iter_next() 7097 * calls (it could be in exactly same location or in some other instruction, 7098 * it doesn't matter, we don't make any unnecessary assumptions about this, 7099 * everything revolves around iterator state in a stack slot, not which 7100 * instruction is calling iter_next()). When that happens, we either will come 7101 * to iter_next() with equivalent state and can conclude that next iteration 7102 * will proceed in exactly the same way as we just verified, so it's safe to 7103 * assume that loop converges. If not, we'll go on another iteration 7104 * simulation with a different input state, until all possible starting states 7105 * are validated or we reach maximum number of instructions limit. 7106 * 7107 * This way, we will either exhaustively discover all possible input states 7108 * that iterator loop can start with and eventually will converge, or we'll 7109 * effectively regress into bounded loop simulation logic and either reach 7110 * maximum number of instructions if loop is not provably convergent, or there 7111 * is some statically known limit on number of iterations (e.g., if there is 7112 * an explicit `if n > 100 then break;` statement somewhere in the loop). 7113 * 7114 * One very subtle but very important aspect is that we *always* simulate NULL 7115 * condition first (as the current state) before we simulate non-NULL case. 7116 * This has to do with intricacies of scalar precision tracking. By simulating 7117 * "exit condition" of iter_next() returning NULL first, we make sure all the 7118 * relevant precision marks *that will be set **after** we exit iterator loop* 7119 * are propagated backwards to common parent state of NULL and non-NULL 7120 * branches. Thanks to that, state equivalence checks done later in forked 7121 * state, when reaching iter_next() for ACTIVE iterator, can assume that 7122 * precision marks are finalized and won't change. Because simulating another 7123 * ACTIVE iterator iteration won't change them (because given same input 7124 * states we'll end up with exactly same output states which we are currently 7125 * comparing; and verification after the loop already propagated back what 7126 * needs to be **additionally** tracked as precise). It's subtle, grok 7127 * precision tracking for more intuitive understanding. 7128 */ 7129 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 7130 struct bpf_kfunc_call_arg_meta *meta) 7131 { 7132 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st; 7133 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 7134 struct bpf_reg_state *cur_iter, *queued_iter; 7135 int iter_frameno = meta->iter.frameno; 7136 int iter_spi = meta->iter.spi; 7137 7138 BTF_TYPE_EMIT(struct bpf_iter); 7139 7140 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7141 7142 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 7143 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 7144 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 7145 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 7146 return -EFAULT; 7147 } 7148 7149 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 7150 /* branch out active iter state */ 7151 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 7152 if (!queued_st) 7153 return -ENOMEM; 7154 7155 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 7156 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 7157 queued_iter->iter.depth++; 7158 7159 queued_fr = queued_st->frame[queued_st->curframe]; 7160 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 7161 } 7162 7163 /* switch to DRAINED state, but keep the depth unchanged */ 7164 /* mark current iter state as drained and assume returned NULL */ 7165 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 7166 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 7167 7168 return 0; 7169 } 7170 7171 static bool arg_type_is_mem_size(enum bpf_arg_type type) 7172 { 7173 return type == ARG_CONST_SIZE || 7174 type == ARG_CONST_SIZE_OR_ZERO; 7175 } 7176 7177 static bool arg_type_is_release(enum bpf_arg_type type) 7178 { 7179 return type & OBJ_RELEASE; 7180 } 7181 7182 static bool arg_type_is_dynptr(enum bpf_arg_type type) 7183 { 7184 return base_type(type) == ARG_PTR_TO_DYNPTR; 7185 } 7186 7187 static int int_ptr_type_to_size(enum bpf_arg_type type) 7188 { 7189 if (type == ARG_PTR_TO_INT) 7190 return sizeof(u32); 7191 else if (type == ARG_PTR_TO_LONG) 7192 return sizeof(u64); 7193 7194 return -EINVAL; 7195 } 7196 7197 static int resolve_map_arg_type(struct bpf_verifier_env *env, 7198 const struct bpf_call_arg_meta *meta, 7199 enum bpf_arg_type *arg_type) 7200 { 7201 if (!meta->map_ptr) { 7202 /* kernel subsystem misconfigured verifier */ 7203 verbose(env, "invalid map_ptr to access map->type\n"); 7204 return -EACCES; 7205 } 7206 7207 switch (meta->map_ptr->map_type) { 7208 case BPF_MAP_TYPE_SOCKMAP: 7209 case BPF_MAP_TYPE_SOCKHASH: 7210 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7211 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7212 } else { 7213 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7214 return -EINVAL; 7215 } 7216 break; 7217 case BPF_MAP_TYPE_BLOOM_FILTER: 7218 if (meta->func_id == BPF_FUNC_map_peek_elem) 7219 *arg_type = ARG_PTR_TO_MAP_VALUE; 7220 break; 7221 default: 7222 break; 7223 } 7224 return 0; 7225 } 7226 7227 struct bpf_reg_types { 7228 const enum bpf_reg_type types[10]; 7229 u32 *btf_id; 7230 }; 7231 7232 static const struct bpf_reg_types sock_types = { 7233 .types = { 7234 PTR_TO_SOCK_COMMON, 7235 PTR_TO_SOCKET, 7236 PTR_TO_TCP_SOCK, 7237 PTR_TO_XDP_SOCK, 7238 }, 7239 }; 7240 7241 #ifdef CONFIG_NET 7242 static const struct bpf_reg_types btf_id_sock_common_types = { 7243 .types = { 7244 PTR_TO_SOCK_COMMON, 7245 PTR_TO_SOCKET, 7246 PTR_TO_TCP_SOCK, 7247 PTR_TO_XDP_SOCK, 7248 PTR_TO_BTF_ID, 7249 PTR_TO_BTF_ID | PTR_TRUSTED, 7250 }, 7251 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7252 }; 7253 #endif 7254 7255 static const struct bpf_reg_types mem_types = { 7256 .types = { 7257 PTR_TO_STACK, 7258 PTR_TO_PACKET, 7259 PTR_TO_PACKET_META, 7260 PTR_TO_MAP_KEY, 7261 PTR_TO_MAP_VALUE, 7262 PTR_TO_MEM, 7263 PTR_TO_MEM | MEM_RINGBUF, 7264 PTR_TO_BUF, 7265 PTR_TO_BTF_ID | PTR_TRUSTED, 7266 }, 7267 }; 7268 7269 static const struct bpf_reg_types int_ptr_types = { 7270 .types = { 7271 PTR_TO_STACK, 7272 PTR_TO_PACKET, 7273 PTR_TO_PACKET_META, 7274 PTR_TO_MAP_KEY, 7275 PTR_TO_MAP_VALUE, 7276 }, 7277 }; 7278 7279 static const struct bpf_reg_types spin_lock_types = { 7280 .types = { 7281 PTR_TO_MAP_VALUE, 7282 PTR_TO_BTF_ID | MEM_ALLOC, 7283 } 7284 }; 7285 7286 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7287 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7288 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7289 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7290 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7291 static const struct bpf_reg_types btf_ptr_types = { 7292 .types = { 7293 PTR_TO_BTF_ID, 7294 PTR_TO_BTF_ID | PTR_TRUSTED, 7295 PTR_TO_BTF_ID | MEM_RCU, 7296 }, 7297 }; 7298 static const struct bpf_reg_types percpu_btf_ptr_types = { 7299 .types = { 7300 PTR_TO_BTF_ID | MEM_PERCPU, 7301 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7302 } 7303 }; 7304 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7305 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7306 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7307 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7308 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7309 static const struct bpf_reg_types dynptr_types = { 7310 .types = { 7311 PTR_TO_STACK, 7312 CONST_PTR_TO_DYNPTR, 7313 } 7314 }; 7315 7316 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7317 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7318 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7319 [ARG_CONST_SIZE] = &scalar_types, 7320 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7321 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7322 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7323 [ARG_PTR_TO_CTX] = &context_types, 7324 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7325 #ifdef CONFIG_NET 7326 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7327 #endif 7328 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7329 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7330 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7331 [ARG_PTR_TO_MEM] = &mem_types, 7332 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7333 [ARG_PTR_TO_INT] = &int_ptr_types, 7334 [ARG_PTR_TO_LONG] = &int_ptr_types, 7335 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7336 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7337 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7338 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7339 [ARG_PTR_TO_TIMER] = &timer_types, 7340 [ARG_PTR_TO_KPTR] = &kptr_types, 7341 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7342 }; 7343 7344 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 7345 enum bpf_arg_type arg_type, 7346 const u32 *arg_btf_id, 7347 struct bpf_call_arg_meta *meta) 7348 { 7349 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7350 enum bpf_reg_type expected, type = reg->type; 7351 const struct bpf_reg_types *compatible; 7352 int i, j; 7353 7354 compatible = compatible_reg_types[base_type(arg_type)]; 7355 if (!compatible) { 7356 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 7357 return -EFAULT; 7358 } 7359 7360 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7361 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7362 * 7363 * Same for MAYBE_NULL: 7364 * 7365 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7366 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7367 * 7368 * Therefore we fold these flags depending on the arg_type before comparison. 7369 */ 7370 if (arg_type & MEM_RDONLY) 7371 type &= ~MEM_RDONLY; 7372 if (arg_type & PTR_MAYBE_NULL) 7373 type &= ~PTR_MAYBE_NULL; 7374 7375 if (meta->func_id == BPF_FUNC_kptr_xchg && type & MEM_ALLOC) 7376 type &= ~MEM_ALLOC; 7377 7378 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7379 expected = compatible->types[i]; 7380 if (expected == NOT_INIT) 7381 break; 7382 7383 if (type == expected) 7384 goto found; 7385 } 7386 7387 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 7388 for (j = 0; j + 1 < i; j++) 7389 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7390 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7391 return -EACCES; 7392 7393 found: 7394 if (base_type(reg->type) != PTR_TO_BTF_ID) 7395 return 0; 7396 7397 if (compatible == &mem_types) { 7398 if (!(arg_type & MEM_RDONLY)) { 7399 verbose(env, 7400 "%s() may write into memory pointed by R%d type=%s\n", 7401 func_id_name(meta->func_id), 7402 regno, reg_type_str(env, reg->type)); 7403 return -EACCES; 7404 } 7405 return 0; 7406 } 7407 7408 switch ((int)reg->type) { 7409 case PTR_TO_BTF_ID: 7410 case PTR_TO_BTF_ID | PTR_TRUSTED: 7411 case PTR_TO_BTF_ID | MEM_RCU: 7412 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 7413 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 7414 { 7415 /* For bpf_sk_release, it needs to match against first member 7416 * 'struct sock_common', hence make an exception for it. This 7417 * allows bpf_sk_release to work for multiple socket types. 7418 */ 7419 bool strict_type_match = arg_type_is_release(arg_type) && 7420 meta->func_id != BPF_FUNC_sk_release; 7421 7422 if (type_may_be_null(reg->type) && 7423 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 7424 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 7425 return -EACCES; 7426 } 7427 7428 if (!arg_btf_id) { 7429 if (!compatible->btf_id) { 7430 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 7431 return -EFAULT; 7432 } 7433 arg_btf_id = compatible->btf_id; 7434 } 7435 7436 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7437 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 7438 return -EACCES; 7439 } else { 7440 if (arg_btf_id == BPF_PTR_POISON) { 7441 verbose(env, "verifier internal error:"); 7442 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 7443 regno); 7444 return -EACCES; 7445 } 7446 7447 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 7448 btf_vmlinux, *arg_btf_id, 7449 strict_type_match)) { 7450 verbose(env, "R%d is of type %s but %s is expected\n", 7451 regno, btf_type_name(reg->btf, reg->btf_id), 7452 btf_type_name(btf_vmlinux, *arg_btf_id)); 7453 return -EACCES; 7454 } 7455 } 7456 break; 7457 } 7458 case PTR_TO_BTF_ID | MEM_ALLOC: 7459 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 7460 meta->func_id != BPF_FUNC_kptr_xchg) { 7461 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 7462 return -EFAULT; 7463 } 7464 /* Handled by helper specific checks */ 7465 break; 7466 case PTR_TO_BTF_ID | MEM_PERCPU: 7467 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 7468 /* Handled by helper specific checks */ 7469 break; 7470 default: 7471 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 7472 return -EFAULT; 7473 } 7474 return 0; 7475 } 7476 7477 static struct btf_field * 7478 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 7479 { 7480 struct btf_field *field; 7481 struct btf_record *rec; 7482 7483 rec = reg_btf_record(reg); 7484 if (!rec) 7485 return NULL; 7486 7487 field = btf_record_find(rec, off, fields); 7488 if (!field) 7489 return NULL; 7490 7491 return field; 7492 } 7493 7494 int check_func_arg_reg_off(struct bpf_verifier_env *env, 7495 const struct bpf_reg_state *reg, int regno, 7496 enum bpf_arg_type arg_type) 7497 { 7498 u32 type = reg->type; 7499 7500 /* When referenced register is passed to release function, its fixed 7501 * offset must be 0. 7502 * 7503 * We will check arg_type_is_release reg has ref_obj_id when storing 7504 * meta->release_regno. 7505 */ 7506 if (arg_type_is_release(arg_type)) { 7507 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 7508 * may not directly point to the object being released, but to 7509 * dynptr pointing to such object, which might be at some offset 7510 * on the stack. In that case, we simply to fallback to the 7511 * default handling. 7512 */ 7513 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 7514 return 0; 7515 7516 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) { 7517 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT)) 7518 return __check_ptr_off_reg(env, reg, regno, true); 7519 7520 verbose(env, "R%d must have zero offset when passed to release func\n", 7521 regno); 7522 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno, 7523 btf_type_name(reg->btf, reg->btf_id), reg->off); 7524 return -EINVAL; 7525 } 7526 7527 /* Doing check_ptr_off_reg check for the offset will catch this 7528 * because fixed_off_ok is false, but checking here allows us 7529 * to give the user a better error message. 7530 */ 7531 if (reg->off) { 7532 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 7533 regno); 7534 return -EINVAL; 7535 } 7536 return __check_ptr_off_reg(env, reg, regno, false); 7537 } 7538 7539 switch (type) { 7540 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 7541 case PTR_TO_STACK: 7542 case PTR_TO_PACKET: 7543 case PTR_TO_PACKET_META: 7544 case PTR_TO_MAP_KEY: 7545 case PTR_TO_MAP_VALUE: 7546 case PTR_TO_MEM: 7547 case PTR_TO_MEM | MEM_RDONLY: 7548 case PTR_TO_MEM | MEM_RINGBUF: 7549 case PTR_TO_BUF: 7550 case PTR_TO_BUF | MEM_RDONLY: 7551 case SCALAR_VALUE: 7552 return 0; 7553 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 7554 * fixed offset. 7555 */ 7556 case PTR_TO_BTF_ID: 7557 case PTR_TO_BTF_ID | MEM_ALLOC: 7558 case PTR_TO_BTF_ID | PTR_TRUSTED: 7559 case PTR_TO_BTF_ID | MEM_RCU: 7560 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 7561 /* When referenced PTR_TO_BTF_ID is passed to release function, 7562 * its fixed offset must be 0. In the other cases, fixed offset 7563 * can be non-zero. This was already checked above. So pass 7564 * fixed_off_ok as true to allow fixed offset for all other 7565 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 7566 * still need to do checks instead of returning. 7567 */ 7568 return __check_ptr_off_reg(env, reg, regno, true); 7569 default: 7570 return __check_ptr_off_reg(env, reg, regno, false); 7571 } 7572 } 7573 7574 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 7575 const struct bpf_func_proto *fn, 7576 struct bpf_reg_state *regs) 7577 { 7578 struct bpf_reg_state *state = NULL; 7579 int i; 7580 7581 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 7582 if (arg_type_is_dynptr(fn->arg_type[i])) { 7583 if (state) { 7584 verbose(env, "verifier internal error: multiple dynptr args\n"); 7585 return NULL; 7586 } 7587 state = ®s[BPF_REG_1 + i]; 7588 } 7589 7590 if (!state) 7591 verbose(env, "verifier internal error: no dynptr arg found\n"); 7592 7593 return state; 7594 } 7595 7596 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 7597 { 7598 struct bpf_func_state *state = func(env, reg); 7599 int spi; 7600 7601 if (reg->type == CONST_PTR_TO_DYNPTR) 7602 return reg->id; 7603 spi = dynptr_get_spi(env, reg); 7604 if (spi < 0) 7605 return spi; 7606 return state->stack[spi].spilled_ptr.id; 7607 } 7608 7609 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 7610 { 7611 struct bpf_func_state *state = func(env, reg); 7612 int spi; 7613 7614 if (reg->type == CONST_PTR_TO_DYNPTR) 7615 return reg->ref_obj_id; 7616 spi = dynptr_get_spi(env, reg); 7617 if (spi < 0) 7618 return spi; 7619 return state->stack[spi].spilled_ptr.ref_obj_id; 7620 } 7621 7622 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 7623 struct bpf_reg_state *reg) 7624 { 7625 struct bpf_func_state *state = func(env, reg); 7626 int spi; 7627 7628 if (reg->type == CONST_PTR_TO_DYNPTR) 7629 return reg->dynptr.type; 7630 7631 spi = __get_spi(reg->off); 7632 if (spi < 0) { 7633 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 7634 return BPF_DYNPTR_TYPE_INVALID; 7635 } 7636 7637 return state->stack[spi].spilled_ptr.dynptr.type; 7638 } 7639 7640 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 7641 struct bpf_call_arg_meta *meta, 7642 const struct bpf_func_proto *fn, 7643 int insn_idx) 7644 { 7645 u32 regno = BPF_REG_1 + arg; 7646 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7647 enum bpf_arg_type arg_type = fn->arg_type[arg]; 7648 enum bpf_reg_type type = reg->type; 7649 u32 *arg_btf_id = NULL; 7650 int err = 0; 7651 7652 if (arg_type == ARG_DONTCARE) 7653 return 0; 7654 7655 err = check_reg_arg(env, regno, SRC_OP); 7656 if (err) 7657 return err; 7658 7659 if (arg_type == ARG_ANYTHING) { 7660 if (is_pointer_value(env, regno)) { 7661 verbose(env, "R%d leaks addr into helper function\n", 7662 regno); 7663 return -EACCES; 7664 } 7665 return 0; 7666 } 7667 7668 if (type_is_pkt_pointer(type) && 7669 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 7670 verbose(env, "helper access to the packet is not allowed\n"); 7671 return -EACCES; 7672 } 7673 7674 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 7675 err = resolve_map_arg_type(env, meta, &arg_type); 7676 if (err) 7677 return err; 7678 } 7679 7680 if (register_is_null(reg) && type_may_be_null(arg_type)) 7681 /* A NULL register has a SCALAR_VALUE type, so skip 7682 * type checking. 7683 */ 7684 goto skip_type_check; 7685 7686 /* arg_btf_id and arg_size are in a union. */ 7687 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 7688 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 7689 arg_btf_id = fn->arg_btf_id[arg]; 7690 7691 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 7692 if (err) 7693 return err; 7694 7695 err = check_func_arg_reg_off(env, reg, regno, arg_type); 7696 if (err) 7697 return err; 7698 7699 skip_type_check: 7700 if (arg_type_is_release(arg_type)) { 7701 if (arg_type_is_dynptr(arg_type)) { 7702 struct bpf_func_state *state = func(env, reg); 7703 int spi; 7704 7705 /* Only dynptr created on stack can be released, thus 7706 * the get_spi and stack state checks for spilled_ptr 7707 * should only be done before process_dynptr_func for 7708 * PTR_TO_STACK. 7709 */ 7710 if (reg->type == PTR_TO_STACK) { 7711 spi = dynptr_get_spi(env, reg); 7712 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 7713 verbose(env, "arg %d is an unacquired reference\n", regno); 7714 return -EINVAL; 7715 } 7716 } else { 7717 verbose(env, "cannot release unowned const bpf_dynptr\n"); 7718 return -EINVAL; 7719 } 7720 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 7721 verbose(env, "R%d must be referenced when passed to release function\n", 7722 regno); 7723 return -EINVAL; 7724 } 7725 if (meta->release_regno) { 7726 verbose(env, "verifier internal error: more than one release argument\n"); 7727 return -EFAULT; 7728 } 7729 meta->release_regno = regno; 7730 } 7731 7732 if (reg->ref_obj_id) { 7733 if (meta->ref_obj_id) { 7734 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 7735 regno, reg->ref_obj_id, 7736 meta->ref_obj_id); 7737 return -EFAULT; 7738 } 7739 meta->ref_obj_id = reg->ref_obj_id; 7740 } 7741 7742 switch (base_type(arg_type)) { 7743 case ARG_CONST_MAP_PTR: 7744 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 7745 if (meta->map_ptr) { 7746 /* Use map_uid (which is unique id of inner map) to reject: 7747 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 7748 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 7749 * if (inner_map1 && inner_map2) { 7750 * timer = bpf_map_lookup_elem(inner_map1); 7751 * if (timer) 7752 * // mismatch would have been allowed 7753 * bpf_timer_init(timer, inner_map2); 7754 * } 7755 * 7756 * Comparing map_ptr is enough to distinguish normal and outer maps. 7757 */ 7758 if (meta->map_ptr != reg->map_ptr || 7759 meta->map_uid != reg->map_uid) { 7760 verbose(env, 7761 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 7762 meta->map_uid, reg->map_uid); 7763 return -EINVAL; 7764 } 7765 } 7766 meta->map_ptr = reg->map_ptr; 7767 meta->map_uid = reg->map_uid; 7768 break; 7769 case ARG_PTR_TO_MAP_KEY: 7770 /* bpf_map_xxx(..., map_ptr, ..., key) call: 7771 * check that [key, key + map->key_size) are within 7772 * stack limits and initialized 7773 */ 7774 if (!meta->map_ptr) { 7775 /* in function declaration map_ptr must come before 7776 * map_key, so that it's verified and known before 7777 * we have to check map_key here. Otherwise it means 7778 * that kernel subsystem misconfigured verifier 7779 */ 7780 verbose(env, "invalid map_ptr to access map->key\n"); 7781 return -EACCES; 7782 } 7783 err = check_helper_mem_access(env, regno, 7784 meta->map_ptr->key_size, false, 7785 NULL); 7786 break; 7787 case ARG_PTR_TO_MAP_VALUE: 7788 if (type_may_be_null(arg_type) && register_is_null(reg)) 7789 return 0; 7790 7791 /* bpf_map_xxx(..., map_ptr, ..., value) call: 7792 * check [value, value + map->value_size) validity 7793 */ 7794 if (!meta->map_ptr) { 7795 /* kernel subsystem misconfigured verifier */ 7796 verbose(env, "invalid map_ptr to access map->value\n"); 7797 return -EACCES; 7798 } 7799 meta->raw_mode = arg_type & MEM_UNINIT; 7800 err = check_helper_mem_access(env, regno, 7801 meta->map_ptr->value_size, false, 7802 meta); 7803 break; 7804 case ARG_PTR_TO_PERCPU_BTF_ID: 7805 if (!reg->btf_id) { 7806 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 7807 return -EACCES; 7808 } 7809 meta->ret_btf = reg->btf; 7810 meta->ret_btf_id = reg->btf_id; 7811 break; 7812 case ARG_PTR_TO_SPIN_LOCK: 7813 if (in_rbtree_lock_required_cb(env)) { 7814 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 7815 return -EACCES; 7816 } 7817 if (meta->func_id == BPF_FUNC_spin_lock) { 7818 err = process_spin_lock(env, regno, true); 7819 if (err) 7820 return err; 7821 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 7822 err = process_spin_lock(env, regno, false); 7823 if (err) 7824 return err; 7825 } else { 7826 verbose(env, "verifier internal error\n"); 7827 return -EFAULT; 7828 } 7829 break; 7830 case ARG_PTR_TO_TIMER: 7831 err = process_timer_func(env, regno, meta); 7832 if (err) 7833 return err; 7834 break; 7835 case ARG_PTR_TO_FUNC: 7836 meta->subprogno = reg->subprogno; 7837 break; 7838 case ARG_PTR_TO_MEM: 7839 /* The access to this pointer is only checked when we hit the 7840 * next is_mem_size argument below. 7841 */ 7842 meta->raw_mode = arg_type & MEM_UNINIT; 7843 if (arg_type & MEM_FIXED_SIZE) { 7844 err = check_helper_mem_access(env, regno, 7845 fn->arg_size[arg], false, 7846 meta); 7847 } 7848 break; 7849 case ARG_CONST_SIZE: 7850 err = check_mem_size_reg(env, reg, regno, false, meta); 7851 break; 7852 case ARG_CONST_SIZE_OR_ZERO: 7853 err = check_mem_size_reg(env, reg, regno, true, meta); 7854 break; 7855 case ARG_PTR_TO_DYNPTR: 7856 err = process_dynptr_func(env, regno, insn_idx, arg_type, 0); 7857 if (err) 7858 return err; 7859 break; 7860 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 7861 if (!tnum_is_const(reg->var_off)) { 7862 verbose(env, "R%d is not a known constant'\n", 7863 regno); 7864 return -EACCES; 7865 } 7866 meta->mem_size = reg->var_off.value; 7867 err = mark_chain_precision(env, regno); 7868 if (err) 7869 return err; 7870 break; 7871 case ARG_PTR_TO_INT: 7872 case ARG_PTR_TO_LONG: 7873 { 7874 int size = int_ptr_type_to_size(arg_type); 7875 7876 err = check_helper_mem_access(env, regno, size, false, meta); 7877 if (err) 7878 return err; 7879 err = check_ptr_alignment(env, reg, 0, size, true); 7880 break; 7881 } 7882 case ARG_PTR_TO_CONST_STR: 7883 { 7884 struct bpf_map *map = reg->map_ptr; 7885 int map_off; 7886 u64 map_addr; 7887 char *str_ptr; 7888 7889 if (!bpf_map_is_rdonly(map)) { 7890 verbose(env, "R%d does not point to a readonly map'\n", regno); 7891 return -EACCES; 7892 } 7893 7894 if (!tnum_is_const(reg->var_off)) { 7895 verbose(env, "R%d is not a constant address'\n", regno); 7896 return -EACCES; 7897 } 7898 7899 if (!map->ops->map_direct_value_addr) { 7900 verbose(env, "no direct value access support for this map type\n"); 7901 return -EACCES; 7902 } 7903 7904 err = check_map_access(env, regno, reg->off, 7905 map->value_size - reg->off, false, 7906 ACCESS_HELPER); 7907 if (err) 7908 return err; 7909 7910 map_off = reg->off + reg->var_off.value; 7911 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 7912 if (err) { 7913 verbose(env, "direct value access on string failed\n"); 7914 return err; 7915 } 7916 7917 str_ptr = (char *)(long)(map_addr); 7918 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 7919 verbose(env, "string is not zero-terminated\n"); 7920 return -EINVAL; 7921 } 7922 break; 7923 } 7924 case ARG_PTR_TO_KPTR: 7925 err = process_kptr_func(env, regno, meta); 7926 if (err) 7927 return err; 7928 break; 7929 } 7930 7931 return err; 7932 } 7933 7934 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 7935 { 7936 enum bpf_attach_type eatype = env->prog->expected_attach_type; 7937 enum bpf_prog_type type = resolve_prog_type(env->prog); 7938 7939 if (func_id != BPF_FUNC_map_update_elem) 7940 return false; 7941 7942 /* It's not possible to get access to a locked struct sock in these 7943 * contexts, so updating is safe. 7944 */ 7945 switch (type) { 7946 case BPF_PROG_TYPE_TRACING: 7947 if (eatype == BPF_TRACE_ITER) 7948 return true; 7949 break; 7950 case BPF_PROG_TYPE_SOCKET_FILTER: 7951 case BPF_PROG_TYPE_SCHED_CLS: 7952 case BPF_PROG_TYPE_SCHED_ACT: 7953 case BPF_PROG_TYPE_XDP: 7954 case BPF_PROG_TYPE_SK_REUSEPORT: 7955 case BPF_PROG_TYPE_FLOW_DISSECTOR: 7956 case BPF_PROG_TYPE_SK_LOOKUP: 7957 return true; 7958 default: 7959 break; 7960 } 7961 7962 verbose(env, "cannot update sockmap in this context\n"); 7963 return false; 7964 } 7965 7966 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 7967 { 7968 return env->prog->jit_requested && 7969 bpf_jit_supports_subprog_tailcalls(); 7970 } 7971 7972 static int check_map_func_compatibility(struct bpf_verifier_env *env, 7973 struct bpf_map *map, int func_id) 7974 { 7975 if (!map) 7976 return 0; 7977 7978 /* We need a two way check, first is from map perspective ... */ 7979 switch (map->map_type) { 7980 case BPF_MAP_TYPE_PROG_ARRAY: 7981 if (func_id != BPF_FUNC_tail_call) 7982 goto error; 7983 break; 7984 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 7985 if (func_id != BPF_FUNC_perf_event_read && 7986 func_id != BPF_FUNC_perf_event_output && 7987 func_id != BPF_FUNC_skb_output && 7988 func_id != BPF_FUNC_perf_event_read_value && 7989 func_id != BPF_FUNC_xdp_output) 7990 goto error; 7991 break; 7992 case BPF_MAP_TYPE_RINGBUF: 7993 if (func_id != BPF_FUNC_ringbuf_output && 7994 func_id != BPF_FUNC_ringbuf_reserve && 7995 func_id != BPF_FUNC_ringbuf_query && 7996 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 7997 func_id != BPF_FUNC_ringbuf_submit_dynptr && 7998 func_id != BPF_FUNC_ringbuf_discard_dynptr) 7999 goto error; 8000 break; 8001 case BPF_MAP_TYPE_USER_RINGBUF: 8002 if (func_id != BPF_FUNC_user_ringbuf_drain) 8003 goto error; 8004 break; 8005 case BPF_MAP_TYPE_STACK_TRACE: 8006 if (func_id != BPF_FUNC_get_stackid) 8007 goto error; 8008 break; 8009 case BPF_MAP_TYPE_CGROUP_ARRAY: 8010 if (func_id != BPF_FUNC_skb_under_cgroup && 8011 func_id != BPF_FUNC_current_task_under_cgroup) 8012 goto error; 8013 break; 8014 case BPF_MAP_TYPE_CGROUP_STORAGE: 8015 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 8016 if (func_id != BPF_FUNC_get_local_storage) 8017 goto error; 8018 break; 8019 case BPF_MAP_TYPE_DEVMAP: 8020 case BPF_MAP_TYPE_DEVMAP_HASH: 8021 if (func_id != BPF_FUNC_redirect_map && 8022 func_id != BPF_FUNC_map_lookup_elem) 8023 goto error; 8024 break; 8025 /* Restrict bpf side of cpumap and xskmap, open when use-cases 8026 * appear. 8027 */ 8028 case BPF_MAP_TYPE_CPUMAP: 8029 if (func_id != BPF_FUNC_redirect_map) 8030 goto error; 8031 break; 8032 case BPF_MAP_TYPE_XSKMAP: 8033 if (func_id != BPF_FUNC_redirect_map && 8034 func_id != BPF_FUNC_map_lookup_elem) 8035 goto error; 8036 break; 8037 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 8038 case BPF_MAP_TYPE_HASH_OF_MAPS: 8039 if (func_id != BPF_FUNC_map_lookup_elem) 8040 goto error; 8041 break; 8042 case BPF_MAP_TYPE_SOCKMAP: 8043 if (func_id != BPF_FUNC_sk_redirect_map && 8044 func_id != BPF_FUNC_sock_map_update && 8045 func_id != BPF_FUNC_map_delete_elem && 8046 func_id != BPF_FUNC_msg_redirect_map && 8047 func_id != BPF_FUNC_sk_select_reuseport && 8048 func_id != BPF_FUNC_map_lookup_elem && 8049 !may_update_sockmap(env, func_id)) 8050 goto error; 8051 break; 8052 case BPF_MAP_TYPE_SOCKHASH: 8053 if (func_id != BPF_FUNC_sk_redirect_hash && 8054 func_id != BPF_FUNC_sock_hash_update && 8055 func_id != BPF_FUNC_map_delete_elem && 8056 func_id != BPF_FUNC_msg_redirect_hash && 8057 func_id != BPF_FUNC_sk_select_reuseport && 8058 func_id != BPF_FUNC_map_lookup_elem && 8059 !may_update_sockmap(env, func_id)) 8060 goto error; 8061 break; 8062 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 8063 if (func_id != BPF_FUNC_sk_select_reuseport) 8064 goto error; 8065 break; 8066 case BPF_MAP_TYPE_QUEUE: 8067 case BPF_MAP_TYPE_STACK: 8068 if (func_id != BPF_FUNC_map_peek_elem && 8069 func_id != BPF_FUNC_map_pop_elem && 8070 func_id != BPF_FUNC_map_push_elem) 8071 goto error; 8072 break; 8073 case BPF_MAP_TYPE_SK_STORAGE: 8074 if (func_id != BPF_FUNC_sk_storage_get && 8075 func_id != BPF_FUNC_sk_storage_delete && 8076 func_id != BPF_FUNC_kptr_xchg) 8077 goto error; 8078 break; 8079 case BPF_MAP_TYPE_INODE_STORAGE: 8080 if (func_id != BPF_FUNC_inode_storage_get && 8081 func_id != BPF_FUNC_inode_storage_delete && 8082 func_id != BPF_FUNC_kptr_xchg) 8083 goto error; 8084 break; 8085 case BPF_MAP_TYPE_TASK_STORAGE: 8086 if (func_id != BPF_FUNC_task_storage_get && 8087 func_id != BPF_FUNC_task_storage_delete && 8088 func_id != BPF_FUNC_kptr_xchg) 8089 goto error; 8090 break; 8091 case BPF_MAP_TYPE_CGRP_STORAGE: 8092 if (func_id != BPF_FUNC_cgrp_storage_get && 8093 func_id != BPF_FUNC_cgrp_storage_delete && 8094 func_id != BPF_FUNC_kptr_xchg) 8095 goto error; 8096 break; 8097 case BPF_MAP_TYPE_BLOOM_FILTER: 8098 if (func_id != BPF_FUNC_map_peek_elem && 8099 func_id != BPF_FUNC_map_push_elem) 8100 goto error; 8101 break; 8102 default: 8103 break; 8104 } 8105 8106 /* ... and second from the function itself. */ 8107 switch (func_id) { 8108 case BPF_FUNC_tail_call: 8109 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 8110 goto error; 8111 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 8112 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 8113 return -EINVAL; 8114 } 8115 break; 8116 case BPF_FUNC_perf_event_read: 8117 case BPF_FUNC_perf_event_output: 8118 case BPF_FUNC_perf_event_read_value: 8119 case BPF_FUNC_skb_output: 8120 case BPF_FUNC_xdp_output: 8121 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 8122 goto error; 8123 break; 8124 case BPF_FUNC_ringbuf_output: 8125 case BPF_FUNC_ringbuf_reserve: 8126 case BPF_FUNC_ringbuf_query: 8127 case BPF_FUNC_ringbuf_reserve_dynptr: 8128 case BPF_FUNC_ringbuf_submit_dynptr: 8129 case BPF_FUNC_ringbuf_discard_dynptr: 8130 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 8131 goto error; 8132 break; 8133 case BPF_FUNC_user_ringbuf_drain: 8134 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 8135 goto error; 8136 break; 8137 case BPF_FUNC_get_stackid: 8138 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 8139 goto error; 8140 break; 8141 case BPF_FUNC_current_task_under_cgroup: 8142 case BPF_FUNC_skb_under_cgroup: 8143 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 8144 goto error; 8145 break; 8146 case BPF_FUNC_redirect_map: 8147 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 8148 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 8149 map->map_type != BPF_MAP_TYPE_CPUMAP && 8150 map->map_type != BPF_MAP_TYPE_XSKMAP) 8151 goto error; 8152 break; 8153 case BPF_FUNC_sk_redirect_map: 8154 case BPF_FUNC_msg_redirect_map: 8155 case BPF_FUNC_sock_map_update: 8156 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 8157 goto error; 8158 break; 8159 case BPF_FUNC_sk_redirect_hash: 8160 case BPF_FUNC_msg_redirect_hash: 8161 case BPF_FUNC_sock_hash_update: 8162 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 8163 goto error; 8164 break; 8165 case BPF_FUNC_get_local_storage: 8166 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 8167 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 8168 goto error; 8169 break; 8170 case BPF_FUNC_sk_select_reuseport: 8171 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 8172 map->map_type != BPF_MAP_TYPE_SOCKMAP && 8173 map->map_type != BPF_MAP_TYPE_SOCKHASH) 8174 goto error; 8175 break; 8176 case BPF_FUNC_map_pop_elem: 8177 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8178 map->map_type != BPF_MAP_TYPE_STACK) 8179 goto error; 8180 break; 8181 case BPF_FUNC_map_peek_elem: 8182 case BPF_FUNC_map_push_elem: 8183 if (map->map_type != BPF_MAP_TYPE_QUEUE && 8184 map->map_type != BPF_MAP_TYPE_STACK && 8185 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 8186 goto error; 8187 break; 8188 case BPF_FUNC_map_lookup_percpu_elem: 8189 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 8190 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8191 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 8192 goto error; 8193 break; 8194 case BPF_FUNC_sk_storage_get: 8195 case BPF_FUNC_sk_storage_delete: 8196 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 8197 goto error; 8198 break; 8199 case BPF_FUNC_inode_storage_get: 8200 case BPF_FUNC_inode_storage_delete: 8201 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8202 goto error; 8203 break; 8204 case BPF_FUNC_task_storage_get: 8205 case BPF_FUNC_task_storage_delete: 8206 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8207 goto error; 8208 break; 8209 case BPF_FUNC_cgrp_storage_get: 8210 case BPF_FUNC_cgrp_storage_delete: 8211 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8212 goto error; 8213 break; 8214 default: 8215 break; 8216 } 8217 8218 return 0; 8219 error: 8220 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8221 map->map_type, func_id_name(func_id), func_id); 8222 return -EINVAL; 8223 } 8224 8225 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8226 { 8227 int count = 0; 8228 8229 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 8230 count++; 8231 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 8232 count++; 8233 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 8234 count++; 8235 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 8236 count++; 8237 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 8238 count++; 8239 8240 /* We only support one arg being in raw mode at the moment, 8241 * which is sufficient for the helper functions we have 8242 * right now. 8243 */ 8244 return count <= 1; 8245 } 8246 8247 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8248 { 8249 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8250 bool has_size = fn->arg_size[arg] != 0; 8251 bool is_next_size = false; 8252 8253 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8254 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8255 8256 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8257 return is_next_size; 8258 8259 return has_size == is_next_size || is_next_size == is_fixed; 8260 } 8261 8262 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8263 { 8264 /* bpf_xxx(..., buf, len) call will access 'len' 8265 * bytes from memory 'buf'. Both arg types need 8266 * to be paired, so make sure there's no buggy 8267 * helper function specification. 8268 */ 8269 if (arg_type_is_mem_size(fn->arg1_type) || 8270 check_args_pair_invalid(fn, 0) || 8271 check_args_pair_invalid(fn, 1) || 8272 check_args_pair_invalid(fn, 2) || 8273 check_args_pair_invalid(fn, 3) || 8274 check_args_pair_invalid(fn, 4)) 8275 return false; 8276 8277 return true; 8278 } 8279 8280 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8281 { 8282 int i; 8283 8284 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8285 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8286 return !!fn->arg_btf_id[i]; 8287 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8288 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8289 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8290 /* arg_btf_id and arg_size are in a union. */ 8291 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8292 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8293 return false; 8294 } 8295 8296 return true; 8297 } 8298 8299 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 8300 { 8301 return check_raw_mode_ok(fn) && 8302 check_arg_pair_ok(fn) && 8303 check_btf_id_ok(fn) ? 0 : -EINVAL; 8304 } 8305 8306 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8307 * are now invalid, so turn them into unknown SCALAR_VALUE. 8308 * 8309 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8310 * since these slices point to packet data. 8311 */ 8312 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8313 { 8314 struct bpf_func_state *state; 8315 struct bpf_reg_state *reg; 8316 8317 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8318 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8319 mark_reg_invalid(env, reg); 8320 })); 8321 } 8322 8323 enum { 8324 AT_PKT_END = -1, 8325 BEYOND_PKT_END = -2, 8326 }; 8327 8328 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8329 { 8330 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8331 struct bpf_reg_state *reg = &state->regs[regn]; 8332 8333 if (reg->type != PTR_TO_PACKET) 8334 /* PTR_TO_PACKET_META is not supported yet */ 8335 return; 8336 8337 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8338 * How far beyond pkt_end it goes is unknown. 8339 * if (!range_open) it's the case of pkt >= pkt_end 8340 * if (range_open) it's the case of pkt > pkt_end 8341 * hence this pointer is at least 1 byte bigger than pkt_end 8342 */ 8343 if (range_open) 8344 reg->range = BEYOND_PKT_END; 8345 else 8346 reg->range = AT_PKT_END; 8347 } 8348 8349 /* The pointer with the specified id has released its reference to kernel 8350 * resources. Identify all copies of the same pointer and clear the reference. 8351 */ 8352 static int release_reference(struct bpf_verifier_env *env, 8353 int ref_obj_id) 8354 { 8355 struct bpf_func_state *state; 8356 struct bpf_reg_state *reg; 8357 int err; 8358 8359 err = release_reference_state(cur_func(env), ref_obj_id); 8360 if (err) 8361 return err; 8362 8363 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8364 if (reg->ref_obj_id == ref_obj_id) 8365 mark_reg_invalid(env, reg); 8366 })); 8367 8368 return 0; 8369 } 8370 8371 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 8372 { 8373 struct bpf_func_state *unused; 8374 struct bpf_reg_state *reg; 8375 8376 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 8377 if (type_is_non_owning_ref(reg->type)) 8378 mark_reg_invalid(env, reg); 8379 })); 8380 } 8381 8382 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 8383 struct bpf_reg_state *regs) 8384 { 8385 int i; 8386 8387 /* after the call registers r0 - r5 were scratched */ 8388 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8389 mark_reg_not_init(env, regs, caller_saved[i]); 8390 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8391 } 8392 } 8393 8394 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 8395 struct bpf_func_state *caller, 8396 struct bpf_func_state *callee, 8397 int insn_idx); 8398 8399 static int set_callee_state(struct bpf_verifier_env *env, 8400 struct bpf_func_state *caller, 8401 struct bpf_func_state *callee, int insn_idx); 8402 8403 static bool is_callback_calling_kfunc(u32 btf_id); 8404 8405 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8406 int *insn_idx, int subprog, 8407 set_callee_state_fn set_callee_state_cb) 8408 { 8409 struct bpf_verifier_state *state = env->cur_state; 8410 struct bpf_func_info_aux *func_info_aux; 8411 struct bpf_func_state *caller, *callee; 8412 int err; 8413 bool is_global = false; 8414 8415 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 8416 verbose(env, "the call stack of %d frames is too deep\n", 8417 state->curframe + 2); 8418 return -E2BIG; 8419 } 8420 8421 caller = state->frame[state->curframe]; 8422 if (state->frame[state->curframe + 1]) { 8423 verbose(env, "verifier bug. Frame %d already allocated\n", 8424 state->curframe + 1); 8425 return -EFAULT; 8426 } 8427 8428 func_info_aux = env->prog->aux->func_info_aux; 8429 if (func_info_aux) 8430 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 8431 err = btf_check_subprog_call(env, subprog, caller->regs); 8432 if (err == -EFAULT) 8433 return err; 8434 if (is_global) { 8435 if (err) { 8436 verbose(env, "Caller passes invalid args into func#%d\n", 8437 subprog); 8438 return err; 8439 } else { 8440 if (env->log.level & BPF_LOG_LEVEL) 8441 verbose(env, 8442 "Func#%d is global and valid. Skipping.\n", 8443 subprog); 8444 clear_caller_saved_regs(env, caller->regs); 8445 8446 /* All global functions return a 64-bit SCALAR_VALUE */ 8447 mark_reg_unknown(env, caller->regs, BPF_REG_0); 8448 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8449 8450 /* continue with next insn after call */ 8451 return 0; 8452 } 8453 } 8454 8455 /* set_callee_state is used for direct subprog calls, but we are 8456 * interested in validating only BPF helpers that can call subprogs as 8457 * callbacks 8458 */ 8459 if (set_callee_state_cb != set_callee_state) { 8460 if (bpf_pseudo_kfunc_call(insn) && 8461 !is_callback_calling_kfunc(insn->imm)) { 8462 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 8463 func_id_name(insn->imm), insn->imm); 8464 return -EFAULT; 8465 } else if (!bpf_pseudo_kfunc_call(insn) && 8466 !is_callback_calling_function(insn->imm)) { /* helper */ 8467 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 8468 func_id_name(insn->imm), insn->imm); 8469 return -EFAULT; 8470 } 8471 } 8472 8473 if (insn->code == (BPF_JMP | BPF_CALL) && 8474 insn->src_reg == 0 && 8475 insn->imm == BPF_FUNC_timer_set_callback) { 8476 struct bpf_verifier_state *async_cb; 8477 8478 /* there is no real recursion here. timer callbacks are async */ 8479 env->subprog_info[subprog].is_async_cb = true; 8480 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 8481 *insn_idx, subprog); 8482 if (!async_cb) 8483 return -EFAULT; 8484 callee = async_cb->frame[0]; 8485 callee->async_entry_cnt = caller->async_entry_cnt + 1; 8486 8487 /* Convert bpf_timer_set_callback() args into timer callback args */ 8488 err = set_callee_state_cb(env, caller, callee, *insn_idx); 8489 if (err) 8490 return err; 8491 8492 clear_caller_saved_regs(env, caller->regs); 8493 mark_reg_unknown(env, caller->regs, BPF_REG_0); 8494 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8495 /* continue with next insn after call */ 8496 return 0; 8497 } 8498 8499 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 8500 if (!callee) 8501 return -ENOMEM; 8502 state->frame[state->curframe + 1] = callee; 8503 8504 /* callee cannot access r0, r6 - r9 for reading and has to write 8505 * into its own stack before reading from it. 8506 * callee can read/write into caller's stack 8507 */ 8508 init_func_state(env, callee, 8509 /* remember the callsite, it will be used by bpf_exit */ 8510 *insn_idx /* callsite */, 8511 state->curframe + 1 /* frameno within this callchain */, 8512 subprog /* subprog number within this prog */); 8513 8514 /* Transfer references to the callee */ 8515 err = copy_reference_state(callee, caller); 8516 if (err) 8517 goto err_out; 8518 8519 err = set_callee_state_cb(env, caller, callee, *insn_idx); 8520 if (err) 8521 goto err_out; 8522 8523 clear_caller_saved_regs(env, caller->regs); 8524 8525 /* only increment it after check_reg_arg() finished */ 8526 state->curframe++; 8527 8528 /* and go analyze first insn of the callee */ 8529 *insn_idx = env->subprog_info[subprog].start - 1; 8530 8531 if (env->log.level & BPF_LOG_LEVEL) { 8532 verbose(env, "caller:\n"); 8533 print_verifier_state(env, caller, true); 8534 verbose(env, "callee:\n"); 8535 print_verifier_state(env, callee, true); 8536 } 8537 return 0; 8538 8539 err_out: 8540 free_func_state(callee); 8541 state->frame[state->curframe + 1] = NULL; 8542 return err; 8543 } 8544 8545 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 8546 struct bpf_func_state *caller, 8547 struct bpf_func_state *callee) 8548 { 8549 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 8550 * void *callback_ctx, u64 flags); 8551 * callback_fn(struct bpf_map *map, void *key, void *value, 8552 * void *callback_ctx); 8553 */ 8554 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 8555 8556 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 8557 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 8558 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 8559 8560 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 8561 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 8562 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 8563 8564 /* pointer to stack or null */ 8565 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 8566 8567 /* unused */ 8568 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8569 return 0; 8570 } 8571 8572 static int set_callee_state(struct bpf_verifier_env *env, 8573 struct bpf_func_state *caller, 8574 struct bpf_func_state *callee, int insn_idx) 8575 { 8576 int i; 8577 8578 /* copy r1 - r5 args that callee can access. The copy includes parent 8579 * pointers, which connects us up to the liveness chain 8580 */ 8581 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 8582 callee->regs[i] = caller->regs[i]; 8583 return 0; 8584 } 8585 8586 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8587 int *insn_idx) 8588 { 8589 int subprog, target_insn; 8590 8591 target_insn = *insn_idx + insn->imm + 1; 8592 subprog = find_subprog(env, target_insn); 8593 if (subprog < 0) { 8594 verbose(env, "verifier bug. No program starts at insn %d\n", 8595 target_insn); 8596 return -EFAULT; 8597 } 8598 8599 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 8600 } 8601 8602 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 8603 struct bpf_func_state *caller, 8604 struct bpf_func_state *callee, 8605 int insn_idx) 8606 { 8607 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 8608 struct bpf_map *map; 8609 int err; 8610 8611 if (bpf_map_ptr_poisoned(insn_aux)) { 8612 verbose(env, "tail_call abusing map_ptr\n"); 8613 return -EINVAL; 8614 } 8615 8616 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 8617 if (!map->ops->map_set_for_each_callback_args || 8618 !map->ops->map_for_each_callback) { 8619 verbose(env, "callback function not allowed for map\n"); 8620 return -ENOTSUPP; 8621 } 8622 8623 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 8624 if (err) 8625 return err; 8626 8627 callee->in_callback_fn = true; 8628 callee->callback_ret_range = tnum_range(0, 1); 8629 return 0; 8630 } 8631 8632 static int set_loop_callback_state(struct bpf_verifier_env *env, 8633 struct bpf_func_state *caller, 8634 struct bpf_func_state *callee, 8635 int insn_idx) 8636 { 8637 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 8638 * u64 flags); 8639 * callback_fn(u32 index, void *callback_ctx); 8640 */ 8641 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 8642 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 8643 8644 /* unused */ 8645 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 8646 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8647 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8648 8649 callee->in_callback_fn = true; 8650 callee->callback_ret_range = tnum_range(0, 1); 8651 return 0; 8652 } 8653 8654 static int set_timer_callback_state(struct bpf_verifier_env *env, 8655 struct bpf_func_state *caller, 8656 struct bpf_func_state *callee, 8657 int insn_idx) 8658 { 8659 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 8660 8661 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 8662 * callback_fn(struct bpf_map *map, void *key, void *value); 8663 */ 8664 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 8665 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 8666 callee->regs[BPF_REG_1].map_ptr = map_ptr; 8667 8668 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 8669 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 8670 callee->regs[BPF_REG_2].map_ptr = map_ptr; 8671 8672 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 8673 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 8674 callee->regs[BPF_REG_3].map_ptr = map_ptr; 8675 8676 /* unused */ 8677 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8678 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8679 callee->in_async_callback_fn = true; 8680 callee->callback_ret_range = tnum_range(0, 1); 8681 return 0; 8682 } 8683 8684 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 8685 struct bpf_func_state *caller, 8686 struct bpf_func_state *callee, 8687 int insn_idx) 8688 { 8689 /* bpf_find_vma(struct task_struct *task, u64 addr, 8690 * void *callback_fn, void *callback_ctx, u64 flags) 8691 * (callback_fn)(struct task_struct *task, 8692 * struct vm_area_struct *vma, void *callback_ctx); 8693 */ 8694 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 8695 8696 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 8697 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 8698 callee->regs[BPF_REG_2].btf = btf_vmlinux; 8699 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 8700 8701 /* pointer to stack or null */ 8702 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 8703 8704 /* unused */ 8705 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8706 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8707 callee->in_callback_fn = true; 8708 callee->callback_ret_range = tnum_range(0, 1); 8709 return 0; 8710 } 8711 8712 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 8713 struct bpf_func_state *caller, 8714 struct bpf_func_state *callee, 8715 int insn_idx) 8716 { 8717 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 8718 * callback_ctx, u64 flags); 8719 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 8720 */ 8721 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 8722 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 8723 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 8724 8725 /* unused */ 8726 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 8727 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8728 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8729 8730 callee->in_callback_fn = true; 8731 callee->callback_ret_range = tnum_range(0, 1); 8732 return 0; 8733 } 8734 8735 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 8736 struct bpf_func_state *caller, 8737 struct bpf_func_state *callee, 8738 int insn_idx) 8739 { 8740 /* void bpf_rbtree_add_impl(struct bpf_rb_root *root, struct bpf_rb_node *node, 8741 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 8742 * 8743 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add_impl is the same PTR_TO_BTF_ID w/ offset 8744 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 8745 * by this point, so look at 'root' 8746 */ 8747 struct btf_field *field; 8748 8749 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 8750 BPF_RB_ROOT); 8751 if (!field || !field->graph_root.value_btf_id) 8752 return -EFAULT; 8753 8754 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 8755 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 8756 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 8757 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 8758 8759 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 8760 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8761 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8762 callee->in_callback_fn = true; 8763 callee->callback_ret_range = tnum_range(0, 1); 8764 return 0; 8765 } 8766 8767 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 8768 8769 /* Are we currently verifying the callback for a rbtree helper that must 8770 * be called with lock held? If so, no need to complain about unreleased 8771 * lock 8772 */ 8773 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 8774 { 8775 struct bpf_verifier_state *state = env->cur_state; 8776 struct bpf_insn *insn = env->prog->insnsi; 8777 struct bpf_func_state *callee; 8778 int kfunc_btf_id; 8779 8780 if (!state->curframe) 8781 return false; 8782 8783 callee = state->frame[state->curframe]; 8784 8785 if (!callee->in_callback_fn) 8786 return false; 8787 8788 kfunc_btf_id = insn[callee->callsite].imm; 8789 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 8790 } 8791 8792 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 8793 { 8794 struct bpf_verifier_state *state = env->cur_state; 8795 struct bpf_func_state *caller, *callee; 8796 struct bpf_reg_state *r0; 8797 int err; 8798 8799 callee = state->frame[state->curframe]; 8800 r0 = &callee->regs[BPF_REG_0]; 8801 if (r0->type == PTR_TO_STACK) { 8802 /* technically it's ok to return caller's stack pointer 8803 * (or caller's caller's pointer) back to the caller, 8804 * since these pointers are valid. Only current stack 8805 * pointer will be invalid as soon as function exits, 8806 * but let's be conservative 8807 */ 8808 verbose(env, "cannot return stack pointer to the caller\n"); 8809 return -EINVAL; 8810 } 8811 8812 caller = state->frame[state->curframe - 1]; 8813 if (callee->in_callback_fn) { 8814 /* enforce R0 return value range [0, 1]. */ 8815 struct tnum range = callee->callback_ret_range; 8816 8817 if (r0->type != SCALAR_VALUE) { 8818 verbose(env, "R0 not a scalar value\n"); 8819 return -EACCES; 8820 } 8821 if (!tnum_in(range, r0->var_off)) { 8822 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 8823 return -EINVAL; 8824 } 8825 } else { 8826 /* return to the caller whatever r0 had in the callee */ 8827 caller->regs[BPF_REG_0] = *r0; 8828 } 8829 8830 /* callback_fn frame should have released its own additions to parent's 8831 * reference state at this point, or check_reference_leak would 8832 * complain, hence it must be the same as the caller. There is no need 8833 * to copy it back. 8834 */ 8835 if (!callee->in_callback_fn) { 8836 /* Transfer references to the caller */ 8837 err = copy_reference_state(caller, callee); 8838 if (err) 8839 return err; 8840 } 8841 8842 *insn_idx = callee->callsite + 1; 8843 if (env->log.level & BPF_LOG_LEVEL) { 8844 verbose(env, "returning from callee:\n"); 8845 print_verifier_state(env, callee, true); 8846 verbose(env, "to caller at %d:\n", *insn_idx); 8847 print_verifier_state(env, caller, true); 8848 } 8849 /* clear everything in the callee */ 8850 free_func_state(callee); 8851 state->frame[state->curframe--] = NULL; 8852 return 0; 8853 } 8854 8855 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 8856 int func_id, 8857 struct bpf_call_arg_meta *meta) 8858 { 8859 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 8860 8861 if (ret_type != RET_INTEGER || 8862 (func_id != BPF_FUNC_get_stack && 8863 func_id != BPF_FUNC_get_task_stack && 8864 func_id != BPF_FUNC_probe_read_str && 8865 func_id != BPF_FUNC_probe_read_kernel_str && 8866 func_id != BPF_FUNC_probe_read_user_str)) 8867 return; 8868 8869 ret_reg->smax_value = meta->msize_max_value; 8870 ret_reg->s32_max_value = meta->msize_max_value; 8871 ret_reg->smin_value = -MAX_ERRNO; 8872 ret_reg->s32_min_value = -MAX_ERRNO; 8873 reg_bounds_sync(ret_reg); 8874 } 8875 8876 static int 8877 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 8878 int func_id, int insn_idx) 8879 { 8880 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 8881 struct bpf_map *map = meta->map_ptr; 8882 8883 if (func_id != BPF_FUNC_tail_call && 8884 func_id != BPF_FUNC_map_lookup_elem && 8885 func_id != BPF_FUNC_map_update_elem && 8886 func_id != BPF_FUNC_map_delete_elem && 8887 func_id != BPF_FUNC_map_push_elem && 8888 func_id != BPF_FUNC_map_pop_elem && 8889 func_id != BPF_FUNC_map_peek_elem && 8890 func_id != BPF_FUNC_for_each_map_elem && 8891 func_id != BPF_FUNC_redirect_map && 8892 func_id != BPF_FUNC_map_lookup_percpu_elem) 8893 return 0; 8894 8895 if (map == NULL) { 8896 verbose(env, "kernel subsystem misconfigured verifier\n"); 8897 return -EINVAL; 8898 } 8899 8900 /* In case of read-only, some additional restrictions 8901 * need to be applied in order to prevent altering the 8902 * state of the map from program side. 8903 */ 8904 if ((map->map_flags & BPF_F_RDONLY_PROG) && 8905 (func_id == BPF_FUNC_map_delete_elem || 8906 func_id == BPF_FUNC_map_update_elem || 8907 func_id == BPF_FUNC_map_push_elem || 8908 func_id == BPF_FUNC_map_pop_elem)) { 8909 verbose(env, "write into map forbidden\n"); 8910 return -EACCES; 8911 } 8912 8913 if (!BPF_MAP_PTR(aux->map_ptr_state)) 8914 bpf_map_ptr_store(aux, meta->map_ptr, 8915 !meta->map_ptr->bypass_spec_v1); 8916 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 8917 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 8918 !meta->map_ptr->bypass_spec_v1); 8919 return 0; 8920 } 8921 8922 static int 8923 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 8924 int func_id, int insn_idx) 8925 { 8926 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 8927 struct bpf_reg_state *regs = cur_regs(env), *reg; 8928 struct bpf_map *map = meta->map_ptr; 8929 u64 val, max; 8930 int err; 8931 8932 if (func_id != BPF_FUNC_tail_call) 8933 return 0; 8934 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 8935 verbose(env, "kernel subsystem misconfigured verifier\n"); 8936 return -EINVAL; 8937 } 8938 8939 reg = ®s[BPF_REG_3]; 8940 val = reg->var_off.value; 8941 max = map->max_entries; 8942 8943 if (!(register_is_const(reg) && val < max)) { 8944 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 8945 return 0; 8946 } 8947 8948 err = mark_chain_precision(env, BPF_REG_3); 8949 if (err) 8950 return err; 8951 if (bpf_map_key_unseen(aux)) 8952 bpf_map_key_store(aux, val); 8953 else if (!bpf_map_key_poisoned(aux) && 8954 bpf_map_key_immediate(aux) != val) 8955 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 8956 return 0; 8957 } 8958 8959 static int check_reference_leak(struct bpf_verifier_env *env) 8960 { 8961 struct bpf_func_state *state = cur_func(env); 8962 bool refs_lingering = false; 8963 int i; 8964 8965 if (state->frameno && !state->in_callback_fn) 8966 return 0; 8967 8968 for (i = 0; i < state->acquired_refs; i++) { 8969 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 8970 continue; 8971 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 8972 state->refs[i].id, state->refs[i].insn_idx); 8973 refs_lingering = true; 8974 } 8975 return refs_lingering ? -EINVAL : 0; 8976 } 8977 8978 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 8979 struct bpf_reg_state *regs) 8980 { 8981 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 8982 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 8983 struct bpf_map *fmt_map = fmt_reg->map_ptr; 8984 struct bpf_bprintf_data data = {}; 8985 int err, fmt_map_off, num_args; 8986 u64 fmt_addr; 8987 char *fmt; 8988 8989 /* data must be an array of u64 */ 8990 if (data_len_reg->var_off.value % 8) 8991 return -EINVAL; 8992 num_args = data_len_reg->var_off.value / 8; 8993 8994 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 8995 * and map_direct_value_addr is set. 8996 */ 8997 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 8998 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 8999 fmt_map_off); 9000 if (err) { 9001 verbose(env, "verifier bug\n"); 9002 return -EFAULT; 9003 } 9004 fmt = (char *)(long)fmt_addr + fmt_map_off; 9005 9006 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 9007 * can focus on validating the format specifiers. 9008 */ 9009 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 9010 if (err < 0) 9011 verbose(env, "Invalid format string\n"); 9012 9013 return err; 9014 } 9015 9016 static int check_get_func_ip(struct bpf_verifier_env *env) 9017 { 9018 enum bpf_prog_type type = resolve_prog_type(env->prog); 9019 int func_id = BPF_FUNC_get_func_ip; 9020 9021 if (type == BPF_PROG_TYPE_TRACING) { 9022 if (!bpf_prog_has_trampoline(env->prog)) { 9023 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 9024 func_id_name(func_id), func_id); 9025 return -ENOTSUPP; 9026 } 9027 return 0; 9028 } else if (type == BPF_PROG_TYPE_KPROBE) { 9029 return 0; 9030 } 9031 9032 verbose(env, "func %s#%d not supported for program type %d\n", 9033 func_id_name(func_id), func_id, type); 9034 return -ENOTSUPP; 9035 } 9036 9037 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 9038 { 9039 return &env->insn_aux_data[env->insn_idx]; 9040 } 9041 9042 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 9043 { 9044 struct bpf_reg_state *regs = cur_regs(env); 9045 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 9046 bool reg_is_null = register_is_null(reg); 9047 9048 if (reg_is_null) 9049 mark_chain_precision(env, BPF_REG_4); 9050 9051 return reg_is_null; 9052 } 9053 9054 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 9055 { 9056 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 9057 9058 if (!state->initialized) { 9059 state->initialized = 1; 9060 state->fit_for_inline = loop_flag_is_zero(env); 9061 state->callback_subprogno = subprogno; 9062 return; 9063 } 9064 9065 if (!state->fit_for_inline) 9066 return; 9067 9068 state->fit_for_inline = (loop_flag_is_zero(env) && 9069 state->callback_subprogno == subprogno); 9070 } 9071 9072 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9073 int *insn_idx_p) 9074 { 9075 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9076 const struct bpf_func_proto *fn = NULL; 9077 enum bpf_return_type ret_type; 9078 enum bpf_type_flag ret_flag; 9079 struct bpf_reg_state *regs; 9080 struct bpf_call_arg_meta meta; 9081 int insn_idx = *insn_idx_p; 9082 bool changes_data; 9083 int i, err, func_id; 9084 9085 /* find function prototype */ 9086 func_id = insn->imm; 9087 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 9088 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 9089 func_id); 9090 return -EINVAL; 9091 } 9092 9093 if (env->ops->get_func_proto) 9094 fn = env->ops->get_func_proto(func_id, env->prog); 9095 if (!fn) { 9096 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 9097 func_id); 9098 return -EINVAL; 9099 } 9100 9101 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 9102 if (!env->prog->gpl_compatible && fn->gpl_only) { 9103 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 9104 return -EINVAL; 9105 } 9106 9107 if (fn->allowed && !fn->allowed(env->prog)) { 9108 verbose(env, "helper call is not allowed in probe\n"); 9109 return -EINVAL; 9110 } 9111 9112 if (!env->prog->aux->sleepable && fn->might_sleep) { 9113 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 9114 return -EINVAL; 9115 } 9116 9117 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 9118 changes_data = bpf_helper_changes_pkt_data(fn->func); 9119 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 9120 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 9121 func_id_name(func_id), func_id); 9122 return -EINVAL; 9123 } 9124 9125 memset(&meta, 0, sizeof(meta)); 9126 meta.pkt_access = fn->pkt_access; 9127 9128 err = check_func_proto(fn, func_id); 9129 if (err) { 9130 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 9131 func_id_name(func_id), func_id); 9132 return err; 9133 } 9134 9135 if (env->cur_state->active_rcu_lock) { 9136 if (fn->might_sleep) { 9137 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 9138 func_id_name(func_id), func_id); 9139 return -EINVAL; 9140 } 9141 9142 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 9143 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 9144 } 9145 9146 meta.func_id = func_id; 9147 /* check args */ 9148 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 9149 err = check_func_arg(env, i, &meta, fn, insn_idx); 9150 if (err) 9151 return err; 9152 } 9153 9154 err = record_func_map(env, &meta, func_id, insn_idx); 9155 if (err) 9156 return err; 9157 9158 err = record_func_key(env, &meta, func_id, insn_idx); 9159 if (err) 9160 return err; 9161 9162 /* Mark slots with STACK_MISC in case of raw mode, stack offset 9163 * is inferred from register state. 9164 */ 9165 for (i = 0; i < meta.access_size; i++) { 9166 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 9167 BPF_WRITE, -1, false); 9168 if (err) 9169 return err; 9170 } 9171 9172 regs = cur_regs(env); 9173 9174 if (meta.release_regno) { 9175 err = -EINVAL; 9176 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 9177 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 9178 * is safe to do directly. 9179 */ 9180 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 9181 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 9182 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 9183 return -EFAULT; 9184 } 9185 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 9186 } else if (meta.ref_obj_id) { 9187 err = release_reference(env, meta.ref_obj_id); 9188 } else if (register_is_null(®s[meta.release_regno])) { 9189 /* meta.ref_obj_id can only be 0 if register that is meant to be 9190 * released is NULL, which must be > R0. 9191 */ 9192 err = 0; 9193 } 9194 if (err) { 9195 verbose(env, "func %s#%d reference has not been acquired before\n", 9196 func_id_name(func_id), func_id); 9197 return err; 9198 } 9199 } 9200 9201 switch (func_id) { 9202 case BPF_FUNC_tail_call: 9203 err = check_reference_leak(env); 9204 if (err) { 9205 verbose(env, "tail_call would lead to reference leak\n"); 9206 return err; 9207 } 9208 break; 9209 case BPF_FUNC_get_local_storage: 9210 /* check that flags argument in get_local_storage(map, flags) is 0, 9211 * this is required because get_local_storage() can't return an error. 9212 */ 9213 if (!register_is_null(®s[BPF_REG_2])) { 9214 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 9215 return -EINVAL; 9216 } 9217 break; 9218 case BPF_FUNC_for_each_map_elem: 9219 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9220 set_map_elem_callback_state); 9221 break; 9222 case BPF_FUNC_timer_set_callback: 9223 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9224 set_timer_callback_state); 9225 break; 9226 case BPF_FUNC_find_vma: 9227 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9228 set_find_vma_callback_state); 9229 break; 9230 case BPF_FUNC_snprintf: 9231 err = check_bpf_snprintf_call(env, regs); 9232 break; 9233 case BPF_FUNC_loop: 9234 update_loop_inline_state(env, meta.subprogno); 9235 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9236 set_loop_callback_state); 9237 break; 9238 case BPF_FUNC_dynptr_from_mem: 9239 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 9240 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 9241 reg_type_str(env, regs[BPF_REG_1].type)); 9242 return -EACCES; 9243 } 9244 break; 9245 case BPF_FUNC_set_retval: 9246 if (prog_type == BPF_PROG_TYPE_LSM && 9247 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9248 if (!env->prog->aux->attach_func_proto->type) { 9249 /* Make sure programs that attach to void 9250 * hooks don't try to modify return value. 9251 */ 9252 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 9253 return -EINVAL; 9254 } 9255 } 9256 break; 9257 case BPF_FUNC_dynptr_data: 9258 { 9259 struct bpf_reg_state *reg; 9260 int id, ref_obj_id; 9261 9262 reg = get_dynptr_arg_reg(env, fn, regs); 9263 if (!reg) 9264 return -EFAULT; 9265 9266 9267 if (meta.dynptr_id) { 9268 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 9269 return -EFAULT; 9270 } 9271 if (meta.ref_obj_id) { 9272 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 9273 return -EFAULT; 9274 } 9275 9276 id = dynptr_id(env, reg); 9277 if (id < 0) { 9278 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 9279 return id; 9280 } 9281 9282 ref_obj_id = dynptr_ref_obj_id(env, reg); 9283 if (ref_obj_id < 0) { 9284 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 9285 return ref_obj_id; 9286 } 9287 9288 meta.dynptr_id = id; 9289 meta.ref_obj_id = ref_obj_id; 9290 9291 break; 9292 } 9293 case BPF_FUNC_dynptr_write: 9294 { 9295 enum bpf_dynptr_type dynptr_type; 9296 struct bpf_reg_state *reg; 9297 9298 reg = get_dynptr_arg_reg(env, fn, regs); 9299 if (!reg) 9300 return -EFAULT; 9301 9302 dynptr_type = dynptr_get_type(env, reg); 9303 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 9304 return -EFAULT; 9305 9306 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 9307 /* this will trigger clear_all_pkt_pointers(), which will 9308 * invalidate all dynptr slices associated with the skb 9309 */ 9310 changes_data = true; 9311 9312 break; 9313 } 9314 case BPF_FUNC_user_ringbuf_drain: 9315 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9316 set_user_ringbuf_callback_state); 9317 break; 9318 } 9319 9320 if (err) 9321 return err; 9322 9323 /* reset caller saved regs */ 9324 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9325 mark_reg_not_init(env, regs, caller_saved[i]); 9326 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9327 } 9328 9329 /* helper call returns 64-bit value. */ 9330 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9331 9332 /* update return register (already marked as written above) */ 9333 ret_type = fn->ret_type; 9334 ret_flag = type_flag(ret_type); 9335 9336 switch (base_type(ret_type)) { 9337 case RET_INTEGER: 9338 /* sets type to SCALAR_VALUE */ 9339 mark_reg_unknown(env, regs, BPF_REG_0); 9340 break; 9341 case RET_VOID: 9342 regs[BPF_REG_0].type = NOT_INIT; 9343 break; 9344 case RET_PTR_TO_MAP_VALUE: 9345 /* There is no offset yet applied, variable or fixed */ 9346 mark_reg_known_zero(env, regs, BPF_REG_0); 9347 /* remember map_ptr, so that check_map_access() 9348 * can check 'value_size' boundary of memory access 9349 * to map element returned from bpf_map_lookup_elem() 9350 */ 9351 if (meta.map_ptr == NULL) { 9352 verbose(env, 9353 "kernel subsystem misconfigured verifier\n"); 9354 return -EINVAL; 9355 } 9356 regs[BPF_REG_0].map_ptr = meta.map_ptr; 9357 regs[BPF_REG_0].map_uid = meta.map_uid; 9358 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 9359 if (!type_may_be_null(ret_type) && 9360 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 9361 regs[BPF_REG_0].id = ++env->id_gen; 9362 } 9363 break; 9364 case RET_PTR_TO_SOCKET: 9365 mark_reg_known_zero(env, regs, BPF_REG_0); 9366 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 9367 break; 9368 case RET_PTR_TO_SOCK_COMMON: 9369 mark_reg_known_zero(env, regs, BPF_REG_0); 9370 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 9371 break; 9372 case RET_PTR_TO_TCP_SOCK: 9373 mark_reg_known_zero(env, regs, BPF_REG_0); 9374 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 9375 break; 9376 case RET_PTR_TO_MEM: 9377 mark_reg_known_zero(env, regs, BPF_REG_0); 9378 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 9379 regs[BPF_REG_0].mem_size = meta.mem_size; 9380 break; 9381 case RET_PTR_TO_MEM_OR_BTF_ID: 9382 { 9383 const struct btf_type *t; 9384 9385 mark_reg_known_zero(env, regs, BPF_REG_0); 9386 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 9387 if (!btf_type_is_struct(t)) { 9388 u32 tsize; 9389 const struct btf_type *ret; 9390 const char *tname; 9391 9392 /* resolve the type size of ksym. */ 9393 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 9394 if (IS_ERR(ret)) { 9395 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 9396 verbose(env, "unable to resolve the size of type '%s': %ld\n", 9397 tname, PTR_ERR(ret)); 9398 return -EINVAL; 9399 } 9400 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 9401 regs[BPF_REG_0].mem_size = tsize; 9402 } else { 9403 /* MEM_RDONLY may be carried from ret_flag, but it 9404 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 9405 * it will confuse the check of PTR_TO_BTF_ID in 9406 * check_mem_access(). 9407 */ 9408 ret_flag &= ~MEM_RDONLY; 9409 9410 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 9411 regs[BPF_REG_0].btf = meta.ret_btf; 9412 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 9413 } 9414 break; 9415 } 9416 case RET_PTR_TO_BTF_ID: 9417 { 9418 struct btf *ret_btf; 9419 int ret_btf_id; 9420 9421 mark_reg_known_zero(env, regs, BPF_REG_0); 9422 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 9423 if (func_id == BPF_FUNC_kptr_xchg) { 9424 ret_btf = meta.kptr_field->kptr.btf; 9425 ret_btf_id = meta.kptr_field->kptr.btf_id; 9426 if (!btf_is_kernel(ret_btf)) 9427 regs[BPF_REG_0].type |= MEM_ALLOC; 9428 } else { 9429 if (fn->ret_btf_id == BPF_PTR_POISON) { 9430 verbose(env, "verifier internal error:"); 9431 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 9432 func_id_name(func_id)); 9433 return -EINVAL; 9434 } 9435 ret_btf = btf_vmlinux; 9436 ret_btf_id = *fn->ret_btf_id; 9437 } 9438 if (ret_btf_id == 0) { 9439 verbose(env, "invalid return type %u of func %s#%d\n", 9440 base_type(ret_type), func_id_name(func_id), 9441 func_id); 9442 return -EINVAL; 9443 } 9444 regs[BPF_REG_0].btf = ret_btf; 9445 regs[BPF_REG_0].btf_id = ret_btf_id; 9446 break; 9447 } 9448 default: 9449 verbose(env, "unknown return type %u of func %s#%d\n", 9450 base_type(ret_type), func_id_name(func_id), func_id); 9451 return -EINVAL; 9452 } 9453 9454 if (type_may_be_null(regs[BPF_REG_0].type)) 9455 regs[BPF_REG_0].id = ++env->id_gen; 9456 9457 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 9458 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 9459 func_id_name(func_id), func_id); 9460 return -EFAULT; 9461 } 9462 9463 if (is_dynptr_ref_function(func_id)) 9464 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 9465 9466 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 9467 /* For release_reference() */ 9468 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 9469 } else if (is_acquire_function(func_id, meta.map_ptr)) { 9470 int id = acquire_reference_state(env, insn_idx); 9471 9472 if (id < 0) 9473 return id; 9474 /* For mark_ptr_or_null_reg() */ 9475 regs[BPF_REG_0].id = id; 9476 /* For release_reference() */ 9477 regs[BPF_REG_0].ref_obj_id = id; 9478 } 9479 9480 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 9481 9482 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 9483 if (err) 9484 return err; 9485 9486 if ((func_id == BPF_FUNC_get_stack || 9487 func_id == BPF_FUNC_get_task_stack) && 9488 !env->prog->has_callchain_buf) { 9489 const char *err_str; 9490 9491 #ifdef CONFIG_PERF_EVENTS 9492 err = get_callchain_buffers(sysctl_perf_event_max_stack); 9493 err_str = "cannot get callchain buffer for func %s#%d\n"; 9494 #else 9495 err = -ENOTSUPP; 9496 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 9497 #endif 9498 if (err) { 9499 verbose(env, err_str, func_id_name(func_id), func_id); 9500 return err; 9501 } 9502 9503 env->prog->has_callchain_buf = true; 9504 } 9505 9506 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 9507 env->prog->call_get_stack = true; 9508 9509 if (func_id == BPF_FUNC_get_func_ip) { 9510 if (check_get_func_ip(env)) 9511 return -ENOTSUPP; 9512 env->prog->call_get_func_ip = true; 9513 } 9514 9515 if (changes_data) 9516 clear_all_pkt_pointers(env); 9517 return 0; 9518 } 9519 9520 /* mark_btf_func_reg_size() is used when the reg size is determined by 9521 * the BTF func_proto's return value size and argument. 9522 */ 9523 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 9524 size_t reg_size) 9525 { 9526 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 9527 9528 if (regno == BPF_REG_0) { 9529 /* Function return value */ 9530 reg->live |= REG_LIVE_WRITTEN; 9531 reg->subreg_def = reg_size == sizeof(u64) ? 9532 DEF_NOT_SUBREG : env->insn_idx + 1; 9533 } else { 9534 /* Function argument */ 9535 if (reg_size == sizeof(u64)) { 9536 mark_insn_zext(env, reg); 9537 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 9538 } else { 9539 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 9540 } 9541 } 9542 } 9543 9544 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 9545 { 9546 return meta->kfunc_flags & KF_ACQUIRE; 9547 } 9548 9549 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 9550 { 9551 return meta->kfunc_flags & KF_RET_NULL; 9552 } 9553 9554 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 9555 { 9556 return meta->kfunc_flags & KF_RELEASE; 9557 } 9558 9559 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 9560 { 9561 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 9562 } 9563 9564 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 9565 { 9566 return meta->kfunc_flags & KF_SLEEPABLE; 9567 } 9568 9569 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 9570 { 9571 return meta->kfunc_flags & KF_DESTRUCTIVE; 9572 } 9573 9574 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 9575 { 9576 return meta->kfunc_flags & KF_RCU; 9577 } 9578 9579 static bool __kfunc_param_match_suffix(const struct btf *btf, 9580 const struct btf_param *arg, 9581 const char *suffix) 9582 { 9583 int suffix_len = strlen(suffix), len; 9584 const char *param_name; 9585 9586 /* In the future, this can be ported to use BTF tagging */ 9587 param_name = btf_name_by_offset(btf, arg->name_off); 9588 if (str_is_empty(param_name)) 9589 return false; 9590 len = strlen(param_name); 9591 if (len < suffix_len) 9592 return false; 9593 param_name += len - suffix_len; 9594 return !strncmp(param_name, suffix, suffix_len); 9595 } 9596 9597 static bool is_kfunc_arg_mem_size(const struct btf *btf, 9598 const struct btf_param *arg, 9599 const struct bpf_reg_state *reg) 9600 { 9601 const struct btf_type *t; 9602 9603 t = btf_type_skip_modifiers(btf, arg->type, NULL); 9604 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 9605 return false; 9606 9607 return __kfunc_param_match_suffix(btf, arg, "__sz"); 9608 } 9609 9610 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 9611 const struct btf_param *arg, 9612 const struct bpf_reg_state *reg) 9613 { 9614 const struct btf_type *t; 9615 9616 t = btf_type_skip_modifiers(btf, arg->type, NULL); 9617 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 9618 return false; 9619 9620 return __kfunc_param_match_suffix(btf, arg, "__szk"); 9621 } 9622 9623 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 9624 { 9625 return __kfunc_param_match_suffix(btf, arg, "__k"); 9626 } 9627 9628 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 9629 { 9630 return __kfunc_param_match_suffix(btf, arg, "__ign"); 9631 } 9632 9633 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 9634 { 9635 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 9636 } 9637 9638 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 9639 { 9640 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 9641 } 9642 9643 static bool is_kfunc_arg_refcounted_kptr(const struct btf *btf, const struct btf_param *arg) 9644 { 9645 return __kfunc_param_match_suffix(btf, arg, "__refcounted_kptr"); 9646 } 9647 9648 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 9649 const struct btf_param *arg, 9650 const char *name) 9651 { 9652 int len, target_len = strlen(name); 9653 const char *param_name; 9654 9655 param_name = btf_name_by_offset(btf, arg->name_off); 9656 if (str_is_empty(param_name)) 9657 return false; 9658 len = strlen(param_name); 9659 if (len != target_len) 9660 return false; 9661 if (strcmp(param_name, name)) 9662 return false; 9663 9664 return true; 9665 } 9666 9667 enum { 9668 KF_ARG_DYNPTR_ID, 9669 KF_ARG_LIST_HEAD_ID, 9670 KF_ARG_LIST_NODE_ID, 9671 KF_ARG_RB_ROOT_ID, 9672 KF_ARG_RB_NODE_ID, 9673 }; 9674 9675 BTF_ID_LIST(kf_arg_btf_ids) 9676 BTF_ID(struct, bpf_dynptr_kern) 9677 BTF_ID(struct, bpf_list_head) 9678 BTF_ID(struct, bpf_list_node) 9679 BTF_ID(struct, bpf_rb_root) 9680 BTF_ID(struct, bpf_rb_node) 9681 9682 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 9683 const struct btf_param *arg, int type) 9684 { 9685 const struct btf_type *t; 9686 u32 res_id; 9687 9688 t = btf_type_skip_modifiers(btf, arg->type, NULL); 9689 if (!t) 9690 return false; 9691 if (!btf_type_is_ptr(t)) 9692 return false; 9693 t = btf_type_skip_modifiers(btf, t->type, &res_id); 9694 if (!t) 9695 return false; 9696 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 9697 } 9698 9699 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 9700 { 9701 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 9702 } 9703 9704 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 9705 { 9706 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 9707 } 9708 9709 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 9710 { 9711 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 9712 } 9713 9714 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 9715 { 9716 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 9717 } 9718 9719 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 9720 { 9721 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 9722 } 9723 9724 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 9725 const struct btf_param *arg) 9726 { 9727 const struct btf_type *t; 9728 9729 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 9730 if (!t) 9731 return false; 9732 9733 return true; 9734 } 9735 9736 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 9737 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 9738 const struct btf *btf, 9739 const struct btf_type *t, int rec) 9740 { 9741 const struct btf_type *member_type; 9742 const struct btf_member *member; 9743 u32 i; 9744 9745 if (!btf_type_is_struct(t)) 9746 return false; 9747 9748 for_each_member(i, t, member) { 9749 const struct btf_array *array; 9750 9751 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 9752 if (btf_type_is_struct(member_type)) { 9753 if (rec >= 3) { 9754 verbose(env, "max struct nesting depth exceeded\n"); 9755 return false; 9756 } 9757 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 9758 return false; 9759 continue; 9760 } 9761 if (btf_type_is_array(member_type)) { 9762 array = btf_array(member_type); 9763 if (!array->nelems) 9764 return false; 9765 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 9766 if (!btf_type_is_scalar(member_type)) 9767 return false; 9768 continue; 9769 } 9770 if (!btf_type_is_scalar(member_type)) 9771 return false; 9772 } 9773 return true; 9774 } 9775 9776 9777 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 9778 #ifdef CONFIG_NET 9779 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 9780 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 9781 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 9782 #endif 9783 }; 9784 9785 enum kfunc_ptr_arg_type { 9786 KF_ARG_PTR_TO_CTX, 9787 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 9788 KF_ARG_PTR_TO_REFCOUNTED_KPTR, /* Refcounted local kptr */ 9789 KF_ARG_PTR_TO_DYNPTR, 9790 KF_ARG_PTR_TO_ITER, 9791 KF_ARG_PTR_TO_LIST_HEAD, 9792 KF_ARG_PTR_TO_LIST_NODE, 9793 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 9794 KF_ARG_PTR_TO_MEM, 9795 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 9796 KF_ARG_PTR_TO_CALLBACK, 9797 KF_ARG_PTR_TO_RB_ROOT, 9798 KF_ARG_PTR_TO_RB_NODE, 9799 }; 9800 9801 enum special_kfunc_type { 9802 KF_bpf_obj_new_impl, 9803 KF_bpf_obj_drop_impl, 9804 KF_bpf_refcount_acquire_impl, 9805 KF_bpf_list_push_front_impl, 9806 KF_bpf_list_push_back_impl, 9807 KF_bpf_list_pop_front, 9808 KF_bpf_list_pop_back, 9809 KF_bpf_cast_to_kern_ctx, 9810 KF_bpf_rdonly_cast, 9811 KF_bpf_rcu_read_lock, 9812 KF_bpf_rcu_read_unlock, 9813 KF_bpf_rbtree_remove, 9814 KF_bpf_rbtree_add_impl, 9815 KF_bpf_rbtree_first, 9816 KF_bpf_dynptr_from_skb, 9817 KF_bpf_dynptr_from_xdp, 9818 KF_bpf_dynptr_slice, 9819 KF_bpf_dynptr_slice_rdwr, 9820 KF_bpf_dynptr_clone, 9821 }; 9822 9823 BTF_SET_START(special_kfunc_set) 9824 BTF_ID(func, bpf_obj_new_impl) 9825 BTF_ID(func, bpf_obj_drop_impl) 9826 BTF_ID(func, bpf_refcount_acquire_impl) 9827 BTF_ID(func, bpf_list_push_front_impl) 9828 BTF_ID(func, bpf_list_push_back_impl) 9829 BTF_ID(func, bpf_list_pop_front) 9830 BTF_ID(func, bpf_list_pop_back) 9831 BTF_ID(func, bpf_cast_to_kern_ctx) 9832 BTF_ID(func, bpf_rdonly_cast) 9833 BTF_ID(func, bpf_rbtree_remove) 9834 BTF_ID(func, bpf_rbtree_add_impl) 9835 BTF_ID(func, bpf_rbtree_first) 9836 BTF_ID(func, bpf_dynptr_from_skb) 9837 BTF_ID(func, bpf_dynptr_from_xdp) 9838 BTF_ID(func, bpf_dynptr_slice) 9839 BTF_ID(func, bpf_dynptr_slice_rdwr) 9840 BTF_ID(func, bpf_dynptr_clone) 9841 BTF_SET_END(special_kfunc_set) 9842 9843 BTF_ID_LIST(special_kfunc_list) 9844 BTF_ID(func, bpf_obj_new_impl) 9845 BTF_ID(func, bpf_obj_drop_impl) 9846 BTF_ID(func, bpf_refcount_acquire_impl) 9847 BTF_ID(func, bpf_list_push_front_impl) 9848 BTF_ID(func, bpf_list_push_back_impl) 9849 BTF_ID(func, bpf_list_pop_front) 9850 BTF_ID(func, bpf_list_pop_back) 9851 BTF_ID(func, bpf_cast_to_kern_ctx) 9852 BTF_ID(func, bpf_rdonly_cast) 9853 BTF_ID(func, bpf_rcu_read_lock) 9854 BTF_ID(func, bpf_rcu_read_unlock) 9855 BTF_ID(func, bpf_rbtree_remove) 9856 BTF_ID(func, bpf_rbtree_add_impl) 9857 BTF_ID(func, bpf_rbtree_first) 9858 BTF_ID(func, bpf_dynptr_from_skb) 9859 BTF_ID(func, bpf_dynptr_from_xdp) 9860 BTF_ID(func, bpf_dynptr_slice) 9861 BTF_ID(func, bpf_dynptr_slice_rdwr) 9862 BTF_ID(func, bpf_dynptr_clone) 9863 9864 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 9865 { 9866 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 9867 } 9868 9869 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 9870 { 9871 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 9872 } 9873 9874 static enum kfunc_ptr_arg_type 9875 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 9876 struct bpf_kfunc_call_arg_meta *meta, 9877 const struct btf_type *t, const struct btf_type *ref_t, 9878 const char *ref_tname, const struct btf_param *args, 9879 int argno, int nargs) 9880 { 9881 u32 regno = argno + 1; 9882 struct bpf_reg_state *regs = cur_regs(env); 9883 struct bpf_reg_state *reg = ®s[regno]; 9884 bool arg_mem_size = false; 9885 9886 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 9887 return KF_ARG_PTR_TO_CTX; 9888 9889 /* In this function, we verify the kfunc's BTF as per the argument type, 9890 * leaving the rest of the verification with respect to the register 9891 * type to our caller. When a set of conditions hold in the BTF type of 9892 * arguments, we resolve it to a known kfunc_ptr_arg_type. 9893 */ 9894 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 9895 return KF_ARG_PTR_TO_CTX; 9896 9897 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 9898 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 9899 9900 if (is_kfunc_arg_refcounted_kptr(meta->btf, &args[argno])) 9901 return KF_ARG_PTR_TO_REFCOUNTED_KPTR; 9902 9903 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 9904 return KF_ARG_PTR_TO_DYNPTR; 9905 9906 if (is_kfunc_arg_iter(meta, argno)) 9907 return KF_ARG_PTR_TO_ITER; 9908 9909 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 9910 return KF_ARG_PTR_TO_LIST_HEAD; 9911 9912 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 9913 return KF_ARG_PTR_TO_LIST_NODE; 9914 9915 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 9916 return KF_ARG_PTR_TO_RB_ROOT; 9917 9918 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 9919 return KF_ARG_PTR_TO_RB_NODE; 9920 9921 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 9922 if (!btf_type_is_struct(ref_t)) { 9923 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 9924 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 9925 return -EINVAL; 9926 } 9927 return KF_ARG_PTR_TO_BTF_ID; 9928 } 9929 9930 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 9931 return KF_ARG_PTR_TO_CALLBACK; 9932 9933 9934 if (argno + 1 < nargs && 9935 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 9936 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 9937 arg_mem_size = true; 9938 9939 /* This is the catch all argument type of register types supported by 9940 * check_helper_mem_access. However, we only allow when argument type is 9941 * pointer to scalar, or struct composed (recursively) of scalars. When 9942 * arg_mem_size is true, the pointer can be void *. 9943 */ 9944 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 9945 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 9946 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 9947 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 9948 return -EINVAL; 9949 } 9950 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 9951 } 9952 9953 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 9954 struct bpf_reg_state *reg, 9955 const struct btf_type *ref_t, 9956 const char *ref_tname, u32 ref_id, 9957 struct bpf_kfunc_call_arg_meta *meta, 9958 int argno) 9959 { 9960 const struct btf_type *reg_ref_t; 9961 bool strict_type_match = false; 9962 const struct btf *reg_btf; 9963 const char *reg_ref_tname; 9964 u32 reg_ref_id; 9965 9966 if (base_type(reg->type) == PTR_TO_BTF_ID) { 9967 reg_btf = reg->btf; 9968 reg_ref_id = reg->btf_id; 9969 } else { 9970 reg_btf = btf_vmlinux; 9971 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 9972 } 9973 9974 /* Enforce strict type matching for calls to kfuncs that are acquiring 9975 * or releasing a reference, or are no-cast aliases. We do _not_ 9976 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 9977 * as we want to enable BPF programs to pass types that are bitwise 9978 * equivalent without forcing them to explicitly cast with something 9979 * like bpf_cast_to_kern_ctx(). 9980 * 9981 * For example, say we had a type like the following: 9982 * 9983 * struct bpf_cpumask { 9984 * cpumask_t cpumask; 9985 * refcount_t usage; 9986 * }; 9987 * 9988 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 9989 * to a struct cpumask, so it would be safe to pass a struct 9990 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 9991 * 9992 * The philosophy here is similar to how we allow scalars of different 9993 * types to be passed to kfuncs as long as the size is the same. The 9994 * only difference here is that we're simply allowing 9995 * btf_struct_ids_match() to walk the struct at the 0th offset, and 9996 * resolve types. 9997 */ 9998 if (is_kfunc_acquire(meta) || 9999 (is_kfunc_release(meta) && reg->ref_obj_id) || 10000 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 10001 strict_type_match = true; 10002 10003 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 10004 10005 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 10006 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 10007 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 10008 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 10009 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 10010 btf_type_str(reg_ref_t), reg_ref_tname); 10011 return -EINVAL; 10012 } 10013 return 0; 10014 } 10015 10016 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10017 { 10018 struct bpf_verifier_state *state = env->cur_state; 10019 10020 if (!state->active_lock.ptr) { 10021 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 10022 return -EFAULT; 10023 } 10024 10025 if (type_flag(reg->type) & NON_OWN_REF) { 10026 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 10027 return -EFAULT; 10028 } 10029 10030 reg->type |= NON_OWN_REF; 10031 return 0; 10032 } 10033 10034 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 10035 { 10036 struct bpf_func_state *state, *unused; 10037 struct bpf_reg_state *reg; 10038 int i; 10039 10040 state = cur_func(env); 10041 10042 if (!ref_obj_id) { 10043 verbose(env, "verifier internal error: ref_obj_id is zero for " 10044 "owning -> non-owning conversion\n"); 10045 return -EFAULT; 10046 } 10047 10048 for (i = 0; i < state->acquired_refs; i++) { 10049 if (state->refs[i].id != ref_obj_id) 10050 continue; 10051 10052 /* Clear ref_obj_id here so release_reference doesn't clobber 10053 * the whole reg 10054 */ 10055 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 10056 if (reg->ref_obj_id == ref_obj_id) { 10057 reg->ref_obj_id = 0; 10058 ref_set_non_owning(env, reg); 10059 } 10060 })); 10061 return 0; 10062 } 10063 10064 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 10065 return -EFAULT; 10066 } 10067 10068 /* Implementation details: 10069 * 10070 * Each register points to some region of memory, which we define as an 10071 * allocation. Each allocation may embed a bpf_spin_lock which protects any 10072 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 10073 * allocation. The lock and the data it protects are colocated in the same 10074 * memory region. 10075 * 10076 * Hence, everytime a register holds a pointer value pointing to such 10077 * allocation, the verifier preserves a unique reg->id for it. 10078 * 10079 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 10080 * bpf_spin_lock is called. 10081 * 10082 * To enable this, lock state in the verifier captures two values: 10083 * active_lock.ptr = Register's type specific pointer 10084 * active_lock.id = A unique ID for each register pointer value 10085 * 10086 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 10087 * supported register types. 10088 * 10089 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 10090 * allocated objects is the reg->btf pointer. 10091 * 10092 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 10093 * can establish the provenance of the map value statically for each distinct 10094 * lookup into such maps. They always contain a single map value hence unique 10095 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 10096 * 10097 * So, in case of global variables, they use array maps with max_entries = 1, 10098 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 10099 * into the same map value as max_entries is 1, as described above). 10100 * 10101 * In case of inner map lookups, the inner map pointer has same map_ptr as the 10102 * outer map pointer (in verifier context), but each lookup into an inner map 10103 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 10104 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 10105 * will get different reg->id assigned to each lookup, hence different 10106 * active_lock.id. 10107 * 10108 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 10109 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 10110 * returned from bpf_obj_new. Each allocation receives a new reg->id. 10111 */ 10112 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 10113 { 10114 void *ptr; 10115 u32 id; 10116 10117 switch ((int)reg->type) { 10118 case PTR_TO_MAP_VALUE: 10119 ptr = reg->map_ptr; 10120 break; 10121 case PTR_TO_BTF_ID | MEM_ALLOC: 10122 ptr = reg->btf; 10123 break; 10124 default: 10125 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 10126 return -EFAULT; 10127 } 10128 id = reg->id; 10129 10130 if (!env->cur_state->active_lock.ptr) 10131 return -EINVAL; 10132 if (env->cur_state->active_lock.ptr != ptr || 10133 env->cur_state->active_lock.id != id) { 10134 verbose(env, "held lock and object are not in the same allocation\n"); 10135 return -EINVAL; 10136 } 10137 return 0; 10138 } 10139 10140 static bool is_bpf_list_api_kfunc(u32 btf_id) 10141 { 10142 return btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10143 btf_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 10144 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 10145 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 10146 } 10147 10148 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 10149 { 10150 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl] || 10151 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10152 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 10153 } 10154 10155 static bool is_bpf_graph_api_kfunc(u32 btf_id) 10156 { 10157 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id) || 10158 btf_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]; 10159 } 10160 10161 static bool is_callback_calling_kfunc(u32 btf_id) 10162 { 10163 return btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]; 10164 } 10165 10166 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 10167 { 10168 return is_bpf_rbtree_api_kfunc(btf_id); 10169 } 10170 10171 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 10172 enum btf_field_type head_field_type, 10173 u32 kfunc_btf_id) 10174 { 10175 bool ret; 10176 10177 switch (head_field_type) { 10178 case BPF_LIST_HEAD: 10179 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 10180 break; 10181 case BPF_RB_ROOT: 10182 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 10183 break; 10184 default: 10185 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 10186 btf_field_type_name(head_field_type)); 10187 return false; 10188 } 10189 10190 if (!ret) 10191 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 10192 btf_field_type_name(head_field_type)); 10193 return ret; 10194 } 10195 10196 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 10197 enum btf_field_type node_field_type, 10198 u32 kfunc_btf_id) 10199 { 10200 bool ret; 10201 10202 switch (node_field_type) { 10203 case BPF_LIST_NODE: 10204 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10205 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back_impl]); 10206 break; 10207 case BPF_RB_NODE: 10208 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10209 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add_impl]); 10210 break; 10211 default: 10212 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 10213 btf_field_type_name(node_field_type)); 10214 return false; 10215 } 10216 10217 if (!ret) 10218 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 10219 btf_field_type_name(node_field_type)); 10220 return ret; 10221 } 10222 10223 static int 10224 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 10225 struct bpf_reg_state *reg, u32 regno, 10226 struct bpf_kfunc_call_arg_meta *meta, 10227 enum btf_field_type head_field_type, 10228 struct btf_field **head_field) 10229 { 10230 const char *head_type_name; 10231 struct btf_field *field; 10232 struct btf_record *rec; 10233 u32 head_off; 10234 10235 if (meta->btf != btf_vmlinux) { 10236 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10237 return -EFAULT; 10238 } 10239 10240 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 10241 return -EFAULT; 10242 10243 head_type_name = btf_field_type_name(head_field_type); 10244 if (!tnum_is_const(reg->var_off)) { 10245 verbose(env, 10246 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10247 regno, head_type_name); 10248 return -EINVAL; 10249 } 10250 10251 rec = reg_btf_record(reg); 10252 head_off = reg->off + reg->var_off.value; 10253 field = btf_record_find(rec, head_off, head_field_type); 10254 if (!field) { 10255 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 10256 return -EINVAL; 10257 } 10258 10259 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 10260 if (check_reg_allocation_locked(env, reg)) { 10261 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 10262 rec->spin_lock_off, head_type_name); 10263 return -EINVAL; 10264 } 10265 10266 if (*head_field) { 10267 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 10268 return -EFAULT; 10269 } 10270 *head_field = field; 10271 return 0; 10272 } 10273 10274 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 10275 struct bpf_reg_state *reg, u32 regno, 10276 struct bpf_kfunc_call_arg_meta *meta) 10277 { 10278 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 10279 &meta->arg_list_head.field); 10280 } 10281 10282 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 10283 struct bpf_reg_state *reg, u32 regno, 10284 struct bpf_kfunc_call_arg_meta *meta) 10285 { 10286 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 10287 &meta->arg_rbtree_root.field); 10288 } 10289 10290 static int 10291 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 10292 struct bpf_reg_state *reg, u32 regno, 10293 struct bpf_kfunc_call_arg_meta *meta, 10294 enum btf_field_type head_field_type, 10295 enum btf_field_type node_field_type, 10296 struct btf_field **node_field) 10297 { 10298 const char *node_type_name; 10299 const struct btf_type *et, *t; 10300 struct btf_field *field; 10301 u32 node_off; 10302 10303 if (meta->btf != btf_vmlinux) { 10304 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10305 return -EFAULT; 10306 } 10307 10308 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 10309 return -EFAULT; 10310 10311 node_type_name = btf_field_type_name(node_field_type); 10312 if (!tnum_is_const(reg->var_off)) { 10313 verbose(env, 10314 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10315 regno, node_type_name); 10316 return -EINVAL; 10317 } 10318 10319 node_off = reg->off + reg->var_off.value; 10320 field = reg_find_field_offset(reg, node_off, node_field_type); 10321 if (!field || field->offset != node_off) { 10322 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 10323 return -EINVAL; 10324 } 10325 10326 field = *node_field; 10327 10328 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 10329 t = btf_type_by_id(reg->btf, reg->btf_id); 10330 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 10331 field->graph_root.value_btf_id, true)) { 10332 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 10333 "in struct %s, but arg is at offset=%d in struct %s\n", 10334 btf_field_type_name(head_field_type), 10335 btf_field_type_name(node_field_type), 10336 field->graph_root.node_offset, 10337 btf_name_by_offset(field->graph_root.btf, et->name_off), 10338 node_off, btf_name_by_offset(reg->btf, t->name_off)); 10339 return -EINVAL; 10340 } 10341 10342 if (node_off != field->graph_root.node_offset) { 10343 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 10344 node_off, btf_field_type_name(node_field_type), 10345 field->graph_root.node_offset, 10346 btf_name_by_offset(field->graph_root.btf, et->name_off)); 10347 return -EINVAL; 10348 } 10349 10350 return 0; 10351 } 10352 10353 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 10354 struct bpf_reg_state *reg, u32 regno, 10355 struct bpf_kfunc_call_arg_meta *meta) 10356 { 10357 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 10358 BPF_LIST_HEAD, BPF_LIST_NODE, 10359 &meta->arg_list_head.field); 10360 } 10361 10362 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 10363 struct bpf_reg_state *reg, u32 regno, 10364 struct bpf_kfunc_call_arg_meta *meta) 10365 { 10366 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 10367 BPF_RB_ROOT, BPF_RB_NODE, 10368 &meta->arg_rbtree_root.field); 10369 } 10370 10371 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 10372 int insn_idx) 10373 { 10374 const char *func_name = meta->func_name, *ref_tname; 10375 const struct btf *btf = meta->btf; 10376 const struct btf_param *args; 10377 struct btf_record *rec; 10378 u32 i, nargs; 10379 int ret; 10380 10381 args = (const struct btf_param *)(meta->func_proto + 1); 10382 nargs = btf_type_vlen(meta->func_proto); 10383 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 10384 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 10385 MAX_BPF_FUNC_REG_ARGS); 10386 return -EINVAL; 10387 } 10388 10389 /* Check that BTF function arguments match actual types that the 10390 * verifier sees. 10391 */ 10392 for (i = 0; i < nargs; i++) { 10393 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 10394 const struct btf_type *t, *ref_t, *resolve_ret; 10395 enum bpf_arg_type arg_type = ARG_DONTCARE; 10396 u32 regno = i + 1, ref_id, type_size; 10397 bool is_ret_buf_sz = false; 10398 int kf_arg_type; 10399 10400 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 10401 10402 if (is_kfunc_arg_ignore(btf, &args[i])) 10403 continue; 10404 10405 if (btf_type_is_scalar(t)) { 10406 if (reg->type != SCALAR_VALUE) { 10407 verbose(env, "R%d is not a scalar\n", regno); 10408 return -EINVAL; 10409 } 10410 10411 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 10412 if (meta->arg_constant.found) { 10413 verbose(env, "verifier internal error: only one constant argument permitted\n"); 10414 return -EFAULT; 10415 } 10416 if (!tnum_is_const(reg->var_off)) { 10417 verbose(env, "R%d must be a known constant\n", regno); 10418 return -EINVAL; 10419 } 10420 ret = mark_chain_precision(env, regno); 10421 if (ret < 0) 10422 return ret; 10423 meta->arg_constant.found = true; 10424 meta->arg_constant.value = reg->var_off.value; 10425 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 10426 meta->r0_rdonly = true; 10427 is_ret_buf_sz = true; 10428 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 10429 is_ret_buf_sz = true; 10430 } 10431 10432 if (is_ret_buf_sz) { 10433 if (meta->r0_size) { 10434 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 10435 return -EINVAL; 10436 } 10437 10438 if (!tnum_is_const(reg->var_off)) { 10439 verbose(env, "R%d is not a const\n", regno); 10440 return -EINVAL; 10441 } 10442 10443 meta->r0_size = reg->var_off.value; 10444 ret = mark_chain_precision(env, regno); 10445 if (ret) 10446 return ret; 10447 } 10448 continue; 10449 } 10450 10451 if (!btf_type_is_ptr(t)) { 10452 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 10453 return -EINVAL; 10454 } 10455 10456 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 10457 (register_is_null(reg) || type_may_be_null(reg->type))) { 10458 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 10459 return -EACCES; 10460 } 10461 10462 if (reg->ref_obj_id) { 10463 if (is_kfunc_release(meta) && meta->ref_obj_id) { 10464 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 10465 regno, reg->ref_obj_id, 10466 meta->ref_obj_id); 10467 return -EFAULT; 10468 } 10469 meta->ref_obj_id = reg->ref_obj_id; 10470 if (is_kfunc_release(meta)) 10471 meta->release_regno = regno; 10472 } 10473 10474 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 10475 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 10476 10477 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 10478 if (kf_arg_type < 0) 10479 return kf_arg_type; 10480 10481 switch (kf_arg_type) { 10482 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 10483 case KF_ARG_PTR_TO_BTF_ID: 10484 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 10485 break; 10486 10487 if (!is_trusted_reg(reg)) { 10488 if (!is_kfunc_rcu(meta)) { 10489 verbose(env, "R%d must be referenced or trusted\n", regno); 10490 return -EINVAL; 10491 } 10492 if (!is_rcu_reg(reg)) { 10493 verbose(env, "R%d must be a rcu pointer\n", regno); 10494 return -EINVAL; 10495 } 10496 } 10497 10498 fallthrough; 10499 case KF_ARG_PTR_TO_CTX: 10500 /* Trusted arguments have the same offset checks as release arguments */ 10501 arg_type |= OBJ_RELEASE; 10502 break; 10503 case KF_ARG_PTR_TO_DYNPTR: 10504 case KF_ARG_PTR_TO_ITER: 10505 case KF_ARG_PTR_TO_LIST_HEAD: 10506 case KF_ARG_PTR_TO_LIST_NODE: 10507 case KF_ARG_PTR_TO_RB_ROOT: 10508 case KF_ARG_PTR_TO_RB_NODE: 10509 case KF_ARG_PTR_TO_MEM: 10510 case KF_ARG_PTR_TO_MEM_SIZE: 10511 case KF_ARG_PTR_TO_CALLBACK: 10512 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 10513 /* Trusted by default */ 10514 break; 10515 default: 10516 WARN_ON_ONCE(1); 10517 return -EFAULT; 10518 } 10519 10520 if (is_kfunc_release(meta) && reg->ref_obj_id) 10521 arg_type |= OBJ_RELEASE; 10522 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 10523 if (ret < 0) 10524 return ret; 10525 10526 switch (kf_arg_type) { 10527 case KF_ARG_PTR_TO_CTX: 10528 if (reg->type != PTR_TO_CTX) { 10529 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 10530 return -EINVAL; 10531 } 10532 10533 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 10534 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 10535 if (ret < 0) 10536 return -EINVAL; 10537 meta->ret_btf_id = ret; 10538 } 10539 break; 10540 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 10541 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10542 verbose(env, "arg#%d expected pointer to allocated object\n", i); 10543 return -EINVAL; 10544 } 10545 if (!reg->ref_obj_id) { 10546 verbose(env, "allocated object must be referenced\n"); 10547 return -EINVAL; 10548 } 10549 if (meta->btf == btf_vmlinux && 10550 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 10551 meta->arg_obj_drop.btf = reg->btf; 10552 meta->arg_obj_drop.btf_id = reg->btf_id; 10553 } 10554 break; 10555 case KF_ARG_PTR_TO_DYNPTR: 10556 { 10557 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 10558 int clone_ref_obj_id = 0; 10559 10560 if (reg->type != PTR_TO_STACK && 10561 reg->type != CONST_PTR_TO_DYNPTR) { 10562 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 10563 return -EINVAL; 10564 } 10565 10566 if (reg->type == CONST_PTR_TO_DYNPTR) 10567 dynptr_arg_type |= MEM_RDONLY; 10568 10569 if (is_kfunc_arg_uninit(btf, &args[i])) 10570 dynptr_arg_type |= MEM_UNINIT; 10571 10572 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 10573 dynptr_arg_type |= DYNPTR_TYPE_SKB; 10574 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) { 10575 dynptr_arg_type |= DYNPTR_TYPE_XDP; 10576 } else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_clone] && 10577 (dynptr_arg_type & MEM_UNINIT)) { 10578 enum bpf_dynptr_type parent_type = meta->initialized_dynptr.type; 10579 10580 if (parent_type == BPF_DYNPTR_TYPE_INVALID) { 10581 verbose(env, "verifier internal error: no dynptr type for parent of clone\n"); 10582 return -EFAULT; 10583 } 10584 10585 dynptr_arg_type |= (unsigned int)get_dynptr_type_flag(parent_type); 10586 clone_ref_obj_id = meta->initialized_dynptr.ref_obj_id; 10587 if (dynptr_type_refcounted(parent_type) && !clone_ref_obj_id) { 10588 verbose(env, "verifier internal error: missing ref obj id for parent of clone\n"); 10589 return -EFAULT; 10590 } 10591 } 10592 10593 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type, clone_ref_obj_id); 10594 if (ret < 0) 10595 return ret; 10596 10597 if (!(dynptr_arg_type & MEM_UNINIT)) { 10598 int id = dynptr_id(env, reg); 10599 10600 if (id < 0) { 10601 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10602 return id; 10603 } 10604 meta->initialized_dynptr.id = id; 10605 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 10606 meta->initialized_dynptr.ref_obj_id = dynptr_ref_obj_id(env, reg); 10607 } 10608 10609 break; 10610 } 10611 case KF_ARG_PTR_TO_ITER: 10612 ret = process_iter_arg(env, regno, insn_idx, meta); 10613 if (ret < 0) 10614 return ret; 10615 break; 10616 case KF_ARG_PTR_TO_LIST_HEAD: 10617 if (reg->type != PTR_TO_MAP_VALUE && 10618 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10619 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 10620 return -EINVAL; 10621 } 10622 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 10623 verbose(env, "allocated object must be referenced\n"); 10624 return -EINVAL; 10625 } 10626 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 10627 if (ret < 0) 10628 return ret; 10629 break; 10630 case KF_ARG_PTR_TO_RB_ROOT: 10631 if (reg->type != PTR_TO_MAP_VALUE && 10632 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10633 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 10634 return -EINVAL; 10635 } 10636 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 10637 verbose(env, "allocated object must be referenced\n"); 10638 return -EINVAL; 10639 } 10640 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 10641 if (ret < 0) 10642 return ret; 10643 break; 10644 case KF_ARG_PTR_TO_LIST_NODE: 10645 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10646 verbose(env, "arg#%d expected pointer to allocated object\n", i); 10647 return -EINVAL; 10648 } 10649 if (!reg->ref_obj_id) { 10650 verbose(env, "allocated object must be referenced\n"); 10651 return -EINVAL; 10652 } 10653 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 10654 if (ret < 0) 10655 return ret; 10656 break; 10657 case KF_ARG_PTR_TO_RB_NODE: 10658 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 10659 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 10660 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 10661 return -EINVAL; 10662 } 10663 if (in_rbtree_lock_required_cb(env)) { 10664 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 10665 return -EINVAL; 10666 } 10667 } else { 10668 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10669 verbose(env, "arg#%d expected pointer to allocated object\n", i); 10670 return -EINVAL; 10671 } 10672 if (!reg->ref_obj_id) { 10673 verbose(env, "allocated object must be referenced\n"); 10674 return -EINVAL; 10675 } 10676 } 10677 10678 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 10679 if (ret < 0) 10680 return ret; 10681 break; 10682 case KF_ARG_PTR_TO_BTF_ID: 10683 /* Only base_type is checked, further checks are done here */ 10684 if ((base_type(reg->type) != PTR_TO_BTF_ID || 10685 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 10686 !reg2btf_ids[base_type(reg->type)]) { 10687 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 10688 verbose(env, "expected %s or socket\n", 10689 reg_type_str(env, base_type(reg->type) | 10690 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 10691 return -EINVAL; 10692 } 10693 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 10694 if (ret < 0) 10695 return ret; 10696 break; 10697 case KF_ARG_PTR_TO_MEM: 10698 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 10699 if (IS_ERR(resolve_ret)) { 10700 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 10701 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 10702 return -EINVAL; 10703 } 10704 ret = check_mem_reg(env, reg, regno, type_size); 10705 if (ret < 0) 10706 return ret; 10707 break; 10708 case KF_ARG_PTR_TO_MEM_SIZE: 10709 { 10710 struct bpf_reg_state *size_reg = ®s[regno + 1]; 10711 const struct btf_param *size_arg = &args[i + 1]; 10712 10713 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 10714 if (ret < 0) { 10715 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 10716 return ret; 10717 } 10718 10719 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 10720 if (meta->arg_constant.found) { 10721 verbose(env, "verifier internal error: only one constant argument permitted\n"); 10722 return -EFAULT; 10723 } 10724 if (!tnum_is_const(size_reg->var_off)) { 10725 verbose(env, "R%d must be a known constant\n", regno + 1); 10726 return -EINVAL; 10727 } 10728 meta->arg_constant.found = true; 10729 meta->arg_constant.value = size_reg->var_off.value; 10730 } 10731 10732 /* Skip next '__sz' or '__szk' argument */ 10733 i++; 10734 break; 10735 } 10736 case KF_ARG_PTR_TO_CALLBACK: 10737 meta->subprogno = reg->subprogno; 10738 break; 10739 case KF_ARG_PTR_TO_REFCOUNTED_KPTR: 10740 if (!type_is_ptr_alloc_obj(reg->type) && !type_is_non_owning_ref(reg->type)) { 10741 verbose(env, "arg#%d is neither owning or non-owning ref\n", i); 10742 return -EINVAL; 10743 } 10744 10745 rec = reg_btf_record(reg); 10746 if (!rec) { 10747 verbose(env, "verifier internal error: Couldn't find btf_record\n"); 10748 return -EFAULT; 10749 } 10750 10751 if (rec->refcount_off < 0) { 10752 verbose(env, "arg#%d doesn't point to a type with bpf_refcount field\n", i); 10753 return -EINVAL; 10754 } 10755 if (rec->refcount_off >= 0) { 10756 verbose(env, "bpf_refcount_acquire calls are disabled for now\n"); 10757 return -EINVAL; 10758 } 10759 meta->arg_refcount_acquire.btf = reg->btf; 10760 meta->arg_refcount_acquire.btf_id = reg->btf_id; 10761 break; 10762 } 10763 } 10764 10765 if (is_kfunc_release(meta) && !meta->release_regno) { 10766 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 10767 func_name); 10768 return -EINVAL; 10769 } 10770 10771 return 0; 10772 } 10773 10774 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 10775 struct bpf_insn *insn, 10776 struct bpf_kfunc_call_arg_meta *meta, 10777 const char **kfunc_name) 10778 { 10779 const struct btf_type *func, *func_proto; 10780 u32 func_id, *kfunc_flags; 10781 const char *func_name; 10782 struct btf *desc_btf; 10783 10784 if (kfunc_name) 10785 *kfunc_name = NULL; 10786 10787 if (!insn->imm) 10788 return -EINVAL; 10789 10790 desc_btf = find_kfunc_desc_btf(env, insn->off); 10791 if (IS_ERR(desc_btf)) 10792 return PTR_ERR(desc_btf); 10793 10794 func_id = insn->imm; 10795 func = btf_type_by_id(desc_btf, func_id); 10796 func_name = btf_name_by_offset(desc_btf, func->name_off); 10797 if (kfunc_name) 10798 *kfunc_name = func_name; 10799 func_proto = btf_type_by_id(desc_btf, func->type); 10800 10801 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id); 10802 if (!kfunc_flags) { 10803 return -EACCES; 10804 } 10805 10806 memset(meta, 0, sizeof(*meta)); 10807 meta->btf = desc_btf; 10808 meta->func_id = func_id; 10809 meta->kfunc_flags = *kfunc_flags; 10810 meta->func_proto = func_proto; 10811 meta->func_name = func_name; 10812 10813 return 0; 10814 } 10815 10816 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10817 int *insn_idx_p) 10818 { 10819 const struct btf_type *t, *ptr_type; 10820 u32 i, nargs, ptr_type_id, release_ref_obj_id; 10821 struct bpf_reg_state *regs = cur_regs(env); 10822 const char *func_name, *ptr_type_name; 10823 bool sleepable, rcu_lock, rcu_unlock; 10824 struct bpf_kfunc_call_arg_meta meta; 10825 struct bpf_insn_aux_data *insn_aux; 10826 int err, insn_idx = *insn_idx_p; 10827 const struct btf_param *args; 10828 const struct btf_type *ret_t; 10829 struct btf *desc_btf; 10830 10831 /* skip for now, but return error when we find this in fixup_kfunc_call */ 10832 if (!insn->imm) 10833 return 0; 10834 10835 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 10836 if (err == -EACCES && func_name) 10837 verbose(env, "calling kernel function %s is not allowed\n", func_name); 10838 if (err) 10839 return err; 10840 desc_btf = meta.btf; 10841 insn_aux = &env->insn_aux_data[insn_idx]; 10842 10843 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 10844 10845 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 10846 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 10847 return -EACCES; 10848 } 10849 10850 sleepable = is_kfunc_sleepable(&meta); 10851 if (sleepable && !env->prog->aux->sleepable) { 10852 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 10853 return -EACCES; 10854 } 10855 10856 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 10857 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 10858 10859 if (env->cur_state->active_rcu_lock) { 10860 struct bpf_func_state *state; 10861 struct bpf_reg_state *reg; 10862 10863 if (rcu_lock) { 10864 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 10865 return -EINVAL; 10866 } else if (rcu_unlock) { 10867 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10868 if (reg->type & MEM_RCU) { 10869 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 10870 reg->type |= PTR_UNTRUSTED; 10871 } 10872 })); 10873 env->cur_state->active_rcu_lock = false; 10874 } else if (sleepable) { 10875 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 10876 return -EACCES; 10877 } 10878 } else if (rcu_lock) { 10879 env->cur_state->active_rcu_lock = true; 10880 } else if (rcu_unlock) { 10881 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 10882 return -EINVAL; 10883 } 10884 10885 /* Check the arguments */ 10886 err = check_kfunc_args(env, &meta, insn_idx); 10887 if (err < 0) 10888 return err; 10889 /* In case of release function, we get register number of refcounted 10890 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 10891 */ 10892 if (meta.release_regno) { 10893 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 10894 if (err) { 10895 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 10896 func_name, meta.func_id); 10897 return err; 10898 } 10899 } 10900 10901 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 10902 meta.func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 10903 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 10904 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 10905 insn_aux->insert_off = regs[BPF_REG_2].off; 10906 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 10907 if (err) { 10908 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 10909 func_name, meta.func_id); 10910 return err; 10911 } 10912 10913 err = release_reference(env, release_ref_obj_id); 10914 if (err) { 10915 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 10916 func_name, meta.func_id); 10917 return err; 10918 } 10919 } 10920 10921 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 10922 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 10923 set_rbtree_add_callback_state); 10924 if (err) { 10925 verbose(env, "kfunc %s#%d failed callback verification\n", 10926 func_name, meta.func_id); 10927 return err; 10928 } 10929 } 10930 10931 for (i = 0; i < CALLER_SAVED_REGS; i++) 10932 mark_reg_not_init(env, regs, caller_saved[i]); 10933 10934 /* Check return type */ 10935 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 10936 10937 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 10938 /* Only exception is bpf_obj_new_impl */ 10939 if (meta.btf != btf_vmlinux || 10940 (meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl] && 10941 meta.func_id != special_kfunc_list[KF_bpf_refcount_acquire_impl])) { 10942 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 10943 return -EINVAL; 10944 } 10945 } 10946 10947 if (btf_type_is_scalar(t)) { 10948 mark_reg_unknown(env, regs, BPF_REG_0); 10949 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 10950 } else if (btf_type_is_ptr(t)) { 10951 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 10952 10953 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 10954 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 10955 struct btf *ret_btf; 10956 u32 ret_btf_id; 10957 10958 if (unlikely(!bpf_global_ma_set)) 10959 return -ENOMEM; 10960 10961 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 10962 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 10963 return -EINVAL; 10964 } 10965 10966 ret_btf = env->prog->aux->btf; 10967 ret_btf_id = meta.arg_constant.value; 10968 10969 /* This may be NULL due to user not supplying a BTF */ 10970 if (!ret_btf) { 10971 verbose(env, "bpf_obj_new requires prog BTF\n"); 10972 return -EINVAL; 10973 } 10974 10975 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 10976 if (!ret_t || !__btf_type_is_struct(ret_t)) { 10977 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 10978 return -EINVAL; 10979 } 10980 10981 mark_reg_known_zero(env, regs, BPF_REG_0); 10982 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 10983 regs[BPF_REG_0].btf = ret_btf; 10984 regs[BPF_REG_0].btf_id = ret_btf_id; 10985 10986 insn_aux->obj_new_size = ret_t->size; 10987 insn_aux->kptr_struct_meta = 10988 btf_find_struct_meta(ret_btf, ret_btf_id); 10989 } else if (meta.func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 10990 mark_reg_known_zero(env, regs, BPF_REG_0); 10991 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 10992 regs[BPF_REG_0].btf = meta.arg_refcount_acquire.btf; 10993 regs[BPF_REG_0].btf_id = meta.arg_refcount_acquire.btf_id; 10994 10995 insn_aux->kptr_struct_meta = 10996 btf_find_struct_meta(meta.arg_refcount_acquire.btf, 10997 meta.arg_refcount_acquire.btf_id); 10998 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 10999 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 11000 struct btf_field *field = meta.arg_list_head.field; 11001 11002 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11003 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 11004 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11005 struct btf_field *field = meta.arg_rbtree_root.field; 11006 11007 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 11008 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 11009 mark_reg_known_zero(env, regs, BPF_REG_0); 11010 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 11011 regs[BPF_REG_0].btf = desc_btf; 11012 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 11013 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 11014 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 11015 if (!ret_t || !btf_type_is_struct(ret_t)) { 11016 verbose(env, 11017 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 11018 return -EINVAL; 11019 } 11020 11021 mark_reg_known_zero(env, regs, BPF_REG_0); 11022 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 11023 regs[BPF_REG_0].btf = desc_btf; 11024 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 11025 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 11026 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 11027 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 11028 11029 mark_reg_known_zero(env, regs, BPF_REG_0); 11030 11031 if (!meta.arg_constant.found) { 11032 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 11033 return -EFAULT; 11034 } 11035 11036 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 11037 11038 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 11039 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 11040 11041 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 11042 regs[BPF_REG_0].type |= MEM_RDONLY; 11043 } else { 11044 /* this will set env->seen_direct_write to true */ 11045 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 11046 verbose(env, "the prog does not allow writes to packet data\n"); 11047 return -EINVAL; 11048 } 11049 } 11050 11051 if (!meta.initialized_dynptr.id) { 11052 verbose(env, "verifier internal error: no dynptr id\n"); 11053 return -EFAULT; 11054 } 11055 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 11056 11057 /* we don't need to set BPF_REG_0's ref obj id 11058 * because packet slices are not refcounted (see 11059 * dynptr_type_refcounted) 11060 */ 11061 } else { 11062 verbose(env, "kernel function %s unhandled dynamic return type\n", 11063 meta.func_name); 11064 return -EFAULT; 11065 } 11066 } else if (!__btf_type_is_struct(ptr_type)) { 11067 if (!meta.r0_size) { 11068 __u32 sz; 11069 11070 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 11071 meta.r0_size = sz; 11072 meta.r0_rdonly = true; 11073 } 11074 } 11075 if (!meta.r0_size) { 11076 ptr_type_name = btf_name_by_offset(desc_btf, 11077 ptr_type->name_off); 11078 verbose(env, 11079 "kernel function %s returns pointer type %s %s is not supported\n", 11080 func_name, 11081 btf_type_str(ptr_type), 11082 ptr_type_name); 11083 return -EINVAL; 11084 } 11085 11086 mark_reg_known_zero(env, regs, BPF_REG_0); 11087 regs[BPF_REG_0].type = PTR_TO_MEM; 11088 regs[BPF_REG_0].mem_size = meta.r0_size; 11089 11090 if (meta.r0_rdonly) 11091 regs[BPF_REG_0].type |= MEM_RDONLY; 11092 11093 /* Ensures we don't access the memory after a release_reference() */ 11094 if (meta.ref_obj_id) 11095 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 11096 } else { 11097 mark_reg_known_zero(env, regs, BPF_REG_0); 11098 regs[BPF_REG_0].btf = desc_btf; 11099 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 11100 regs[BPF_REG_0].btf_id = ptr_type_id; 11101 } 11102 11103 if (is_kfunc_ret_null(&meta)) { 11104 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 11105 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 11106 regs[BPF_REG_0].id = ++env->id_gen; 11107 } 11108 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 11109 if (is_kfunc_acquire(&meta)) { 11110 int id = acquire_reference_state(env, insn_idx); 11111 11112 if (id < 0) 11113 return id; 11114 if (is_kfunc_ret_null(&meta)) 11115 regs[BPF_REG_0].id = id; 11116 regs[BPF_REG_0].ref_obj_id = id; 11117 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 11118 ref_set_non_owning(env, ®s[BPF_REG_0]); 11119 } 11120 11121 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 11122 regs[BPF_REG_0].id = ++env->id_gen; 11123 } else if (btf_type_is_void(t)) { 11124 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 11125 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 11126 insn_aux->kptr_struct_meta = 11127 btf_find_struct_meta(meta.arg_obj_drop.btf, 11128 meta.arg_obj_drop.btf_id); 11129 } 11130 } 11131 } 11132 11133 nargs = btf_type_vlen(meta.func_proto); 11134 args = (const struct btf_param *)(meta.func_proto + 1); 11135 for (i = 0; i < nargs; i++) { 11136 u32 regno = i + 1; 11137 11138 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 11139 if (btf_type_is_ptr(t)) 11140 mark_btf_func_reg_size(env, regno, sizeof(void *)); 11141 else 11142 /* scalar. ensured by btf_check_kfunc_arg_match() */ 11143 mark_btf_func_reg_size(env, regno, t->size); 11144 } 11145 11146 if (is_iter_next_kfunc(&meta)) { 11147 err = process_iter_next_call(env, insn_idx, &meta); 11148 if (err) 11149 return err; 11150 } 11151 11152 return 0; 11153 } 11154 11155 static bool signed_add_overflows(s64 a, s64 b) 11156 { 11157 /* Do the add in u64, where overflow is well-defined */ 11158 s64 res = (s64)((u64)a + (u64)b); 11159 11160 if (b < 0) 11161 return res > a; 11162 return res < a; 11163 } 11164 11165 static bool signed_add32_overflows(s32 a, s32 b) 11166 { 11167 /* Do the add in u32, where overflow is well-defined */ 11168 s32 res = (s32)((u32)a + (u32)b); 11169 11170 if (b < 0) 11171 return res > a; 11172 return res < a; 11173 } 11174 11175 static bool signed_sub_overflows(s64 a, s64 b) 11176 { 11177 /* Do the sub in u64, where overflow is well-defined */ 11178 s64 res = (s64)((u64)a - (u64)b); 11179 11180 if (b < 0) 11181 return res < a; 11182 return res > a; 11183 } 11184 11185 static bool signed_sub32_overflows(s32 a, s32 b) 11186 { 11187 /* Do the sub in u32, where overflow is well-defined */ 11188 s32 res = (s32)((u32)a - (u32)b); 11189 11190 if (b < 0) 11191 return res < a; 11192 return res > a; 11193 } 11194 11195 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 11196 const struct bpf_reg_state *reg, 11197 enum bpf_reg_type type) 11198 { 11199 bool known = tnum_is_const(reg->var_off); 11200 s64 val = reg->var_off.value; 11201 s64 smin = reg->smin_value; 11202 11203 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 11204 verbose(env, "math between %s pointer and %lld is not allowed\n", 11205 reg_type_str(env, type), val); 11206 return false; 11207 } 11208 11209 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 11210 verbose(env, "%s pointer offset %d is not allowed\n", 11211 reg_type_str(env, type), reg->off); 11212 return false; 11213 } 11214 11215 if (smin == S64_MIN) { 11216 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 11217 reg_type_str(env, type)); 11218 return false; 11219 } 11220 11221 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 11222 verbose(env, "value %lld makes %s pointer be out of bounds\n", 11223 smin, reg_type_str(env, type)); 11224 return false; 11225 } 11226 11227 return true; 11228 } 11229 11230 enum { 11231 REASON_BOUNDS = -1, 11232 REASON_TYPE = -2, 11233 REASON_PATHS = -3, 11234 REASON_LIMIT = -4, 11235 REASON_STACK = -5, 11236 }; 11237 11238 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 11239 u32 *alu_limit, bool mask_to_left) 11240 { 11241 u32 max = 0, ptr_limit = 0; 11242 11243 switch (ptr_reg->type) { 11244 case PTR_TO_STACK: 11245 /* Offset 0 is out-of-bounds, but acceptable start for the 11246 * left direction, see BPF_REG_FP. Also, unknown scalar 11247 * offset where we would need to deal with min/max bounds is 11248 * currently prohibited for unprivileged. 11249 */ 11250 max = MAX_BPF_STACK + mask_to_left; 11251 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 11252 break; 11253 case PTR_TO_MAP_VALUE: 11254 max = ptr_reg->map_ptr->value_size; 11255 ptr_limit = (mask_to_left ? 11256 ptr_reg->smin_value : 11257 ptr_reg->umax_value) + ptr_reg->off; 11258 break; 11259 default: 11260 return REASON_TYPE; 11261 } 11262 11263 if (ptr_limit >= max) 11264 return REASON_LIMIT; 11265 *alu_limit = ptr_limit; 11266 return 0; 11267 } 11268 11269 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 11270 const struct bpf_insn *insn) 11271 { 11272 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 11273 } 11274 11275 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 11276 u32 alu_state, u32 alu_limit) 11277 { 11278 /* If we arrived here from different branches with different 11279 * state or limits to sanitize, then this won't work. 11280 */ 11281 if (aux->alu_state && 11282 (aux->alu_state != alu_state || 11283 aux->alu_limit != alu_limit)) 11284 return REASON_PATHS; 11285 11286 /* Corresponding fixup done in do_misc_fixups(). */ 11287 aux->alu_state = alu_state; 11288 aux->alu_limit = alu_limit; 11289 return 0; 11290 } 11291 11292 static int sanitize_val_alu(struct bpf_verifier_env *env, 11293 struct bpf_insn *insn) 11294 { 11295 struct bpf_insn_aux_data *aux = cur_aux(env); 11296 11297 if (can_skip_alu_sanitation(env, insn)) 11298 return 0; 11299 11300 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 11301 } 11302 11303 static bool sanitize_needed(u8 opcode) 11304 { 11305 return opcode == BPF_ADD || opcode == BPF_SUB; 11306 } 11307 11308 struct bpf_sanitize_info { 11309 struct bpf_insn_aux_data aux; 11310 bool mask_to_left; 11311 }; 11312 11313 static struct bpf_verifier_state * 11314 sanitize_speculative_path(struct bpf_verifier_env *env, 11315 const struct bpf_insn *insn, 11316 u32 next_idx, u32 curr_idx) 11317 { 11318 struct bpf_verifier_state *branch; 11319 struct bpf_reg_state *regs; 11320 11321 branch = push_stack(env, next_idx, curr_idx, true); 11322 if (branch && insn) { 11323 regs = branch->frame[branch->curframe]->regs; 11324 if (BPF_SRC(insn->code) == BPF_K) { 11325 mark_reg_unknown(env, regs, insn->dst_reg); 11326 } else if (BPF_SRC(insn->code) == BPF_X) { 11327 mark_reg_unknown(env, regs, insn->dst_reg); 11328 mark_reg_unknown(env, regs, insn->src_reg); 11329 } 11330 } 11331 return branch; 11332 } 11333 11334 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 11335 struct bpf_insn *insn, 11336 const struct bpf_reg_state *ptr_reg, 11337 const struct bpf_reg_state *off_reg, 11338 struct bpf_reg_state *dst_reg, 11339 struct bpf_sanitize_info *info, 11340 const bool commit_window) 11341 { 11342 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 11343 struct bpf_verifier_state *vstate = env->cur_state; 11344 bool off_is_imm = tnum_is_const(off_reg->var_off); 11345 bool off_is_neg = off_reg->smin_value < 0; 11346 bool ptr_is_dst_reg = ptr_reg == dst_reg; 11347 u8 opcode = BPF_OP(insn->code); 11348 u32 alu_state, alu_limit; 11349 struct bpf_reg_state tmp; 11350 bool ret; 11351 int err; 11352 11353 if (can_skip_alu_sanitation(env, insn)) 11354 return 0; 11355 11356 /* We already marked aux for masking from non-speculative 11357 * paths, thus we got here in the first place. We only care 11358 * to explore bad access from here. 11359 */ 11360 if (vstate->speculative) 11361 goto do_sim; 11362 11363 if (!commit_window) { 11364 if (!tnum_is_const(off_reg->var_off) && 11365 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 11366 return REASON_BOUNDS; 11367 11368 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 11369 (opcode == BPF_SUB && !off_is_neg); 11370 } 11371 11372 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 11373 if (err < 0) 11374 return err; 11375 11376 if (commit_window) { 11377 /* In commit phase we narrow the masking window based on 11378 * the observed pointer move after the simulated operation. 11379 */ 11380 alu_state = info->aux.alu_state; 11381 alu_limit = abs(info->aux.alu_limit - alu_limit); 11382 } else { 11383 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 11384 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 11385 alu_state |= ptr_is_dst_reg ? 11386 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 11387 11388 /* Limit pruning on unknown scalars to enable deep search for 11389 * potential masking differences from other program paths. 11390 */ 11391 if (!off_is_imm) 11392 env->explore_alu_limits = true; 11393 } 11394 11395 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 11396 if (err < 0) 11397 return err; 11398 do_sim: 11399 /* If we're in commit phase, we're done here given we already 11400 * pushed the truncated dst_reg into the speculative verification 11401 * stack. 11402 * 11403 * Also, when register is a known constant, we rewrite register-based 11404 * operation to immediate-based, and thus do not need masking (and as 11405 * a consequence, do not need to simulate the zero-truncation either). 11406 */ 11407 if (commit_window || off_is_imm) 11408 return 0; 11409 11410 /* Simulate and find potential out-of-bounds access under 11411 * speculative execution from truncation as a result of 11412 * masking when off was not within expected range. If off 11413 * sits in dst, then we temporarily need to move ptr there 11414 * to simulate dst (== 0) +/-= ptr. Needed, for example, 11415 * for cases where we use K-based arithmetic in one direction 11416 * and truncated reg-based in the other in order to explore 11417 * bad access. 11418 */ 11419 if (!ptr_is_dst_reg) { 11420 tmp = *dst_reg; 11421 copy_register_state(dst_reg, ptr_reg); 11422 } 11423 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 11424 env->insn_idx); 11425 if (!ptr_is_dst_reg && ret) 11426 *dst_reg = tmp; 11427 return !ret ? REASON_STACK : 0; 11428 } 11429 11430 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 11431 { 11432 struct bpf_verifier_state *vstate = env->cur_state; 11433 11434 /* If we simulate paths under speculation, we don't update the 11435 * insn as 'seen' such that when we verify unreachable paths in 11436 * the non-speculative domain, sanitize_dead_code() can still 11437 * rewrite/sanitize them. 11438 */ 11439 if (!vstate->speculative) 11440 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 11441 } 11442 11443 static int sanitize_err(struct bpf_verifier_env *env, 11444 const struct bpf_insn *insn, int reason, 11445 const struct bpf_reg_state *off_reg, 11446 const struct bpf_reg_state *dst_reg) 11447 { 11448 static const char *err = "pointer arithmetic with it prohibited for !root"; 11449 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 11450 u32 dst = insn->dst_reg, src = insn->src_reg; 11451 11452 switch (reason) { 11453 case REASON_BOUNDS: 11454 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 11455 off_reg == dst_reg ? dst : src, err); 11456 break; 11457 case REASON_TYPE: 11458 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 11459 off_reg == dst_reg ? src : dst, err); 11460 break; 11461 case REASON_PATHS: 11462 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 11463 dst, op, err); 11464 break; 11465 case REASON_LIMIT: 11466 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 11467 dst, op, err); 11468 break; 11469 case REASON_STACK: 11470 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 11471 dst, err); 11472 break; 11473 default: 11474 verbose(env, "verifier internal error: unknown reason (%d)\n", 11475 reason); 11476 break; 11477 } 11478 11479 return -EACCES; 11480 } 11481 11482 /* check that stack access falls within stack limits and that 'reg' doesn't 11483 * have a variable offset. 11484 * 11485 * Variable offset is prohibited for unprivileged mode for simplicity since it 11486 * requires corresponding support in Spectre masking for stack ALU. See also 11487 * retrieve_ptr_limit(). 11488 * 11489 * 11490 * 'off' includes 'reg->off'. 11491 */ 11492 static int check_stack_access_for_ptr_arithmetic( 11493 struct bpf_verifier_env *env, 11494 int regno, 11495 const struct bpf_reg_state *reg, 11496 int off) 11497 { 11498 if (!tnum_is_const(reg->var_off)) { 11499 char tn_buf[48]; 11500 11501 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 11502 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 11503 regno, tn_buf, off); 11504 return -EACCES; 11505 } 11506 11507 if (off >= 0 || off < -MAX_BPF_STACK) { 11508 verbose(env, "R%d stack pointer arithmetic goes out of range, " 11509 "prohibited for !root; off=%d\n", regno, off); 11510 return -EACCES; 11511 } 11512 11513 return 0; 11514 } 11515 11516 static int sanitize_check_bounds(struct bpf_verifier_env *env, 11517 const struct bpf_insn *insn, 11518 const struct bpf_reg_state *dst_reg) 11519 { 11520 u32 dst = insn->dst_reg; 11521 11522 /* For unprivileged we require that resulting offset must be in bounds 11523 * in order to be able to sanitize access later on. 11524 */ 11525 if (env->bypass_spec_v1) 11526 return 0; 11527 11528 switch (dst_reg->type) { 11529 case PTR_TO_STACK: 11530 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 11531 dst_reg->off + dst_reg->var_off.value)) 11532 return -EACCES; 11533 break; 11534 case PTR_TO_MAP_VALUE: 11535 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 11536 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 11537 "prohibited for !root\n", dst); 11538 return -EACCES; 11539 } 11540 break; 11541 default: 11542 break; 11543 } 11544 11545 return 0; 11546 } 11547 11548 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 11549 * Caller should also handle BPF_MOV case separately. 11550 * If we return -EACCES, caller may want to try again treating pointer as a 11551 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 11552 */ 11553 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 11554 struct bpf_insn *insn, 11555 const struct bpf_reg_state *ptr_reg, 11556 const struct bpf_reg_state *off_reg) 11557 { 11558 struct bpf_verifier_state *vstate = env->cur_state; 11559 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 11560 struct bpf_reg_state *regs = state->regs, *dst_reg; 11561 bool known = tnum_is_const(off_reg->var_off); 11562 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 11563 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 11564 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 11565 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 11566 struct bpf_sanitize_info info = {}; 11567 u8 opcode = BPF_OP(insn->code); 11568 u32 dst = insn->dst_reg; 11569 int ret; 11570 11571 dst_reg = ®s[dst]; 11572 11573 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 11574 smin_val > smax_val || umin_val > umax_val) { 11575 /* Taint dst register if offset had invalid bounds derived from 11576 * e.g. dead branches. 11577 */ 11578 __mark_reg_unknown(env, dst_reg); 11579 return 0; 11580 } 11581 11582 if (BPF_CLASS(insn->code) != BPF_ALU64) { 11583 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 11584 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 11585 __mark_reg_unknown(env, dst_reg); 11586 return 0; 11587 } 11588 11589 verbose(env, 11590 "R%d 32-bit pointer arithmetic prohibited\n", 11591 dst); 11592 return -EACCES; 11593 } 11594 11595 if (ptr_reg->type & PTR_MAYBE_NULL) { 11596 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 11597 dst, reg_type_str(env, ptr_reg->type)); 11598 return -EACCES; 11599 } 11600 11601 switch (base_type(ptr_reg->type)) { 11602 case CONST_PTR_TO_MAP: 11603 /* smin_val represents the known value */ 11604 if (known && smin_val == 0 && opcode == BPF_ADD) 11605 break; 11606 fallthrough; 11607 case PTR_TO_PACKET_END: 11608 case PTR_TO_SOCKET: 11609 case PTR_TO_SOCK_COMMON: 11610 case PTR_TO_TCP_SOCK: 11611 case PTR_TO_XDP_SOCK: 11612 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 11613 dst, reg_type_str(env, ptr_reg->type)); 11614 return -EACCES; 11615 default: 11616 break; 11617 } 11618 11619 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 11620 * The id may be overwritten later if we create a new variable offset. 11621 */ 11622 dst_reg->type = ptr_reg->type; 11623 dst_reg->id = ptr_reg->id; 11624 11625 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 11626 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 11627 return -EINVAL; 11628 11629 /* pointer types do not carry 32-bit bounds at the moment. */ 11630 __mark_reg32_unbounded(dst_reg); 11631 11632 if (sanitize_needed(opcode)) { 11633 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 11634 &info, false); 11635 if (ret < 0) 11636 return sanitize_err(env, insn, ret, off_reg, dst_reg); 11637 } 11638 11639 switch (opcode) { 11640 case BPF_ADD: 11641 /* We can take a fixed offset as long as it doesn't overflow 11642 * the s32 'off' field 11643 */ 11644 if (known && (ptr_reg->off + smin_val == 11645 (s64)(s32)(ptr_reg->off + smin_val))) { 11646 /* pointer += K. Accumulate it into fixed offset */ 11647 dst_reg->smin_value = smin_ptr; 11648 dst_reg->smax_value = smax_ptr; 11649 dst_reg->umin_value = umin_ptr; 11650 dst_reg->umax_value = umax_ptr; 11651 dst_reg->var_off = ptr_reg->var_off; 11652 dst_reg->off = ptr_reg->off + smin_val; 11653 dst_reg->raw = ptr_reg->raw; 11654 break; 11655 } 11656 /* A new variable offset is created. Note that off_reg->off 11657 * == 0, since it's a scalar. 11658 * dst_reg gets the pointer type and since some positive 11659 * integer value was added to the pointer, give it a new 'id' 11660 * if it's a PTR_TO_PACKET. 11661 * this creates a new 'base' pointer, off_reg (variable) gets 11662 * added into the variable offset, and we copy the fixed offset 11663 * from ptr_reg. 11664 */ 11665 if (signed_add_overflows(smin_ptr, smin_val) || 11666 signed_add_overflows(smax_ptr, smax_val)) { 11667 dst_reg->smin_value = S64_MIN; 11668 dst_reg->smax_value = S64_MAX; 11669 } else { 11670 dst_reg->smin_value = smin_ptr + smin_val; 11671 dst_reg->smax_value = smax_ptr + smax_val; 11672 } 11673 if (umin_ptr + umin_val < umin_ptr || 11674 umax_ptr + umax_val < umax_ptr) { 11675 dst_reg->umin_value = 0; 11676 dst_reg->umax_value = U64_MAX; 11677 } else { 11678 dst_reg->umin_value = umin_ptr + umin_val; 11679 dst_reg->umax_value = umax_ptr + umax_val; 11680 } 11681 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 11682 dst_reg->off = ptr_reg->off; 11683 dst_reg->raw = ptr_reg->raw; 11684 if (reg_is_pkt_pointer(ptr_reg)) { 11685 dst_reg->id = ++env->id_gen; 11686 /* something was added to pkt_ptr, set range to zero */ 11687 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 11688 } 11689 break; 11690 case BPF_SUB: 11691 if (dst_reg == off_reg) { 11692 /* scalar -= pointer. Creates an unknown scalar */ 11693 verbose(env, "R%d tried to subtract pointer from scalar\n", 11694 dst); 11695 return -EACCES; 11696 } 11697 /* We don't allow subtraction from FP, because (according to 11698 * test_verifier.c test "invalid fp arithmetic", JITs might not 11699 * be able to deal with it. 11700 */ 11701 if (ptr_reg->type == PTR_TO_STACK) { 11702 verbose(env, "R%d subtraction from stack pointer prohibited\n", 11703 dst); 11704 return -EACCES; 11705 } 11706 if (known && (ptr_reg->off - smin_val == 11707 (s64)(s32)(ptr_reg->off - smin_val))) { 11708 /* pointer -= K. Subtract it from fixed offset */ 11709 dst_reg->smin_value = smin_ptr; 11710 dst_reg->smax_value = smax_ptr; 11711 dst_reg->umin_value = umin_ptr; 11712 dst_reg->umax_value = umax_ptr; 11713 dst_reg->var_off = ptr_reg->var_off; 11714 dst_reg->id = ptr_reg->id; 11715 dst_reg->off = ptr_reg->off - smin_val; 11716 dst_reg->raw = ptr_reg->raw; 11717 break; 11718 } 11719 /* A new variable offset is created. If the subtrahend is known 11720 * nonnegative, then any reg->range we had before is still good. 11721 */ 11722 if (signed_sub_overflows(smin_ptr, smax_val) || 11723 signed_sub_overflows(smax_ptr, smin_val)) { 11724 /* Overflow possible, we know nothing */ 11725 dst_reg->smin_value = S64_MIN; 11726 dst_reg->smax_value = S64_MAX; 11727 } else { 11728 dst_reg->smin_value = smin_ptr - smax_val; 11729 dst_reg->smax_value = smax_ptr - smin_val; 11730 } 11731 if (umin_ptr < umax_val) { 11732 /* Overflow possible, we know nothing */ 11733 dst_reg->umin_value = 0; 11734 dst_reg->umax_value = U64_MAX; 11735 } else { 11736 /* Cannot overflow (as long as bounds are consistent) */ 11737 dst_reg->umin_value = umin_ptr - umax_val; 11738 dst_reg->umax_value = umax_ptr - umin_val; 11739 } 11740 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 11741 dst_reg->off = ptr_reg->off; 11742 dst_reg->raw = ptr_reg->raw; 11743 if (reg_is_pkt_pointer(ptr_reg)) { 11744 dst_reg->id = ++env->id_gen; 11745 /* something was added to pkt_ptr, set range to zero */ 11746 if (smin_val < 0) 11747 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 11748 } 11749 break; 11750 case BPF_AND: 11751 case BPF_OR: 11752 case BPF_XOR: 11753 /* bitwise ops on pointers are troublesome, prohibit. */ 11754 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 11755 dst, bpf_alu_string[opcode >> 4]); 11756 return -EACCES; 11757 default: 11758 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 11759 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 11760 dst, bpf_alu_string[opcode >> 4]); 11761 return -EACCES; 11762 } 11763 11764 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 11765 return -EINVAL; 11766 reg_bounds_sync(dst_reg); 11767 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 11768 return -EACCES; 11769 if (sanitize_needed(opcode)) { 11770 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 11771 &info, true); 11772 if (ret < 0) 11773 return sanitize_err(env, insn, ret, off_reg, dst_reg); 11774 } 11775 11776 return 0; 11777 } 11778 11779 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 11780 struct bpf_reg_state *src_reg) 11781 { 11782 s32 smin_val = src_reg->s32_min_value; 11783 s32 smax_val = src_reg->s32_max_value; 11784 u32 umin_val = src_reg->u32_min_value; 11785 u32 umax_val = src_reg->u32_max_value; 11786 11787 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 11788 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 11789 dst_reg->s32_min_value = S32_MIN; 11790 dst_reg->s32_max_value = S32_MAX; 11791 } else { 11792 dst_reg->s32_min_value += smin_val; 11793 dst_reg->s32_max_value += smax_val; 11794 } 11795 if (dst_reg->u32_min_value + umin_val < umin_val || 11796 dst_reg->u32_max_value + umax_val < umax_val) { 11797 dst_reg->u32_min_value = 0; 11798 dst_reg->u32_max_value = U32_MAX; 11799 } else { 11800 dst_reg->u32_min_value += umin_val; 11801 dst_reg->u32_max_value += umax_val; 11802 } 11803 } 11804 11805 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 11806 struct bpf_reg_state *src_reg) 11807 { 11808 s64 smin_val = src_reg->smin_value; 11809 s64 smax_val = src_reg->smax_value; 11810 u64 umin_val = src_reg->umin_value; 11811 u64 umax_val = src_reg->umax_value; 11812 11813 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 11814 signed_add_overflows(dst_reg->smax_value, smax_val)) { 11815 dst_reg->smin_value = S64_MIN; 11816 dst_reg->smax_value = S64_MAX; 11817 } else { 11818 dst_reg->smin_value += smin_val; 11819 dst_reg->smax_value += smax_val; 11820 } 11821 if (dst_reg->umin_value + umin_val < umin_val || 11822 dst_reg->umax_value + umax_val < umax_val) { 11823 dst_reg->umin_value = 0; 11824 dst_reg->umax_value = U64_MAX; 11825 } else { 11826 dst_reg->umin_value += umin_val; 11827 dst_reg->umax_value += umax_val; 11828 } 11829 } 11830 11831 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 11832 struct bpf_reg_state *src_reg) 11833 { 11834 s32 smin_val = src_reg->s32_min_value; 11835 s32 smax_val = src_reg->s32_max_value; 11836 u32 umin_val = src_reg->u32_min_value; 11837 u32 umax_val = src_reg->u32_max_value; 11838 11839 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 11840 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 11841 /* Overflow possible, we know nothing */ 11842 dst_reg->s32_min_value = S32_MIN; 11843 dst_reg->s32_max_value = S32_MAX; 11844 } else { 11845 dst_reg->s32_min_value -= smax_val; 11846 dst_reg->s32_max_value -= smin_val; 11847 } 11848 if (dst_reg->u32_min_value < umax_val) { 11849 /* Overflow possible, we know nothing */ 11850 dst_reg->u32_min_value = 0; 11851 dst_reg->u32_max_value = U32_MAX; 11852 } else { 11853 /* Cannot overflow (as long as bounds are consistent) */ 11854 dst_reg->u32_min_value -= umax_val; 11855 dst_reg->u32_max_value -= umin_val; 11856 } 11857 } 11858 11859 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 11860 struct bpf_reg_state *src_reg) 11861 { 11862 s64 smin_val = src_reg->smin_value; 11863 s64 smax_val = src_reg->smax_value; 11864 u64 umin_val = src_reg->umin_value; 11865 u64 umax_val = src_reg->umax_value; 11866 11867 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 11868 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 11869 /* Overflow possible, we know nothing */ 11870 dst_reg->smin_value = S64_MIN; 11871 dst_reg->smax_value = S64_MAX; 11872 } else { 11873 dst_reg->smin_value -= smax_val; 11874 dst_reg->smax_value -= smin_val; 11875 } 11876 if (dst_reg->umin_value < umax_val) { 11877 /* Overflow possible, we know nothing */ 11878 dst_reg->umin_value = 0; 11879 dst_reg->umax_value = U64_MAX; 11880 } else { 11881 /* Cannot overflow (as long as bounds are consistent) */ 11882 dst_reg->umin_value -= umax_val; 11883 dst_reg->umax_value -= umin_val; 11884 } 11885 } 11886 11887 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 11888 struct bpf_reg_state *src_reg) 11889 { 11890 s32 smin_val = src_reg->s32_min_value; 11891 u32 umin_val = src_reg->u32_min_value; 11892 u32 umax_val = src_reg->u32_max_value; 11893 11894 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 11895 /* Ain't nobody got time to multiply that sign */ 11896 __mark_reg32_unbounded(dst_reg); 11897 return; 11898 } 11899 /* Both values are positive, so we can work with unsigned and 11900 * copy the result to signed (unless it exceeds S32_MAX). 11901 */ 11902 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 11903 /* Potential overflow, we know nothing */ 11904 __mark_reg32_unbounded(dst_reg); 11905 return; 11906 } 11907 dst_reg->u32_min_value *= umin_val; 11908 dst_reg->u32_max_value *= umax_val; 11909 if (dst_reg->u32_max_value > S32_MAX) { 11910 /* Overflow possible, we know nothing */ 11911 dst_reg->s32_min_value = S32_MIN; 11912 dst_reg->s32_max_value = S32_MAX; 11913 } else { 11914 dst_reg->s32_min_value = dst_reg->u32_min_value; 11915 dst_reg->s32_max_value = dst_reg->u32_max_value; 11916 } 11917 } 11918 11919 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 11920 struct bpf_reg_state *src_reg) 11921 { 11922 s64 smin_val = src_reg->smin_value; 11923 u64 umin_val = src_reg->umin_value; 11924 u64 umax_val = src_reg->umax_value; 11925 11926 if (smin_val < 0 || dst_reg->smin_value < 0) { 11927 /* Ain't nobody got time to multiply that sign */ 11928 __mark_reg64_unbounded(dst_reg); 11929 return; 11930 } 11931 /* Both values are positive, so we can work with unsigned and 11932 * copy the result to signed (unless it exceeds S64_MAX). 11933 */ 11934 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 11935 /* Potential overflow, we know nothing */ 11936 __mark_reg64_unbounded(dst_reg); 11937 return; 11938 } 11939 dst_reg->umin_value *= umin_val; 11940 dst_reg->umax_value *= umax_val; 11941 if (dst_reg->umax_value > S64_MAX) { 11942 /* Overflow possible, we know nothing */ 11943 dst_reg->smin_value = S64_MIN; 11944 dst_reg->smax_value = S64_MAX; 11945 } else { 11946 dst_reg->smin_value = dst_reg->umin_value; 11947 dst_reg->smax_value = dst_reg->umax_value; 11948 } 11949 } 11950 11951 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 11952 struct bpf_reg_state *src_reg) 11953 { 11954 bool src_known = tnum_subreg_is_const(src_reg->var_off); 11955 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 11956 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 11957 s32 smin_val = src_reg->s32_min_value; 11958 u32 umax_val = src_reg->u32_max_value; 11959 11960 if (src_known && dst_known) { 11961 __mark_reg32_known(dst_reg, var32_off.value); 11962 return; 11963 } 11964 11965 /* We get our minimum from the var_off, since that's inherently 11966 * bitwise. Our maximum is the minimum of the operands' maxima. 11967 */ 11968 dst_reg->u32_min_value = var32_off.value; 11969 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 11970 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 11971 /* Lose signed bounds when ANDing negative numbers, 11972 * ain't nobody got time for that. 11973 */ 11974 dst_reg->s32_min_value = S32_MIN; 11975 dst_reg->s32_max_value = S32_MAX; 11976 } else { 11977 /* ANDing two positives gives a positive, so safe to 11978 * cast result into s64. 11979 */ 11980 dst_reg->s32_min_value = dst_reg->u32_min_value; 11981 dst_reg->s32_max_value = dst_reg->u32_max_value; 11982 } 11983 } 11984 11985 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 11986 struct bpf_reg_state *src_reg) 11987 { 11988 bool src_known = tnum_is_const(src_reg->var_off); 11989 bool dst_known = tnum_is_const(dst_reg->var_off); 11990 s64 smin_val = src_reg->smin_value; 11991 u64 umax_val = src_reg->umax_value; 11992 11993 if (src_known && dst_known) { 11994 __mark_reg_known(dst_reg, dst_reg->var_off.value); 11995 return; 11996 } 11997 11998 /* We get our minimum from the var_off, since that's inherently 11999 * bitwise. Our maximum is the minimum of the operands' maxima. 12000 */ 12001 dst_reg->umin_value = dst_reg->var_off.value; 12002 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 12003 if (dst_reg->smin_value < 0 || smin_val < 0) { 12004 /* Lose signed bounds when ANDing negative numbers, 12005 * ain't nobody got time for that. 12006 */ 12007 dst_reg->smin_value = S64_MIN; 12008 dst_reg->smax_value = S64_MAX; 12009 } else { 12010 /* ANDing two positives gives a positive, so safe to 12011 * cast result into s64. 12012 */ 12013 dst_reg->smin_value = dst_reg->umin_value; 12014 dst_reg->smax_value = dst_reg->umax_value; 12015 } 12016 /* We may learn something more from the var_off */ 12017 __update_reg_bounds(dst_reg); 12018 } 12019 12020 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 12021 struct bpf_reg_state *src_reg) 12022 { 12023 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12024 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12025 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12026 s32 smin_val = src_reg->s32_min_value; 12027 u32 umin_val = src_reg->u32_min_value; 12028 12029 if (src_known && dst_known) { 12030 __mark_reg32_known(dst_reg, var32_off.value); 12031 return; 12032 } 12033 12034 /* We get our maximum from the var_off, and our minimum is the 12035 * maximum of the operands' minima 12036 */ 12037 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 12038 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12039 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 12040 /* Lose signed bounds when ORing negative numbers, 12041 * ain't nobody got time for that. 12042 */ 12043 dst_reg->s32_min_value = S32_MIN; 12044 dst_reg->s32_max_value = S32_MAX; 12045 } else { 12046 /* ORing two positives gives a positive, so safe to 12047 * cast result into s64. 12048 */ 12049 dst_reg->s32_min_value = dst_reg->u32_min_value; 12050 dst_reg->s32_max_value = dst_reg->u32_max_value; 12051 } 12052 } 12053 12054 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 12055 struct bpf_reg_state *src_reg) 12056 { 12057 bool src_known = tnum_is_const(src_reg->var_off); 12058 bool dst_known = tnum_is_const(dst_reg->var_off); 12059 s64 smin_val = src_reg->smin_value; 12060 u64 umin_val = src_reg->umin_value; 12061 12062 if (src_known && dst_known) { 12063 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12064 return; 12065 } 12066 12067 /* We get our maximum from the var_off, and our minimum is the 12068 * maximum of the operands' minima 12069 */ 12070 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 12071 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12072 if (dst_reg->smin_value < 0 || smin_val < 0) { 12073 /* Lose signed bounds when ORing negative numbers, 12074 * ain't nobody got time for that. 12075 */ 12076 dst_reg->smin_value = S64_MIN; 12077 dst_reg->smax_value = S64_MAX; 12078 } else { 12079 /* ORing two positives gives a positive, so safe to 12080 * cast result into s64. 12081 */ 12082 dst_reg->smin_value = dst_reg->umin_value; 12083 dst_reg->smax_value = dst_reg->umax_value; 12084 } 12085 /* We may learn something more from the var_off */ 12086 __update_reg_bounds(dst_reg); 12087 } 12088 12089 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 12090 struct bpf_reg_state *src_reg) 12091 { 12092 bool src_known = tnum_subreg_is_const(src_reg->var_off); 12093 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 12094 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 12095 s32 smin_val = src_reg->s32_min_value; 12096 12097 if (src_known && dst_known) { 12098 __mark_reg32_known(dst_reg, var32_off.value); 12099 return; 12100 } 12101 12102 /* We get both minimum and maximum from the var32_off. */ 12103 dst_reg->u32_min_value = var32_off.value; 12104 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 12105 12106 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 12107 /* XORing two positive sign numbers gives a positive, 12108 * so safe to cast u32 result into s32. 12109 */ 12110 dst_reg->s32_min_value = dst_reg->u32_min_value; 12111 dst_reg->s32_max_value = dst_reg->u32_max_value; 12112 } else { 12113 dst_reg->s32_min_value = S32_MIN; 12114 dst_reg->s32_max_value = S32_MAX; 12115 } 12116 } 12117 12118 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 12119 struct bpf_reg_state *src_reg) 12120 { 12121 bool src_known = tnum_is_const(src_reg->var_off); 12122 bool dst_known = tnum_is_const(dst_reg->var_off); 12123 s64 smin_val = src_reg->smin_value; 12124 12125 if (src_known && dst_known) { 12126 /* dst_reg->var_off.value has been updated earlier */ 12127 __mark_reg_known(dst_reg, dst_reg->var_off.value); 12128 return; 12129 } 12130 12131 /* We get both minimum and maximum from the var_off. */ 12132 dst_reg->umin_value = dst_reg->var_off.value; 12133 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 12134 12135 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 12136 /* XORing two positive sign numbers gives a positive, 12137 * so safe to cast u64 result into s64. 12138 */ 12139 dst_reg->smin_value = dst_reg->umin_value; 12140 dst_reg->smax_value = dst_reg->umax_value; 12141 } else { 12142 dst_reg->smin_value = S64_MIN; 12143 dst_reg->smax_value = S64_MAX; 12144 } 12145 12146 __update_reg_bounds(dst_reg); 12147 } 12148 12149 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12150 u64 umin_val, u64 umax_val) 12151 { 12152 /* We lose all sign bit information (except what we can pick 12153 * up from var_off) 12154 */ 12155 dst_reg->s32_min_value = S32_MIN; 12156 dst_reg->s32_max_value = S32_MAX; 12157 /* If we might shift our top bit out, then we know nothing */ 12158 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 12159 dst_reg->u32_min_value = 0; 12160 dst_reg->u32_max_value = U32_MAX; 12161 } else { 12162 dst_reg->u32_min_value <<= umin_val; 12163 dst_reg->u32_max_value <<= umax_val; 12164 } 12165 } 12166 12167 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 12168 struct bpf_reg_state *src_reg) 12169 { 12170 u32 umax_val = src_reg->u32_max_value; 12171 u32 umin_val = src_reg->u32_min_value; 12172 /* u32 alu operation will zext upper bits */ 12173 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12174 12175 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12176 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 12177 /* Not required but being careful mark reg64 bounds as unknown so 12178 * that we are forced to pick them up from tnum and zext later and 12179 * if some path skips this step we are still safe. 12180 */ 12181 __mark_reg64_unbounded(dst_reg); 12182 __update_reg32_bounds(dst_reg); 12183 } 12184 12185 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 12186 u64 umin_val, u64 umax_val) 12187 { 12188 /* Special case <<32 because it is a common compiler pattern to sign 12189 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 12190 * positive we know this shift will also be positive so we can track 12191 * bounds correctly. Otherwise we lose all sign bit information except 12192 * what we can pick up from var_off. Perhaps we can generalize this 12193 * later to shifts of any length. 12194 */ 12195 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 12196 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 12197 else 12198 dst_reg->smax_value = S64_MAX; 12199 12200 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 12201 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 12202 else 12203 dst_reg->smin_value = S64_MIN; 12204 12205 /* If we might shift our top bit out, then we know nothing */ 12206 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 12207 dst_reg->umin_value = 0; 12208 dst_reg->umax_value = U64_MAX; 12209 } else { 12210 dst_reg->umin_value <<= umin_val; 12211 dst_reg->umax_value <<= umax_val; 12212 } 12213 } 12214 12215 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 12216 struct bpf_reg_state *src_reg) 12217 { 12218 u64 umax_val = src_reg->umax_value; 12219 u64 umin_val = src_reg->umin_value; 12220 12221 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 12222 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 12223 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12224 12225 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 12226 /* We may learn something more from the var_off */ 12227 __update_reg_bounds(dst_reg); 12228 } 12229 12230 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 12231 struct bpf_reg_state *src_reg) 12232 { 12233 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12234 u32 umax_val = src_reg->u32_max_value; 12235 u32 umin_val = src_reg->u32_min_value; 12236 12237 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12238 * be negative, then either: 12239 * 1) src_reg might be zero, so the sign bit of the result is 12240 * unknown, so we lose our signed bounds 12241 * 2) it's known negative, thus the unsigned bounds capture the 12242 * signed bounds 12243 * 3) the signed bounds cross zero, so they tell us nothing 12244 * about the result 12245 * If the value in dst_reg is known nonnegative, then again the 12246 * unsigned bounds capture the signed bounds. 12247 * Thus, in all cases it suffices to blow away our signed bounds 12248 * and rely on inferring new ones from the unsigned bounds and 12249 * var_off of the result. 12250 */ 12251 dst_reg->s32_min_value = S32_MIN; 12252 dst_reg->s32_max_value = S32_MAX; 12253 12254 dst_reg->var_off = tnum_rshift(subreg, umin_val); 12255 dst_reg->u32_min_value >>= umax_val; 12256 dst_reg->u32_max_value >>= umin_val; 12257 12258 __mark_reg64_unbounded(dst_reg); 12259 __update_reg32_bounds(dst_reg); 12260 } 12261 12262 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 12263 struct bpf_reg_state *src_reg) 12264 { 12265 u64 umax_val = src_reg->umax_value; 12266 u64 umin_val = src_reg->umin_value; 12267 12268 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12269 * be negative, then either: 12270 * 1) src_reg might be zero, so the sign bit of the result is 12271 * unknown, so we lose our signed bounds 12272 * 2) it's known negative, thus the unsigned bounds capture the 12273 * signed bounds 12274 * 3) the signed bounds cross zero, so they tell us nothing 12275 * about the result 12276 * If the value in dst_reg is known nonnegative, then again the 12277 * unsigned bounds capture the signed bounds. 12278 * Thus, in all cases it suffices to blow away our signed bounds 12279 * and rely on inferring new ones from the unsigned bounds and 12280 * var_off of the result. 12281 */ 12282 dst_reg->smin_value = S64_MIN; 12283 dst_reg->smax_value = S64_MAX; 12284 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 12285 dst_reg->umin_value >>= umax_val; 12286 dst_reg->umax_value >>= umin_val; 12287 12288 /* Its not easy to operate on alu32 bounds here because it depends 12289 * on bits being shifted in. Take easy way out and mark unbounded 12290 * so we can recalculate later from tnum. 12291 */ 12292 __mark_reg32_unbounded(dst_reg); 12293 __update_reg_bounds(dst_reg); 12294 } 12295 12296 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 12297 struct bpf_reg_state *src_reg) 12298 { 12299 u64 umin_val = src_reg->u32_min_value; 12300 12301 /* Upon reaching here, src_known is true and 12302 * umax_val is equal to umin_val. 12303 */ 12304 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 12305 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 12306 12307 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 12308 12309 /* blow away the dst_reg umin_value/umax_value and rely on 12310 * dst_reg var_off to refine the result. 12311 */ 12312 dst_reg->u32_min_value = 0; 12313 dst_reg->u32_max_value = U32_MAX; 12314 12315 __mark_reg64_unbounded(dst_reg); 12316 __update_reg32_bounds(dst_reg); 12317 } 12318 12319 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 12320 struct bpf_reg_state *src_reg) 12321 { 12322 u64 umin_val = src_reg->umin_value; 12323 12324 /* Upon reaching here, src_known is true and umax_val is equal 12325 * to umin_val. 12326 */ 12327 dst_reg->smin_value >>= umin_val; 12328 dst_reg->smax_value >>= umin_val; 12329 12330 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 12331 12332 /* blow away the dst_reg umin_value/umax_value and rely on 12333 * dst_reg var_off to refine the result. 12334 */ 12335 dst_reg->umin_value = 0; 12336 dst_reg->umax_value = U64_MAX; 12337 12338 /* Its not easy to operate on alu32 bounds here because it depends 12339 * on bits being shifted in from upper 32-bits. Take easy way out 12340 * and mark unbounded so we can recalculate later from tnum. 12341 */ 12342 __mark_reg32_unbounded(dst_reg); 12343 __update_reg_bounds(dst_reg); 12344 } 12345 12346 /* WARNING: This function does calculations on 64-bit values, but the actual 12347 * execution may occur on 32-bit values. Therefore, things like bitshifts 12348 * need extra checks in the 32-bit case. 12349 */ 12350 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 12351 struct bpf_insn *insn, 12352 struct bpf_reg_state *dst_reg, 12353 struct bpf_reg_state src_reg) 12354 { 12355 struct bpf_reg_state *regs = cur_regs(env); 12356 u8 opcode = BPF_OP(insn->code); 12357 bool src_known; 12358 s64 smin_val, smax_val; 12359 u64 umin_val, umax_val; 12360 s32 s32_min_val, s32_max_val; 12361 u32 u32_min_val, u32_max_val; 12362 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 12363 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 12364 int ret; 12365 12366 smin_val = src_reg.smin_value; 12367 smax_val = src_reg.smax_value; 12368 umin_val = src_reg.umin_value; 12369 umax_val = src_reg.umax_value; 12370 12371 s32_min_val = src_reg.s32_min_value; 12372 s32_max_val = src_reg.s32_max_value; 12373 u32_min_val = src_reg.u32_min_value; 12374 u32_max_val = src_reg.u32_max_value; 12375 12376 if (alu32) { 12377 src_known = tnum_subreg_is_const(src_reg.var_off); 12378 if ((src_known && 12379 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 12380 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 12381 /* Taint dst register if offset had invalid bounds 12382 * derived from e.g. dead branches. 12383 */ 12384 __mark_reg_unknown(env, dst_reg); 12385 return 0; 12386 } 12387 } else { 12388 src_known = tnum_is_const(src_reg.var_off); 12389 if ((src_known && 12390 (smin_val != smax_val || umin_val != umax_val)) || 12391 smin_val > smax_val || umin_val > umax_val) { 12392 /* Taint dst register if offset had invalid bounds 12393 * derived from e.g. dead branches. 12394 */ 12395 __mark_reg_unknown(env, dst_reg); 12396 return 0; 12397 } 12398 } 12399 12400 if (!src_known && 12401 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 12402 __mark_reg_unknown(env, dst_reg); 12403 return 0; 12404 } 12405 12406 if (sanitize_needed(opcode)) { 12407 ret = sanitize_val_alu(env, insn); 12408 if (ret < 0) 12409 return sanitize_err(env, insn, ret, NULL, NULL); 12410 } 12411 12412 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 12413 * There are two classes of instructions: The first class we track both 12414 * alu32 and alu64 sign/unsigned bounds independently this provides the 12415 * greatest amount of precision when alu operations are mixed with jmp32 12416 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 12417 * and BPF_OR. This is possible because these ops have fairly easy to 12418 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 12419 * See alu32 verifier tests for examples. The second class of 12420 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 12421 * with regards to tracking sign/unsigned bounds because the bits may 12422 * cross subreg boundaries in the alu64 case. When this happens we mark 12423 * the reg unbounded in the subreg bound space and use the resulting 12424 * tnum to calculate an approximation of the sign/unsigned bounds. 12425 */ 12426 switch (opcode) { 12427 case BPF_ADD: 12428 scalar32_min_max_add(dst_reg, &src_reg); 12429 scalar_min_max_add(dst_reg, &src_reg); 12430 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 12431 break; 12432 case BPF_SUB: 12433 scalar32_min_max_sub(dst_reg, &src_reg); 12434 scalar_min_max_sub(dst_reg, &src_reg); 12435 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 12436 break; 12437 case BPF_MUL: 12438 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 12439 scalar32_min_max_mul(dst_reg, &src_reg); 12440 scalar_min_max_mul(dst_reg, &src_reg); 12441 break; 12442 case BPF_AND: 12443 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 12444 scalar32_min_max_and(dst_reg, &src_reg); 12445 scalar_min_max_and(dst_reg, &src_reg); 12446 break; 12447 case BPF_OR: 12448 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 12449 scalar32_min_max_or(dst_reg, &src_reg); 12450 scalar_min_max_or(dst_reg, &src_reg); 12451 break; 12452 case BPF_XOR: 12453 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 12454 scalar32_min_max_xor(dst_reg, &src_reg); 12455 scalar_min_max_xor(dst_reg, &src_reg); 12456 break; 12457 case BPF_LSH: 12458 if (umax_val >= insn_bitness) { 12459 /* Shifts greater than 31 or 63 are undefined. 12460 * This includes shifts by a negative number. 12461 */ 12462 mark_reg_unknown(env, regs, insn->dst_reg); 12463 break; 12464 } 12465 if (alu32) 12466 scalar32_min_max_lsh(dst_reg, &src_reg); 12467 else 12468 scalar_min_max_lsh(dst_reg, &src_reg); 12469 break; 12470 case BPF_RSH: 12471 if (umax_val >= insn_bitness) { 12472 /* Shifts greater than 31 or 63 are undefined. 12473 * This includes shifts by a negative number. 12474 */ 12475 mark_reg_unknown(env, regs, insn->dst_reg); 12476 break; 12477 } 12478 if (alu32) 12479 scalar32_min_max_rsh(dst_reg, &src_reg); 12480 else 12481 scalar_min_max_rsh(dst_reg, &src_reg); 12482 break; 12483 case BPF_ARSH: 12484 if (umax_val >= insn_bitness) { 12485 /* Shifts greater than 31 or 63 are undefined. 12486 * This includes shifts by a negative number. 12487 */ 12488 mark_reg_unknown(env, regs, insn->dst_reg); 12489 break; 12490 } 12491 if (alu32) 12492 scalar32_min_max_arsh(dst_reg, &src_reg); 12493 else 12494 scalar_min_max_arsh(dst_reg, &src_reg); 12495 break; 12496 default: 12497 mark_reg_unknown(env, regs, insn->dst_reg); 12498 break; 12499 } 12500 12501 /* ALU32 ops are zero extended into 64bit register */ 12502 if (alu32) 12503 zext_32_to_64(dst_reg); 12504 reg_bounds_sync(dst_reg); 12505 return 0; 12506 } 12507 12508 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 12509 * and var_off. 12510 */ 12511 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 12512 struct bpf_insn *insn) 12513 { 12514 struct bpf_verifier_state *vstate = env->cur_state; 12515 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12516 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 12517 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 12518 u8 opcode = BPF_OP(insn->code); 12519 int err; 12520 12521 dst_reg = ®s[insn->dst_reg]; 12522 src_reg = NULL; 12523 if (dst_reg->type != SCALAR_VALUE) 12524 ptr_reg = dst_reg; 12525 else 12526 /* Make sure ID is cleared otherwise dst_reg min/max could be 12527 * incorrectly propagated into other registers by find_equal_scalars() 12528 */ 12529 dst_reg->id = 0; 12530 if (BPF_SRC(insn->code) == BPF_X) { 12531 src_reg = ®s[insn->src_reg]; 12532 if (src_reg->type != SCALAR_VALUE) { 12533 if (dst_reg->type != SCALAR_VALUE) { 12534 /* Combining two pointers by any ALU op yields 12535 * an arbitrary scalar. Disallow all math except 12536 * pointer subtraction 12537 */ 12538 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12539 mark_reg_unknown(env, regs, insn->dst_reg); 12540 return 0; 12541 } 12542 verbose(env, "R%d pointer %s pointer prohibited\n", 12543 insn->dst_reg, 12544 bpf_alu_string[opcode >> 4]); 12545 return -EACCES; 12546 } else { 12547 /* scalar += pointer 12548 * This is legal, but we have to reverse our 12549 * src/dest handling in computing the range 12550 */ 12551 err = mark_chain_precision(env, insn->dst_reg); 12552 if (err) 12553 return err; 12554 return adjust_ptr_min_max_vals(env, insn, 12555 src_reg, dst_reg); 12556 } 12557 } else if (ptr_reg) { 12558 /* pointer += scalar */ 12559 err = mark_chain_precision(env, insn->src_reg); 12560 if (err) 12561 return err; 12562 return adjust_ptr_min_max_vals(env, insn, 12563 dst_reg, src_reg); 12564 } else if (dst_reg->precise) { 12565 /* if dst_reg is precise, src_reg should be precise as well */ 12566 err = mark_chain_precision(env, insn->src_reg); 12567 if (err) 12568 return err; 12569 } 12570 } else { 12571 /* Pretend the src is a reg with a known value, since we only 12572 * need to be able to read from this state. 12573 */ 12574 off_reg.type = SCALAR_VALUE; 12575 __mark_reg_known(&off_reg, insn->imm); 12576 src_reg = &off_reg; 12577 if (ptr_reg) /* pointer += K */ 12578 return adjust_ptr_min_max_vals(env, insn, 12579 ptr_reg, src_reg); 12580 } 12581 12582 /* Got here implies adding two SCALAR_VALUEs */ 12583 if (WARN_ON_ONCE(ptr_reg)) { 12584 print_verifier_state(env, state, true); 12585 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 12586 return -EINVAL; 12587 } 12588 if (WARN_ON(!src_reg)) { 12589 print_verifier_state(env, state, true); 12590 verbose(env, "verifier internal error: no src_reg\n"); 12591 return -EINVAL; 12592 } 12593 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 12594 } 12595 12596 /* check validity of 32-bit and 64-bit arithmetic operations */ 12597 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 12598 { 12599 struct bpf_reg_state *regs = cur_regs(env); 12600 u8 opcode = BPF_OP(insn->code); 12601 int err; 12602 12603 if (opcode == BPF_END || opcode == BPF_NEG) { 12604 if (opcode == BPF_NEG) { 12605 if (BPF_SRC(insn->code) != BPF_K || 12606 insn->src_reg != BPF_REG_0 || 12607 insn->off != 0 || insn->imm != 0) { 12608 verbose(env, "BPF_NEG uses reserved fields\n"); 12609 return -EINVAL; 12610 } 12611 } else { 12612 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 12613 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 12614 BPF_CLASS(insn->code) == BPF_ALU64) { 12615 verbose(env, "BPF_END uses reserved fields\n"); 12616 return -EINVAL; 12617 } 12618 } 12619 12620 /* check src operand */ 12621 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 12622 if (err) 12623 return err; 12624 12625 if (is_pointer_value(env, insn->dst_reg)) { 12626 verbose(env, "R%d pointer arithmetic prohibited\n", 12627 insn->dst_reg); 12628 return -EACCES; 12629 } 12630 12631 /* check dest operand */ 12632 err = check_reg_arg(env, insn->dst_reg, DST_OP); 12633 if (err) 12634 return err; 12635 12636 } else if (opcode == BPF_MOV) { 12637 12638 if (BPF_SRC(insn->code) == BPF_X) { 12639 if (insn->imm != 0 || insn->off != 0) { 12640 verbose(env, "BPF_MOV uses reserved fields\n"); 12641 return -EINVAL; 12642 } 12643 12644 /* check src operand */ 12645 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12646 if (err) 12647 return err; 12648 } else { 12649 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 12650 verbose(env, "BPF_MOV uses reserved fields\n"); 12651 return -EINVAL; 12652 } 12653 } 12654 12655 /* check dest operand, mark as required later */ 12656 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 12657 if (err) 12658 return err; 12659 12660 if (BPF_SRC(insn->code) == BPF_X) { 12661 struct bpf_reg_state *src_reg = regs + insn->src_reg; 12662 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 12663 12664 if (BPF_CLASS(insn->code) == BPF_ALU64) { 12665 /* case: R1 = R2 12666 * copy register state to dest reg 12667 */ 12668 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 12669 /* Assign src and dst registers the same ID 12670 * that will be used by find_equal_scalars() 12671 * to propagate min/max range. 12672 */ 12673 src_reg->id = ++env->id_gen; 12674 copy_register_state(dst_reg, src_reg); 12675 dst_reg->live |= REG_LIVE_WRITTEN; 12676 dst_reg->subreg_def = DEF_NOT_SUBREG; 12677 } else { 12678 /* R1 = (u32) R2 */ 12679 if (is_pointer_value(env, insn->src_reg)) { 12680 verbose(env, 12681 "R%d partial copy of pointer\n", 12682 insn->src_reg); 12683 return -EACCES; 12684 } else if (src_reg->type == SCALAR_VALUE) { 12685 bool is_src_reg_u32 = src_reg->umax_value <= U32_MAX; 12686 12687 if (is_src_reg_u32 && !src_reg->id) 12688 src_reg->id = ++env->id_gen; 12689 copy_register_state(dst_reg, src_reg); 12690 /* Make sure ID is cleared if src_reg is not in u32 range otherwise 12691 * dst_reg min/max could be incorrectly 12692 * propagated into src_reg by find_equal_scalars() 12693 */ 12694 if (!is_src_reg_u32) 12695 dst_reg->id = 0; 12696 dst_reg->live |= REG_LIVE_WRITTEN; 12697 dst_reg->subreg_def = env->insn_idx + 1; 12698 } else { 12699 mark_reg_unknown(env, regs, 12700 insn->dst_reg); 12701 } 12702 zext_32_to_64(dst_reg); 12703 reg_bounds_sync(dst_reg); 12704 } 12705 } else { 12706 /* case: R = imm 12707 * remember the value we stored into this reg 12708 */ 12709 /* clear any state __mark_reg_known doesn't set */ 12710 mark_reg_unknown(env, regs, insn->dst_reg); 12711 regs[insn->dst_reg].type = SCALAR_VALUE; 12712 if (BPF_CLASS(insn->code) == BPF_ALU64) { 12713 __mark_reg_known(regs + insn->dst_reg, 12714 insn->imm); 12715 } else { 12716 __mark_reg_known(regs + insn->dst_reg, 12717 (u32)insn->imm); 12718 } 12719 } 12720 12721 } else if (opcode > BPF_END) { 12722 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 12723 return -EINVAL; 12724 12725 } else { /* all other ALU ops: and, sub, xor, add, ... */ 12726 12727 if (BPF_SRC(insn->code) == BPF_X) { 12728 if (insn->imm != 0 || insn->off != 0) { 12729 verbose(env, "BPF_ALU uses reserved fields\n"); 12730 return -EINVAL; 12731 } 12732 /* check src1 operand */ 12733 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12734 if (err) 12735 return err; 12736 } else { 12737 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 12738 verbose(env, "BPF_ALU uses reserved fields\n"); 12739 return -EINVAL; 12740 } 12741 } 12742 12743 /* check src2 operand */ 12744 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 12745 if (err) 12746 return err; 12747 12748 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 12749 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 12750 verbose(env, "div by zero\n"); 12751 return -EINVAL; 12752 } 12753 12754 if ((opcode == BPF_LSH || opcode == BPF_RSH || 12755 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 12756 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 12757 12758 if (insn->imm < 0 || insn->imm >= size) { 12759 verbose(env, "invalid shift %d\n", insn->imm); 12760 return -EINVAL; 12761 } 12762 } 12763 12764 /* check dest operand */ 12765 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 12766 if (err) 12767 return err; 12768 12769 return adjust_reg_min_max_vals(env, insn); 12770 } 12771 12772 return 0; 12773 } 12774 12775 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 12776 struct bpf_reg_state *dst_reg, 12777 enum bpf_reg_type type, 12778 bool range_right_open) 12779 { 12780 struct bpf_func_state *state; 12781 struct bpf_reg_state *reg; 12782 int new_range; 12783 12784 if (dst_reg->off < 0 || 12785 (dst_reg->off == 0 && range_right_open)) 12786 /* This doesn't give us any range */ 12787 return; 12788 12789 if (dst_reg->umax_value > MAX_PACKET_OFF || 12790 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 12791 /* Risk of overflow. For instance, ptr + (1<<63) may be less 12792 * than pkt_end, but that's because it's also less than pkt. 12793 */ 12794 return; 12795 12796 new_range = dst_reg->off; 12797 if (range_right_open) 12798 new_range++; 12799 12800 /* Examples for register markings: 12801 * 12802 * pkt_data in dst register: 12803 * 12804 * r2 = r3; 12805 * r2 += 8; 12806 * if (r2 > pkt_end) goto <handle exception> 12807 * <access okay> 12808 * 12809 * r2 = r3; 12810 * r2 += 8; 12811 * if (r2 < pkt_end) goto <access okay> 12812 * <handle exception> 12813 * 12814 * Where: 12815 * r2 == dst_reg, pkt_end == src_reg 12816 * r2=pkt(id=n,off=8,r=0) 12817 * r3=pkt(id=n,off=0,r=0) 12818 * 12819 * pkt_data in src register: 12820 * 12821 * r2 = r3; 12822 * r2 += 8; 12823 * if (pkt_end >= r2) goto <access okay> 12824 * <handle exception> 12825 * 12826 * r2 = r3; 12827 * r2 += 8; 12828 * if (pkt_end <= r2) goto <handle exception> 12829 * <access okay> 12830 * 12831 * Where: 12832 * pkt_end == dst_reg, r2 == src_reg 12833 * r2=pkt(id=n,off=8,r=0) 12834 * r3=pkt(id=n,off=0,r=0) 12835 * 12836 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 12837 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 12838 * and [r3, r3 + 8-1) respectively is safe to access depending on 12839 * the check. 12840 */ 12841 12842 /* If our ids match, then we must have the same max_value. And we 12843 * don't care about the other reg's fixed offset, since if it's too big 12844 * the range won't allow anything. 12845 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 12846 */ 12847 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 12848 if (reg->type == type && reg->id == dst_reg->id) 12849 /* keep the maximum range already checked */ 12850 reg->range = max(reg->range, new_range); 12851 })); 12852 } 12853 12854 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 12855 { 12856 struct tnum subreg = tnum_subreg(reg->var_off); 12857 s32 sval = (s32)val; 12858 12859 switch (opcode) { 12860 case BPF_JEQ: 12861 if (tnum_is_const(subreg)) 12862 return !!tnum_equals_const(subreg, val); 12863 else if (val < reg->u32_min_value || val > reg->u32_max_value) 12864 return 0; 12865 break; 12866 case BPF_JNE: 12867 if (tnum_is_const(subreg)) 12868 return !tnum_equals_const(subreg, val); 12869 else if (val < reg->u32_min_value || val > reg->u32_max_value) 12870 return 1; 12871 break; 12872 case BPF_JSET: 12873 if ((~subreg.mask & subreg.value) & val) 12874 return 1; 12875 if (!((subreg.mask | subreg.value) & val)) 12876 return 0; 12877 break; 12878 case BPF_JGT: 12879 if (reg->u32_min_value > val) 12880 return 1; 12881 else if (reg->u32_max_value <= val) 12882 return 0; 12883 break; 12884 case BPF_JSGT: 12885 if (reg->s32_min_value > sval) 12886 return 1; 12887 else if (reg->s32_max_value <= sval) 12888 return 0; 12889 break; 12890 case BPF_JLT: 12891 if (reg->u32_max_value < val) 12892 return 1; 12893 else if (reg->u32_min_value >= val) 12894 return 0; 12895 break; 12896 case BPF_JSLT: 12897 if (reg->s32_max_value < sval) 12898 return 1; 12899 else if (reg->s32_min_value >= sval) 12900 return 0; 12901 break; 12902 case BPF_JGE: 12903 if (reg->u32_min_value >= val) 12904 return 1; 12905 else if (reg->u32_max_value < val) 12906 return 0; 12907 break; 12908 case BPF_JSGE: 12909 if (reg->s32_min_value >= sval) 12910 return 1; 12911 else if (reg->s32_max_value < sval) 12912 return 0; 12913 break; 12914 case BPF_JLE: 12915 if (reg->u32_max_value <= val) 12916 return 1; 12917 else if (reg->u32_min_value > val) 12918 return 0; 12919 break; 12920 case BPF_JSLE: 12921 if (reg->s32_max_value <= sval) 12922 return 1; 12923 else if (reg->s32_min_value > sval) 12924 return 0; 12925 break; 12926 } 12927 12928 return -1; 12929 } 12930 12931 12932 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 12933 { 12934 s64 sval = (s64)val; 12935 12936 switch (opcode) { 12937 case BPF_JEQ: 12938 if (tnum_is_const(reg->var_off)) 12939 return !!tnum_equals_const(reg->var_off, val); 12940 else if (val < reg->umin_value || val > reg->umax_value) 12941 return 0; 12942 break; 12943 case BPF_JNE: 12944 if (tnum_is_const(reg->var_off)) 12945 return !tnum_equals_const(reg->var_off, val); 12946 else if (val < reg->umin_value || val > reg->umax_value) 12947 return 1; 12948 break; 12949 case BPF_JSET: 12950 if ((~reg->var_off.mask & reg->var_off.value) & val) 12951 return 1; 12952 if (!((reg->var_off.mask | reg->var_off.value) & val)) 12953 return 0; 12954 break; 12955 case BPF_JGT: 12956 if (reg->umin_value > val) 12957 return 1; 12958 else if (reg->umax_value <= val) 12959 return 0; 12960 break; 12961 case BPF_JSGT: 12962 if (reg->smin_value > sval) 12963 return 1; 12964 else if (reg->smax_value <= sval) 12965 return 0; 12966 break; 12967 case BPF_JLT: 12968 if (reg->umax_value < val) 12969 return 1; 12970 else if (reg->umin_value >= val) 12971 return 0; 12972 break; 12973 case BPF_JSLT: 12974 if (reg->smax_value < sval) 12975 return 1; 12976 else if (reg->smin_value >= sval) 12977 return 0; 12978 break; 12979 case BPF_JGE: 12980 if (reg->umin_value >= val) 12981 return 1; 12982 else if (reg->umax_value < val) 12983 return 0; 12984 break; 12985 case BPF_JSGE: 12986 if (reg->smin_value >= sval) 12987 return 1; 12988 else if (reg->smax_value < sval) 12989 return 0; 12990 break; 12991 case BPF_JLE: 12992 if (reg->umax_value <= val) 12993 return 1; 12994 else if (reg->umin_value > val) 12995 return 0; 12996 break; 12997 case BPF_JSLE: 12998 if (reg->smax_value <= sval) 12999 return 1; 13000 else if (reg->smin_value > sval) 13001 return 0; 13002 break; 13003 } 13004 13005 return -1; 13006 } 13007 13008 /* compute branch direction of the expression "if (reg opcode val) goto target;" 13009 * and return: 13010 * 1 - branch will be taken and "goto target" will be executed 13011 * 0 - branch will not be taken and fall-through to next insn 13012 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 13013 * range [0,10] 13014 */ 13015 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 13016 bool is_jmp32) 13017 { 13018 if (__is_pointer_value(false, reg)) { 13019 if (!reg_type_not_null(reg->type)) 13020 return -1; 13021 13022 /* If pointer is valid tests against zero will fail so we can 13023 * use this to direct branch taken. 13024 */ 13025 if (val != 0) 13026 return -1; 13027 13028 switch (opcode) { 13029 case BPF_JEQ: 13030 return 0; 13031 case BPF_JNE: 13032 return 1; 13033 default: 13034 return -1; 13035 } 13036 } 13037 13038 if (is_jmp32) 13039 return is_branch32_taken(reg, val, opcode); 13040 return is_branch64_taken(reg, val, opcode); 13041 } 13042 13043 static int flip_opcode(u32 opcode) 13044 { 13045 /* How can we transform "a <op> b" into "b <op> a"? */ 13046 static const u8 opcode_flip[16] = { 13047 /* these stay the same */ 13048 [BPF_JEQ >> 4] = BPF_JEQ, 13049 [BPF_JNE >> 4] = BPF_JNE, 13050 [BPF_JSET >> 4] = BPF_JSET, 13051 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 13052 [BPF_JGE >> 4] = BPF_JLE, 13053 [BPF_JGT >> 4] = BPF_JLT, 13054 [BPF_JLE >> 4] = BPF_JGE, 13055 [BPF_JLT >> 4] = BPF_JGT, 13056 [BPF_JSGE >> 4] = BPF_JSLE, 13057 [BPF_JSGT >> 4] = BPF_JSLT, 13058 [BPF_JSLE >> 4] = BPF_JSGE, 13059 [BPF_JSLT >> 4] = BPF_JSGT 13060 }; 13061 return opcode_flip[opcode >> 4]; 13062 } 13063 13064 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 13065 struct bpf_reg_state *src_reg, 13066 u8 opcode) 13067 { 13068 struct bpf_reg_state *pkt; 13069 13070 if (src_reg->type == PTR_TO_PACKET_END) { 13071 pkt = dst_reg; 13072 } else if (dst_reg->type == PTR_TO_PACKET_END) { 13073 pkt = src_reg; 13074 opcode = flip_opcode(opcode); 13075 } else { 13076 return -1; 13077 } 13078 13079 if (pkt->range >= 0) 13080 return -1; 13081 13082 switch (opcode) { 13083 case BPF_JLE: 13084 /* pkt <= pkt_end */ 13085 fallthrough; 13086 case BPF_JGT: 13087 /* pkt > pkt_end */ 13088 if (pkt->range == BEYOND_PKT_END) 13089 /* pkt has at last one extra byte beyond pkt_end */ 13090 return opcode == BPF_JGT; 13091 break; 13092 case BPF_JLT: 13093 /* pkt < pkt_end */ 13094 fallthrough; 13095 case BPF_JGE: 13096 /* pkt >= pkt_end */ 13097 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 13098 return opcode == BPF_JGE; 13099 break; 13100 } 13101 return -1; 13102 } 13103 13104 /* Adjusts the register min/max values in the case that the dst_reg is the 13105 * variable register that we are working on, and src_reg is a constant or we're 13106 * simply doing a BPF_K check. 13107 * In JEQ/JNE cases we also adjust the var_off values. 13108 */ 13109 static void reg_set_min_max(struct bpf_reg_state *true_reg, 13110 struct bpf_reg_state *false_reg, 13111 u64 val, u32 val32, 13112 u8 opcode, bool is_jmp32) 13113 { 13114 struct tnum false_32off = tnum_subreg(false_reg->var_off); 13115 struct tnum false_64off = false_reg->var_off; 13116 struct tnum true_32off = tnum_subreg(true_reg->var_off); 13117 struct tnum true_64off = true_reg->var_off; 13118 s64 sval = (s64)val; 13119 s32 sval32 = (s32)val32; 13120 13121 /* If the dst_reg is a pointer, we can't learn anything about its 13122 * variable offset from the compare (unless src_reg were a pointer into 13123 * the same object, but we don't bother with that. 13124 * Since false_reg and true_reg have the same type by construction, we 13125 * only need to check one of them for pointerness. 13126 */ 13127 if (__is_pointer_value(false, false_reg)) 13128 return; 13129 13130 switch (opcode) { 13131 /* JEQ/JNE comparison doesn't change the register equivalence. 13132 * 13133 * r1 = r2; 13134 * if (r1 == 42) goto label; 13135 * ... 13136 * label: // here both r1 and r2 are known to be 42. 13137 * 13138 * Hence when marking register as known preserve it's ID. 13139 */ 13140 case BPF_JEQ: 13141 if (is_jmp32) { 13142 __mark_reg32_known(true_reg, val32); 13143 true_32off = tnum_subreg(true_reg->var_off); 13144 } else { 13145 ___mark_reg_known(true_reg, val); 13146 true_64off = true_reg->var_off; 13147 } 13148 break; 13149 case BPF_JNE: 13150 if (is_jmp32) { 13151 __mark_reg32_known(false_reg, val32); 13152 false_32off = tnum_subreg(false_reg->var_off); 13153 } else { 13154 ___mark_reg_known(false_reg, val); 13155 false_64off = false_reg->var_off; 13156 } 13157 break; 13158 case BPF_JSET: 13159 if (is_jmp32) { 13160 false_32off = tnum_and(false_32off, tnum_const(~val32)); 13161 if (is_power_of_2(val32)) 13162 true_32off = tnum_or(true_32off, 13163 tnum_const(val32)); 13164 } else { 13165 false_64off = tnum_and(false_64off, tnum_const(~val)); 13166 if (is_power_of_2(val)) 13167 true_64off = tnum_or(true_64off, 13168 tnum_const(val)); 13169 } 13170 break; 13171 case BPF_JGE: 13172 case BPF_JGT: 13173 { 13174 if (is_jmp32) { 13175 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 13176 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 13177 13178 false_reg->u32_max_value = min(false_reg->u32_max_value, 13179 false_umax); 13180 true_reg->u32_min_value = max(true_reg->u32_min_value, 13181 true_umin); 13182 } else { 13183 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 13184 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 13185 13186 false_reg->umax_value = min(false_reg->umax_value, false_umax); 13187 true_reg->umin_value = max(true_reg->umin_value, true_umin); 13188 } 13189 break; 13190 } 13191 case BPF_JSGE: 13192 case BPF_JSGT: 13193 { 13194 if (is_jmp32) { 13195 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 13196 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 13197 13198 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 13199 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 13200 } else { 13201 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 13202 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 13203 13204 false_reg->smax_value = min(false_reg->smax_value, false_smax); 13205 true_reg->smin_value = max(true_reg->smin_value, true_smin); 13206 } 13207 break; 13208 } 13209 case BPF_JLE: 13210 case BPF_JLT: 13211 { 13212 if (is_jmp32) { 13213 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 13214 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 13215 13216 false_reg->u32_min_value = max(false_reg->u32_min_value, 13217 false_umin); 13218 true_reg->u32_max_value = min(true_reg->u32_max_value, 13219 true_umax); 13220 } else { 13221 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 13222 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 13223 13224 false_reg->umin_value = max(false_reg->umin_value, false_umin); 13225 true_reg->umax_value = min(true_reg->umax_value, true_umax); 13226 } 13227 break; 13228 } 13229 case BPF_JSLE: 13230 case BPF_JSLT: 13231 { 13232 if (is_jmp32) { 13233 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 13234 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 13235 13236 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 13237 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 13238 } else { 13239 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 13240 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 13241 13242 false_reg->smin_value = max(false_reg->smin_value, false_smin); 13243 true_reg->smax_value = min(true_reg->smax_value, true_smax); 13244 } 13245 break; 13246 } 13247 default: 13248 return; 13249 } 13250 13251 if (is_jmp32) { 13252 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 13253 tnum_subreg(false_32off)); 13254 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 13255 tnum_subreg(true_32off)); 13256 __reg_combine_32_into_64(false_reg); 13257 __reg_combine_32_into_64(true_reg); 13258 } else { 13259 false_reg->var_off = false_64off; 13260 true_reg->var_off = true_64off; 13261 __reg_combine_64_into_32(false_reg); 13262 __reg_combine_64_into_32(true_reg); 13263 } 13264 } 13265 13266 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 13267 * the variable reg. 13268 */ 13269 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 13270 struct bpf_reg_state *false_reg, 13271 u64 val, u32 val32, 13272 u8 opcode, bool is_jmp32) 13273 { 13274 opcode = flip_opcode(opcode); 13275 /* This uses zero as "not present in table"; luckily the zero opcode, 13276 * BPF_JA, can't get here. 13277 */ 13278 if (opcode) 13279 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 13280 } 13281 13282 /* Regs are known to be equal, so intersect their min/max/var_off */ 13283 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 13284 struct bpf_reg_state *dst_reg) 13285 { 13286 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 13287 dst_reg->umin_value); 13288 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 13289 dst_reg->umax_value); 13290 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 13291 dst_reg->smin_value); 13292 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 13293 dst_reg->smax_value); 13294 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 13295 dst_reg->var_off); 13296 reg_bounds_sync(src_reg); 13297 reg_bounds_sync(dst_reg); 13298 } 13299 13300 static void reg_combine_min_max(struct bpf_reg_state *true_src, 13301 struct bpf_reg_state *true_dst, 13302 struct bpf_reg_state *false_src, 13303 struct bpf_reg_state *false_dst, 13304 u8 opcode) 13305 { 13306 switch (opcode) { 13307 case BPF_JEQ: 13308 __reg_combine_min_max(true_src, true_dst); 13309 break; 13310 case BPF_JNE: 13311 __reg_combine_min_max(false_src, false_dst); 13312 break; 13313 } 13314 } 13315 13316 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 13317 struct bpf_reg_state *reg, u32 id, 13318 bool is_null) 13319 { 13320 if (type_may_be_null(reg->type) && reg->id == id && 13321 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 13322 /* Old offset (both fixed and variable parts) should have been 13323 * known-zero, because we don't allow pointer arithmetic on 13324 * pointers that might be NULL. If we see this happening, don't 13325 * convert the register. 13326 * 13327 * But in some cases, some helpers that return local kptrs 13328 * advance offset for the returned pointer. In those cases, it 13329 * is fine to expect to see reg->off. 13330 */ 13331 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 13332 return; 13333 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 13334 WARN_ON_ONCE(reg->off)) 13335 return; 13336 13337 if (is_null) { 13338 reg->type = SCALAR_VALUE; 13339 /* We don't need id and ref_obj_id from this point 13340 * onwards anymore, thus we should better reset it, 13341 * so that state pruning has chances to take effect. 13342 */ 13343 reg->id = 0; 13344 reg->ref_obj_id = 0; 13345 13346 return; 13347 } 13348 13349 mark_ptr_not_null_reg(reg); 13350 13351 if (!reg_may_point_to_spin_lock(reg)) { 13352 /* For not-NULL ptr, reg->ref_obj_id will be reset 13353 * in release_reference(). 13354 * 13355 * reg->id is still used by spin_lock ptr. Other 13356 * than spin_lock ptr type, reg->id can be reset. 13357 */ 13358 reg->id = 0; 13359 } 13360 } 13361 } 13362 13363 /* The logic is similar to find_good_pkt_pointers(), both could eventually 13364 * be folded together at some point. 13365 */ 13366 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 13367 bool is_null) 13368 { 13369 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13370 struct bpf_reg_state *regs = state->regs, *reg; 13371 u32 ref_obj_id = regs[regno].ref_obj_id; 13372 u32 id = regs[regno].id; 13373 13374 if (ref_obj_id && ref_obj_id == id && is_null) 13375 /* regs[regno] is in the " == NULL" branch. 13376 * No one could have freed the reference state before 13377 * doing the NULL check. 13378 */ 13379 WARN_ON_ONCE(release_reference_state(state, id)); 13380 13381 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13382 mark_ptr_or_null_reg(state, reg, id, is_null); 13383 })); 13384 } 13385 13386 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 13387 struct bpf_reg_state *dst_reg, 13388 struct bpf_reg_state *src_reg, 13389 struct bpf_verifier_state *this_branch, 13390 struct bpf_verifier_state *other_branch) 13391 { 13392 if (BPF_SRC(insn->code) != BPF_X) 13393 return false; 13394 13395 /* Pointers are always 64-bit. */ 13396 if (BPF_CLASS(insn->code) == BPF_JMP32) 13397 return false; 13398 13399 switch (BPF_OP(insn->code)) { 13400 case BPF_JGT: 13401 if ((dst_reg->type == PTR_TO_PACKET && 13402 src_reg->type == PTR_TO_PACKET_END) || 13403 (dst_reg->type == PTR_TO_PACKET_META && 13404 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13405 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 13406 find_good_pkt_pointers(this_branch, dst_reg, 13407 dst_reg->type, false); 13408 mark_pkt_end(other_branch, insn->dst_reg, true); 13409 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13410 src_reg->type == PTR_TO_PACKET) || 13411 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13412 src_reg->type == PTR_TO_PACKET_META)) { 13413 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 13414 find_good_pkt_pointers(other_branch, src_reg, 13415 src_reg->type, true); 13416 mark_pkt_end(this_branch, insn->src_reg, false); 13417 } else { 13418 return false; 13419 } 13420 break; 13421 case BPF_JLT: 13422 if ((dst_reg->type == PTR_TO_PACKET && 13423 src_reg->type == PTR_TO_PACKET_END) || 13424 (dst_reg->type == PTR_TO_PACKET_META && 13425 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13426 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 13427 find_good_pkt_pointers(other_branch, dst_reg, 13428 dst_reg->type, true); 13429 mark_pkt_end(this_branch, insn->dst_reg, false); 13430 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13431 src_reg->type == PTR_TO_PACKET) || 13432 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13433 src_reg->type == PTR_TO_PACKET_META)) { 13434 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 13435 find_good_pkt_pointers(this_branch, src_reg, 13436 src_reg->type, false); 13437 mark_pkt_end(other_branch, insn->src_reg, true); 13438 } else { 13439 return false; 13440 } 13441 break; 13442 case BPF_JGE: 13443 if ((dst_reg->type == PTR_TO_PACKET && 13444 src_reg->type == PTR_TO_PACKET_END) || 13445 (dst_reg->type == PTR_TO_PACKET_META && 13446 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13447 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 13448 find_good_pkt_pointers(this_branch, dst_reg, 13449 dst_reg->type, true); 13450 mark_pkt_end(other_branch, insn->dst_reg, false); 13451 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13452 src_reg->type == PTR_TO_PACKET) || 13453 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13454 src_reg->type == PTR_TO_PACKET_META)) { 13455 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 13456 find_good_pkt_pointers(other_branch, src_reg, 13457 src_reg->type, false); 13458 mark_pkt_end(this_branch, insn->src_reg, true); 13459 } else { 13460 return false; 13461 } 13462 break; 13463 case BPF_JLE: 13464 if ((dst_reg->type == PTR_TO_PACKET && 13465 src_reg->type == PTR_TO_PACKET_END) || 13466 (dst_reg->type == PTR_TO_PACKET_META && 13467 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13468 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 13469 find_good_pkt_pointers(other_branch, dst_reg, 13470 dst_reg->type, false); 13471 mark_pkt_end(this_branch, insn->dst_reg, true); 13472 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13473 src_reg->type == PTR_TO_PACKET) || 13474 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13475 src_reg->type == PTR_TO_PACKET_META)) { 13476 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 13477 find_good_pkt_pointers(this_branch, src_reg, 13478 src_reg->type, true); 13479 mark_pkt_end(other_branch, insn->src_reg, false); 13480 } else { 13481 return false; 13482 } 13483 break; 13484 default: 13485 return false; 13486 } 13487 13488 return true; 13489 } 13490 13491 static void find_equal_scalars(struct bpf_verifier_state *vstate, 13492 struct bpf_reg_state *known_reg) 13493 { 13494 struct bpf_func_state *state; 13495 struct bpf_reg_state *reg; 13496 13497 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13498 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 13499 copy_register_state(reg, known_reg); 13500 })); 13501 } 13502 13503 static int check_cond_jmp_op(struct bpf_verifier_env *env, 13504 struct bpf_insn *insn, int *insn_idx) 13505 { 13506 struct bpf_verifier_state *this_branch = env->cur_state; 13507 struct bpf_verifier_state *other_branch; 13508 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 13509 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 13510 struct bpf_reg_state *eq_branch_regs; 13511 u8 opcode = BPF_OP(insn->code); 13512 bool is_jmp32; 13513 int pred = -1; 13514 int err; 13515 13516 /* Only conditional jumps are expected to reach here. */ 13517 if (opcode == BPF_JA || opcode > BPF_JSLE) { 13518 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 13519 return -EINVAL; 13520 } 13521 13522 if (BPF_SRC(insn->code) == BPF_X) { 13523 if (insn->imm != 0) { 13524 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 13525 return -EINVAL; 13526 } 13527 13528 /* check src1 operand */ 13529 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13530 if (err) 13531 return err; 13532 13533 if (is_pointer_value(env, insn->src_reg)) { 13534 verbose(env, "R%d pointer comparison prohibited\n", 13535 insn->src_reg); 13536 return -EACCES; 13537 } 13538 src_reg = ®s[insn->src_reg]; 13539 } else { 13540 if (insn->src_reg != BPF_REG_0) { 13541 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 13542 return -EINVAL; 13543 } 13544 } 13545 13546 /* check src2 operand */ 13547 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13548 if (err) 13549 return err; 13550 13551 dst_reg = ®s[insn->dst_reg]; 13552 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 13553 13554 if (BPF_SRC(insn->code) == BPF_K) { 13555 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 13556 } else if (src_reg->type == SCALAR_VALUE && 13557 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 13558 pred = is_branch_taken(dst_reg, 13559 tnum_subreg(src_reg->var_off).value, 13560 opcode, 13561 is_jmp32); 13562 } else if (src_reg->type == SCALAR_VALUE && 13563 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 13564 pred = is_branch_taken(dst_reg, 13565 src_reg->var_off.value, 13566 opcode, 13567 is_jmp32); 13568 } else if (dst_reg->type == SCALAR_VALUE && 13569 is_jmp32 && tnum_is_const(tnum_subreg(dst_reg->var_off))) { 13570 pred = is_branch_taken(src_reg, 13571 tnum_subreg(dst_reg->var_off).value, 13572 flip_opcode(opcode), 13573 is_jmp32); 13574 } else if (dst_reg->type == SCALAR_VALUE && 13575 !is_jmp32 && tnum_is_const(dst_reg->var_off)) { 13576 pred = is_branch_taken(src_reg, 13577 dst_reg->var_off.value, 13578 flip_opcode(opcode), 13579 is_jmp32); 13580 } else if (reg_is_pkt_pointer_any(dst_reg) && 13581 reg_is_pkt_pointer_any(src_reg) && 13582 !is_jmp32) { 13583 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 13584 } 13585 13586 if (pred >= 0) { 13587 /* If we get here with a dst_reg pointer type it is because 13588 * above is_branch_taken() special cased the 0 comparison. 13589 */ 13590 if (!__is_pointer_value(false, dst_reg)) 13591 err = mark_chain_precision(env, insn->dst_reg); 13592 if (BPF_SRC(insn->code) == BPF_X && !err && 13593 !__is_pointer_value(false, src_reg)) 13594 err = mark_chain_precision(env, insn->src_reg); 13595 if (err) 13596 return err; 13597 } 13598 13599 if (pred == 1) { 13600 /* Only follow the goto, ignore fall-through. If needed, push 13601 * the fall-through branch for simulation under speculative 13602 * execution. 13603 */ 13604 if (!env->bypass_spec_v1 && 13605 !sanitize_speculative_path(env, insn, *insn_idx + 1, 13606 *insn_idx)) 13607 return -EFAULT; 13608 *insn_idx += insn->off; 13609 return 0; 13610 } else if (pred == 0) { 13611 /* Only follow the fall-through branch, since that's where the 13612 * program will go. If needed, push the goto branch for 13613 * simulation under speculative execution. 13614 */ 13615 if (!env->bypass_spec_v1 && 13616 !sanitize_speculative_path(env, insn, 13617 *insn_idx + insn->off + 1, 13618 *insn_idx)) 13619 return -EFAULT; 13620 return 0; 13621 } 13622 13623 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 13624 false); 13625 if (!other_branch) 13626 return -EFAULT; 13627 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 13628 13629 /* detect if we are comparing against a constant value so we can adjust 13630 * our min/max values for our dst register. 13631 * this is only legit if both are scalars (or pointers to the same 13632 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 13633 * because otherwise the different base pointers mean the offsets aren't 13634 * comparable. 13635 */ 13636 if (BPF_SRC(insn->code) == BPF_X) { 13637 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 13638 13639 if (dst_reg->type == SCALAR_VALUE && 13640 src_reg->type == SCALAR_VALUE) { 13641 if (tnum_is_const(src_reg->var_off) || 13642 (is_jmp32 && 13643 tnum_is_const(tnum_subreg(src_reg->var_off)))) 13644 reg_set_min_max(&other_branch_regs[insn->dst_reg], 13645 dst_reg, 13646 src_reg->var_off.value, 13647 tnum_subreg(src_reg->var_off).value, 13648 opcode, is_jmp32); 13649 else if (tnum_is_const(dst_reg->var_off) || 13650 (is_jmp32 && 13651 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 13652 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 13653 src_reg, 13654 dst_reg->var_off.value, 13655 tnum_subreg(dst_reg->var_off).value, 13656 opcode, is_jmp32); 13657 else if (!is_jmp32 && 13658 (opcode == BPF_JEQ || opcode == BPF_JNE)) 13659 /* Comparing for equality, we can combine knowledge */ 13660 reg_combine_min_max(&other_branch_regs[insn->src_reg], 13661 &other_branch_regs[insn->dst_reg], 13662 src_reg, dst_reg, opcode); 13663 if (src_reg->id && 13664 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 13665 find_equal_scalars(this_branch, src_reg); 13666 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 13667 } 13668 13669 } 13670 } else if (dst_reg->type == SCALAR_VALUE) { 13671 reg_set_min_max(&other_branch_regs[insn->dst_reg], 13672 dst_reg, insn->imm, (u32)insn->imm, 13673 opcode, is_jmp32); 13674 } 13675 13676 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 13677 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 13678 find_equal_scalars(this_branch, dst_reg); 13679 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 13680 } 13681 13682 /* if one pointer register is compared to another pointer 13683 * register check if PTR_MAYBE_NULL could be lifted. 13684 * E.g. register A - maybe null 13685 * register B - not null 13686 * for JNE A, B, ... - A is not null in the false branch; 13687 * for JEQ A, B, ... - A is not null in the true branch. 13688 * 13689 * Since PTR_TO_BTF_ID points to a kernel struct that does 13690 * not need to be null checked by the BPF program, i.e., 13691 * could be null even without PTR_MAYBE_NULL marking, so 13692 * only propagate nullness when neither reg is that type. 13693 */ 13694 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 13695 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 13696 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 13697 base_type(src_reg->type) != PTR_TO_BTF_ID && 13698 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 13699 eq_branch_regs = NULL; 13700 switch (opcode) { 13701 case BPF_JEQ: 13702 eq_branch_regs = other_branch_regs; 13703 break; 13704 case BPF_JNE: 13705 eq_branch_regs = regs; 13706 break; 13707 default: 13708 /* do nothing */ 13709 break; 13710 } 13711 if (eq_branch_regs) { 13712 if (type_may_be_null(src_reg->type)) 13713 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 13714 else 13715 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 13716 } 13717 } 13718 13719 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 13720 * NOTE: these optimizations below are related with pointer comparison 13721 * which will never be JMP32. 13722 */ 13723 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 13724 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 13725 type_may_be_null(dst_reg->type)) { 13726 /* Mark all identical registers in each branch as either 13727 * safe or unknown depending R == 0 or R != 0 conditional. 13728 */ 13729 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 13730 opcode == BPF_JNE); 13731 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 13732 opcode == BPF_JEQ); 13733 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 13734 this_branch, other_branch) && 13735 is_pointer_value(env, insn->dst_reg)) { 13736 verbose(env, "R%d pointer comparison prohibited\n", 13737 insn->dst_reg); 13738 return -EACCES; 13739 } 13740 if (env->log.level & BPF_LOG_LEVEL) 13741 print_insn_state(env, this_branch->frame[this_branch->curframe]); 13742 return 0; 13743 } 13744 13745 /* verify BPF_LD_IMM64 instruction */ 13746 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 13747 { 13748 struct bpf_insn_aux_data *aux = cur_aux(env); 13749 struct bpf_reg_state *regs = cur_regs(env); 13750 struct bpf_reg_state *dst_reg; 13751 struct bpf_map *map; 13752 int err; 13753 13754 if (BPF_SIZE(insn->code) != BPF_DW) { 13755 verbose(env, "invalid BPF_LD_IMM insn\n"); 13756 return -EINVAL; 13757 } 13758 if (insn->off != 0) { 13759 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 13760 return -EINVAL; 13761 } 13762 13763 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13764 if (err) 13765 return err; 13766 13767 dst_reg = ®s[insn->dst_reg]; 13768 if (insn->src_reg == 0) { 13769 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 13770 13771 dst_reg->type = SCALAR_VALUE; 13772 __mark_reg_known(®s[insn->dst_reg], imm); 13773 return 0; 13774 } 13775 13776 /* All special src_reg cases are listed below. From this point onwards 13777 * we either succeed and assign a corresponding dst_reg->type after 13778 * zeroing the offset, or fail and reject the program. 13779 */ 13780 mark_reg_known_zero(env, regs, insn->dst_reg); 13781 13782 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 13783 dst_reg->type = aux->btf_var.reg_type; 13784 switch (base_type(dst_reg->type)) { 13785 case PTR_TO_MEM: 13786 dst_reg->mem_size = aux->btf_var.mem_size; 13787 break; 13788 case PTR_TO_BTF_ID: 13789 dst_reg->btf = aux->btf_var.btf; 13790 dst_reg->btf_id = aux->btf_var.btf_id; 13791 break; 13792 default: 13793 verbose(env, "bpf verifier is misconfigured\n"); 13794 return -EFAULT; 13795 } 13796 return 0; 13797 } 13798 13799 if (insn->src_reg == BPF_PSEUDO_FUNC) { 13800 struct bpf_prog_aux *aux = env->prog->aux; 13801 u32 subprogno = find_subprog(env, 13802 env->insn_idx + insn->imm + 1); 13803 13804 if (!aux->func_info) { 13805 verbose(env, "missing btf func_info\n"); 13806 return -EINVAL; 13807 } 13808 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 13809 verbose(env, "callback function not static\n"); 13810 return -EINVAL; 13811 } 13812 13813 dst_reg->type = PTR_TO_FUNC; 13814 dst_reg->subprogno = subprogno; 13815 return 0; 13816 } 13817 13818 map = env->used_maps[aux->map_index]; 13819 dst_reg->map_ptr = map; 13820 13821 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 13822 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 13823 dst_reg->type = PTR_TO_MAP_VALUE; 13824 dst_reg->off = aux->map_off; 13825 WARN_ON_ONCE(map->max_entries != 1); 13826 /* We want reg->id to be same (0) as map_value is not distinct */ 13827 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 13828 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 13829 dst_reg->type = CONST_PTR_TO_MAP; 13830 } else { 13831 verbose(env, "bpf verifier is misconfigured\n"); 13832 return -EINVAL; 13833 } 13834 13835 return 0; 13836 } 13837 13838 static bool may_access_skb(enum bpf_prog_type type) 13839 { 13840 switch (type) { 13841 case BPF_PROG_TYPE_SOCKET_FILTER: 13842 case BPF_PROG_TYPE_SCHED_CLS: 13843 case BPF_PROG_TYPE_SCHED_ACT: 13844 return true; 13845 default: 13846 return false; 13847 } 13848 } 13849 13850 /* verify safety of LD_ABS|LD_IND instructions: 13851 * - they can only appear in the programs where ctx == skb 13852 * - since they are wrappers of function calls, they scratch R1-R5 registers, 13853 * preserve R6-R9, and store return value into R0 13854 * 13855 * Implicit input: 13856 * ctx == skb == R6 == CTX 13857 * 13858 * Explicit input: 13859 * SRC == any register 13860 * IMM == 32-bit immediate 13861 * 13862 * Output: 13863 * R0 - 8/16/32-bit skb data converted to cpu endianness 13864 */ 13865 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 13866 { 13867 struct bpf_reg_state *regs = cur_regs(env); 13868 static const int ctx_reg = BPF_REG_6; 13869 u8 mode = BPF_MODE(insn->code); 13870 int i, err; 13871 13872 if (!may_access_skb(resolve_prog_type(env->prog))) { 13873 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 13874 return -EINVAL; 13875 } 13876 13877 if (!env->ops->gen_ld_abs) { 13878 verbose(env, "bpf verifier is misconfigured\n"); 13879 return -EINVAL; 13880 } 13881 13882 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 13883 BPF_SIZE(insn->code) == BPF_DW || 13884 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 13885 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 13886 return -EINVAL; 13887 } 13888 13889 /* check whether implicit source operand (register R6) is readable */ 13890 err = check_reg_arg(env, ctx_reg, SRC_OP); 13891 if (err) 13892 return err; 13893 13894 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 13895 * gen_ld_abs() may terminate the program at runtime, leading to 13896 * reference leak. 13897 */ 13898 err = check_reference_leak(env); 13899 if (err) { 13900 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 13901 return err; 13902 } 13903 13904 if (env->cur_state->active_lock.ptr) { 13905 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 13906 return -EINVAL; 13907 } 13908 13909 if (env->cur_state->active_rcu_lock) { 13910 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 13911 return -EINVAL; 13912 } 13913 13914 if (regs[ctx_reg].type != PTR_TO_CTX) { 13915 verbose(env, 13916 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 13917 return -EINVAL; 13918 } 13919 13920 if (mode == BPF_IND) { 13921 /* check explicit source operand */ 13922 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13923 if (err) 13924 return err; 13925 } 13926 13927 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 13928 if (err < 0) 13929 return err; 13930 13931 /* reset caller saved regs to unreadable */ 13932 for (i = 0; i < CALLER_SAVED_REGS; i++) { 13933 mark_reg_not_init(env, regs, caller_saved[i]); 13934 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 13935 } 13936 13937 /* mark destination R0 register as readable, since it contains 13938 * the value fetched from the packet. 13939 * Already marked as written above. 13940 */ 13941 mark_reg_unknown(env, regs, BPF_REG_0); 13942 /* ld_abs load up to 32-bit skb data. */ 13943 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 13944 return 0; 13945 } 13946 13947 static int check_return_code(struct bpf_verifier_env *env) 13948 { 13949 struct tnum enforce_attach_type_range = tnum_unknown; 13950 const struct bpf_prog *prog = env->prog; 13951 struct bpf_reg_state *reg; 13952 struct tnum range = tnum_range(0, 1); 13953 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 13954 int err; 13955 struct bpf_func_state *frame = env->cur_state->frame[0]; 13956 const bool is_subprog = frame->subprogno; 13957 13958 /* LSM and struct_ops func-ptr's return type could be "void" */ 13959 if (!is_subprog) { 13960 switch (prog_type) { 13961 case BPF_PROG_TYPE_LSM: 13962 if (prog->expected_attach_type == BPF_LSM_CGROUP) 13963 /* See below, can be 0 or 0-1 depending on hook. */ 13964 break; 13965 fallthrough; 13966 case BPF_PROG_TYPE_STRUCT_OPS: 13967 if (!prog->aux->attach_func_proto->type) 13968 return 0; 13969 break; 13970 default: 13971 break; 13972 } 13973 } 13974 13975 /* eBPF calling convention is such that R0 is used 13976 * to return the value from eBPF program. 13977 * Make sure that it's readable at this time 13978 * of bpf_exit, which means that program wrote 13979 * something into it earlier 13980 */ 13981 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 13982 if (err) 13983 return err; 13984 13985 if (is_pointer_value(env, BPF_REG_0)) { 13986 verbose(env, "R0 leaks addr as return value\n"); 13987 return -EACCES; 13988 } 13989 13990 reg = cur_regs(env) + BPF_REG_0; 13991 13992 if (frame->in_async_callback_fn) { 13993 /* enforce return zero from async callbacks like timer */ 13994 if (reg->type != SCALAR_VALUE) { 13995 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 13996 reg_type_str(env, reg->type)); 13997 return -EINVAL; 13998 } 13999 14000 if (!tnum_in(tnum_const(0), reg->var_off)) { 14001 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 14002 return -EINVAL; 14003 } 14004 return 0; 14005 } 14006 14007 if (is_subprog) { 14008 if (reg->type != SCALAR_VALUE) { 14009 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 14010 reg_type_str(env, reg->type)); 14011 return -EINVAL; 14012 } 14013 return 0; 14014 } 14015 14016 switch (prog_type) { 14017 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 14018 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 14019 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 14020 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 14021 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 14022 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 14023 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 14024 range = tnum_range(1, 1); 14025 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 14026 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 14027 range = tnum_range(0, 3); 14028 break; 14029 case BPF_PROG_TYPE_CGROUP_SKB: 14030 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 14031 range = tnum_range(0, 3); 14032 enforce_attach_type_range = tnum_range(2, 3); 14033 } 14034 break; 14035 case BPF_PROG_TYPE_CGROUP_SOCK: 14036 case BPF_PROG_TYPE_SOCK_OPS: 14037 case BPF_PROG_TYPE_CGROUP_DEVICE: 14038 case BPF_PROG_TYPE_CGROUP_SYSCTL: 14039 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 14040 break; 14041 case BPF_PROG_TYPE_RAW_TRACEPOINT: 14042 if (!env->prog->aux->attach_btf_id) 14043 return 0; 14044 range = tnum_const(0); 14045 break; 14046 case BPF_PROG_TYPE_TRACING: 14047 switch (env->prog->expected_attach_type) { 14048 case BPF_TRACE_FENTRY: 14049 case BPF_TRACE_FEXIT: 14050 range = tnum_const(0); 14051 break; 14052 case BPF_TRACE_RAW_TP: 14053 case BPF_MODIFY_RETURN: 14054 return 0; 14055 case BPF_TRACE_ITER: 14056 break; 14057 default: 14058 return -ENOTSUPP; 14059 } 14060 break; 14061 case BPF_PROG_TYPE_SK_LOOKUP: 14062 range = tnum_range(SK_DROP, SK_PASS); 14063 break; 14064 14065 case BPF_PROG_TYPE_LSM: 14066 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 14067 /* Regular BPF_PROG_TYPE_LSM programs can return 14068 * any value. 14069 */ 14070 return 0; 14071 } 14072 if (!env->prog->aux->attach_func_proto->type) { 14073 /* Make sure programs that attach to void 14074 * hooks don't try to modify return value. 14075 */ 14076 range = tnum_range(1, 1); 14077 } 14078 break; 14079 14080 case BPF_PROG_TYPE_NETFILTER: 14081 range = tnum_range(NF_DROP, NF_ACCEPT); 14082 break; 14083 case BPF_PROG_TYPE_EXT: 14084 /* freplace program can return anything as its return value 14085 * depends on the to-be-replaced kernel func or bpf program. 14086 */ 14087 default: 14088 return 0; 14089 } 14090 14091 if (reg->type != SCALAR_VALUE) { 14092 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 14093 reg_type_str(env, reg->type)); 14094 return -EINVAL; 14095 } 14096 14097 if (!tnum_in(range, reg->var_off)) { 14098 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 14099 if (prog->expected_attach_type == BPF_LSM_CGROUP && 14100 prog_type == BPF_PROG_TYPE_LSM && 14101 !prog->aux->attach_func_proto->type) 14102 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 14103 return -EINVAL; 14104 } 14105 14106 if (!tnum_is_unknown(enforce_attach_type_range) && 14107 tnum_in(enforce_attach_type_range, reg->var_off)) 14108 env->prog->enforce_expected_attach_type = 1; 14109 return 0; 14110 } 14111 14112 /* non-recursive DFS pseudo code 14113 * 1 procedure DFS-iterative(G,v): 14114 * 2 label v as discovered 14115 * 3 let S be a stack 14116 * 4 S.push(v) 14117 * 5 while S is not empty 14118 * 6 t <- S.peek() 14119 * 7 if t is what we're looking for: 14120 * 8 return t 14121 * 9 for all edges e in G.adjacentEdges(t) do 14122 * 10 if edge e is already labelled 14123 * 11 continue with the next edge 14124 * 12 w <- G.adjacentVertex(t,e) 14125 * 13 if vertex w is not discovered and not explored 14126 * 14 label e as tree-edge 14127 * 15 label w as discovered 14128 * 16 S.push(w) 14129 * 17 continue at 5 14130 * 18 else if vertex w is discovered 14131 * 19 label e as back-edge 14132 * 20 else 14133 * 21 // vertex w is explored 14134 * 22 label e as forward- or cross-edge 14135 * 23 label t as explored 14136 * 24 S.pop() 14137 * 14138 * convention: 14139 * 0x10 - discovered 14140 * 0x11 - discovered and fall-through edge labelled 14141 * 0x12 - discovered and fall-through and branch edges labelled 14142 * 0x20 - explored 14143 */ 14144 14145 enum { 14146 DISCOVERED = 0x10, 14147 EXPLORED = 0x20, 14148 FALLTHROUGH = 1, 14149 BRANCH = 2, 14150 }; 14151 14152 static u32 state_htab_size(struct bpf_verifier_env *env) 14153 { 14154 return env->prog->len; 14155 } 14156 14157 static struct bpf_verifier_state_list **explored_state( 14158 struct bpf_verifier_env *env, 14159 int idx) 14160 { 14161 struct bpf_verifier_state *cur = env->cur_state; 14162 struct bpf_func_state *state = cur->frame[cur->curframe]; 14163 14164 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 14165 } 14166 14167 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 14168 { 14169 env->insn_aux_data[idx].prune_point = true; 14170 } 14171 14172 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 14173 { 14174 return env->insn_aux_data[insn_idx].prune_point; 14175 } 14176 14177 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 14178 { 14179 env->insn_aux_data[idx].force_checkpoint = true; 14180 } 14181 14182 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 14183 { 14184 return env->insn_aux_data[insn_idx].force_checkpoint; 14185 } 14186 14187 14188 enum { 14189 DONE_EXPLORING = 0, 14190 KEEP_EXPLORING = 1, 14191 }; 14192 14193 /* t, w, e - match pseudo-code above: 14194 * t - index of current instruction 14195 * w - next instruction 14196 * e - edge 14197 */ 14198 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 14199 bool loop_ok) 14200 { 14201 int *insn_stack = env->cfg.insn_stack; 14202 int *insn_state = env->cfg.insn_state; 14203 14204 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 14205 return DONE_EXPLORING; 14206 14207 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 14208 return DONE_EXPLORING; 14209 14210 if (w < 0 || w >= env->prog->len) { 14211 verbose_linfo(env, t, "%d: ", t); 14212 verbose(env, "jump out of range from insn %d to %d\n", t, w); 14213 return -EINVAL; 14214 } 14215 14216 if (e == BRANCH) { 14217 /* mark branch target for state pruning */ 14218 mark_prune_point(env, w); 14219 mark_jmp_point(env, w); 14220 } 14221 14222 if (insn_state[w] == 0) { 14223 /* tree-edge */ 14224 insn_state[t] = DISCOVERED | e; 14225 insn_state[w] = DISCOVERED; 14226 if (env->cfg.cur_stack >= env->prog->len) 14227 return -E2BIG; 14228 insn_stack[env->cfg.cur_stack++] = w; 14229 return KEEP_EXPLORING; 14230 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 14231 if (loop_ok && env->bpf_capable) 14232 return DONE_EXPLORING; 14233 verbose_linfo(env, t, "%d: ", t); 14234 verbose_linfo(env, w, "%d: ", w); 14235 verbose(env, "back-edge from insn %d to %d\n", t, w); 14236 return -EINVAL; 14237 } else if (insn_state[w] == EXPLORED) { 14238 /* forward- or cross-edge */ 14239 insn_state[t] = DISCOVERED | e; 14240 } else { 14241 verbose(env, "insn state internal bug\n"); 14242 return -EFAULT; 14243 } 14244 return DONE_EXPLORING; 14245 } 14246 14247 static int visit_func_call_insn(int t, struct bpf_insn *insns, 14248 struct bpf_verifier_env *env, 14249 bool visit_callee) 14250 { 14251 int ret; 14252 14253 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 14254 if (ret) 14255 return ret; 14256 14257 mark_prune_point(env, t + 1); 14258 /* when we exit from subprog, we need to record non-linear history */ 14259 mark_jmp_point(env, t + 1); 14260 14261 if (visit_callee) { 14262 mark_prune_point(env, t); 14263 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 14264 /* It's ok to allow recursion from CFG point of 14265 * view. __check_func_call() will do the actual 14266 * check. 14267 */ 14268 bpf_pseudo_func(insns + t)); 14269 } 14270 return ret; 14271 } 14272 14273 /* Visits the instruction at index t and returns one of the following: 14274 * < 0 - an error occurred 14275 * DONE_EXPLORING - the instruction was fully explored 14276 * KEEP_EXPLORING - there is still work to be done before it is fully explored 14277 */ 14278 static int visit_insn(int t, struct bpf_verifier_env *env) 14279 { 14280 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 14281 int ret; 14282 14283 if (bpf_pseudo_func(insn)) 14284 return visit_func_call_insn(t, insns, env, true); 14285 14286 /* All non-branch instructions have a single fall-through edge. */ 14287 if (BPF_CLASS(insn->code) != BPF_JMP && 14288 BPF_CLASS(insn->code) != BPF_JMP32) 14289 return push_insn(t, t + 1, FALLTHROUGH, env, false); 14290 14291 switch (BPF_OP(insn->code)) { 14292 case BPF_EXIT: 14293 return DONE_EXPLORING; 14294 14295 case BPF_CALL: 14296 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 14297 /* Mark this call insn as a prune point to trigger 14298 * is_state_visited() check before call itself is 14299 * processed by __check_func_call(). Otherwise new 14300 * async state will be pushed for further exploration. 14301 */ 14302 mark_prune_point(env, t); 14303 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 14304 struct bpf_kfunc_call_arg_meta meta; 14305 14306 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 14307 if (ret == 0 && is_iter_next_kfunc(&meta)) { 14308 mark_prune_point(env, t); 14309 /* Checking and saving state checkpoints at iter_next() call 14310 * is crucial for fast convergence of open-coded iterator loop 14311 * logic, so we need to force it. If we don't do that, 14312 * is_state_visited() might skip saving a checkpoint, causing 14313 * unnecessarily long sequence of not checkpointed 14314 * instructions and jumps, leading to exhaustion of jump 14315 * history buffer, and potentially other undesired outcomes. 14316 * It is expected that with correct open-coded iterators 14317 * convergence will happen quickly, so we don't run a risk of 14318 * exhausting memory. 14319 */ 14320 mark_force_checkpoint(env, t); 14321 } 14322 } 14323 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 14324 14325 case BPF_JA: 14326 if (BPF_SRC(insn->code) != BPF_K) 14327 return -EINVAL; 14328 14329 /* unconditional jump with single edge */ 14330 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env, 14331 true); 14332 if (ret) 14333 return ret; 14334 14335 mark_prune_point(env, t + insn->off + 1); 14336 mark_jmp_point(env, t + insn->off + 1); 14337 14338 return ret; 14339 14340 default: 14341 /* conditional jump with two edges */ 14342 mark_prune_point(env, t); 14343 14344 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 14345 if (ret) 14346 return ret; 14347 14348 return push_insn(t, t + insn->off + 1, BRANCH, env, true); 14349 } 14350 } 14351 14352 /* non-recursive depth-first-search to detect loops in BPF program 14353 * loop == back-edge in directed graph 14354 */ 14355 static int check_cfg(struct bpf_verifier_env *env) 14356 { 14357 int insn_cnt = env->prog->len; 14358 int *insn_stack, *insn_state; 14359 int ret = 0; 14360 int i; 14361 14362 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 14363 if (!insn_state) 14364 return -ENOMEM; 14365 14366 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 14367 if (!insn_stack) { 14368 kvfree(insn_state); 14369 return -ENOMEM; 14370 } 14371 14372 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 14373 insn_stack[0] = 0; /* 0 is the first instruction */ 14374 env->cfg.cur_stack = 1; 14375 14376 while (env->cfg.cur_stack > 0) { 14377 int t = insn_stack[env->cfg.cur_stack - 1]; 14378 14379 ret = visit_insn(t, env); 14380 switch (ret) { 14381 case DONE_EXPLORING: 14382 insn_state[t] = EXPLORED; 14383 env->cfg.cur_stack--; 14384 break; 14385 case KEEP_EXPLORING: 14386 break; 14387 default: 14388 if (ret > 0) { 14389 verbose(env, "visit_insn internal bug\n"); 14390 ret = -EFAULT; 14391 } 14392 goto err_free; 14393 } 14394 } 14395 14396 if (env->cfg.cur_stack < 0) { 14397 verbose(env, "pop stack internal bug\n"); 14398 ret = -EFAULT; 14399 goto err_free; 14400 } 14401 14402 for (i = 0; i < insn_cnt; i++) { 14403 if (insn_state[i] != EXPLORED) { 14404 verbose(env, "unreachable insn %d\n", i); 14405 ret = -EINVAL; 14406 goto err_free; 14407 } 14408 } 14409 ret = 0; /* cfg looks good */ 14410 14411 err_free: 14412 kvfree(insn_state); 14413 kvfree(insn_stack); 14414 env->cfg.insn_state = env->cfg.insn_stack = NULL; 14415 return ret; 14416 } 14417 14418 static int check_abnormal_return(struct bpf_verifier_env *env) 14419 { 14420 int i; 14421 14422 for (i = 1; i < env->subprog_cnt; i++) { 14423 if (env->subprog_info[i].has_ld_abs) { 14424 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 14425 return -EINVAL; 14426 } 14427 if (env->subprog_info[i].has_tail_call) { 14428 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 14429 return -EINVAL; 14430 } 14431 } 14432 return 0; 14433 } 14434 14435 /* The minimum supported BTF func info size */ 14436 #define MIN_BPF_FUNCINFO_SIZE 8 14437 #define MAX_FUNCINFO_REC_SIZE 252 14438 14439 static int check_btf_func(struct bpf_verifier_env *env, 14440 const union bpf_attr *attr, 14441 bpfptr_t uattr) 14442 { 14443 const struct btf_type *type, *func_proto, *ret_type; 14444 u32 i, nfuncs, urec_size, min_size; 14445 u32 krec_size = sizeof(struct bpf_func_info); 14446 struct bpf_func_info *krecord; 14447 struct bpf_func_info_aux *info_aux = NULL; 14448 struct bpf_prog *prog; 14449 const struct btf *btf; 14450 bpfptr_t urecord; 14451 u32 prev_offset = 0; 14452 bool scalar_return; 14453 int ret = -ENOMEM; 14454 14455 nfuncs = attr->func_info_cnt; 14456 if (!nfuncs) { 14457 if (check_abnormal_return(env)) 14458 return -EINVAL; 14459 return 0; 14460 } 14461 14462 if (nfuncs != env->subprog_cnt) { 14463 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 14464 return -EINVAL; 14465 } 14466 14467 urec_size = attr->func_info_rec_size; 14468 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 14469 urec_size > MAX_FUNCINFO_REC_SIZE || 14470 urec_size % sizeof(u32)) { 14471 verbose(env, "invalid func info rec size %u\n", urec_size); 14472 return -EINVAL; 14473 } 14474 14475 prog = env->prog; 14476 btf = prog->aux->btf; 14477 14478 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 14479 min_size = min_t(u32, krec_size, urec_size); 14480 14481 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 14482 if (!krecord) 14483 return -ENOMEM; 14484 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 14485 if (!info_aux) 14486 goto err_free; 14487 14488 for (i = 0; i < nfuncs; i++) { 14489 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 14490 if (ret) { 14491 if (ret == -E2BIG) { 14492 verbose(env, "nonzero tailing record in func info"); 14493 /* set the size kernel expects so loader can zero 14494 * out the rest of the record. 14495 */ 14496 if (copy_to_bpfptr_offset(uattr, 14497 offsetof(union bpf_attr, func_info_rec_size), 14498 &min_size, sizeof(min_size))) 14499 ret = -EFAULT; 14500 } 14501 goto err_free; 14502 } 14503 14504 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 14505 ret = -EFAULT; 14506 goto err_free; 14507 } 14508 14509 /* check insn_off */ 14510 ret = -EINVAL; 14511 if (i == 0) { 14512 if (krecord[i].insn_off) { 14513 verbose(env, 14514 "nonzero insn_off %u for the first func info record", 14515 krecord[i].insn_off); 14516 goto err_free; 14517 } 14518 } else if (krecord[i].insn_off <= prev_offset) { 14519 verbose(env, 14520 "same or smaller insn offset (%u) than previous func info record (%u)", 14521 krecord[i].insn_off, prev_offset); 14522 goto err_free; 14523 } 14524 14525 if (env->subprog_info[i].start != krecord[i].insn_off) { 14526 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 14527 goto err_free; 14528 } 14529 14530 /* check type_id */ 14531 type = btf_type_by_id(btf, krecord[i].type_id); 14532 if (!type || !btf_type_is_func(type)) { 14533 verbose(env, "invalid type id %d in func info", 14534 krecord[i].type_id); 14535 goto err_free; 14536 } 14537 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 14538 14539 func_proto = btf_type_by_id(btf, type->type); 14540 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 14541 /* btf_func_check() already verified it during BTF load */ 14542 goto err_free; 14543 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 14544 scalar_return = 14545 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 14546 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 14547 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 14548 goto err_free; 14549 } 14550 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 14551 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 14552 goto err_free; 14553 } 14554 14555 prev_offset = krecord[i].insn_off; 14556 bpfptr_add(&urecord, urec_size); 14557 } 14558 14559 prog->aux->func_info = krecord; 14560 prog->aux->func_info_cnt = nfuncs; 14561 prog->aux->func_info_aux = info_aux; 14562 return 0; 14563 14564 err_free: 14565 kvfree(krecord); 14566 kfree(info_aux); 14567 return ret; 14568 } 14569 14570 static void adjust_btf_func(struct bpf_verifier_env *env) 14571 { 14572 struct bpf_prog_aux *aux = env->prog->aux; 14573 int i; 14574 14575 if (!aux->func_info) 14576 return; 14577 14578 for (i = 0; i < env->subprog_cnt; i++) 14579 aux->func_info[i].insn_off = env->subprog_info[i].start; 14580 } 14581 14582 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 14583 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 14584 14585 static int check_btf_line(struct bpf_verifier_env *env, 14586 const union bpf_attr *attr, 14587 bpfptr_t uattr) 14588 { 14589 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 14590 struct bpf_subprog_info *sub; 14591 struct bpf_line_info *linfo; 14592 struct bpf_prog *prog; 14593 const struct btf *btf; 14594 bpfptr_t ulinfo; 14595 int err; 14596 14597 nr_linfo = attr->line_info_cnt; 14598 if (!nr_linfo) 14599 return 0; 14600 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 14601 return -EINVAL; 14602 14603 rec_size = attr->line_info_rec_size; 14604 if (rec_size < MIN_BPF_LINEINFO_SIZE || 14605 rec_size > MAX_LINEINFO_REC_SIZE || 14606 rec_size & (sizeof(u32) - 1)) 14607 return -EINVAL; 14608 14609 /* Need to zero it in case the userspace may 14610 * pass in a smaller bpf_line_info object. 14611 */ 14612 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 14613 GFP_KERNEL | __GFP_NOWARN); 14614 if (!linfo) 14615 return -ENOMEM; 14616 14617 prog = env->prog; 14618 btf = prog->aux->btf; 14619 14620 s = 0; 14621 sub = env->subprog_info; 14622 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 14623 expected_size = sizeof(struct bpf_line_info); 14624 ncopy = min_t(u32, expected_size, rec_size); 14625 for (i = 0; i < nr_linfo; i++) { 14626 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 14627 if (err) { 14628 if (err == -E2BIG) { 14629 verbose(env, "nonzero tailing record in line_info"); 14630 if (copy_to_bpfptr_offset(uattr, 14631 offsetof(union bpf_attr, line_info_rec_size), 14632 &expected_size, sizeof(expected_size))) 14633 err = -EFAULT; 14634 } 14635 goto err_free; 14636 } 14637 14638 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 14639 err = -EFAULT; 14640 goto err_free; 14641 } 14642 14643 /* 14644 * Check insn_off to ensure 14645 * 1) strictly increasing AND 14646 * 2) bounded by prog->len 14647 * 14648 * The linfo[0].insn_off == 0 check logically falls into 14649 * the later "missing bpf_line_info for func..." case 14650 * because the first linfo[0].insn_off must be the 14651 * first sub also and the first sub must have 14652 * subprog_info[0].start == 0. 14653 */ 14654 if ((i && linfo[i].insn_off <= prev_offset) || 14655 linfo[i].insn_off >= prog->len) { 14656 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 14657 i, linfo[i].insn_off, prev_offset, 14658 prog->len); 14659 err = -EINVAL; 14660 goto err_free; 14661 } 14662 14663 if (!prog->insnsi[linfo[i].insn_off].code) { 14664 verbose(env, 14665 "Invalid insn code at line_info[%u].insn_off\n", 14666 i); 14667 err = -EINVAL; 14668 goto err_free; 14669 } 14670 14671 if (!btf_name_by_offset(btf, linfo[i].line_off) || 14672 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 14673 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 14674 err = -EINVAL; 14675 goto err_free; 14676 } 14677 14678 if (s != env->subprog_cnt) { 14679 if (linfo[i].insn_off == sub[s].start) { 14680 sub[s].linfo_idx = i; 14681 s++; 14682 } else if (sub[s].start < linfo[i].insn_off) { 14683 verbose(env, "missing bpf_line_info for func#%u\n", s); 14684 err = -EINVAL; 14685 goto err_free; 14686 } 14687 } 14688 14689 prev_offset = linfo[i].insn_off; 14690 bpfptr_add(&ulinfo, rec_size); 14691 } 14692 14693 if (s != env->subprog_cnt) { 14694 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 14695 env->subprog_cnt - s, s); 14696 err = -EINVAL; 14697 goto err_free; 14698 } 14699 14700 prog->aux->linfo = linfo; 14701 prog->aux->nr_linfo = nr_linfo; 14702 14703 return 0; 14704 14705 err_free: 14706 kvfree(linfo); 14707 return err; 14708 } 14709 14710 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 14711 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 14712 14713 static int check_core_relo(struct bpf_verifier_env *env, 14714 const union bpf_attr *attr, 14715 bpfptr_t uattr) 14716 { 14717 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 14718 struct bpf_core_relo core_relo = {}; 14719 struct bpf_prog *prog = env->prog; 14720 const struct btf *btf = prog->aux->btf; 14721 struct bpf_core_ctx ctx = { 14722 .log = &env->log, 14723 .btf = btf, 14724 }; 14725 bpfptr_t u_core_relo; 14726 int err; 14727 14728 nr_core_relo = attr->core_relo_cnt; 14729 if (!nr_core_relo) 14730 return 0; 14731 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 14732 return -EINVAL; 14733 14734 rec_size = attr->core_relo_rec_size; 14735 if (rec_size < MIN_CORE_RELO_SIZE || 14736 rec_size > MAX_CORE_RELO_SIZE || 14737 rec_size % sizeof(u32)) 14738 return -EINVAL; 14739 14740 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 14741 expected_size = sizeof(struct bpf_core_relo); 14742 ncopy = min_t(u32, expected_size, rec_size); 14743 14744 /* Unlike func_info and line_info, copy and apply each CO-RE 14745 * relocation record one at a time. 14746 */ 14747 for (i = 0; i < nr_core_relo; i++) { 14748 /* future proofing when sizeof(bpf_core_relo) changes */ 14749 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 14750 if (err) { 14751 if (err == -E2BIG) { 14752 verbose(env, "nonzero tailing record in core_relo"); 14753 if (copy_to_bpfptr_offset(uattr, 14754 offsetof(union bpf_attr, core_relo_rec_size), 14755 &expected_size, sizeof(expected_size))) 14756 err = -EFAULT; 14757 } 14758 break; 14759 } 14760 14761 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 14762 err = -EFAULT; 14763 break; 14764 } 14765 14766 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 14767 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 14768 i, core_relo.insn_off, prog->len); 14769 err = -EINVAL; 14770 break; 14771 } 14772 14773 err = bpf_core_apply(&ctx, &core_relo, i, 14774 &prog->insnsi[core_relo.insn_off / 8]); 14775 if (err) 14776 break; 14777 bpfptr_add(&u_core_relo, rec_size); 14778 } 14779 return err; 14780 } 14781 14782 static int check_btf_info(struct bpf_verifier_env *env, 14783 const union bpf_attr *attr, 14784 bpfptr_t uattr) 14785 { 14786 struct btf *btf; 14787 int err; 14788 14789 if (!attr->func_info_cnt && !attr->line_info_cnt) { 14790 if (check_abnormal_return(env)) 14791 return -EINVAL; 14792 return 0; 14793 } 14794 14795 btf = btf_get_by_fd(attr->prog_btf_fd); 14796 if (IS_ERR(btf)) 14797 return PTR_ERR(btf); 14798 if (btf_is_kernel(btf)) { 14799 btf_put(btf); 14800 return -EACCES; 14801 } 14802 env->prog->aux->btf = btf; 14803 14804 err = check_btf_func(env, attr, uattr); 14805 if (err) 14806 return err; 14807 14808 err = check_btf_line(env, attr, uattr); 14809 if (err) 14810 return err; 14811 14812 err = check_core_relo(env, attr, uattr); 14813 if (err) 14814 return err; 14815 14816 return 0; 14817 } 14818 14819 /* check %cur's range satisfies %old's */ 14820 static bool range_within(struct bpf_reg_state *old, 14821 struct bpf_reg_state *cur) 14822 { 14823 return old->umin_value <= cur->umin_value && 14824 old->umax_value >= cur->umax_value && 14825 old->smin_value <= cur->smin_value && 14826 old->smax_value >= cur->smax_value && 14827 old->u32_min_value <= cur->u32_min_value && 14828 old->u32_max_value >= cur->u32_max_value && 14829 old->s32_min_value <= cur->s32_min_value && 14830 old->s32_max_value >= cur->s32_max_value; 14831 } 14832 14833 /* If in the old state two registers had the same id, then they need to have 14834 * the same id in the new state as well. But that id could be different from 14835 * the old state, so we need to track the mapping from old to new ids. 14836 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 14837 * regs with old id 5 must also have new id 9 for the new state to be safe. But 14838 * regs with a different old id could still have new id 9, we don't care about 14839 * that. 14840 * So we look through our idmap to see if this old id has been seen before. If 14841 * so, we require the new id to match; otherwise, we add the id pair to the map. 14842 */ 14843 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap) 14844 { 14845 unsigned int i; 14846 14847 /* either both IDs should be set or both should be zero */ 14848 if (!!old_id != !!cur_id) 14849 return false; 14850 14851 if (old_id == 0) /* cur_id == 0 as well */ 14852 return true; 14853 14854 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 14855 if (!idmap[i].old) { 14856 /* Reached an empty slot; haven't seen this id before */ 14857 idmap[i].old = old_id; 14858 idmap[i].cur = cur_id; 14859 return true; 14860 } 14861 if (idmap[i].old == old_id) 14862 return idmap[i].cur == cur_id; 14863 } 14864 /* We ran out of idmap slots, which should be impossible */ 14865 WARN_ON_ONCE(1); 14866 return false; 14867 } 14868 14869 static void clean_func_state(struct bpf_verifier_env *env, 14870 struct bpf_func_state *st) 14871 { 14872 enum bpf_reg_liveness live; 14873 int i, j; 14874 14875 for (i = 0; i < BPF_REG_FP; i++) { 14876 live = st->regs[i].live; 14877 /* liveness must not touch this register anymore */ 14878 st->regs[i].live |= REG_LIVE_DONE; 14879 if (!(live & REG_LIVE_READ)) 14880 /* since the register is unused, clear its state 14881 * to make further comparison simpler 14882 */ 14883 __mark_reg_not_init(env, &st->regs[i]); 14884 } 14885 14886 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 14887 live = st->stack[i].spilled_ptr.live; 14888 /* liveness must not touch this stack slot anymore */ 14889 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 14890 if (!(live & REG_LIVE_READ)) { 14891 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 14892 for (j = 0; j < BPF_REG_SIZE; j++) 14893 st->stack[i].slot_type[j] = STACK_INVALID; 14894 } 14895 } 14896 } 14897 14898 static void clean_verifier_state(struct bpf_verifier_env *env, 14899 struct bpf_verifier_state *st) 14900 { 14901 int i; 14902 14903 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 14904 /* all regs in this state in all frames were already marked */ 14905 return; 14906 14907 for (i = 0; i <= st->curframe; i++) 14908 clean_func_state(env, st->frame[i]); 14909 } 14910 14911 /* the parentage chains form a tree. 14912 * the verifier states are added to state lists at given insn and 14913 * pushed into state stack for future exploration. 14914 * when the verifier reaches bpf_exit insn some of the verifer states 14915 * stored in the state lists have their final liveness state already, 14916 * but a lot of states will get revised from liveness point of view when 14917 * the verifier explores other branches. 14918 * Example: 14919 * 1: r0 = 1 14920 * 2: if r1 == 100 goto pc+1 14921 * 3: r0 = 2 14922 * 4: exit 14923 * when the verifier reaches exit insn the register r0 in the state list of 14924 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 14925 * of insn 2 and goes exploring further. At the insn 4 it will walk the 14926 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 14927 * 14928 * Since the verifier pushes the branch states as it sees them while exploring 14929 * the program the condition of walking the branch instruction for the second 14930 * time means that all states below this branch were already explored and 14931 * their final liveness marks are already propagated. 14932 * Hence when the verifier completes the search of state list in is_state_visited() 14933 * we can call this clean_live_states() function to mark all liveness states 14934 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 14935 * will not be used. 14936 * This function also clears the registers and stack for states that !READ 14937 * to simplify state merging. 14938 * 14939 * Important note here that walking the same branch instruction in the callee 14940 * doesn't meant that the states are DONE. The verifier has to compare 14941 * the callsites 14942 */ 14943 static void clean_live_states(struct bpf_verifier_env *env, int insn, 14944 struct bpf_verifier_state *cur) 14945 { 14946 struct bpf_verifier_state_list *sl; 14947 int i; 14948 14949 sl = *explored_state(env, insn); 14950 while (sl) { 14951 if (sl->state.branches) 14952 goto next; 14953 if (sl->state.insn_idx != insn || 14954 sl->state.curframe != cur->curframe) 14955 goto next; 14956 for (i = 0; i <= cur->curframe; i++) 14957 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 14958 goto next; 14959 clean_verifier_state(env, &sl->state); 14960 next: 14961 sl = sl->next; 14962 } 14963 } 14964 14965 static bool regs_exact(const struct bpf_reg_state *rold, 14966 const struct bpf_reg_state *rcur, 14967 struct bpf_id_pair *idmap) 14968 { 14969 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 14970 check_ids(rold->id, rcur->id, idmap) && 14971 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 14972 } 14973 14974 /* Returns true if (rold safe implies rcur safe) */ 14975 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 14976 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap) 14977 { 14978 if (!(rold->live & REG_LIVE_READ)) 14979 /* explored state didn't use this */ 14980 return true; 14981 if (rold->type == NOT_INIT) 14982 /* explored state can't have used this */ 14983 return true; 14984 if (rcur->type == NOT_INIT) 14985 return false; 14986 14987 /* Enforce that register types have to match exactly, including their 14988 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 14989 * rule. 14990 * 14991 * One can make a point that using a pointer register as unbounded 14992 * SCALAR would be technically acceptable, but this could lead to 14993 * pointer leaks because scalars are allowed to leak while pointers 14994 * are not. We could make this safe in special cases if root is 14995 * calling us, but it's probably not worth the hassle. 14996 * 14997 * Also, register types that are *not* MAYBE_NULL could technically be 14998 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 14999 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 15000 * to the same map). 15001 * However, if the old MAYBE_NULL register then got NULL checked, 15002 * doing so could have affected others with the same id, and we can't 15003 * check for that because we lost the id when we converted to 15004 * a non-MAYBE_NULL variant. 15005 * So, as a general rule we don't allow mixing MAYBE_NULL and 15006 * non-MAYBE_NULL registers as well. 15007 */ 15008 if (rold->type != rcur->type) 15009 return false; 15010 15011 switch (base_type(rold->type)) { 15012 case SCALAR_VALUE: 15013 if (regs_exact(rold, rcur, idmap)) 15014 return true; 15015 if (env->explore_alu_limits) 15016 return false; 15017 if (!rold->precise) 15018 return true; 15019 /* new val must satisfy old val knowledge */ 15020 return range_within(rold, rcur) && 15021 tnum_in(rold->var_off, rcur->var_off); 15022 case PTR_TO_MAP_KEY: 15023 case PTR_TO_MAP_VALUE: 15024 case PTR_TO_MEM: 15025 case PTR_TO_BUF: 15026 case PTR_TO_TP_BUFFER: 15027 /* If the new min/max/var_off satisfy the old ones and 15028 * everything else matches, we are OK. 15029 */ 15030 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 15031 range_within(rold, rcur) && 15032 tnum_in(rold->var_off, rcur->var_off) && 15033 check_ids(rold->id, rcur->id, idmap) && 15034 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 15035 case PTR_TO_PACKET_META: 15036 case PTR_TO_PACKET: 15037 /* We must have at least as much range as the old ptr 15038 * did, so that any accesses which were safe before are 15039 * still safe. This is true even if old range < old off, 15040 * since someone could have accessed through (ptr - k), or 15041 * even done ptr -= k in a register, to get a safe access. 15042 */ 15043 if (rold->range > rcur->range) 15044 return false; 15045 /* If the offsets don't match, we can't trust our alignment; 15046 * nor can we be sure that we won't fall out of range. 15047 */ 15048 if (rold->off != rcur->off) 15049 return false; 15050 /* id relations must be preserved */ 15051 if (!check_ids(rold->id, rcur->id, idmap)) 15052 return false; 15053 /* new val must satisfy old val knowledge */ 15054 return range_within(rold, rcur) && 15055 tnum_in(rold->var_off, rcur->var_off); 15056 case PTR_TO_STACK: 15057 /* two stack pointers are equal only if they're pointing to 15058 * the same stack frame, since fp-8 in foo != fp-8 in bar 15059 */ 15060 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 15061 default: 15062 return regs_exact(rold, rcur, idmap); 15063 } 15064 } 15065 15066 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 15067 struct bpf_func_state *cur, struct bpf_id_pair *idmap) 15068 { 15069 int i, spi; 15070 15071 /* walk slots of the explored stack and ignore any additional 15072 * slots in the current stack, since explored(safe) state 15073 * didn't use them 15074 */ 15075 for (i = 0; i < old->allocated_stack; i++) { 15076 struct bpf_reg_state *old_reg, *cur_reg; 15077 15078 spi = i / BPF_REG_SIZE; 15079 15080 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 15081 i += BPF_REG_SIZE - 1; 15082 /* explored state didn't use this */ 15083 continue; 15084 } 15085 15086 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 15087 continue; 15088 15089 if (env->allow_uninit_stack && 15090 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 15091 continue; 15092 15093 /* explored stack has more populated slots than current stack 15094 * and these slots were used 15095 */ 15096 if (i >= cur->allocated_stack) 15097 return false; 15098 15099 /* if old state was safe with misc data in the stack 15100 * it will be safe with zero-initialized stack. 15101 * The opposite is not true 15102 */ 15103 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 15104 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 15105 continue; 15106 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 15107 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 15108 /* Ex: old explored (safe) state has STACK_SPILL in 15109 * this stack slot, but current has STACK_MISC -> 15110 * this verifier states are not equivalent, 15111 * return false to continue verification of this path 15112 */ 15113 return false; 15114 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 15115 continue; 15116 /* Both old and cur are having same slot_type */ 15117 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 15118 case STACK_SPILL: 15119 /* when explored and current stack slot are both storing 15120 * spilled registers, check that stored pointers types 15121 * are the same as well. 15122 * Ex: explored safe path could have stored 15123 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 15124 * but current path has stored: 15125 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 15126 * such verifier states are not equivalent. 15127 * return false to continue verification of this path 15128 */ 15129 if (!regsafe(env, &old->stack[spi].spilled_ptr, 15130 &cur->stack[spi].spilled_ptr, idmap)) 15131 return false; 15132 break; 15133 case STACK_DYNPTR: 15134 old_reg = &old->stack[spi].spilled_ptr; 15135 cur_reg = &cur->stack[spi].spilled_ptr; 15136 if (old_reg->dynptr.type != cur_reg->dynptr.type || 15137 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 15138 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 15139 return false; 15140 break; 15141 case STACK_ITER: 15142 old_reg = &old->stack[spi].spilled_ptr; 15143 cur_reg = &cur->stack[spi].spilled_ptr; 15144 /* iter.depth is not compared between states as it 15145 * doesn't matter for correctness and would otherwise 15146 * prevent convergence; we maintain it only to prevent 15147 * infinite loop check triggering, see 15148 * iter_active_depths_differ() 15149 */ 15150 if (old_reg->iter.btf != cur_reg->iter.btf || 15151 old_reg->iter.btf_id != cur_reg->iter.btf_id || 15152 old_reg->iter.state != cur_reg->iter.state || 15153 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 15154 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 15155 return false; 15156 break; 15157 case STACK_MISC: 15158 case STACK_ZERO: 15159 case STACK_INVALID: 15160 continue; 15161 /* Ensure that new unhandled slot types return false by default */ 15162 default: 15163 return false; 15164 } 15165 } 15166 return true; 15167 } 15168 15169 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 15170 struct bpf_id_pair *idmap) 15171 { 15172 int i; 15173 15174 if (old->acquired_refs != cur->acquired_refs) 15175 return false; 15176 15177 for (i = 0; i < old->acquired_refs; i++) { 15178 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 15179 return false; 15180 } 15181 15182 return true; 15183 } 15184 15185 /* compare two verifier states 15186 * 15187 * all states stored in state_list are known to be valid, since 15188 * verifier reached 'bpf_exit' instruction through them 15189 * 15190 * this function is called when verifier exploring different branches of 15191 * execution popped from the state stack. If it sees an old state that has 15192 * more strict register state and more strict stack state then this execution 15193 * branch doesn't need to be explored further, since verifier already 15194 * concluded that more strict state leads to valid finish. 15195 * 15196 * Therefore two states are equivalent if register state is more conservative 15197 * and explored stack state is more conservative than the current one. 15198 * Example: 15199 * explored current 15200 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 15201 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 15202 * 15203 * In other words if current stack state (one being explored) has more 15204 * valid slots than old one that already passed validation, it means 15205 * the verifier can stop exploring and conclude that current state is valid too 15206 * 15207 * Similarly with registers. If explored state has register type as invalid 15208 * whereas register type in current state is meaningful, it means that 15209 * the current state will reach 'bpf_exit' instruction safely 15210 */ 15211 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 15212 struct bpf_func_state *cur) 15213 { 15214 int i; 15215 15216 for (i = 0; i < MAX_BPF_REG; i++) 15217 if (!regsafe(env, &old->regs[i], &cur->regs[i], 15218 env->idmap_scratch)) 15219 return false; 15220 15221 if (!stacksafe(env, old, cur, env->idmap_scratch)) 15222 return false; 15223 15224 if (!refsafe(old, cur, env->idmap_scratch)) 15225 return false; 15226 15227 return true; 15228 } 15229 15230 static bool states_equal(struct bpf_verifier_env *env, 15231 struct bpf_verifier_state *old, 15232 struct bpf_verifier_state *cur) 15233 { 15234 int i; 15235 15236 if (old->curframe != cur->curframe) 15237 return false; 15238 15239 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch)); 15240 15241 /* Verification state from speculative execution simulation 15242 * must never prune a non-speculative execution one. 15243 */ 15244 if (old->speculative && !cur->speculative) 15245 return false; 15246 15247 if (old->active_lock.ptr != cur->active_lock.ptr) 15248 return false; 15249 15250 /* Old and cur active_lock's have to be either both present 15251 * or both absent. 15252 */ 15253 if (!!old->active_lock.id != !!cur->active_lock.id) 15254 return false; 15255 15256 if (old->active_lock.id && 15257 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch)) 15258 return false; 15259 15260 if (old->active_rcu_lock != cur->active_rcu_lock) 15261 return false; 15262 15263 /* for states to be equal callsites have to be the same 15264 * and all frame states need to be equivalent 15265 */ 15266 for (i = 0; i <= old->curframe; i++) { 15267 if (old->frame[i]->callsite != cur->frame[i]->callsite) 15268 return false; 15269 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 15270 return false; 15271 } 15272 return true; 15273 } 15274 15275 /* Return 0 if no propagation happened. Return negative error code if error 15276 * happened. Otherwise, return the propagated bit. 15277 */ 15278 static int propagate_liveness_reg(struct bpf_verifier_env *env, 15279 struct bpf_reg_state *reg, 15280 struct bpf_reg_state *parent_reg) 15281 { 15282 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 15283 u8 flag = reg->live & REG_LIVE_READ; 15284 int err; 15285 15286 /* When comes here, read flags of PARENT_REG or REG could be any of 15287 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 15288 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 15289 */ 15290 if (parent_flag == REG_LIVE_READ64 || 15291 /* Or if there is no read flag from REG. */ 15292 !flag || 15293 /* Or if the read flag from REG is the same as PARENT_REG. */ 15294 parent_flag == flag) 15295 return 0; 15296 15297 err = mark_reg_read(env, reg, parent_reg, flag); 15298 if (err) 15299 return err; 15300 15301 return flag; 15302 } 15303 15304 /* A write screens off any subsequent reads; but write marks come from the 15305 * straight-line code between a state and its parent. When we arrive at an 15306 * equivalent state (jump target or such) we didn't arrive by the straight-line 15307 * code, so read marks in the state must propagate to the parent regardless 15308 * of the state's write marks. That's what 'parent == state->parent' comparison 15309 * in mark_reg_read() is for. 15310 */ 15311 static int propagate_liveness(struct bpf_verifier_env *env, 15312 const struct bpf_verifier_state *vstate, 15313 struct bpf_verifier_state *vparent) 15314 { 15315 struct bpf_reg_state *state_reg, *parent_reg; 15316 struct bpf_func_state *state, *parent; 15317 int i, frame, err = 0; 15318 15319 if (vparent->curframe != vstate->curframe) { 15320 WARN(1, "propagate_live: parent frame %d current frame %d\n", 15321 vparent->curframe, vstate->curframe); 15322 return -EFAULT; 15323 } 15324 /* Propagate read liveness of registers... */ 15325 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 15326 for (frame = 0; frame <= vstate->curframe; frame++) { 15327 parent = vparent->frame[frame]; 15328 state = vstate->frame[frame]; 15329 parent_reg = parent->regs; 15330 state_reg = state->regs; 15331 /* We don't need to worry about FP liveness, it's read-only */ 15332 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 15333 err = propagate_liveness_reg(env, &state_reg[i], 15334 &parent_reg[i]); 15335 if (err < 0) 15336 return err; 15337 if (err == REG_LIVE_READ64) 15338 mark_insn_zext(env, &parent_reg[i]); 15339 } 15340 15341 /* Propagate stack slots. */ 15342 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 15343 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 15344 parent_reg = &parent->stack[i].spilled_ptr; 15345 state_reg = &state->stack[i].spilled_ptr; 15346 err = propagate_liveness_reg(env, state_reg, 15347 parent_reg); 15348 if (err < 0) 15349 return err; 15350 } 15351 } 15352 return 0; 15353 } 15354 15355 /* find precise scalars in the previous equivalent state and 15356 * propagate them into the current state 15357 */ 15358 static int propagate_precision(struct bpf_verifier_env *env, 15359 const struct bpf_verifier_state *old) 15360 { 15361 struct bpf_reg_state *state_reg; 15362 struct bpf_func_state *state; 15363 int i, err = 0, fr; 15364 15365 for (fr = old->curframe; fr >= 0; fr--) { 15366 state = old->frame[fr]; 15367 state_reg = state->regs; 15368 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 15369 if (state_reg->type != SCALAR_VALUE || 15370 !state_reg->precise || 15371 !(state_reg->live & REG_LIVE_READ)) 15372 continue; 15373 if (env->log.level & BPF_LOG_LEVEL2) 15374 verbose(env, "frame %d: propagating r%d\n", fr, i); 15375 err = mark_chain_precision_frame(env, fr, i); 15376 if (err < 0) 15377 return err; 15378 } 15379 15380 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 15381 if (!is_spilled_reg(&state->stack[i])) 15382 continue; 15383 state_reg = &state->stack[i].spilled_ptr; 15384 if (state_reg->type != SCALAR_VALUE || 15385 !state_reg->precise || 15386 !(state_reg->live & REG_LIVE_READ)) 15387 continue; 15388 if (env->log.level & BPF_LOG_LEVEL2) 15389 verbose(env, "frame %d: propagating fp%d\n", 15390 fr, (-i - 1) * BPF_REG_SIZE); 15391 err = mark_chain_precision_stack_frame(env, fr, i); 15392 if (err < 0) 15393 return err; 15394 } 15395 } 15396 return 0; 15397 } 15398 15399 static bool states_maybe_looping(struct bpf_verifier_state *old, 15400 struct bpf_verifier_state *cur) 15401 { 15402 struct bpf_func_state *fold, *fcur; 15403 int i, fr = cur->curframe; 15404 15405 if (old->curframe != fr) 15406 return false; 15407 15408 fold = old->frame[fr]; 15409 fcur = cur->frame[fr]; 15410 for (i = 0; i < MAX_BPF_REG; i++) 15411 if (memcmp(&fold->regs[i], &fcur->regs[i], 15412 offsetof(struct bpf_reg_state, parent))) 15413 return false; 15414 return true; 15415 } 15416 15417 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 15418 { 15419 return env->insn_aux_data[insn_idx].is_iter_next; 15420 } 15421 15422 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 15423 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 15424 * states to match, which otherwise would look like an infinite loop. So while 15425 * iter_next() calls are taken care of, we still need to be careful and 15426 * prevent erroneous and too eager declaration of "ininite loop", when 15427 * iterators are involved. 15428 * 15429 * Here's a situation in pseudo-BPF assembly form: 15430 * 15431 * 0: again: ; set up iter_next() call args 15432 * 1: r1 = &it ; <CHECKPOINT HERE> 15433 * 2: call bpf_iter_num_next ; this is iter_next() call 15434 * 3: if r0 == 0 goto done 15435 * 4: ... something useful here ... 15436 * 5: goto again ; another iteration 15437 * 6: done: 15438 * 7: r1 = &it 15439 * 8: call bpf_iter_num_destroy ; clean up iter state 15440 * 9: exit 15441 * 15442 * This is a typical loop. Let's assume that we have a prune point at 1:, 15443 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 15444 * again`, assuming other heuristics don't get in a way). 15445 * 15446 * When we first time come to 1:, let's say we have some state X. We proceed 15447 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 15448 * Now we come back to validate that forked ACTIVE state. We proceed through 15449 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 15450 * are converging. But the problem is that we don't know that yet, as this 15451 * convergence has to happen at iter_next() call site only. So if nothing is 15452 * done, at 1: verifier will use bounded loop logic and declare infinite 15453 * looping (and would be *technically* correct, if not for iterator's 15454 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 15455 * don't want that. So what we do in process_iter_next_call() when we go on 15456 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 15457 * a different iteration. So when we suspect an infinite loop, we additionally 15458 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 15459 * pretend we are not looping and wait for next iter_next() call. 15460 * 15461 * This only applies to ACTIVE state. In DRAINED state we don't expect to 15462 * loop, because that would actually mean infinite loop, as DRAINED state is 15463 * "sticky", and so we'll keep returning into the same instruction with the 15464 * same state (at least in one of possible code paths). 15465 * 15466 * This approach allows to keep infinite loop heuristic even in the face of 15467 * active iterator. E.g., C snippet below is and will be detected as 15468 * inifintely looping: 15469 * 15470 * struct bpf_iter_num it; 15471 * int *p, x; 15472 * 15473 * bpf_iter_num_new(&it, 0, 10); 15474 * while ((p = bpf_iter_num_next(&t))) { 15475 * x = p; 15476 * while (x--) {} // <<-- infinite loop here 15477 * } 15478 * 15479 */ 15480 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 15481 { 15482 struct bpf_reg_state *slot, *cur_slot; 15483 struct bpf_func_state *state; 15484 int i, fr; 15485 15486 for (fr = old->curframe; fr >= 0; fr--) { 15487 state = old->frame[fr]; 15488 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 15489 if (state->stack[i].slot_type[0] != STACK_ITER) 15490 continue; 15491 15492 slot = &state->stack[i].spilled_ptr; 15493 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 15494 continue; 15495 15496 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 15497 if (cur_slot->iter.depth != slot->iter.depth) 15498 return true; 15499 } 15500 } 15501 return false; 15502 } 15503 15504 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 15505 { 15506 struct bpf_verifier_state_list *new_sl; 15507 struct bpf_verifier_state_list *sl, **pprev; 15508 struct bpf_verifier_state *cur = env->cur_state, *new; 15509 int i, j, err, states_cnt = 0; 15510 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 15511 bool add_new_state = force_new_state; 15512 15513 /* bpf progs typically have pruning point every 4 instructions 15514 * http://vger.kernel.org/bpfconf2019.html#session-1 15515 * Do not add new state for future pruning if the verifier hasn't seen 15516 * at least 2 jumps and at least 8 instructions. 15517 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 15518 * In tests that amounts to up to 50% reduction into total verifier 15519 * memory consumption and 20% verifier time speedup. 15520 */ 15521 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 15522 env->insn_processed - env->prev_insn_processed >= 8) 15523 add_new_state = true; 15524 15525 pprev = explored_state(env, insn_idx); 15526 sl = *pprev; 15527 15528 clean_live_states(env, insn_idx, cur); 15529 15530 while (sl) { 15531 states_cnt++; 15532 if (sl->state.insn_idx != insn_idx) 15533 goto next; 15534 15535 if (sl->state.branches) { 15536 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 15537 15538 if (frame->in_async_callback_fn && 15539 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 15540 /* Different async_entry_cnt means that the verifier is 15541 * processing another entry into async callback. 15542 * Seeing the same state is not an indication of infinite 15543 * loop or infinite recursion. 15544 * But finding the same state doesn't mean that it's safe 15545 * to stop processing the current state. The previous state 15546 * hasn't yet reached bpf_exit, since state.branches > 0. 15547 * Checking in_async_callback_fn alone is not enough either. 15548 * Since the verifier still needs to catch infinite loops 15549 * inside async callbacks. 15550 */ 15551 goto skip_inf_loop_check; 15552 } 15553 /* BPF open-coded iterators loop detection is special. 15554 * states_maybe_looping() logic is too simplistic in detecting 15555 * states that *might* be equivalent, because it doesn't know 15556 * about ID remapping, so don't even perform it. 15557 * See process_iter_next_call() and iter_active_depths_differ() 15558 * for overview of the logic. When current and one of parent 15559 * states are detected as equivalent, it's a good thing: we prove 15560 * convergence and can stop simulating further iterations. 15561 * It's safe to assume that iterator loop will finish, taking into 15562 * account iter_next() contract of eventually returning 15563 * sticky NULL result. 15564 */ 15565 if (is_iter_next_insn(env, insn_idx)) { 15566 if (states_equal(env, &sl->state, cur)) { 15567 struct bpf_func_state *cur_frame; 15568 struct bpf_reg_state *iter_state, *iter_reg; 15569 int spi; 15570 15571 cur_frame = cur->frame[cur->curframe]; 15572 /* btf_check_iter_kfuncs() enforces that 15573 * iter state pointer is always the first arg 15574 */ 15575 iter_reg = &cur_frame->regs[BPF_REG_1]; 15576 /* current state is valid due to states_equal(), 15577 * so we can assume valid iter and reg state, 15578 * no need for extra (re-)validations 15579 */ 15580 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 15581 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 15582 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) 15583 goto hit; 15584 } 15585 goto skip_inf_loop_check; 15586 } 15587 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 15588 if (states_maybe_looping(&sl->state, cur) && 15589 states_equal(env, &sl->state, cur) && 15590 !iter_active_depths_differ(&sl->state, cur)) { 15591 verbose_linfo(env, insn_idx, "; "); 15592 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 15593 return -EINVAL; 15594 } 15595 /* if the verifier is processing a loop, avoid adding new state 15596 * too often, since different loop iterations have distinct 15597 * states and may not help future pruning. 15598 * This threshold shouldn't be too low to make sure that 15599 * a loop with large bound will be rejected quickly. 15600 * The most abusive loop will be: 15601 * r1 += 1 15602 * if r1 < 1000000 goto pc-2 15603 * 1M insn_procssed limit / 100 == 10k peak states. 15604 * This threshold shouldn't be too high either, since states 15605 * at the end of the loop are likely to be useful in pruning. 15606 */ 15607 skip_inf_loop_check: 15608 if (!force_new_state && 15609 env->jmps_processed - env->prev_jmps_processed < 20 && 15610 env->insn_processed - env->prev_insn_processed < 100) 15611 add_new_state = false; 15612 goto miss; 15613 } 15614 if (states_equal(env, &sl->state, cur)) { 15615 hit: 15616 sl->hit_cnt++; 15617 /* reached equivalent register/stack state, 15618 * prune the search. 15619 * Registers read by the continuation are read by us. 15620 * If we have any write marks in env->cur_state, they 15621 * will prevent corresponding reads in the continuation 15622 * from reaching our parent (an explored_state). Our 15623 * own state will get the read marks recorded, but 15624 * they'll be immediately forgotten as we're pruning 15625 * this state and will pop a new one. 15626 */ 15627 err = propagate_liveness(env, &sl->state, cur); 15628 15629 /* if previous state reached the exit with precision and 15630 * current state is equivalent to it (except precsion marks) 15631 * the precision needs to be propagated back in 15632 * the current state. 15633 */ 15634 err = err ? : push_jmp_history(env, cur); 15635 err = err ? : propagate_precision(env, &sl->state); 15636 if (err) 15637 return err; 15638 return 1; 15639 } 15640 miss: 15641 /* when new state is not going to be added do not increase miss count. 15642 * Otherwise several loop iterations will remove the state 15643 * recorded earlier. The goal of these heuristics is to have 15644 * states from some iterations of the loop (some in the beginning 15645 * and some at the end) to help pruning. 15646 */ 15647 if (add_new_state) 15648 sl->miss_cnt++; 15649 /* heuristic to determine whether this state is beneficial 15650 * to keep checking from state equivalence point of view. 15651 * Higher numbers increase max_states_per_insn and verification time, 15652 * but do not meaningfully decrease insn_processed. 15653 */ 15654 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 15655 /* the state is unlikely to be useful. Remove it to 15656 * speed up verification 15657 */ 15658 *pprev = sl->next; 15659 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 15660 u32 br = sl->state.branches; 15661 15662 WARN_ONCE(br, 15663 "BUG live_done but branches_to_explore %d\n", 15664 br); 15665 free_verifier_state(&sl->state, false); 15666 kfree(sl); 15667 env->peak_states--; 15668 } else { 15669 /* cannot free this state, since parentage chain may 15670 * walk it later. Add it for free_list instead to 15671 * be freed at the end of verification 15672 */ 15673 sl->next = env->free_list; 15674 env->free_list = sl; 15675 } 15676 sl = *pprev; 15677 continue; 15678 } 15679 next: 15680 pprev = &sl->next; 15681 sl = *pprev; 15682 } 15683 15684 if (env->max_states_per_insn < states_cnt) 15685 env->max_states_per_insn = states_cnt; 15686 15687 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 15688 return 0; 15689 15690 if (!add_new_state) 15691 return 0; 15692 15693 /* There were no equivalent states, remember the current one. 15694 * Technically the current state is not proven to be safe yet, 15695 * but it will either reach outer most bpf_exit (which means it's safe) 15696 * or it will be rejected. When there are no loops the verifier won't be 15697 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 15698 * again on the way to bpf_exit. 15699 * When looping the sl->state.branches will be > 0 and this state 15700 * will not be considered for equivalence until branches == 0. 15701 */ 15702 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 15703 if (!new_sl) 15704 return -ENOMEM; 15705 env->total_states++; 15706 env->peak_states++; 15707 env->prev_jmps_processed = env->jmps_processed; 15708 env->prev_insn_processed = env->insn_processed; 15709 15710 /* forget precise markings we inherited, see __mark_chain_precision */ 15711 if (env->bpf_capable) 15712 mark_all_scalars_imprecise(env, cur); 15713 15714 /* add new state to the head of linked list */ 15715 new = &new_sl->state; 15716 err = copy_verifier_state(new, cur); 15717 if (err) { 15718 free_verifier_state(new, false); 15719 kfree(new_sl); 15720 return err; 15721 } 15722 new->insn_idx = insn_idx; 15723 WARN_ONCE(new->branches != 1, 15724 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 15725 15726 cur->parent = new; 15727 cur->first_insn_idx = insn_idx; 15728 clear_jmp_history(cur); 15729 new_sl->next = *explored_state(env, insn_idx); 15730 *explored_state(env, insn_idx) = new_sl; 15731 /* connect new state to parentage chain. Current frame needs all 15732 * registers connected. Only r6 - r9 of the callers are alive (pushed 15733 * to the stack implicitly by JITs) so in callers' frames connect just 15734 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 15735 * the state of the call instruction (with WRITTEN set), and r0 comes 15736 * from callee with its full parentage chain, anyway. 15737 */ 15738 /* clear write marks in current state: the writes we did are not writes 15739 * our child did, so they don't screen off its reads from us. 15740 * (There are no read marks in current state, because reads always mark 15741 * their parent and current state never has children yet. Only 15742 * explored_states can get read marks.) 15743 */ 15744 for (j = 0; j <= cur->curframe; j++) { 15745 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 15746 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 15747 for (i = 0; i < BPF_REG_FP; i++) 15748 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 15749 } 15750 15751 /* all stack frames are accessible from callee, clear them all */ 15752 for (j = 0; j <= cur->curframe; j++) { 15753 struct bpf_func_state *frame = cur->frame[j]; 15754 struct bpf_func_state *newframe = new->frame[j]; 15755 15756 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 15757 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 15758 frame->stack[i].spilled_ptr.parent = 15759 &newframe->stack[i].spilled_ptr; 15760 } 15761 } 15762 return 0; 15763 } 15764 15765 /* Return true if it's OK to have the same insn return a different type. */ 15766 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 15767 { 15768 switch (base_type(type)) { 15769 case PTR_TO_CTX: 15770 case PTR_TO_SOCKET: 15771 case PTR_TO_SOCK_COMMON: 15772 case PTR_TO_TCP_SOCK: 15773 case PTR_TO_XDP_SOCK: 15774 case PTR_TO_BTF_ID: 15775 return false; 15776 default: 15777 return true; 15778 } 15779 } 15780 15781 /* If an instruction was previously used with particular pointer types, then we 15782 * need to be careful to avoid cases such as the below, where it may be ok 15783 * for one branch accessing the pointer, but not ok for the other branch: 15784 * 15785 * R1 = sock_ptr 15786 * goto X; 15787 * ... 15788 * R1 = some_other_valid_ptr; 15789 * goto X; 15790 * ... 15791 * R2 = *(u32 *)(R1 + 0); 15792 */ 15793 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 15794 { 15795 return src != prev && (!reg_type_mismatch_ok(src) || 15796 !reg_type_mismatch_ok(prev)); 15797 } 15798 15799 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 15800 bool allow_trust_missmatch) 15801 { 15802 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 15803 15804 if (*prev_type == NOT_INIT) { 15805 /* Saw a valid insn 15806 * dst_reg = *(u32 *)(src_reg + off) 15807 * save type to validate intersecting paths 15808 */ 15809 *prev_type = type; 15810 } else if (reg_type_mismatch(type, *prev_type)) { 15811 /* Abuser program is trying to use the same insn 15812 * dst_reg = *(u32*) (src_reg + off) 15813 * with different pointer types: 15814 * src_reg == ctx in one branch and 15815 * src_reg == stack|map in some other branch. 15816 * Reject it. 15817 */ 15818 if (allow_trust_missmatch && 15819 base_type(type) == PTR_TO_BTF_ID && 15820 base_type(*prev_type) == PTR_TO_BTF_ID) { 15821 /* 15822 * Have to support a use case when one path through 15823 * the program yields TRUSTED pointer while another 15824 * is UNTRUSTED. Fallback to UNTRUSTED to generate 15825 * BPF_PROBE_MEM. 15826 */ 15827 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 15828 } else { 15829 verbose(env, "same insn cannot be used with different pointers\n"); 15830 return -EINVAL; 15831 } 15832 } 15833 15834 return 0; 15835 } 15836 15837 static int do_check(struct bpf_verifier_env *env) 15838 { 15839 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 15840 struct bpf_verifier_state *state = env->cur_state; 15841 struct bpf_insn *insns = env->prog->insnsi; 15842 struct bpf_reg_state *regs; 15843 int insn_cnt = env->prog->len; 15844 bool do_print_state = false; 15845 int prev_insn_idx = -1; 15846 15847 for (;;) { 15848 struct bpf_insn *insn; 15849 u8 class; 15850 int err; 15851 15852 env->prev_insn_idx = prev_insn_idx; 15853 if (env->insn_idx >= insn_cnt) { 15854 verbose(env, "invalid insn idx %d insn_cnt %d\n", 15855 env->insn_idx, insn_cnt); 15856 return -EFAULT; 15857 } 15858 15859 insn = &insns[env->insn_idx]; 15860 class = BPF_CLASS(insn->code); 15861 15862 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 15863 verbose(env, 15864 "BPF program is too large. Processed %d insn\n", 15865 env->insn_processed); 15866 return -E2BIG; 15867 } 15868 15869 state->last_insn_idx = env->prev_insn_idx; 15870 15871 if (is_prune_point(env, env->insn_idx)) { 15872 err = is_state_visited(env, env->insn_idx); 15873 if (err < 0) 15874 return err; 15875 if (err == 1) { 15876 /* found equivalent state, can prune the search */ 15877 if (env->log.level & BPF_LOG_LEVEL) { 15878 if (do_print_state) 15879 verbose(env, "\nfrom %d to %d%s: safe\n", 15880 env->prev_insn_idx, env->insn_idx, 15881 env->cur_state->speculative ? 15882 " (speculative execution)" : ""); 15883 else 15884 verbose(env, "%d: safe\n", env->insn_idx); 15885 } 15886 goto process_bpf_exit; 15887 } 15888 } 15889 15890 if (is_jmp_point(env, env->insn_idx)) { 15891 err = push_jmp_history(env, state); 15892 if (err) 15893 return err; 15894 } 15895 15896 if (signal_pending(current)) 15897 return -EAGAIN; 15898 15899 if (need_resched()) 15900 cond_resched(); 15901 15902 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 15903 verbose(env, "\nfrom %d to %d%s:", 15904 env->prev_insn_idx, env->insn_idx, 15905 env->cur_state->speculative ? 15906 " (speculative execution)" : ""); 15907 print_verifier_state(env, state->frame[state->curframe], true); 15908 do_print_state = false; 15909 } 15910 15911 if (env->log.level & BPF_LOG_LEVEL) { 15912 const struct bpf_insn_cbs cbs = { 15913 .cb_call = disasm_kfunc_name, 15914 .cb_print = verbose, 15915 .private_data = env, 15916 }; 15917 15918 if (verifier_state_scratched(env)) 15919 print_insn_state(env, state->frame[state->curframe]); 15920 15921 verbose_linfo(env, env->insn_idx, "; "); 15922 env->prev_log_pos = env->log.end_pos; 15923 verbose(env, "%d: ", env->insn_idx); 15924 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 15925 env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos; 15926 env->prev_log_pos = env->log.end_pos; 15927 } 15928 15929 if (bpf_prog_is_offloaded(env->prog->aux)) { 15930 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 15931 env->prev_insn_idx); 15932 if (err) 15933 return err; 15934 } 15935 15936 regs = cur_regs(env); 15937 sanitize_mark_insn_seen(env); 15938 prev_insn_idx = env->insn_idx; 15939 15940 if (class == BPF_ALU || class == BPF_ALU64) { 15941 err = check_alu_op(env, insn); 15942 if (err) 15943 return err; 15944 15945 } else if (class == BPF_LDX) { 15946 enum bpf_reg_type src_reg_type; 15947 15948 /* check for reserved fields is already done */ 15949 15950 /* check src operand */ 15951 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15952 if (err) 15953 return err; 15954 15955 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15956 if (err) 15957 return err; 15958 15959 src_reg_type = regs[insn->src_reg].type; 15960 15961 /* check that memory (src_reg + off) is readable, 15962 * the state of dst_reg will be updated by this func 15963 */ 15964 err = check_mem_access(env, env->insn_idx, insn->src_reg, 15965 insn->off, BPF_SIZE(insn->code), 15966 BPF_READ, insn->dst_reg, false); 15967 if (err) 15968 return err; 15969 15970 err = save_aux_ptr_type(env, src_reg_type, true); 15971 if (err) 15972 return err; 15973 } else if (class == BPF_STX) { 15974 enum bpf_reg_type dst_reg_type; 15975 15976 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 15977 err = check_atomic(env, env->insn_idx, insn); 15978 if (err) 15979 return err; 15980 env->insn_idx++; 15981 continue; 15982 } 15983 15984 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 15985 verbose(env, "BPF_STX uses reserved fields\n"); 15986 return -EINVAL; 15987 } 15988 15989 /* check src1 operand */ 15990 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15991 if (err) 15992 return err; 15993 /* check src2 operand */ 15994 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15995 if (err) 15996 return err; 15997 15998 dst_reg_type = regs[insn->dst_reg].type; 15999 16000 /* check that memory (dst_reg + off) is writeable */ 16001 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16002 insn->off, BPF_SIZE(insn->code), 16003 BPF_WRITE, insn->src_reg, false); 16004 if (err) 16005 return err; 16006 16007 err = save_aux_ptr_type(env, dst_reg_type, false); 16008 if (err) 16009 return err; 16010 } else if (class == BPF_ST) { 16011 enum bpf_reg_type dst_reg_type; 16012 16013 if (BPF_MODE(insn->code) != BPF_MEM || 16014 insn->src_reg != BPF_REG_0) { 16015 verbose(env, "BPF_ST uses reserved fields\n"); 16016 return -EINVAL; 16017 } 16018 /* check src operand */ 16019 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 16020 if (err) 16021 return err; 16022 16023 dst_reg_type = regs[insn->dst_reg].type; 16024 16025 /* check that memory (dst_reg + off) is writeable */ 16026 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 16027 insn->off, BPF_SIZE(insn->code), 16028 BPF_WRITE, -1, false); 16029 if (err) 16030 return err; 16031 16032 err = save_aux_ptr_type(env, dst_reg_type, false); 16033 if (err) 16034 return err; 16035 } else if (class == BPF_JMP || class == BPF_JMP32) { 16036 u8 opcode = BPF_OP(insn->code); 16037 16038 env->jmps_processed++; 16039 if (opcode == BPF_CALL) { 16040 if (BPF_SRC(insn->code) != BPF_K || 16041 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 16042 && insn->off != 0) || 16043 (insn->src_reg != BPF_REG_0 && 16044 insn->src_reg != BPF_PSEUDO_CALL && 16045 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 16046 insn->dst_reg != BPF_REG_0 || 16047 class == BPF_JMP32) { 16048 verbose(env, "BPF_CALL uses reserved fields\n"); 16049 return -EINVAL; 16050 } 16051 16052 if (env->cur_state->active_lock.ptr) { 16053 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 16054 (insn->src_reg == BPF_PSEUDO_CALL) || 16055 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 16056 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 16057 verbose(env, "function calls are not allowed while holding a lock\n"); 16058 return -EINVAL; 16059 } 16060 } 16061 if (insn->src_reg == BPF_PSEUDO_CALL) 16062 err = check_func_call(env, insn, &env->insn_idx); 16063 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 16064 err = check_kfunc_call(env, insn, &env->insn_idx); 16065 else 16066 err = check_helper_call(env, insn, &env->insn_idx); 16067 if (err) 16068 return err; 16069 16070 mark_reg_scratched(env, BPF_REG_0); 16071 } else if (opcode == BPF_JA) { 16072 if (BPF_SRC(insn->code) != BPF_K || 16073 insn->imm != 0 || 16074 insn->src_reg != BPF_REG_0 || 16075 insn->dst_reg != BPF_REG_0 || 16076 class == BPF_JMP32) { 16077 verbose(env, "BPF_JA uses reserved fields\n"); 16078 return -EINVAL; 16079 } 16080 16081 env->insn_idx += insn->off + 1; 16082 continue; 16083 16084 } else if (opcode == BPF_EXIT) { 16085 if (BPF_SRC(insn->code) != BPF_K || 16086 insn->imm != 0 || 16087 insn->src_reg != BPF_REG_0 || 16088 insn->dst_reg != BPF_REG_0 || 16089 class == BPF_JMP32) { 16090 verbose(env, "BPF_EXIT uses reserved fields\n"); 16091 return -EINVAL; 16092 } 16093 16094 if (env->cur_state->active_lock.ptr && 16095 !in_rbtree_lock_required_cb(env)) { 16096 verbose(env, "bpf_spin_unlock is missing\n"); 16097 return -EINVAL; 16098 } 16099 16100 if (env->cur_state->active_rcu_lock) { 16101 verbose(env, "bpf_rcu_read_unlock is missing\n"); 16102 return -EINVAL; 16103 } 16104 16105 /* We must do check_reference_leak here before 16106 * prepare_func_exit to handle the case when 16107 * state->curframe > 0, it may be a callback 16108 * function, for which reference_state must 16109 * match caller reference state when it exits. 16110 */ 16111 err = check_reference_leak(env); 16112 if (err) 16113 return err; 16114 16115 if (state->curframe) { 16116 /* exit from nested function */ 16117 err = prepare_func_exit(env, &env->insn_idx); 16118 if (err) 16119 return err; 16120 do_print_state = true; 16121 continue; 16122 } 16123 16124 err = check_return_code(env); 16125 if (err) 16126 return err; 16127 process_bpf_exit: 16128 mark_verifier_state_scratched(env); 16129 update_branch_counts(env, env->cur_state); 16130 err = pop_stack(env, &prev_insn_idx, 16131 &env->insn_idx, pop_log); 16132 if (err < 0) { 16133 if (err != -ENOENT) 16134 return err; 16135 break; 16136 } else { 16137 do_print_state = true; 16138 continue; 16139 } 16140 } else { 16141 err = check_cond_jmp_op(env, insn, &env->insn_idx); 16142 if (err) 16143 return err; 16144 } 16145 } else if (class == BPF_LD) { 16146 u8 mode = BPF_MODE(insn->code); 16147 16148 if (mode == BPF_ABS || mode == BPF_IND) { 16149 err = check_ld_abs(env, insn); 16150 if (err) 16151 return err; 16152 16153 } else if (mode == BPF_IMM) { 16154 err = check_ld_imm(env, insn); 16155 if (err) 16156 return err; 16157 16158 env->insn_idx++; 16159 sanitize_mark_insn_seen(env); 16160 } else { 16161 verbose(env, "invalid BPF_LD mode\n"); 16162 return -EINVAL; 16163 } 16164 } else { 16165 verbose(env, "unknown insn class %d\n", class); 16166 return -EINVAL; 16167 } 16168 16169 env->insn_idx++; 16170 } 16171 16172 return 0; 16173 } 16174 16175 static int find_btf_percpu_datasec(struct btf *btf) 16176 { 16177 const struct btf_type *t; 16178 const char *tname; 16179 int i, n; 16180 16181 /* 16182 * Both vmlinux and module each have their own ".data..percpu" 16183 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 16184 * types to look at only module's own BTF types. 16185 */ 16186 n = btf_nr_types(btf); 16187 if (btf_is_module(btf)) 16188 i = btf_nr_types(btf_vmlinux); 16189 else 16190 i = 1; 16191 16192 for(; i < n; i++) { 16193 t = btf_type_by_id(btf, i); 16194 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 16195 continue; 16196 16197 tname = btf_name_by_offset(btf, t->name_off); 16198 if (!strcmp(tname, ".data..percpu")) 16199 return i; 16200 } 16201 16202 return -ENOENT; 16203 } 16204 16205 /* replace pseudo btf_id with kernel symbol address */ 16206 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 16207 struct bpf_insn *insn, 16208 struct bpf_insn_aux_data *aux) 16209 { 16210 const struct btf_var_secinfo *vsi; 16211 const struct btf_type *datasec; 16212 struct btf_mod_pair *btf_mod; 16213 const struct btf_type *t; 16214 const char *sym_name; 16215 bool percpu = false; 16216 u32 type, id = insn->imm; 16217 struct btf *btf; 16218 s32 datasec_id; 16219 u64 addr; 16220 int i, btf_fd, err; 16221 16222 btf_fd = insn[1].imm; 16223 if (btf_fd) { 16224 btf = btf_get_by_fd(btf_fd); 16225 if (IS_ERR(btf)) { 16226 verbose(env, "invalid module BTF object FD specified.\n"); 16227 return -EINVAL; 16228 } 16229 } else { 16230 if (!btf_vmlinux) { 16231 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 16232 return -EINVAL; 16233 } 16234 btf = btf_vmlinux; 16235 btf_get(btf); 16236 } 16237 16238 t = btf_type_by_id(btf, id); 16239 if (!t) { 16240 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 16241 err = -ENOENT; 16242 goto err_put; 16243 } 16244 16245 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 16246 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 16247 err = -EINVAL; 16248 goto err_put; 16249 } 16250 16251 sym_name = btf_name_by_offset(btf, t->name_off); 16252 addr = kallsyms_lookup_name(sym_name); 16253 if (!addr) { 16254 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 16255 sym_name); 16256 err = -ENOENT; 16257 goto err_put; 16258 } 16259 insn[0].imm = (u32)addr; 16260 insn[1].imm = addr >> 32; 16261 16262 if (btf_type_is_func(t)) { 16263 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 16264 aux->btf_var.mem_size = 0; 16265 goto check_btf; 16266 } 16267 16268 datasec_id = find_btf_percpu_datasec(btf); 16269 if (datasec_id > 0) { 16270 datasec = btf_type_by_id(btf, datasec_id); 16271 for_each_vsi(i, datasec, vsi) { 16272 if (vsi->type == id) { 16273 percpu = true; 16274 break; 16275 } 16276 } 16277 } 16278 16279 type = t->type; 16280 t = btf_type_skip_modifiers(btf, type, NULL); 16281 if (percpu) { 16282 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 16283 aux->btf_var.btf = btf; 16284 aux->btf_var.btf_id = type; 16285 } else if (!btf_type_is_struct(t)) { 16286 const struct btf_type *ret; 16287 const char *tname; 16288 u32 tsize; 16289 16290 /* resolve the type size of ksym. */ 16291 ret = btf_resolve_size(btf, t, &tsize); 16292 if (IS_ERR(ret)) { 16293 tname = btf_name_by_offset(btf, t->name_off); 16294 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 16295 tname, PTR_ERR(ret)); 16296 err = -EINVAL; 16297 goto err_put; 16298 } 16299 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 16300 aux->btf_var.mem_size = tsize; 16301 } else { 16302 aux->btf_var.reg_type = PTR_TO_BTF_ID; 16303 aux->btf_var.btf = btf; 16304 aux->btf_var.btf_id = type; 16305 } 16306 check_btf: 16307 /* check whether we recorded this BTF (and maybe module) already */ 16308 for (i = 0; i < env->used_btf_cnt; i++) { 16309 if (env->used_btfs[i].btf == btf) { 16310 btf_put(btf); 16311 return 0; 16312 } 16313 } 16314 16315 if (env->used_btf_cnt >= MAX_USED_BTFS) { 16316 err = -E2BIG; 16317 goto err_put; 16318 } 16319 16320 btf_mod = &env->used_btfs[env->used_btf_cnt]; 16321 btf_mod->btf = btf; 16322 btf_mod->module = NULL; 16323 16324 /* if we reference variables from kernel module, bump its refcount */ 16325 if (btf_is_module(btf)) { 16326 btf_mod->module = btf_try_get_module(btf); 16327 if (!btf_mod->module) { 16328 err = -ENXIO; 16329 goto err_put; 16330 } 16331 } 16332 16333 env->used_btf_cnt++; 16334 16335 return 0; 16336 err_put: 16337 btf_put(btf); 16338 return err; 16339 } 16340 16341 static bool is_tracing_prog_type(enum bpf_prog_type type) 16342 { 16343 switch (type) { 16344 case BPF_PROG_TYPE_KPROBE: 16345 case BPF_PROG_TYPE_TRACEPOINT: 16346 case BPF_PROG_TYPE_PERF_EVENT: 16347 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16348 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 16349 return true; 16350 default: 16351 return false; 16352 } 16353 } 16354 16355 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 16356 struct bpf_map *map, 16357 struct bpf_prog *prog) 16358 16359 { 16360 enum bpf_prog_type prog_type = resolve_prog_type(prog); 16361 16362 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 16363 btf_record_has_field(map->record, BPF_RB_ROOT)) { 16364 if (is_tracing_prog_type(prog_type)) { 16365 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 16366 return -EINVAL; 16367 } 16368 } 16369 16370 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 16371 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 16372 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 16373 return -EINVAL; 16374 } 16375 16376 if (is_tracing_prog_type(prog_type)) { 16377 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 16378 return -EINVAL; 16379 } 16380 16381 if (prog->aux->sleepable) { 16382 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 16383 return -EINVAL; 16384 } 16385 } 16386 16387 if (btf_record_has_field(map->record, BPF_TIMER)) { 16388 if (is_tracing_prog_type(prog_type)) { 16389 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 16390 return -EINVAL; 16391 } 16392 } 16393 16394 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 16395 !bpf_offload_prog_map_match(prog, map)) { 16396 verbose(env, "offload device mismatch between prog and map\n"); 16397 return -EINVAL; 16398 } 16399 16400 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 16401 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 16402 return -EINVAL; 16403 } 16404 16405 if (prog->aux->sleepable) 16406 switch (map->map_type) { 16407 case BPF_MAP_TYPE_HASH: 16408 case BPF_MAP_TYPE_LRU_HASH: 16409 case BPF_MAP_TYPE_ARRAY: 16410 case BPF_MAP_TYPE_PERCPU_HASH: 16411 case BPF_MAP_TYPE_PERCPU_ARRAY: 16412 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 16413 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 16414 case BPF_MAP_TYPE_HASH_OF_MAPS: 16415 case BPF_MAP_TYPE_RINGBUF: 16416 case BPF_MAP_TYPE_USER_RINGBUF: 16417 case BPF_MAP_TYPE_INODE_STORAGE: 16418 case BPF_MAP_TYPE_SK_STORAGE: 16419 case BPF_MAP_TYPE_TASK_STORAGE: 16420 case BPF_MAP_TYPE_CGRP_STORAGE: 16421 break; 16422 default: 16423 verbose(env, 16424 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 16425 return -EINVAL; 16426 } 16427 16428 return 0; 16429 } 16430 16431 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 16432 { 16433 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 16434 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 16435 } 16436 16437 /* find and rewrite pseudo imm in ld_imm64 instructions: 16438 * 16439 * 1. if it accesses map FD, replace it with actual map pointer. 16440 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 16441 * 16442 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 16443 */ 16444 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 16445 { 16446 struct bpf_insn *insn = env->prog->insnsi; 16447 int insn_cnt = env->prog->len; 16448 int i, j, err; 16449 16450 err = bpf_prog_calc_tag(env->prog); 16451 if (err) 16452 return err; 16453 16454 for (i = 0; i < insn_cnt; i++, insn++) { 16455 if (BPF_CLASS(insn->code) == BPF_LDX && 16456 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 16457 verbose(env, "BPF_LDX uses reserved fields\n"); 16458 return -EINVAL; 16459 } 16460 16461 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 16462 struct bpf_insn_aux_data *aux; 16463 struct bpf_map *map; 16464 struct fd f; 16465 u64 addr; 16466 u32 fd; 16467 16468 if (i == insn_cnt - 1 || insn[1].code != 0 || 16469 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 16470 insn[1].off != 0) { 16471 verbose(env, "invalid bpf_ld_imm64 insn\n"); 16472 return -EINVAL; 16473 } 16474 16475 if (insn[0].src_reg == 0) 16476 /* valid generic load 64-bit imm */ 16477 goto next_insn; 16478 16479 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 16480 aux = &env->insn_aux_data[i]; 16481 err = check_pseudo_btf_id(env, insn, aux); 16482 if (err) 16483 return err; 16484 goto next_insn; 16485 } 16486 16487 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 16488 aux = &env->insn_aux_data[i]; 16489 aux->ptr_type = PTR_TO_FUNC; 16490 goto next_insn; 16491 } 16492 16493 /* In final convert_pseudo_ld_imm64() step, this is 16494 * converted into regular 64-bit imm load insn. 16495 */ 16496 switch (insn[0].src_reg) { 16497 case BPF_PSEUDO_MAP_VALUE: 16498 case BPF_PSEUDO_MAP_IDX_VALUE: 16499 break; 16500 case BPF_PSEUDO_MAP_FD: 16501 case BPF_PSEUDO_MAP_IDX: 16502 if (insn[1].imm == 0) 16503 break; 16504 fallthrough; 16505 default: 16506 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 16507 return -EINVAL; 16508 } 16509 16510 switch (insn[0].src_reg) { 16511 case BPF_PSEUDO_MAP_IDX_VALUE: 16512 case BPF_PSEUDO_MAP_IDX: 16513 if (bpfptr_is_null(env->fd_array)) { 16514 verbose(env, "fd_idx without fd_array is invalid\n"); 16515 return -EPROTO; 16516 } 16517 if (copy_from_bpfptr_offset(&fd, env->fd_array, 16518 insn[0].imm * sizeof(fd), 16519 sizeof(fd))) 16520 return -EFAULT; 16521 break; 16522 default: 16523 fd = insn[0].imm; 16524 break; 16525 } 16526 16527 f = fdget(fd); 16528 map = __bpf_map_get(f); 16529 if (IS_ERR(map)) { 16530 verbose(env, "fd %d is not pointing to valid bpf_map\n", 16531 insn[0].imm); 16532 return PTR_ERR(map); 16533 } 16534 16535 err = check_map_prog_compatibility(env, map, env->prog); 16536 if (err) { 16537 fdput(f); 16538 return err; 16539 } 16540 16541 aux = &env->insn_aux_data[i]; 16542 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 16543 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 16544 addr = (unsigned long)map; 16545 } else { 16546 u32 off = insn[1].imm; 16547 16548 if (off >= BPF_MAX_VAR_OFF) { 16549 verbose(env, "direct value offset of %u is not allowed\n", off); 16550 fdput(f); 16551 return -EINVAL; 16552 } 16553 16554 if (!map->ops->map_direct_value_addr) { 16555 verbose(env, "no direct value access support for this map type\n"); 16556 fdput(f); 16557 return -EINVAL; 16558 } 16559 16560 err = map->ops->map_direct_value_addr(map, &addr, off); 16561 if (err) { 16562 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 16563 map->value_size, off); 16564 fdput(f); 16565 return err; 16566 } 16567 16568 aux->map_off = off; 16569 addr += off; 16570 } 16571 16572 insn[0].imm = (u32)addr; 16573 insn[1].imm = addr >> 32; 16574 16575 /* check whether we recorded this map already */ 16576 for (j = 0; j < env->used_map_cnt; j++) { 16577 if (env->used_maps[j] == map) { 16578 aux->map_index = j; 16579 fdput(f); 16580 goto next_insn; 16581 } 16582 } 16583 16584 if (env->used_map_cnt >= MAX_USED_MAPS) { 16585 fdput(f); 16586 return -E2BIG; 16587 } 16588 16589 /* hold the map. If the program is rejected by verifier, 16590 * the map will be released by release_maps() or it 16591 * will be used by the valid program until it's unloaded 16592 * and all maps are released in free_used_maps() 16593 */ 16594 bpf_map_inc(map); 16595 16596 aux->map_index = env->used_map_cnt; 16597 env->used_maps[env->used_map_cnt++] = map; 16598 16599 if (bpf_map_is_cgroup_storage(map) && 16600 bpf_cgroup_storage_assign(env->prog->aux, map)) { 16601 verbose(env, "only one cgroup storage of each type is allowed\n"); 16602 fdput(f); 16603 return -EBUSY; 16604 } 16605 16606 fdput(f); 16607 next_insn: 16608 insn++; 16609 i++; 16610 continue; 16611 } 16612 16613 /* Basic sanity check before we invest more work here. */ 16614 if (!bpf_opcode_in_insntable(insn->code)) { 16615 verbose(env, "unknown opcode %02x\n", insn->code); 16616 return -EINVAL; 16617 } 16618 } 16619 16620 /* now all pseudo BPF_LD_IMM64 instructions load valid 16621 * 'struct bpf_map *' into a register instead of user map_fd. 16622 * These pointers will be used later by verifier to validate map access. 16623 */ 16624 return 0; 16625 } 16626 16627 /* drop refcnt of maps used by the rejected program */ 16628 static void release_maps(struct bpf_verifier_env *env) 16629 { 16630 __bpf_free_used_maps(env->prog->aux, env->used_maps, 16631 env->used_map_cnt); 16632 } 16633 16634 /* drop refcnt of maps used by the rejected program */ 16635 static void release_btfs(struct bpf_verifier_env *env) 16636 { 16637 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 16638 env->used_btf_cnt); 16639 } 16640 16641 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 16642 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 16643 { 16644 struct bpf_insn *insn = env->prog->insnsi; 16645 int insn_cnt = env->prog->len; 16646 int i; 16647 16648 for (i = 0; i < insn_cnt; i++, insn++) { 16649 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 16650 continue; 16651 if (insn->src_reg == BPF_PSEUDO_FUNC) 16652 continue; 16653 insn->src_reg = 0; 16654 } 16655 } 16656 16657 /* single env->prog->insni[off] instruction was replaced with the range 16658 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 16659 * [0, off) and [off, end) to new locations, so the patched range stays zero 16660 */ 16661 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 16662 struct bpf_insn_aux_data *new_data, 16663 struct bpf_prog *new_prog, u32 off, u32 cnt) 16664 { 16665 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 16666 struct bpf_insn *insn = new_prog->insnsi; 16667 u32 old_seen = old_data[off].seen; 16668 u32 prog_len; 16669 int i; 16670 16671 /* aux info at OFF always needs adjustment, no matter fast path 16672 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 16673 * original insn at old prog. 16674 */ 16675 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 16676 16677 if (cnt == 1) 16678 return; 16679 prog_len = new_prog->len; 16680 16681 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 16682 memcpy(new_data + off + cnt - 1, old_data + off, 16683 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 16684 for (i = off; i < off + cnt - 1; i++) { 16685 /* Expand insni[off]'s seen count to the patched range. */ 16686 new_data[i].seen = old_seen; 16687 new_data[i].zext_dst = insn_has_def32(env, insn + i); 16688 } 16689 env->insn_aux_data = new_data; 16690 vfree(old_data); 16691 } 16692 16693 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 16694 { 16695 int i; 16696 16697 if (len == 1) 16698 return; 16699 /* NOTE: fake 'exit' subprog should be updated as well. */ 16700 for (i = 0; i <= env->subprog_cnt; i++) { 16701 if (env->subprog_info[i].start <= off) 16702 continue; 16703 env->subprog_info[i].start += len - 1; 16704 } 16705 } 16706 16707 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 16708 { 16709 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 16710 int i, sz = prog->aux->size_poke_tab; 16711 struct bpf_jit_poke_descriptor *desc; 16712 16713 for (i = 0; i < sz; i++) { 16714 desc = &tab[i]; 16715 if (desc->insn_idx <= off) 16716 continue; 16717 desc->insn_idx += len - 1; 16718 } 16719 } 16720 16721 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 16722 const struct bpf_insn *patch, u32 len) 16723 { 16724 struct bpf_prog *new_prog; 16725 struct bpf_insn_aux_data *new_data = NULL; 16726 16727 if (len > 1) { 16728 new_data = vzalloc(array_size(env->prog->len + len - 1, 16729 sizeof(struct bpf_insn_aux_data))); 16730 if (!new_data) 16731 return NULL; 16732 } 16733 16734 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 16735 if (IS_ERR(new_prog)) { 16736 if (PTR_ERR(new_prog) == -ERANGE) 16737 verbose(env, 16738 "insn %d cannot be patched due to 16-bit range\n", 16739 env->insn_aux_data[off].orig_idx); 16740 vfree(new_data); 16741 return NULL; 16742 } 16743 adjust_insn_aux_data(env, new_data, new_prog, off, len); 16744 adjust_subprog_starts(env, off, len); 16745 adjust_poke_descs(new_prog, off, len); 16746 return new_prog; 16747 } 16748 16749 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 16750 u32 off, u32 cnt) 16751 { 16752 int i, j; 16753 16754 /* find first prog starting at or after off (first to remove) */ 16755 for (i = 0; i < env->subprog_cnt; i++) 16756 if (env->subprog_info[i].start >= off) 16757 break; 16758 /* find first prog starting at or after off + cnt (first to stay) */ 16759 for (j = i; j < env->subprog_cnt; j++) 16760 if (env->subprog_info[j].start >= off + cnt) 16761 break; 16762 /* if j doesn't start exactly at off + cnt, we are just removing 16763 * the front of previous prog 16764 */ 16765 if (env->subprog_info[j].start != off + cnt) 16766 j--; 16767 16768 if (j > i) { 16769 struct bpf_prog_aux *aux = env->prog->aux; 16770 int move; 16771 16772 /* move fake 'exit' subprog as well */ 16773 move = env->subprog_cnt + 1 - j; 16774 16775 memmove(env->subprog_info + i, 16776 env->subprog_info + j, 16777 sizeof(*env->subprog_info) * move); 16778 env->subprog_cnt -= j - i; 16779 16780 /* remove func_info */ 16781 if (aux->func_info) { 16782 move = aux->func_info_cnt - j; 16783 16784 memmove(aux->func_info + i, 16785 aux->func_info + j, 16786 sizeof(*aux->func_info) * move); 16787 aux->func_info_cnt -= j - i; 16788 /* func_info->insn_off is set after all code rewrites, 16789 * in adjust_btf_func() - no need to adjust 16790 */ 16791 } 16792 } else { 16793 /* convert i from "first prog to remove" to "first to adjust" */ 16794 if (env->subprog_info[i].start == off) 16795 i++; 16796 } 16797 16798 /* update fake 'exit' subprog as well */ 16799 for (; i <= env->subprog_cnt; i++) 16800 env->subprog_info[i].start -= cnt; 16801 16802 return 0; 16803 } 16804 16805 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 16806 u32 cnt) 16807 { 16808 struct bpf_prog *prog = env->prog; 16809 u32 i, l_off, l_cnt, nr_linfo; 16810 struct bpf_line_info *linfo; 16811 16812 nr_linfo = prog->aux->nr_linfo; 16813 if (!nr_linfo) 16814 return 0; 16815 16816 linfo = prog->aux->linfo; 16817 16818 /* find first line info to remove, count lines to be removed */ 16819 for (i = 0; i < nr_linfo; i++) 16820 if (linfo[i].insn_off >= off) 16821 break; 16822 16823 l_off = i; 16824 l_cnt = 0; 16825 for (; i < nr_linfo; i++) 16826 if (linfo[i].insn_off < off + cnt) 16827 l_cnt++; 16828 else 16829 break; 16830 16831 /* First live insn doesn't match first live linfo, it needs to "inherit" 16832 * last removed linfo. prog is already modified, so prog->len == off 16833 * means no live instructions after (tail of the program was removed). 16834 */ 16835 if (prog->len != off && l_cnt && 16836 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 16837 l_cnt--; 16838 linfo[--i].insn_off = off + cnt; 16839 } 16840 16841 /* remove the line info which refer to the removed instructions */ 16842 if (l_cnt) { 16843 memmove(linfo + l_off, linfo + i, 16844 sizeof(*linfo) * (nr_linfo - i)); 16845 16846 prog->aux->nr_linfo -= l_cnt; 16847 nr_linfo = prog->aux->nr_linfo; 16848 } 16849 16850 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 16851 for (i = l_off; i < nr_linfo; i++) 16852 linfo[i].insn_off -= cnt; 16853 16854 /* fix up all subprogs (incl. 'exit') which start >= off */ 16855 for (i = 0; i <= env->subprog_cnt; i++) 16856 if (env->subprog_info[i].linfo_idx > l_off) { 16857 /* program may have started in the removed region but 16858 * may not be fully removed 16859 */ 16860 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 16861 env->subprog_info[i].linfo_idx -= l_cnt; 16862 else 16863 env->subprog_info[i].linfo_idx = l_off; 16864 } 16865 16866 return 0; 16867 } 16868 16869 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 16870 { 16871 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 16872 unsigned int orig_prog_len = env->prog->len; 16873 int err; 16874 16875 if (bpf_prog_is_offloaded(env->prog->aux)) 16876 bpf_prog_offload_remove_insns(env, off, cnt); 16877 16878 err = bpf_remove_insns(env->prog, off, cnt); 16879 if (err) 16880 return err; 16881 16882 err = adjust_subprog_starts_after_remove(env, off, cnt); 16883 if (err) 16884 return err; 16885 16886 err = bpf_adj_linfo_after_remove(env, off, cnt); 16887 if (err) 16888 return err; 16889 16890 memmove(aux_data + off, aux_data + off + cnt, 16891 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 16892 16893 return 0; 16894 } 16895 16896 /* The verifier does more data flow analysis than llvm and will not 16897 * explore branches that are dead at run time. Malicious programs can 16898 * have dead code too. Therefore replace all dead at-run-time code 16899 * with 'ja -1'. 16900 * 16901 * Just nops are not optimal, e.g. if they would sit at the end of the 16902 * program and through another bug we would manage to jump there, then 16903 * we'd execute beyond program memory otherwise. Returning exception 16904 * code also wouldn't work since we can have subprogs where the dead 16905 * code could be located. 16906 */ 16907 static void sanitize_dead_code(struct bpf_verifier_env *env) 16908 { 16909 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 16910 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 16911 struct bpf_insn *insn = env->prog->insnsi; 16912 const int insn_cnt = env->prog->len; 16913 int i; 16914 16915 for (i = 0; i < insn_cnt; i++) { 16916 if (aux_data[i].seen) 16917 continue; 16918 memcpy(insn + i, &trap, sizeof(trap)); 16919 aux_data[i].zext_dst = false; 16920 } 16921 } 16922 16923 static bool insn_is_cond_jump(u8 code) 16924 { 16925 u8 op; 16926 16927 if (BPF_CLASS(code) == BPF_JMP32) 16928 return true; 16929 16930 if (BPF_CLASS(code) != BPF_JMP) 16931 return false; 16932 16933 op = BPF_OP(code); 16934 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 16935 } 16936 16937 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 16938 { 16939 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 16940 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 16941 struct bpf_insn *insn = env->prog->insnsi; 16942 const int insn_cnt = env->prog->len; 16943 int i; 16944 16945 for (i = 0; i < insn_cnt; i++, insn++) { 16946 if (!insn_is_cond_jump(insn->code)) 16947 continue; 16948 16949 if (!aux_data[i + 1].seen) 16950 ja.off = insn->off; 16951 else if (!aux_data[i + 1 + insn->off].seen) 16952 ja.off = 0; 16953 else 16954 continue; 16955 16956 if (bpf_prog_is_offloaded(env->prog->aux)) 16957 bpf_prog_offload_replace_insn(env, i, &ja); 16958 16959 memcpy(insn, &ja, sizeof(ja)); 16960 } 16961 } 16962 16963 static int opt_remove_dead_code(struct bpf_verifier_env *env) 16964 { 16965 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 16966 int insn_cnt = env->prog->len; 16967 int i, err; 16968 16969 for (i = 0; i < insn_cnt; i++) { 16970 int j; 16971 16972 j = 0; 16973 while (i + j < insn_cnt && !aux_data[i + j].seen) 16974 j++; 16975 if (!j) 16976 continue; 16977 16978 err = verifier_remove_insns(env, i, j); 16979 if (err) 16980 return err; 16981 insn_cnt = env->prog->len; 16982 } 16983 16984 return 0; 16985 } 16986 16987 static int opt_remove_nops(struct bpf_verifier_env *env) 16988 { 16989 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 16990 struct bpf_insn *insn = env->prog->insnsi; 16991 int insn_cnt = env->prog->len; 16992 int i, err; 16993 16994 for (i = 0; i < insn_cnt; i++) { 16995 if (memcmp(&insn[i], &ja, sizeof(ja))) 16996 continue; 16997 16998 err = verifier_remove_insns(env, i, 1); 16999 if (err) 17000 return err; 17001 insn_cnt--; 17002 i--; 17003 } 17004 17005 return 0; 17006 } 17007 17008 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 17009 const union bpf_attr *attr) 17010 { 17011 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 17012 struct bpf_insn_aux_data *aux = env->insn_aux_data; 17013 int i, patch_len, delta = 0, len = env->prog->len; 17014 struct bpf_insn *insns = env->prog->insnsi; 17015 struct bpf_prog *new_prog; 17016 bool rnd_hi32; 17017 17018 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 17019 zext_patch[1] = BPF_ZEXT_REG(0); 17020 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 17021 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 17022 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 17023 for (i = 0; i < len; i++) { 17024 int adj_idx = i + delta; 17025 struct bpf_insn insn; 17026 int load_reg; 17027 17028 insn = insns[adj_idx]; 17029 load_reg = insn_def_regno(&insn); 17030 if (!aux[adj_idx].zext_dst) { 17031 u8 code, class; 17032 u32 imm_rnd; 17033 17034 if (!rnd_hi32) 17035 continue; 17036 17037 code = insn.code; 17038 class = BPF_CLASS(code); 17039 if (load_reg == -1) 17040 continue; 17041 17042 /* NOTE: arg "reg" (the fourth one) is only used for 17043 * BPF_STX + SRC_OP, so it is safe to pass NULL 17044 * here. 17045 */ 17046 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 17047 if (class == BPF_LD && 17048 BPF_MODE(code) == BPF_IMM) 17049 i++; 17050 continue; 17051 } 17052 17053 /* ctx load could be transformed into wider load. */ 17054 if (class == BPF_LDX && 17055 aux[adj_idx].ptr_type == PTR_TO_CTX) 17056 continue; 17057 17058 imm_rnd = get_random_u32(); 17059 rnd_hi32_patch[0] = insn; 17060 rnd_hi32_patch[1].imm = imm_rnd; 17061 rnd_hi32_patch[3].dst_reg = load_reg; 17062 patch = rnd_hi32_patch; 17063 patch_len = 4; 17064 goto apply_patch_buffer; 17065 } 17066 17067 /* Add in an zero-extend instruction if a) the JIT has requested 17068 * it or b) it's a CMPXCHG. 17069 * 17070 * The latter is because: BPF_CMPXCHG always loads a value into 17071 * R0, therefore always zero-extends. However some archs' 17072 * equivalent instruction only does this load when the 17073 * comparison is successful. This detail of CMPXCHG is 17074 * orthogonal to the general zero-extension behaviour of the 17075 * CPU, so it's treated independently of bpf_jit_needs_zext. 17076 */ 17077 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 17078 continue; 17079 17080 /* Zero-extension is done by the caller. */ 17081 if (bpf_pseudo_kfunc_call(&insn)) 17082 continue; 17083 17084 if (WARN_ON(load_reg == -1)) { 17085 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 17086 return -EFAULT; 17087 } 17088 17089 zext_patch[0] = insn; 17090 zext_patch[1].dst_reg = load_reg; 17091 zext_patch[1].src_reg = load_reg; 17092 patch = zext_patch; 17093 patch_len = 2; 17094 apply_patch_buffer: 17095 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 17096 if (!new_prog) 17097 return -ENOMEM; 17098 env->prog = new_prog; 17099 insns = new_prog->insnsi; 17100 aux = env->insn_aux_data; 17101 delta += patch_len - 1; 17102 } 17103 17104 return 0; 17105 } 17106 17107 /* convert load instructions that access fields of a context type into a 17108 * sequence of instructions that access fields of the underlying structure: 17109 * struct __sk_buff -> struct sk_buff 17110 * struct bpf_sock_ops -> struct sock 17111 */ 17112 static int convert_ctx_accesses(struct bpf_verifier_env *env) 17113 { 17114 const struct bpf_verifier_ops *ops = env->ops; 17115 int i, cnt, size, ctx_field_size, delta = 0; 17116 const int insn_cnt = env->prog->len; 17117 struct bpf_insn insn_buf[16], *insn; 17118 u32 target_size, size_default, off; 17119 struct bpf_prog *new_prog; 17120 enum bpf_access_type type; 17121 bool is_narrower_load; 17122 17123 if (ops->gen_prologue || env->seen_direct_write) { 17124 if (!ops->gen_prologue) { 17125 verbose(env, "bpf verifier is misconfigured\n"); 17126 return -EINVAL; 17127 } 17128 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 17129 env->prog); 17130 if (cnt >= ARRAY_SIZE(insn_buf)) { 17131 verbose(env, "bpf verifier is misconfigured\n"); 17132 return -EINVAL; 17133 } else if (cnt) { 17134 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 17135 if (!new_prog) 17136 return -ENOMEM; 17137 17138 env->prog = new_prog; 17139 delta += cnt - 1; 17140 } 17141 } 17142 17143 if (bpf_prog_is_offloaded(env->prog->aux)) 17144 return 0; 17145 17146 insn = env->prog->insnsi + delta; 17147 17148 for (i = 0; i < insn_cnt; i++, insn++) { 17149 bpf_convert_ctx_access_t convert_ctx_access; 17150 17151 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 17152 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 17153 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 17154 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) { 17155 type = BPF_READ; 17156 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 17157 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 17158 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 17159 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 17160 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 17161 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 17162 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 17163 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 17164 type = BPF_WRITE; 17165 } else { 17166 continue; 17167 } 17168 17169 if (type == BPF_WRITE && 17170 env->insn_aux_data[i + delta].sanitize_stack_spill) { 17171 struct bpf_insn patch[] = { 17172 *insn, 17173 BPF_ST_NOSPEC(), 17174 }; 17175 17176 cnt = ARRAY_SIZE(patch); 17177 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 17178 if (!new_prog) 17179 return -ENOMEM; 17180 17181 delta += cnt - 1; 17182 env->prog = new_prog; 17183 insn = new_prog->insnsi + i + delta; 17184 continue; 17185 } 17186 17187 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 17188 case PTR_TO_CTX: 17189 if (!ops->convert_ctx_access) 17190 continue; 17191 convert_ctx_access = ops->convert_ctx_access; 17192 break; 17193 case PTR_TO_SOCKET: 17194 case PTR_TO_SOCK_COMMON: 17195 convert_ctx_access = bpf_sock_convert_ctx_access; 17196 break; 17197 case PTR_TO_TCP_SOCK: 17198 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 17199 break; 17200 case PTR_TO_XDP_SOCK: 17201 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 17202 break; 17203 case PTR_TO_BTF_ID: 17204 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 17205 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 17206 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 17207 * be said once it is marked PTR_UNTRUSTED, hence we must handle 17208 * any faults for loads into such types. BPF_WRITE is disallowed 17209 * for this case. 17210 */ 17211 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 17212 if (type == BPF_READ) { 17213 insn->code = BPF_LDX | BPF_PROBE_MEM | 17214 BPF_SIZE((insn)->code); 17215 env->prog->aux->num_exentries++; 17216 } 17217 continue; 17218 default: 17219 continue; 17220 } 17221 17222 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 17223 size = BPF_LDST_BYTES(insn); 17224 17225 /* If the read access is a narrower load of the field, 17226 * convert to a 4/8-byte load, to minimum program type specific 17227 * convert_ctx_access changes. If conversion is successful, 17228 * we will apply proper mask to the result. 17229 */ 17230 is_narrower_load = size < ctx_field_size; 17231 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 17232 off = insn->off; 17233 if (is_narrower_load) { 17234 u8 size_code; 17235 17236 if (type == BPF_WRITE) { 17237 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 17238 return -EINVAL; 17239 } 17240 17241 size_code = BPF_H; 17242 if (ctx_field_size == 4) 17243 size_code = BPF_W; 17244 else if (ctx_field_size == 8) 17245 size_code = BPF_DW; 17246 17247 insn->off = off & ~(size_default - 1); 17248 insn->code = BPF_LDX | BPF_MEM | size_code; 17249 } 17250 17251 target_size = 0; 17252 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 17253 &target_size); 17254 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 17255 (ctx_field_size && !target_size)) { 17256 verbose(env, "bpf verifier is misconfigured\n"); 17257 return -EINVAL; 17258 } 17259 17260 if (is_narrower_load && size < target_size) { 17261 u8 shift = bpf_ctx_narrow_access_offset( 17262 off, size, size_default) * 8; 17263 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 17264 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 17265 return -EINVAL; 17266 } 17267 if (ctx_field_size <= 4) { 17268 if (shift) 17269 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 17270 insn->dst_reg, 17271 shift); 17272 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 17273 (1 << size * 8) - 1); 17274 } else { 17275 if (shift) 17276 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 17277 insn->dst_reg, 17278 shift); 17279 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 17280 (1ULL << size * 8) - 1); 17281 } 17282 } 17283 17284 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17285 if (!new_prog) 17286 return -ENOMEM; 17287 17288 delta += cnt - 1; 17289 17290 /* keep walking new program and skip insns we just inserted */ 17291 env->prog = new_prog; 17292 insn = new_prog->insnsi + i + delta; 17293 } 17294 17295 return 0; 17296 } 17297 17298 static int jit_subprogs(struct bpf_verifier_env *env) 17299 { 17300 struct bpf_prog *prog = env->prog, **func, *tmp; 17301 int i, j, subprog_start, subprog_end = 0, len, subprog; 17302 struct bpf_map *map_ptr; 17303 struct bpf_insn *insn; 17304 void *old_bpf_func; 17305 int err, num_exentries; 17306 17307 if (env->subprog_cnt <= 1) 17308 return 0; 17309 17310 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 17311 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 17312 continue; 17313 17314 /* Upon error here we cannot fall back to interpreter but 17315 * need a hard reject of the program. Thus -EFAULT is 17316 * propagated in any case. 17317 */ 17318 subprog = find_subprog(env, i + insn->imm + 1); 17319 if (subprog < 0) { 17320 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 17321 i + insn->imm + 1); 17322 return -EFAULT; 17323 } 17324 /* temporarily remember subprog id inside insn instead of 17325 * aux_data, since next loop will split up all insns into funcs 17326 */ 17327 insn->off = subprog; 17328 /* remember original imm in case JIT fails and fallback 17329 * to interpreter will be needed 17330 */ 17331 env->insn_aux_data[i].call_imm = insn->imm; 17332 /* point imm to __bpf_call_base+1 from JITs point of view */ 17333 insn->imm = 1; 17334 if (bpf_pseudo_func(insn)) 17335 /* jit (e.g. x86_64) may emit fewer instructions 17336 * if it learns a u32 imm is the same as a u64 imm. 17337 * Force a non zero here. 17338 */ 17339 insn[1].imm = 1; 17340 } 17341 17342 err = bpf_prog_alloc_jited_linfo(prog); 17343 if (err) 17344 goto out_undo_insn; 17345 17346 err = -ENOMEM; 17347 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 17348 if (!func) 17349 goto out_undo_insn; 17350 17351 for (i = 0; i < env->subprog_cnt; i++) { 17352 subprog_start = subprog_end; 17353 subprog_end = env->subprog_info[i + 1].start; 17354 17355 len = subprog_end - subprog_start; 17356 /* bpf_prog_run() doesn't call subprogs directly, 17357 * hence main prog stats include the runtime of subprogs. 17358 * subprogs don't have IDs and not reachable via prog_get_next_id 17359 * func[i]->stats will never be accessed and stays NULL 17360 */ 17361 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 17362 if (!func[i]) 17363 goto out_free; 17364 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 17365 len * sizeof(struct bpf_insn)); 17366 func[i]->type = prog->type; 17367 func[i]->len = len; 17368 if (bpf_prog_calc_tag(func[i])) 17369 goto out_free; 17370 func[i]->is_func = 1; 17371 func[i]->aux->func_idx = i; 17372 /* Below members will be freed only at prog->aux */ 17373 func[i]->aux->btf = prog->aux->btf; 17374 func[i]->aux->func_info = prog->aux->func_info; 17375 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 17376 func[i]->aux->poke_tab = prog->aux->poke_tab; 17377 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 17378 17379 for (j = 0; j < prog->aux->size_poke_tab; j++) { 17380 struct bpf_jit_poke_descriptor *poke; 17381 17382 poke = &prog->aux->poke_tab[j]; 17383 if (poke->insn_idx < subprog_end && 17384 poke->insn_idx >= subprog_start) 17385 poke->aux = func[i]->aux; 17386 } 17387 17388 func[i]->aux->name[0] = 'F'; 17389 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 17390 func[i]->jit_requested = 1; 17391 func[i]->blinding_requested = prog->blinding_requested; 17392 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 17393 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 17394 func[i]->aux->linfo = prog->aux->linfo; 17395 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 17396 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 17397 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 17398 num_exentries = 0; 17399 insn = func[i]->insnsi; 17400 for (j = 0; j < func[i]->len; j++, insn++) { 17401 if (BPF_CLASS(insn->code) == BPF_LDX && 17402 BPF_MODE(insn->code) == BPF_PROBE_MEM) 17403 num_exentries++; 17404 } 17405 func[i]->aux->num_exentries = num_exentries; 17406 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 17407 func[i] = bpf_int_jit_compile(func[i]); 17408 if (!func[i]->jited) { 17409 err = -ENOTSUPP; 17410 goto out_free; 17411 } 17412 cond_resched(); 17413 } 17414 17415 /* at this point all bpf functions were successfully JITed 17416 * now populate all bpf_calls with correct addresses and 17417 * run last pass of JIT 17418 */ 17419 for (i = 0; i < env->subprog_cnt; i++) { 17420 insn = func[i]->insnsi; 17421 for (j = 0; j < func[i]->len; j++, insn++) { 17422 if (bpf_pseudo_func(insn)) { 17423 subprog = insn->off; 17424 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 17425 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 17426 continue; 17427 } 17428 if (!bpf_pseudo_call(insn)) 17429 continue; 17430 subprog = insn->off; 17431 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 17432 } 17433 17434 /* we use the aux data to keep a list of the start addresses 17435 * of the JITed images for each function in the program 17436 * 17437 * for some architectures, such as powerpc64, the imm field 17438 * might not be large enough to hold the offset of the start 17439 * address of the callee's JITed image from __bpf_call_base 17440 * 17441 * in such cases, we can lookup the start address of a callee 17442 * by using its subprog id, available from the off field of 17443 * the call instruction, as an index for this list 17444 */ 17445 func[i]->aux->func = func; 17446 func[i]->aux->func_cnt = env->subprog_cnt; 17447 } 17448 for (i = 0; i < env->subprog_cnt; i++) { 17449 old_bpf_func = func[i]->bpf_func; 17450 tmp = bpf_int_jit_compile(func[i]); 17451 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 17452 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 17453 err = -ENOTSUPP; 17454 goto out_free; 17455 } 17456 cond_resched(); 17457 } 17458 17459 /* finally lock prog and jit images for all functions and 17460 * populate kallsysm 17461 */ 17462 for (i = 0; i < env->subprog_cnt; i++) { 17463 bpf_prog_lock_ro(func[i]); 17464 bpf_prog_kallsyms_add(func[i]); 17465 } 17466 17467 /* Last step: make now unused interpreter insns from main 17468 * prog consistent for later dump requests, so they can 17469 * later look the same as if they were interpreted only. 17470 */ 17471 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 17472 if (bpf_pseudo_func(insn)) { 17473 insn[0].imm = env->insn_aux_data[i].call_imm; 17474 insn[1].imm = insn->off; 17475 insn->off = 0; 17476 continue; 17477 } 17478 if (!bpf_pseudo_call(insn)) 17479 continue; 17480 insn->off = env->insn_aux_data[i].call_imm; 17481 subprog = find_subprog(env, i + insn->off + 1); 17482 insn->imm = subprog; 17483 } 17484 17485 prog->jited = 1; 17486 prog->bpf_func = func[0]->bpf_func; 17487 prog->jited_len = func[0]->jited_len; 17488 prog->aux->func = func; 17489 prog->aux->func_cnt = env->subprog_cnt; 17490 bpf_prog_jit_attempt_done(prog); 17491 return 0; 17492 out_free: 17493 /* We failed JIT'ing, so at this point we need to unregister poke 17494 * descriptors from subprogs, so that kernel is not attempting to 17495 * patch it anymore as we're freeing the subprog JIT memory. 17496 */ 17497 for (i = 0; i < prog->aux->size_poke_tab; i++) { 17498 map_ptr = prog->aux->poke_tab[i].tail_call.map; 17499 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 17500 } 17501 /* At this point we're guaranteed that poke descriptors are not 17502 * live anymore. We can just unlink its descriptor table as it's 17503 * released with the main prog. 17504 */ 17505 for (i = 0; i < env->subprog_cnt; i++) { 17506 if (!func[i]) 17507 continue; 17508 func[i]->aux->poke_tab = NULL; 17509 bpf_jit_free(func[i]); 17510 } 17511 kfree(func); 17512 out_undo_insn: 17513 /* cleanup main prog to be interpreted */ 17514 prog->jit_requested = 0; 17515 prog->blinding_requested = 0; 17516 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 17517 if (!bpf_pseudo_call(insn)) 17518 continue; 17519 insn->off = 0; 17520 insn->imm = env->insn_aux_data[i].call_imm; 17521 } 17522 bpf_prog_jit_attempt_done(prog); 17523 return err; 17524 } 17525 17526 static int fixup_call_args(struct bpf_verifier_env *env) 17527 { 17528 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 17529 struct bpf_prog *prog = env->prog; 17530 struct bpf_insn *insn = prog->insnsi; 17531 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 17532 int i, depth; 17533 #endif 17534 int err = 0; 17535 17536 if (env->prog->jit_requested && 17537 !bpf_prog_is_offloaded(env->prog->aux)) { 17538 err = jit_subprogs(env); 17539 if (err == 0) 17540 return 0; 17541 if (err == -EFAULT) 17542 return err; 17543 } 17544 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 17545 if (has_kfunc_call) { 17546 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 17547 return -EINVAL; 17548 } 17549 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 17550 /* When JIT fails the progs with bpf2bpf calls and tail_calls 17551 * have to be rejected, since interpreter doesn't support them yet. 17552 */ 17553 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 17554 return -EINVAL; 17555 } 17556 for (i = 0; i < prog->len; i++, insn++) { 17557 if (bpf_pseudo_func(insn)) { 17558 /* When JIT fails the progs with callback calls 17559 * have to be rejected, since interpreter doesn't support them yet. 17560 */ 17561 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 17562 return -EINVAL; 17563 } 17564 17565 if (!bpf_pseudo_call(insn)) 17566 continue; 17567 depth = get_callee_stack_depth(env, insn, i); 17568 if (depth < 0) 17569 return depth; 17570 bpf_patch_call_args(insn, depth); 17571 } 17572 err = 0; 17573 #endif 17574 return err; 17575 } 17576 17577 /* replace a generic kfunc with a specialized version if necessary */ 17578 static void specialize_kfunc(struct bpf_verifier_env *env, 17579 u32 func_id, u16 offset, unsigned long *addr) 17580 { 17581 struct bpf_prog *prog = env->prog; 17582 bool seen_direct_write; 17583 void *xdp_kfunc; 17584 bool is_rdonly; 17585 17586 if (bpf_dev_bound_kfunc_id(func_id)) { 17587 xdp_kfunc = bpf_dev_bound_resolve_kfunc(prog, func_id); 17588 if (xdp_kfunc) { 17589 *addr = (unsigned long)xdp_kfunc; 17590 return; 17591 } 17592 /* fallback to default kfunc when not supported by netdev */ 17593 } 17594 17595 if (offset) 17596 return; 17597 17598 if (func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 17599 seen_direct_write = env->seen_direct_write; 17600 is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 17601 17602 if (is_rdonly) 17603 *addr = (unsigned long)bpf_dynptr_from_skb_rdonly; 17604 17605 /* restore env->seen_direct_write to its original value, since 17606 * may_access_direct_pkt_data mutates it 17607 */ 17608 env->seen_direct_write = seen_direct_write; 17609 } 17610 } 17611 17612 static void __fixup_collection_insert_kfunc(struct bpf_insn_aux_data *insn_aux, 17613 u16 struct_meta_reg, 17614 u16 node_offset_reg, 17615 struct bpf_insn *insn, 17616 struct bpf_insn *insn_buf, 17617 int *cnt) 17618 { 17619 struct btf_struct_meta *kptr_struct_meta = insn_aux->kptr_struct_meta; 17620 struct bpf_insn addr[2] = { BPF_LD_IMM64(struct_meta_reg, (long)kptr_struct_meta) }; 17621 17622 insn_buf[0] = addr[0]; 17623 insn_buf[1] = addr[1]; 17624 insn_buf[2] = BPF_MOV64_IMM(node_offset_reg, insn_aux->insert_off); 17625 insn_buf[3] = *insn; 17626 *cnt = 4; 17627 } 17628 17629 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 17630 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 17631 { 17632 const struct bpf_kfunc_desc *desc; 17633 17634 if (!insn->imm) { 17635 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 17636 return -EINVAL; 17637 } 17638 17639 *cnt = 0; 17640 17641 /* insn->imm has the btf func_id. Replace it with an offset relative to 17642 * __bpf_call_base, unless the JIT needs to call functions that are 17643 * further than 32 bits away (bpf_jit_supports_far_kfunc_call()). 17644 */ 17645 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 17646 if (!desc) { 17647 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 17648 insn->imm); 17649 return -EFAULT; 17650 } 17651 17652 if (!bpf_jit_supports_far_kfunc_call()) 17653 insn->imm = BPF_CALL_IMM(desc->addr); 17654 if (insn->off) 17655 return 0; 17656 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 17657 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 17658 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 17659 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 17660 17661 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 17662 insn_buf[1] = addr[0]; 17663 insn_buf[2] = addr[1]; 17664 insn_buf[3] = *insn; 17665 *cnt = 4; 17666 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl] || 17667 desc->func_id == special_kfunc_list[KF_bpf_refcount_acquire_impl]) { 17668 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 17669 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 17670 17671 insn_buf[0] = addr[0]; 17672 insn_buf[1] = addr[1]; 17673 insn_buf[2] = *insn; 17674 *cnt = 3; 17675 } else if (desc->func_id == special_kfunc_list[KF_bpf_list_push_back_impl] || 17676 desc->func_id == special_kfunc_list[KF_bpf_list_push_front_impl] || 17677 desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 17678 int struct_meta_reg = BPF_REG_3; 17679 int node_offset_reg = BPF_REG_4; 17680 17681 /* rbtree_add has extra 'less' arg, so args-to-fixup are in diff regs */ 17682 if (desc->func_id == special_kfunc_list[KF_bpf_rbtree_add_impl]) { 17683 struct_meta_reg = BPF_REG_4; 17684 node_offset_reg = BPF_REG_5; 17685 } 17686 17687 __fixup_collection_insert_kfunc(&env->insn_aux_data[insn_idx], struct_meta_reg, 17688 node_offset_reg, insn, insn_buf, cnt); 17689 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 17690 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 17691 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 17692 *cnt = 1; 17693 } 17694 return 0; 17695 } 17696 17697 /* Do various post-verification rewrites in a single program pass. 17698 * These rewrites simplify JIT and interpreter implementations. 17699 */ 17700 static int do_misc_fixups(struct bpf_verifier_env *env) 17701 { 17702 struct bpf_prog *prog = env->prog; 17703 enum bpf_attach_type eatype = prog->expected_attach_type; 17704 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17705 struct bpf_insn *insn = prog->insnsi; 17706 const struct bpf_func_proto *fn; 17707 const int insn_cnt = prog->len; 17708 const struct bpf_map_ops *ops; 17709 struct bpf_insn_aux_data *aux; 17710 struct bpf_insn insn_buf[16]; 17711 struct bpf_prog *new_prog; 17712 struct bpf_map *map_ptr; 17713 int i, ret, cnt, delta = 0; 17714 17715 for (i = 0; i < insn_cnt; i++, insn++) { 17716 /* Make divide-by-zero exceptions impossible. */ 17717 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 17718 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 17719 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 17720 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 17721 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 17722 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 17723 struct bpf_insn *patchlet; 17724 struct bpf_insn chk_and_div[] = { 17725 /* [R,W]x div 0 -> 0 */ 17726 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 17727 BPF_JNE | BPF_K, insn->src_reg, 17728 0, 2, 0), 17729 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 17730 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 17731 *insn, 17732 }; 17733 struct bpf_insn chk_and_mod[] = { 17734 /* [R,W]x mod 0 -> [R,W]x */ 17735 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 17736 BPF_JEQ | BPF_K, insn->src_reg, 17737 0, 1 + (is64 ? 0 : 1), 0), 17738 *insn, 17739 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 17740 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 17741 }; 17742 17743 patchlet = isdiv ? chk_and_div : chk_and_mod; 17744 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 17745 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 17746 17747 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 17748 if (!new_prog) 17749 return -ENOMEM; 17750 17751 delta += cnt - 1; 17752 env->prog = prog = new_prog; 17753 insn = new_prog->insnsi + i + delta; 17754 continue; 17755 } 17756 17757 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 17758 if (BPF_CLASS(insn->code) == BPF_LD && 17759 (BPF_MODE(insn->code) == BPF_ABS || 17760 BPF_MODE(insn->code) == BPF_IND)) { 17761 cnt = env->ops->gen_ld_abs(insn, insn_buf); 17762 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 17763 verbose(env, "bpf verifier is misconfigured\n"); 17764 return -EINVAL; 17765 } 17766 17767 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17768 if (!new_prog) 17769 return -ENOMEM; 17770 17771 delta += cnt - 1; 17772 env->prog = prog = new_prog; 17773 insn = new_prog->insnsi + i + delta; 17774 continue; 17775 } 17776 17777 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 17778 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 17779 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 17780 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 17781 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 17782 struct bpf_insn *patch = &insn_buf[0]; 17783 bool issrc, isneg, isimm; 17784 u32 off_reg; 17785 17786 aux = &env->insn_aux_data[i + delta]; 17787 if (!aux->alu_state || 17788 aux->alu_state == BPF_ALU_NON_POINTER) 17789 continue; 17790 17791 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 17792 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 17793 BPF_ALU_SANITIZE_SRC; 17794 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 17795 17796 off_reg = issrc ? insn->src_reg : insn->dst_reg; 17797 if (isimm) { 17798 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 17799 } else { 17800 if (isneg) 17801 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 17802 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 17803 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 17804 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 17805 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 17806 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 17807 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 17808 } 17809 if (!issrc) 17810 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 17811 insn->src_reg = BPF_REG_AX; 17812 if (isneg) 17813 insn->code = insn->code == code_add ? 17814 code_sub : code_add; 17815 *patch++ = *insn; 17816 if (issrc && isneg && !isimm) 17817 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 17818 cnt = patch - insn_buf; 17819 17820 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17821 if (!new_prog) 17822 return -ENOMEM; 17823 17824 delta += cnt - 1; 17825 env->prog = prog = new_prog; 17826 insn = new_prog->insnsi + i + delta; 17827 continue; 17828 } 17829 17830 if (insn->code != (BPF_JMP | BPF_CALL)) 17831 continue; 17832 if (insn->src_reg == BPF_PSEUDO_CALL) 17833 continue; 17834 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17835 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 17836 if (ret) 17837 return ret; 17838 if (cnt == 0) 17839 continue; 17840 17841 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17842 if (!new_prog) 17843 return -ENOMEM; 17844 17845 delta += cnt - 1; 17846 env->prog = prog = new_prog; 17847 insn = new_prog->insnsi + i + delta; 17848 continue; 17849 } 17850 17851 if (insn->imm == BPF_FUNC_get_route_realm) 17852 prog->dst_needed = 1; 17853 if (insn->imm == BPF_FUNC_get_prandom_u32) 17854 bpf_user_rnd_init_once(); 17855 if (insn->imm == BPF_FUNC_override_return) 17856 prog->kprobe_override = 1; 17857 if (insn->imm == BPF_FUNC_tail_call) { 17858 /* If we tail call into other programs, we 17859 * cannot make any assumptions since they can 17860 * be replaced dynamically during runtime in 17861 * the program array. 17862 */ 17863 prog->cb_access = 1; 17864 if (!allow_tail_call_in_subprogs(env)) 17865 prog->aux->stack_depth = MAX_BPF_STACK; 17866 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 17867 17868 /* mark bpf_tail_call as different opcode to avoid 17869 * conditional branch in the interpreter for every normal 17870 * call and to prevent accidental JITing by JIT compiler 17871 * that doesn't support bpf_tail_call yet 17872 */ 17873 insn->imm = 0; 17874 insn->code = BPF_JMP | BPF_TAIL_CALL; 17875 17876 aux = &env->insn_aux_data[i + delta]; 17877 if (env->bpf_capable && !prog->blinding_requested && 17878 prog->jit_requested && 17879 !bpf_map_key_poisoned(aux) && 17880 !bpf_map_ptr_poisoned(aux) && 17881 !bpf_map_ptr_unpriv(aux)) { 17882 struct bpf_jit_poke_descriptor desc = { 17883 .reason = BPF_POKE_REASON_TAIL_CALL, 17884 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 17885 .tail_call.key = bpf_map_key_immediate(aux), 17886 .insn_idx = i + delta, 17887 }; 17888 17889 ret = bpf_jit_add_poke_descriptor(prog, &desc); 17890 if (ret < 0) { 17891 verbose(env, "adding tail call poke descriptor failed\n"); 17892 return ret; 17893 } 17894 17895 insn->imm = ret + 1; 17896 continue; 17897 } 17898 17899 if (!bpf_map_ptr_unpriv(aux)) 17900 continue; 17901 17902 /* instead of changing every JIT dealing with tail_call 17903 * emit two extra insns: 17904 * if (index >= max_entries) goto out; 17905 * index &= array->index_mask; 17906 * to avoid out-of-bounds cpu speculation 17907 */ 17908 if (bpf_map_ptr_poisoned(aux)) { 17909 verbose(env, "tail_call abusing map_ptr\n"); 17910 return -EINVAL; 17911 } 17912 17913 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 17914 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 17915 map_ptr->max_entries, 2); 17916 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 17917 container_of(map_ptr, 17918 struct bpf_array, 17919 map)->index_mask); 17920 insn_buf[2] = *insn; 17921 cnt = 3; 17922 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17923 if (!new_prog) 17924 return -ENOMEM; 17925 17926 delta += cnt - 1; 17927 env->prog = prog = new_prog; 17928 insn = new_prog->insnsi + i + delta; 17929 continue; 17930 } 17931 17932 if (insn->imm == BPF_FUNC_timer_set_callback) { 17933 /* The verifier will process callback_fn as many times as necessary 17934 * with different maps and the register states prepared by 17935 * set_timer_callback_state will be accurate. 17936 * 17937 * The following use case is valid: 17938 * map1 is shared by prog1, prog2, prog3. 17939 * prog1 calls bpf_timer_init for some map1 elements 17940 * prog2 calls bpf_timer_set_callback for some map1 elements. 17941 * Those that were not bpf_timer_init-ed will return -EINVAL. 17942 * prog3 calls bpf_timer_start for some map1 elements. 17943 * Those that were not both bpf_timer_init-ed and 17944 * bpf_timer_set_callback-ed will return -EINVAL. 17945 */ 17946 struct bpf_insn ld_addrs[2] = { 17947 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 17948 }; 17949 17950 insn_buf[0] = ld_addrs[0]; 17951 insn_buf[1] = ld_addrs[1]; 17952 insn_buf[2] = *insn; 17953 cnt = 3; 17954 17955 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17956 if (!new_prog) 17957 return -ENOMEM; 17958 17959 delta += cnt - 1; 17960 env->prog = prog = new_prog; 17961 insn = new_prog->insnsi + i + delta; 17962 goto patch_call_imm; 17963 } 17964 17965 if (is_storage_get_function(insn->imm)) { 17966 if (!env->prog->aux->sleepable || 17967 env->insn_aux_data[i + delta].storage_get_func_atomic) 17968 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 17969 else 17970 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 17971 insn_buf[1] = *insn; 17972 cnt = 2; 17973 17974 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17975 if (!new_prog) 17976 return -ENOMEM; 17977 17978 delta += cnt - 1; 17979 env->prog = prog = new_prog; 17980 insn = new_prog->insnsi + i + delta; 17981 goto patch_call_imm; 17982 } 17983 17984 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 17985 * and other inlining handlers are currently limited to 64 bit 17986 * only. 17987 */ 17988 if (prog->jit_requested && BITS_PER_LONG == 64 && 17989 (insn->imm == BPF_FUNC_map_lookup_elem || 17990 insn->imm == BPF_FUNC_map_update_elem || 17991 insn->imm == BPF_FUNC_map_delete_elem || 17992 insn->imm == BPF_FUNC_map_push_elem || 17993 insn->imm == BPF_FUNC_map_pop_elem || 17994 insn->imm == BPF_FUNC_map_peek_elem || 17995 insn->imm == BPF_FUNC_redirect_map || 17996 insn->imm == BPF_FUNC_for_each_map_elem || 17997 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 17998 aux = &env->insn_aux_data[i + delta]; 17999 if (bpf_map_ptr_poisoned(aux)) 18000 goto patch_call_imm; 18001 18002 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 18003 ops = map_ptr->ops; 18004 if (insn->imm == BPF_FUNC_map_lookup_elem && 18005 ops->map_gen_lookup) { 18006 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 18007 if (cnt == -EOPNOTSUPP) 18008 goto patch_map_ops_generic; 18009 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 18010 verbose(env, "bpf verifier is misconfigured\n"); 18011 return -EINVAL; 18012 } 18013 18014 new_prog = bpf_patch_insn_data(env, i + delta, 18015 insn_buf, cnt); 18016 if (!new_prog) 18017 return -ENOMEM; 18018 18019 delta += cnt - 1; 18020 env->prog = prog = new_prog; 18021 insn = new_prog->insnsi + i + delta; 18022 continue; 18023 } 18024 18025 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 18026 (void *(*)(struct bpf_map *map, void *key))NULL)); 18027 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 18028 (long (*)(struct bpf_map *map, void *key))NULL)); 18029 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 18030 (long (*)(struct bpf_map *map, void *key, void *value, 18031 u64 flags))NULL)); 18032 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 18033 (long (*)(struct bpf_map *map, void *value, 18034 u64 flags))NULL)); 18035 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 18036 (long (*)(struct bpf_map *map, void *value))NULL)); 18037 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 18038 (long (*)(struct bpf_map *map, void *value))NULL)); 18039 BUILD_BUG_ON(!__same_type(ops->map_redirect, 18040 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 18041 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 18042 (long (*)(struct bpf_map *map, 18043 bpf_callback_t callback_fn, 18044 void *callback_ctx, 18045 u64 flags))NULL)); 18046 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 18047 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 18048 18049 patch_map_ops_generic: 18050 switch (insn->imm) { 18051 case BPF_FUNC_map_lookup_elem: 18052 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 18053 continue; 18054 case BPF_FUNC_map_update_elem: 18055 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 18056 continue; 18057 case BPF_FUNC_map_delete_elem: 18058 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 18059 continue; 18060 case BPF_FUNC_map_push_elem: 18061 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 18062 continue; 18063 case BPF_FUNC_map_pop_elem: 18064 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 18065 continue; 18066 case BPF_FUNC_map_peek_elem: 18067 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 18068 continue; 18069 case BPF_FUNC_redirect_map: 18070 insn->imm = BPF_CALL_IMM(ops->map_redirect); 18071 continue; 18072 case BPF_FUNC_for_each_map_elem: 18073 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 18074 continue; 18075 case BPF_FUNC_map_lookup_percpu_elem: 18076 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 18077 continue; 18078 } 18079 18080 goto patch_call_imm; 18081 } 18082 18083 /* Implement bpf_jiffies64 inline. */ 18084 if (prog->jit_requested && BITS_PER_LONG == 64 && 18085 insn->imm == BPF_FUNC_jiffies64) { 18086 struct bpf_insn ld_jiffies_addr[2] = { 18087 BPF_LD_IMM64(BPF_REG_0, 18088 (unsigned long)&jiffies), 18089 }; 18090 18091 insn_buf[0] = ld_jiffies_addr[0]; 18092 insn_buf[1] = ld_jiffies_addr[1]; 18093 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 18094 BPF_REG_0, 0); 18095 cnt = 3; 18096 18097 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 18098 cnt); 18099 if (!new_prog) 18100 return -ENOMEM; 18101 18102 delta += cnt - 1; 18103 env->prog = prog = new_prog; 18104 insn = new_prog->insnsi + i + delta; 18105 continue; 18106 } 18107 18108 /* Implement bpf_get_func_arg inline. */ 18109 if (prog_type == BPF_PROG_TYPE_TRACING && 18110 insn->imm == BPF_FUNC_get_func_arg) { 18111 /* Load nr_args from ctx - 8 */ 18112 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 18113 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 18114 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 18115 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 18116 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 18117 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 18118 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 18119 insn_buf[7] = BPF_JMP_A(1); 18120 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 18121 cnt = 9; 18122 18123 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18124 if (!new_prog) 18125 return -ENOMEM; 18126 18127 delta += cnt - 1; 18128 env->prog = prog = new_prog; 18129 insn = new_prog->insnsi + i + delta; 18130 continue; 18131 } 18132 18133 /* Implement bpf_get_func_ret inline. */ 18134 if (prog_type == BPF_PROG_TYPE_TRACING && 18135 insn->imm == BPF_FUNC_get_func_ret) { 18136 if (eatype == BPF_TRACE_FEXIT || 18137 eatype == BPF_MODIFY_RETURN) { 18138 /* Load nr_args from ctx - 8 */ 18139 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 18140 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 18141 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 18142 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 18143 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 18144 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 18145 cnt = 6; 18146 } else { 18147 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 18148 cnt = 1; 18149 } 18150 18151 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 18152 if (!new_prog) 18153 return -ENOMEM; 18154 18155 delta += cnt - 1; 18156 env->prog = prog = new_prog; 18157 insn = new_prog->insnsi + i + delta; 18158 continue; 18159 } 18160 18161 /* Implement get_func_arg_cnt inline. */ 18162 if (prog_type == BPF_PROG_TYPE_TRACING && 18163 insn->imm == BPF_FUNC_get_func_arg_cnt) { 18164 /* Load nr_args from ctx - 8 */ 18165 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 18166 18167 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 18168 if (!new_prog) 18169 return -ENOMEM; 18170 18171 env->prog = prog = new_prog; 18172 insn = new_prog->insnsi + i + delta; 18173 continue; 18174 } 18175 18176 /* Implement bpf_get_func_ip inline. */ 18177 if (prog_type == BPF_PROG_TYPE_TRACING && 18178 insn->imm == BPF_FUNC_get_func_ip) { 18179 /* Load IP address from ctx - 16 */ 18180 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 18181 18182 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 18183 if (!new_prog) 18184 return -ENOMEM; 18185 18186 env->prog = prog = new_prog; 18187 insn = new_prog->insnsi + i + delta; 18188 continue; 18189 } 18190 18191 patch_call_imm: 18192 fn = env->ops->get_func_proto(insn->imm, env->prog); 18193 /* all functions that have prototype and verifier allowed 18194 * programs to call them, must be real in-kernel functions 18195 */ 18196 if (!fn->func) { 18197 verbose(env, 18198 "kernel subsystem misconfigured func %s#%d\n", 18199 func_id_name(insn->imm), insn->imm); 18200 return -EFAULT; 18201 } 18202 insn->imm = fn->func - __bpf_call_base; 18203 } 18204 18205 /* Since poke tab is now finalized, publish aux to tracker. */ 18206 for (i = 0; i < prog->aux->size_poke_tab; i++) { 18207 map_ptr = prog->aux->poke_tab[i].tail_call.map; 18208 if (!map_ptr->ops->map_poke_track || 18209 !map_ptr->ops->map_poke_untrack || 18210 !map_ptr->ops->map_poke_run) { 18211 verbose(env, "bpf verifier is misconfigured\n"); 18212 return -EINVAL; 18213 } 18214 18215 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 18216 if (ret < 0) { 18217 verbose(env, "tracking tail call prog failed\n"); 18218 return ret; 18219 } 18220 } 18221 18222 sort_kfunc_descs_by_imm_off(env->prog); 18223 18224 return 0; 18225 } 18226 18227 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 18228 int position, 18229 s32 stack_base, 18230 u32 callback_subprogno, 18231 u32 *cnt) 18232 { 18233 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 18234 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 18235 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 18236 int reg_loop_max = BPF_REG_6; 18237 int reg_loop_cnt = BPF_REG_7; 18238 int reg_loop_ctx = BPF_REG_8; 18239 18240 struct bpf_prog *new_prog; 18241 u32 callback_start; 18242 u32 call_insn_offset; 18243 s32 callback_offset; 18244 18245 /* This represents an inlined version of bpf_iter.c:bpf_loop, 18246 * be careful to modify this code in sync. 18247 */ 18248 struct bpf_insn insn_buf[] = { 18249 /* Return error and jump to the end of the patch if 18250 * expected number of iterations is too big. 18251 */ 18252 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 18253 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 18254 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 18255 /* spill R6, R7, R8 to use these as loop vars */ 18256 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 18257 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 18258 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 18259 /* initialize loop vars */ 18260 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 18261 BPF_MOV32_IMM(reg_loop_cnt, 0), 18262 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 18263 /* loop header, 18264 * if reg_loop_cnt >= reg_loop_max skip the loop body 18265 */ 18266 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 18267 /* callback call, 18268 * correct callback offset would be set after patching 18269 */ 18270 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 18271 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 18272 BPF_CALL_REL(0), 18273 /* increment loop counter */ 18274 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 18275 /* jump to loop header if callback returned 0 */ 18276 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 18277 /* return value of bpf_loop, 18278 * set R0 to the number of iterations 18279 */ 18280 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 18281 /* restore original values of R6, R7, R8 */ 18282 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 18283 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 18284 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 18285 }; 18286 18287 *cnt = ARRAY_SIZE(insn_buf); 18288 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 18289 if (!new_prog) 18290 return new_prog; 18291 18292 /* callback start is known only after patching */ 18293 callback_start = env->subprog_info[callback_subprogno].start; 18294 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 18295 call_insn_offset = position + 12; 18296 callback_offset = callback_start - call_insn_offset - 1; 18297 new_prog->insnsi[call_insn_offset].imm = callback_offset; 18298 18299 return new_prog; 18300 } 18301 18302 static bool is_bpf_loop_call(struct bpf_insn *insn) 18303 { 18304 return insn->code == (BPF_JMP | BPF_CALL) && 18305 insn->src_reg == 0 && 18306 insn->imm == BPF_FUNC_loop; 18307 } 18308 18309 /* For all sub-programs in the program (including main) check 18310 * insn_aux_data to see if there are bpf_loop calls that require 18311 * inlining. If such calls are found the calls are replaced with a 18312 * sequence of instructions produced by `inline_bpf_loop` function and 18313 * subprog stack_depth is increased by the size of 3 registers. 18314 * This stack space is used to spill values of the R6, R7, R8. These 18315 * registers are used to store the loop bound, counter and context 18316 * variables. 18317 */ 18318 static int optimize_bpf_loop(struct bpf_verifier_env *env) 18319 { 18320 struct bpf_subprog_info *subprogs = env->subprog_info; 18321 int i, cur_subprog = 0, cnt, delta = 0; 18322 struct bpf_insn *insn = env->prog->insnsi; 18323 int insn_cnt = env->prog->len; 18324 u16 stack_depth = subprogs[cur_subprog].stack_depth; 18325 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 18326 u16 stack_depth_extra = 0; 18327 18328 for (i = 0; i < insn_cnt; i++, insn++) { 18329 struct bpf_loop_inline_state *inline_state = 18330 &env->insn_aux_data[i + delta].loop_inline_state; 18331 18332 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 18333 struct bpf_prog *new_prog; 18334 18335 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 18336 new_prog = inline_bpf_loop(env, 18337 i + delta, 18338 -(stack_depth + stack_depth_extra), 18339 inline_state->callback_subprogno, 18340 &cnt); 18341 if (!new_prog) 18342 return -ENOMEM; 18343 18344 delta += cnt - 1; 18345 env->prog = new_prog; 18346 insn = new_prog->insnsi + i + delta; 18347 } 18348 18349 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 18350 subprogs[cur_subprog].stack_depth += stack_depth_extra; 18351 cur_subprog++; 18352 stack_depth = subprogs[cur_subprog].stack_depth; 18353 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 18354 stack_depth_extra = 0; 18355 } 18356 } 18357 18358 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18359 18360 return 0; 18361 } 18362 18363 static void free_states(struct bpf_verifier_env *env) 18364 { 18365 struct bpf_verifier_state_list *sl, *sln; 18366 int i; 18367 18368 sl = env->free_list; 18369 while (sl) { 18370 sln = sl->next; 18371 free_verifier_state(&sl->state, false); 18372 kfree(sl); 18373 sl = sln; 18374 } 18375 env->free_list = NULL; 18376 18377 if (!env->explored_states) 18378 return; 18379 18380 for (i = 0; i < state_htab_size(env); i++) { 18381 sl = env->explored_states[i]; 18382 18383 while (sl) { 18384 sln = sl->next; 18385 free_verifier_state(&sl->state, false); 18386 kfree(sl); 18387 sl = sln; 18388 } 18389 env->explored_states[i] = NULL; 18390 } 18391 } 18392 18393 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18394 { 18395 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18396 struct bpf_verifier_state *state; 18397 struct bpf_reg_state *regs; 18398 int ret, i; 18399 18400 env->prev_linfo = NULL; 18401 env->pass_cnt++; 18402 18403 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 18404 if (!state) 18405 return -ENOMEM; 18406 state->curframe = 0; 18407 state->speculative = false; 18408 state->branches = 1; 18409 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 18410 if (!state->frame[0]) { 18411 kfree(state); 18412 return -ENOMEM; 18413 } 18414 env->cur_state = state; 18415 init_func_state(env, state->frame[0], 18416 BPF_MAIN_FUNC /* callsite */, 18417 0 /* frameno */, 18418 subprog); 18419 state->first_insn_idx = env->subprog_info[subprog].start; 18420 state->last_insn_idx = -1; 18421 18422 regs = state->frame[state->curframe]->regs; 18423 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18424 ret = btf_prepare_func_args(env, subprog, regs); 18425 if (ret) 18426 goto out; 18427 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 18428 if (regs[i].type == PTR_TO_CTX) 18429 mark_reg_known_zero(env, regs, i); 18430 else if (regs[i].type == SCALAR_VALUE) 18431 mark_reg_unknown(env, regs, i); 18432 else if (base_type(regs[i].type) == PTR_TO_MEM) { 18433 const u32 mem_size = regs[i].mem_size; 18434 18435 mark_reg_known_zero(env, regs, i); 18436 regs[i].mem_size = mem_size; 18437 regs[i].id = ++env->id_gen; 18438 } 18439 } 18440 } else { 18441 /* 1st arg to a function */ 18442 regs[BPF_REG_1].type = PTR_TO_CTX; 18443 mark_reg_known_zero(env, regs, BPF_REG_1); 18444 ret = btf_check_subprog_arg_match(env, subprog, regs); 18445 if (ret == -EFAULT) 18446 /* unlikely verifier bug. abort. 18447 * ret == 0 and ret < 0 are sadly acceptable for 18448 * main() function due to backward compatibility. 18449 * Like socket filter program may be written as: 18450 * int bpf_prog(struct pt_regs *ctx) 18451 * and never dereference that ctx in the program. 18452 * 'struct pt_regs' is a type mismatch for socket 18453 * filter that should be using 'struct __sk_buff'. 18454 */ 18455 goto out; 18456 } 18457 18458 ret = do_check(env); 18459 out: 18460 /* check for NULL is necessary, since cur_state can be freed inside 18461 * do_check() under memory pressure. 18462 */ 18463 if (env->cur_state) { 18464 free_verifier_state(env->cur_state, true); 18465 env->cur_state = NULL; 18466 } 18467 while (!pop_stack(env, NULL, NULL, false)); 18468 if (!ret && pop_log) 18469 bpf_vlog_reset(&env->log, 0); 18470 free_states(env); 18471 return ret; 18472 } 18473 18474 /* Verify all global functions in a BPF program one by one based on their BTF. 18475 * All global functions must pass verification. Otherwise the whole program is rejected. 18476 * Consider: 18477 * int bar(int); 18478 * int foo(int f) 18479 * { 18480 * return bar(f); 18481 * } 18482 * int bar(int b) 18483 * { 18484 * ... 18485 * } 18486 * foo() will be verified first for R1=any_scalar_value. During verification it 18487 * will be assumed that bar() already verified successfully and call to bar() 18488 * from foo() will be checked for type match only. Later bar() will be verified 18489 * independently to check that it's safe for R1=any_scalar_value. 18490 */ 18491 static int do_check_subprogs(struct bpf_verifier_env *env) 18492 { 18493 struct bpf_prog_aux *aux = env->prog->aux; 18494 int i, ret; 18495 18496 if (!aux->func_info) 18497 return 0; 18498 18499 for (i = 1; i < env->subprog_cnt; i++) { 18500 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 18501 continue; 18502 env->insn_idx = env->subprog_info[i].start; 18503 WARN_ON_ONCE(env->insn_idx == 0); 18504 ret = do_check_common(env, i); 18505 if (ret) { 18506 return ret; 18507 } else if (env->log.level & BPF_LOG_LEVEL) { 18508 verbose(env, 18509 "Func#%d is safe for any args that match its prototype\n", 18510 i); 18511 } 18512 } 18513 return 0; 18514 } 18515 18516 static int do_check_main(struct bpf_verifier_env *env) 18517 { 18518 int ret; 18519 18520 env->insn_idx = 0; 18521 ret = do_check_common(env, 0); 18522 if (!ret) 18523 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18524 return ret; 18525 } 18526 18527 18528 static void print_verification_stats(struct bpf_verifier_env *env) 18529 { 18530 int i; 18531 18532 if (env->log.level & BPF_LOG_STATS) { 18533 verbose(env, "verification time %lld usec\n", 18534 div_u64(env->verification_time, 1000)); 18535 verbose(env, "stack depth "); 18536 for (i = 0; i < env->subprog_cnt; i++) { 18537 u32 depth = env->subprog_info[i].stack_depth; 18538 18539 verbose(env, "%d", depth); 18540 if (i + 1 < env->subprog_cnt) 18541 verbose(env, "+"); 18542 } 18543 verbose(env, "\n"); 18544 } 18545 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18546 "total_states %d peak_states %d mark_read %d\n", 18547 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18548 env->max_states_per_insn, env->total_states, 18549 env->peak_states, env->longest_mark_read_walk); 18550 } 18551 18552 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18553 { 18554 const struct btf_type *t, *func_proto; 18555 const struct bpf_struct_ops *st_ops; 18556 const struct btf_member *member; 18557 struct bpf_prog *prog = env->prog; 18558 u32 btf_id, member_idx; 18559 const char *mname; 18560 18561 if (!prog->gpl_compatible) { 18562 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18563 return -EINVAL; 18564 } 18565 18566 btf_id = prog->aux->attach_btf_id; 18567 st_ops = bpf_struct_ops_find(btf_id); 18568 if (!st_ops) { 18569 verbose(env, "attach_btf_id %u is not a supported struct\n", 18570 btf_id); 18571 return -ENOTSUPP; 18572 } 18573 18574 t = st_ops->type; 18575 member_idx = prog->expected_attach_type; 18576 if (member_idx >= btf_type_vlen(t)) { 18577 verbose(env, "attach to invalid member idx %u of struct %s\n", 18578 member_idx, st_ops->name); 18579 return -EINVAL; 18580 } 18581 18582 member = &btf_type_member(t)[member_idx]; 18583 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 18584 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 18585 NULL); 18586 if (!func_proto) { 18587 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18588 mname, member_idx, st_ops->name); 18589 return -EINVAL; 18590 } 18591 18592 if (st_ops->check_member) { 18593 int err = st_ops->check_member(t, member, prog); 18594 18595 if (err) { 18596 verbose(env, "attach to unsupported member %s of struct %s\n", 18597 mname, st_ops->name); 18598 return err; 18599 } 18600 } 18601 18602 prog->aux->attach_func_proto = func_proto; 18603 prog->aux->attach_func_name = mname; 18604 env->ops = st_ops->verifier_ops; 18605 18606 return 0; 18607 } 18608 #define SECURITY_PREFIX "security_" 18609 18610 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18611 { 18612 if (within_error_injection_list(addr) || 18613 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18614 return 0; 18615 18616 return -EINVAL; 18617 } 18618 18619 /* list of non-sleepable functions that are otherwise on 18620 * ALLOW_ERROR_INJECTION list 18621 */ 18622 BTF_SET_START(btf_non_sleepable_error_inject) 18623 /* Three functions below can be called from sleepable and non-sleepable context. 18624 * Assume non-sleepable from bpf safety point of view. 18625 */ 18626 BTF_ID(func, __filemap_add_folio) 18627 BTF_ID(func, should_fail_alloc_page) 18628 BTF_ID(func, should_failslab) 18629 BTF_SET_END(btf_non_sleepable_error_inject) 18630 18631 static int check_non_sleepable_error_inject(u32 btf_id) 18632 { 18633 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 18634 } 18635 18636 int bpf_check_attach_target(struct bpf_verifier_log *log, 18637 const struct bpf_prog *prog, 18638 const struct bpf_prog *tgt_prog, 18639 u32 btf_id, 18640 struct bpf_attach_target_info *tgt_info) 18641 { 18642 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 18643 const char prefix[] = "btf_trace_"; 18644 int ret = 0, subprog = -1, i; 18645 const struct btf_type *t; 18646 bool conservative = true; 18647 const char *tname; 18648 struct btf *btf; 18649 long addr = 0; 18650 struct module *mod = NULL; 18651 18652 if (!btf_id) { 18653 bpf_log(log, "Tracing programs must provide btf_id\n"); 18654 return -EINVAL; 18655 } 18656 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 18657 if (!btf) { 18658 bpf_log(log, 18659 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 18660 return -EINVAL; 18661 } 18662 t = btf_type_by_id(btf, btf_id); 18663 if (!t) { 18664 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 18665 return -EINVAL; 18666 } 18667 tname = btf_name_by_offset(btf, t->name_off); 18668 if (!tname) { 18669 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 18670 return -EINVAL; 18671 } 18672 if (tgt_prog) { 18673 struct bpf_prog_aux *aux = tgt_prog->aux; 18674 18675 if (bpf_prog_is_dev_bound(prog->aux) && 18676 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 18677 bpf_log(log, "Target program bound device mismatch"); 18678 return -EINVAL; 18679 } 18680 18681 for (i = 0; i < aux->func_info_cnt; i++) 18682 if (aux->func_info[i].type_id == btf_id) { 18683 subprog = i; 18684 break; 18685 } 18686 if (subprog == -1) { 18687 bpf_log(log, "Subprog %s doesn't exist\n", tname); 18688 return -EINVAL; 18689 } 18690 conservative = aux->func_info_aux[subprog].unreliable; 18691 if (prog_extension) { 18692 if (conservative) { 18693 bpf_log(log, 18694 "Cannot replace static functions\n"); 18695 return -EINVAL; 18696 } 18697 if (!prog->jit_requested) { 18698 bpf_log(log, 18699 "Extension programs should be JITed\n"); 18700 return -EINVAL; 18701 } 18702 } 18703 if (!tgt_prog->jited) { 18704 bpf_log(log, "Can attach to only JITed progs\n"); 18705 return -EINVAL; 18706 } 18707 if (tgt_prog->type == prog->type) { 18708 /* Cannot fentry/fexit another fentry/fexit program. 18709 * Cannot attach program extension to another extension. 18710 * It's ok to attach fentry/fexit to extension program. 18711 */ 18712 bpf_log(log, "Cannot recursively attach\n"); 18713 return -EINVAL; 18714 } 18715 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 18716 prog_extension && 18717 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 18718 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 18719 /* Program extensions can extend all program types 18720 * except fentry/fexit. The reason is the following. 18721 * The fentry/fexit programs are used for performance 18722 * analysis, stats and can be attached to any program 18723 * type except themselves. When extension program is 18724 * replacing XDP function it is necessary to allow 18725 * performance analysis of all functions. Both original 18726 * XDP program and its program extension. Hence 18727 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 18728 * allowed. If extending of fentry/fexit was allowed it 18729 * would be possible to create long call chain 18730 * fentry->extension->fentry->extension beyond 18731 * reasonable stack size. Hence extending fentry is not 18732 * allowed. 18733 */ 18734 bpf_log(log, "Cannot extend fentry/fexit\n"); 18735 return -EINVAL; 18736 } 18737 } else { 18738 if (prog_extension) { 18739 bpf_log(log, "Cannot replace kernel functions\n"); 18740 return -EINVAL; 18741 } 18742 } 18743 18744 switch (prog->expected_attach_type) { 18745 case BPF_TRACE_RAW_TP: 18746 if (tgt_prog) { 18747 bpf_log(log, 18748 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 18749 return -EINVAL; 18750 } 18751 if (!btf_type_is_typedef(t)) { 18752 bpf_log(log, "attach_btf_id %u is not a typedef\n", 18753 btf_id); 18754 return -EINVAL; 18755 } 18756 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 18757 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 18758 btf_id, tname); 18759 return -EINVAL; 18760 } 18761 tname += sizeof(prefix) - 1; 18762 t = btf_type_by_id(btf, t->type); 18763 if (!btf_type_is_ptr(t)) 18764 /* should never happen in valid vmlinux build */ 18765 return -EINVAL; 18766 t = btf_type_by_id(btf, t->type); 18767 if (!btf_type_is_func_proto(t)) 18768 /* should never happen in valid vmlinux build */ 18769 return -EINVAL; 18770 18771 break; 18772 case BPF_TRACE_ITER: 18773 if (!btf_type_is_func(t)) { 18774 bpf_log(log, "attach_btf_id %u is not a function\n", 18775 btf_id); 18776 return -EINVAL; 18777 } 18778 t = btf_type_by_id(btf, t->type); 18779 if (!btf_type_is_func_proto(t)) 18780 return -EINVAL; 18781 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 18782 if (ret) 18783 return ret; 18784 break; 18785 default: 18786 if (!prog_extension) 18787 return -EINVAL; 18788 fallthrough; 18789 case BPF_MODIFY_RETURN: 18790 case BPF_LSM_MAC: 18791 case BPF_LSM_CGROUP: 18792 case BPF_TRACE_FENTRY: 18793 case BPF_TRACE_FEXIT: 18794 if (!btf_type_is_func(t)) { 18795 bpf_log(log, "attach_btf_id %u is not a function\n", 18796 btf_id); 18797 return -EINVAL; 18798 } 18799 if (prog_extension && 18800 btf_check_type_match(log, prog, btf, t)) 18801 return -EINVAL; 18802 t = btf_type_by_id(btf, t->type); 18803 if (!btf_type_is_func_proto(t)) 18804 return -EINVAL; 18805 18806 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 18807 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 18808 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 18809 return -EINVAL; 18810 18811 if (tgt_prog && conservative) 18812 t = NULL; 18813 18814 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 18815 if (ret < 0) 18816 return ret; 18817 18818 if (tgt_prog) { 18819 if (subprog == 0) 18820 addr = (long) tgt_prog->bpf_func; 18821 else 18822 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 18823 } else { 18824 if (btf_is_module(btf)) { 18825 mod = btf_try_get_module(btf); 18826 if (mod) 18827 addr = find_kallsyms_symbol_value(mod, tname); 18828 else 18829 addr = 0; 18830 } else { 18831 addr = kallsyms_lookup_name(tname); 18832 } 18833 if (!addr) { 18834 module_put(mod); 18835 bpf_log(log, 18836 "The address of function %s cannot be found\n", 18837 tname); 18838 return -ENOENT; 18839 } 18840 } 18841 18842 if (prog->aux->sleepable) { 18843 ret = -EINVAL; 18844 switch (prog->type) { 18845 case BPF_PROG_TYPE_TRACING: 18846 18847 /* fentry/fexit/fmod_ret progs can be sleepable if they are 18848 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 18849 */ 18850 if (!check_non_sleepable_error_inject(btf_id) && 18851 within_error_injection_list(addr)) 18852 ret = 0; 18853 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 18854 * in the fmodret id set with the KF_SLEEPABLE flag. 18855 */ 18856 else { 18857 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id); 18858 18859 if (flags && (*flags & KF_SLEEPABLE)) 18860 ret = 0; 18861 } 18862 break; 18863 case BPF_PROG_TYPE_LSM: 18864 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 18865 * Only some of them are sleepable. 18866 */ 18867 if (bpf_lsm_is_sleepable_hook(btf_id)) 18868 ret = 0; 18869 break; 18870 default: 18871 break; 18872 } 18873 if (ret) { 18874 module_put(mod); 18875 bpf_log(log, "%s is not sleepable\n", tname); 18876 return ret; 18877 } 18878 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 18879 if (tgt_prog) { 18880 module_put(mod); 18881 bpf_log(log, "can't modify return codes of BPF programs\n"); 18882 return -EINVAL; 18883 } 18884 ret = -EINVAL; 18885 if (btf_kfunc_is_modify_return(btf, btf_id) || 18886 !check_attach_modify_return(addr, tname)) 18887 ret = 0; 18888 if (ret) { 18889 module_put(mod); 18890 bpf_log(log, "%s() is not modifiable\n", tname); 18891 return ret; 18892 } 18893 } 18894 18895 break; 18896 } 18897 tgt_info->tgt_addr = addr; 18898 tgt_info->tgt_name = tname; 18899 tgt_info->tgt_type = t; 18900 tgt_info->tgt_mod = mod; 18901 return 0; 18902 } 18903 18904 BTF_SET_START(btf_id_deny) 18905 BTF_ID_UNUSED 18906 #ifdef CONFIG_SMP 18907 BTF_ID(func, migrate_disable) 18908 BTF_ID(func, migrate_enable) 18909 #endif 18910 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 18911 BTF_ID(func, rcu_read_unlock_strict) 18912 #endif 18913 #if defined(CONFIG_DEBUG_PREEMPT) || defined(CONFIG_TRACE_PREEMPT_TOGGLE) 18914 BTF_ID(func, preempt_count_add) 18915 BTF_ID(func, preempt_count_sub) 18916 #endif 18917 #ifdef CONFIG_PREEMPT_RCU 18918 BTF_ID(func, __rcu_read_lock) 18919 BTF_ID(func, __rcu_read_unlock) 18920 #endif 18921 BTF_SET_END(btf_id_deny) 18922 18923 static bool can_be_sleepable(struct bpf_prog *prog) 18924 { 18925 if (prog->type == BPF_PROG_TYPE_TRACING) { 18926 switch (prog->expected_attach_type) { 18927 case BPF_TRACE_FENTRY: 18928 case BPF_TRACE_FEXIT: 18929 case BPF_MODIFY_RETURN: 18930 case BPF_TRACE_ITER: 18931 return true; 18932 default: 18933 return false; 18934 } 18935 } 18936 return prog->type == BPF_PROG_TYPE_LSM || 18937 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 18938 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 18939 } 18940 18941 static int check_attach_btf_id(struct bpf_verifier_env *env) 18942 { 18943 struct bpf_prog *prog = env->prog; 18944 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 18945 struct bpf_attach_target_info tgt_info = {}; 18946 u32 btf_id = prog->aux->attach_btf_id; 18947 struct bpf_trampoline *tr; 18948 int ret; 18949 u64 key; 18950 18951 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 18952 if (prog->aux->sleepable) 18953 /* attach_btf_id checked to be zero already */ 18954 return 0; 18955 verbose(env, "Syscall programs can only be sleepable\n"); 18956 return -EINVAL; 18957 } 18958 18959 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 18960 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 18961 return -EINVAL; 18962 } 18963 18964 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 18965 return check_struct_ops_btf_id(env); 18966 18967 if (prog->type != BPF_PROG_TYPE_TRACING && 18968 prog->type != BPF_PROG_TYPE_LSM && 18969 prog->type != BPF_PROG_TYPE_EXT) 18970 return 0; 18971 18972 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 18973 if (ret) 18974 return ret; 18975 18976 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 18977 /* to make freplace equivalent to their targets, they need to 18978 * inherit env->ops and expected_attach_type for the rest of the 18979 * verification 18980 */ 18981 env->ops = bpf_verifier_ops[tgt_prog->type]; 18982 prog->expected_attach_type = tgt_prog->expected_attach_type; 18983 } 18984 18985 /* store info about the attachment target that will be used later */ 18986 prog->aux->attach_func_proto = tgt_info.tgt_type; 18987 prog->aux->attach_func_name = tgt_info.tgt_name; 18988 prog->aux->mod = tgt_info.tgt_mod; 18989 18990 if (tgt_prog) { 18991 prog->aux->saved_dst_prog_type = tgt_prog->type; 18992 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 18993 } 18994 18995 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 18996 prog->aux->attach_btf_trace = true; 18997 return 0; 18998 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 18999 if (!bpf_iter_prog_supported(prog)) 19000 return -EINVAL; 19001 return 0; 19002 } 19003 19004 if (prog->type == BPF_PROG_TYPE_LSM) { 19005 ret = bpf_lsm_verify_prog(&env->log, prog); 19006 if (ret < 0) 19007 return ret; 19008 } else if (prog->type == BPF_PROG_TYPE_TRACING && 19009 btf_id_set_contains(&btf_id_deny, btf_id)) { 19010 return -EINVAL; 19011 } 19012 19013 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 19014 tr = bpf_trampoline_get(key, &tgt_info); 19015 if (!tr) 19016 return -ENOMEM; 19017 19018 prog->aux->dst_trampoline = tr; 19019 return 0; 19020 } 19021 19022 struct btf *bpf_get_btf_vmlinux(void) 19023 { 19024 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 19025 mutex_lock(&bpf_verifier_lock); 19026 if (!btf_vmlinux) 19027 btf_vmlinux = btf_parse_vmlinux(); 19028 mutex_unlock(&bpf_verifier_lock); 19029 } 19030 return btf_vmlinux; 19031 } 19032 19033 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, __u32 uattr_size) 19034 { 19035 u64 start_time = ktime_get_ns(); 19036 struct bpf_verifier_env *env; 19037 int i, len, ret = -EINVAL, err; 19038 u32 log_true_size; 19039 bool is_priv; 19040 19041 /* no program is valid */ 19042 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 19043 return -EINVAL; 19044 19045 /* 'struct bpf_verifier_env' can be global, but since it's not small, 19046 * allocate/free it every time bpf_check() is called 19047 */ 19048 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 19049 if (!env) 19050 return -ENOMEM; 19051 19052 env->bt.env = env; 19053 19054 len = (*prog)->len; 19055 env->insn_aux_data = 19056 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 19057 ret = -ENOMEM; 19058 if (!env->insn_aux_data) 19059 goto err_free_env; 19060 for (i = 0; i < len; i++) 19061 env->insn_aux_data[i].orig_idx = i; 19062 env->prog = *prog; 19063 env->ops = bpf_verifier_ops[env->prog->type]; 19064 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 19065 is_priv = bpf_capable(); 19066 19067 bpf_get_btf_vmlinux(); 19068 19069 /* grab the mutex to protect few globals used by verifier */ 19070 if (!is_priv) 19071 mutex_lock(&bpf_verifier_lock); 19072 19073 /* user could have requested verbose verifier output 19074 * and supplied buffer to store the verification trace 19075 */ 19076 ret = bpf_vlog_init(&env->log, attr->log_level, 19077 (char __user *) (unsigned long) attr->log_buf, 19078 attr->log_size); 19079 if (ret) 19080 goto err_unlock; 19081 19082 mark_verifier_state_clean(env); 19083 19084 if (IS_ERR(btf_vmlinux)) { 19085 /* Either gcc or pahole or kernel are broken. */ 19086 verbose(env, "in-kernel BTF is malformed\n"); 19087 ret = PTR_ERR(btf_vmlinux); 19088 goto skip_full_check; 19089 } 19090 19091 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 19092 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 19093 env->strict_alignment = true; 19094 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 19095 env->strict_alignment = false; 19096 19097 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 19098 env->allow_uninit_stack = bpf_allow_uninit_stack(); 19099 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 19100 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 19101 env->bpf_capable = bpf_capable(); 19102 19103 if (is_priv) 19104 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 19105 19106 env->explored_states = kvcalloc(state_htab_size(env), 19107 sizeof(struct bpf_verifier_state_list *), 19108 GFP_USER); 19109 ret = -ENOMEM; 19110 if (!env->explored_states) 19111 goto skip_full_check; 19112 19113 ret = add_subprog_and_kfunc(env); 19114 if (ret < 0) 19115 goto skip_full_check; 19116 19117 ret = check_subprogs(env); 19118 if (ret < 0) 19119 goto skip_full_check; 19120 19121 ret = check_btf_info(env, attr, uattr); 19122 if (ret < 0) 19123 goto skip_full_check; 19124 19125 ret = check_attach_btf_id(env); 19126 if (ret) 19127 goto skip_full_check; 19128 19129 ret = resolve_pseudo_ldimm64(env); 19130 if (ret < 0) 19131 goto skip_full_check; 19132 19133 if (bpf_prog_is_offloaded(env->prog->aux)) { 19134 ret = bpf_prog_offload_verifier_prep(env->prog); 19135 if (ret) 19136 goto skip_full_check; 19137 } 19138 19139 ret = check_cfg(env); 19140 if (ret < 0) 19141 goto skip_full_check; 19142 19143 ret = do_check_subprogs(env); 19144 ret = ret ?: do_check_main(env); 19145 19146 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 19147 ret = bpf_prog_offload_finalize(env); 19148 19149 skip_full_check: 19150 kvfree(env->explored_states); 19151 19152 if (ret == 0) 19153 ret = check_max_stack_depth(env); 19154 19155 /* instruction rewrites happen after this point */ 19156 if (ret == 0) 19157 ret = optimize_bpf_loop(env); 19158 19159 if (is_priv) { 19160 if (ret == 0) 19161 opt_hard_wire_dead_code_branches(env); 19162 if (ret == 0) 19163 ret = opt_remove_dead_code(env); 19164 if (ret == 0) 19165 ret = opt_remove_nops(env); 19166 } else { 19167 if (ret == 0) 19168 sanitize_dead_code(env); 19169 } 19170 19171 if (ret == 0) 19172 /* program is valid, convert *(u32*)(ctx + off) accesses */ 19173 ret = convert_ctx_accesses(env); 19174 19175 if (ret == 0) 19176 ret = do_misc_fixups(env); 19177 19178 /* do 32-bit optimization after insn patching has done so those patched 19179 * insns could be handled correctly. 19180 */ 19181 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 19182 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 19183 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 19184 : false; 19185 } 19186 19187 if (ret == 0) 19188 ret = fixup_call_args(env); 19189 19190 env->verification_time = ktime_get_ns() - start_time; 19191 print_verification_stats(env); 19192 env->prog->aux->verified_insns = env->insn_processed; 19193 19194 /* preserve original error even if log finalization is successful */ 19195 err = bpf_vlog_finalize(&env->log, &log_true_size); 19196 if (err) 19197 ret = err; 19198 19199 if (uattr_size >= offsetofend(union bpf_attr, log_true_size) && 19200 copy_to_bpfptr_offset(uattr, offsetof(union bpf_attr, log_true_size), 19201 &log_true_size, sizeof(log_true_size))) { 19202 ret = -EFAULT; 19203 goto err_release_maps; 19204 } 19205 19206 if (ret) 19207 goto err_release_maps; 19208 19209 if (env->used_map_cnt) { 19210 /* if program passed verifier, update used_maps in bpf_prog_info */ 19211 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 19212 sizeof(env->used_maps[0]), 19213 GFP_KERNEL); 19214 19215 if (!env->prog->aux->used_maps) { 19216 ret = -ENOMEM; 19217 goto err_release_maps; 19218 } 19219 19220 memcpy(env->prog->aux->used_maps, env->used_maps, 19221 sizeof(env->used_maps[0]) * env->used_map_cnt); 19222 env->prog->aux->used_map_cnt = env->used_map_cnt; 19223 } 19224 if (env->used_btf_cnt) { 19225 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 19226 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 19227 sizeof(env->used_btfs[0]), 19228 GFP_KERNEL); 19229 if (!env->prog->aux->used_btfs) { 19230 ret = -ENOMEM; 19231 goto err_release_maps; 19232 } 19233 19234 memcpy(env->prog->aux->used_btfs, env->used_btfs, 19235 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 19236 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 19237 } 19238 if (env->used_map_cnt || env->used_btf_cnt) { 19239 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 19240 * bpf_ld_imm64 instructions 19241 */ 19242 convert_pseudo_ld_imm64(env); 19243 } 19244 19245 adjust_btf_func(env); 19246 19247 err_release_maps: 19248 if (!env->prog->aux->used_maps) 19249 /* if we didn't copy map pointers into bpf_prog_info, release 19250 * them now. Otherwise free_used_maps() will release them. 19251 */ 19252 release_maps(env); 19253 if (!env->prog->aux->used_btfs) 19254 release_btfs(env); 19255 19256 /* extension progs temporarily inherit the attach_type of their targets 19257 for verification purposes, so set it back to zero before returning 19258 */ 19259 if (env->prog->type == BPF_PROG_TYPE_EXT) 19260 env->prog->expected_attach_type = 0; 19261 19262 *prog = env->prog; 19263 err_unlock: 19264 if (!is_priv) 19265 mutex_unlock(&bpf_verifier_lock); 19266 vfree(env->insn_aux_data); 19267 err_free_env: 19268 kfree(env); 19269 return ret; 19270 } 19271