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 199 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 200 { 201 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 202 } 203 204 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 205 { 206 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 207 } 208 209 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 210 const struct bpf_map *map, bool unpriv) 211 { 212 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 213 unpriv |= bpf_map_ptr_unpriv(aux); 214 aux->map_ptr_state = (unsigned long)map | 215 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 216 } 217 218 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 219 { 220 return aux->map_key_state & BPF_MAP_KEY_POISON; 221 } 222 223 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 224 { 225 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 226 } 227 228 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 229 { 230 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 231 } 232 233 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 234 { 235 bool poisoned = bpf_map_key_poisoned(aux); 236 237 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 238 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 239 } 240 241 static bool bpf_pseudo_call(const struct bpf_insn *insn) 242 { 243 return insn->code == (BPF_JMP | BPF_CALL) && 244 insn->src_reg == BPF_PSEUDO_CALL; 245 } 246 247 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 248 { 249 return insn->code == (BPF_JMP | BPF_CALL) && 250 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 251 } 252 253 struct bpf_call_arg_meta { 254 struct bpf_map *map_ptr; 255 bool raw_mode; 256 bool pkt_access; 257 u8 release_regno; 258 int regno; 259 int access_size; 260 int mem_size; 261 u64 msize_max_value; 262 int ref_obj_id; 263 int dynptr_id; 264 int map_uid; 265 int func_id; 266 struct btf *btf; 267 u32 btf_id; 268 struct btf *ret_btf; 269 u32 ret_btf_id; 270 u32 subprogno; 271 struct btf_field *kptr_field; 272 }; 273 274 struct bpf_kfunc_call_arg_meta { 275 /* In parameters */ 276 struct btf *btf; 277 u32 func_id; 278 u32 kfunc_flags; 279 const struct btf_type *func_proto; 280 const char *func_name; 281 /* Out parameters */ 282 u32 ref_obj_id; 283 u8 release_regno; 284 bool r0_rdonly; 285 u32 ret_btf_id; 286 u64 r0_size; 287 u32 subprogno; 288 struct { 289 u64 value; 290 bool found; 291 } arg_constant; 292 struct { 293 struct btf *btf; 294 u32 btf_id; 295 } arg_obj_drop; 296 struct { 297 struct btf_field *field; 298 } arg_list_head; 299 struct { 300 struct btf_field *field; 301 } arg_rbtree_root; 302 struct { 303 enum bpf_dynptr_type type; 304 u32 id; 305 } initialized_dynptr; 306 struct { 307 u8 spi; 308 u8 frameno; 309 } iter; 310 u64 mem_size; 311 }; 312 313 struct btf *btf_vmlinux; 314 315 static DEFINE_MUTEX(bpf_verifier_lock); 316 317 static const struct bpf_line_info * 318 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 319 { 320 const struct bpf_line_info *linfo; 321 const struct bpf_prog *prog; 322 u32 i, nr_linfo; 323 324 prog = env->prog; 325 nr_linfo = prog->aux->nr_linfo; 326 327 if (!nr_linfo || insn_off >= prog->len) 328 return NULL; 329 330 linfo = prog->aux->linfo; 331 for (i = 1; i < nr_linfo; i++) 332 if (insn_off < linfo[i].insn_off) 333 break; 334 335 return &linfo[i - 1]; 336 } 337 338 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, 339 va_list args) 340 { 341 unsigned int n; 342 343 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); 344 345 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, 346 "verifier log line truncated - local buffer too short\n"); 347 348 if (log->level == BPF_LOG_KERNEL) { 349 bool newline = n > 0 && log->kbuf[n - 1] == '\n'; 350 351 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n"); 352 return; 353 } 354 355 n = min(log->len_total - log->len_used - 1, n); 356 log->kbuf[n] = '\0'; 357 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) 358 log->len_used += n; 359 else 360 log->ubuf = NULL; 361 } 362 363 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos) 364 { 365 char zero = 0; 366 367 if (!bpf_verifier_log_needed(log)) 368 return; 369 370 log->len_used = new_pos; 371 if (put_user(zero, log->ubuf + new_pos)) 372 log->ubuf = NULL; 373 } 374 375 /* log_level controls verbosity level of eBPF verifier. 376 * bpf_verifier_log_write() is used to dump the verification trace to the log, 377 * so the user can figure out what's wrong with the program 378 */ 379 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 380 const char *fmt, ...) 381 { 382 va_list args; 383 384 if (!bpf_verifier_log_needed(&env->log)) 385 return; 386 387 va_start(args, fmt); 388 bpf_verifier_vlog(&env->log, fmt, args); 389 va_end(args); 390 } 391 EXPORT_SYMBOL_GPL(bpf_verifier_log_write); 392 393 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 394 { 395 struct bpf_verifier_env *env = private_data; 396 va_list args; 397 398 if (!bpf_verifier_log_needed(&env->log)) 399 return; 400 401 va_start(args, fmt); 402 bpf_verifier_vlog(&env->log, fmt, args); 403 va_end(args); 404 } 405 406 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log, 407 const char *fmt, ...) 408 { 409 va_list args; 410 411 if (!bpf_verifier_log_needed(log)) 412 return; 413 414 va_start(args, fmt); 415 bpf_verifier_vlog(log, fmt, args); 416 va_end(args); 417 } 418 EXPORT_SYMBOL_GPL(bpf_log); 419 420 static const char *ltrim(const char *s) 421 { 422 while (isspace(*s)) 423 s++; 424 425 return s; 426 } 427 428 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 429 u32 insn_off, 430 const char *prefix_fmt, ...) 431 { 432 const struct bpf_line_info *linfo; 433 434 if (!bpf_verifier_log_needed(&env->log)) 435 return; 436 437 linfo = find_linfo(env, insn_off); 438 if (!linfo || linfo == env->prev_linfo) 439 return; 440 441 if (prefix_fmt) { 442 va_list args; 443 444 va_start(args, prefix_fmt); 445 bpf_verifier_vlog(&env->log, prefix_fmt, args); 446 va_end(args); 447 } 448 449 verbose(env, "%s\n", 450 ltrim(btf_name_by_offset(env->prog->aux->btf, 451 linfo->line_off))); 452 453 env->prev_linfo = linfo; 454 } 455 456 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 457 struct bpf_reg_state *reg, 458 struct tnum *range, const char *ctx, 459 const char *reg_name) 460 { 461 char tn_buf[48]; 462 463 verbose(env, "At %s the register %s ", ctx, reg_name); 464 if (!tnum_is_unknown(reg->var_off)) { 465 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 466 verbose(env, "has value %s", tn_buf); 467 } else { 468 verbose(env, "has unknown scalar value"); 469 } 470 tnum_strn(tn_buf, sizeof(tn_buf), *range); 471 verbose(env, " should have been in %s\n", tn_buf); 472 } 473 474 static bool type_is_pkt_pointer(enum bpf_reg_type type) 475 { 476 type = base_type(type); 477 return type == PTR_TO_PACKET || 478 type == PTR_TO_PACKET_META; 479 } 480 481 static bool type_is_sk_pointer(enum bpf_reg_type type) 482 { 483 return type == PTR_TO_SOCKET || 484 type == PTR_TO_SOCK_COMMON || 485 type == PTR_TO_TCP_SOCK || 486 type == PTR_TO_XDP_SOCK; 487 } 488 489 static bool type_may_be_null(u32 type) 490 { 491 return type & PTR_MAYBE_NULL; 492 } 493 494 static bool reg_type_not_null(enum bpf_reg_type type) 495 { 496 if (type_may_be_null(type)) 497 return false; 498 499 type = base_type(type); 500 return type == PTR_TO_SOCKET || 501 type == PTR_TO_TCP_SOCK || 502 type == PTR_TO_MAP_VALUE || 503 type == PTR_TO_MAP_KEY || 504 type == PTR_TO_SOCK_COMMON || 505 type == PTR_TO_MEM; 506 } 507 508 static bool type_is_ptr_alloc_obj(u32 type) 509 { 510 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 511 } 512 513 static bool type_is_non_owning_ref(u32 type) 514 { 515 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF; 516 } 517 518 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 519 { 520 struct btf_record *rec = NULL; 521 struct btf_struct_meta *meta; 522 523 if (reg->type == PTR_TO_MAP_VALUE) { 524 rec = reg->map_ptr->record; 525 } else if (type_is_ptr_alloc_obj(reg->type)) { 526 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 527 if (meta) 528 rec = meta->record; 529 } 530 return rec; 531 } 532 533 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 534 { 535 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 536 } 537 538 static bool type_is_rdonly_mem(u32 type) 539 { 540 return type & MEM_RDONLY; 541 } 542 543 static bool is_acquire_function(enum bpf_func_id func_id, 544 const struct bpf_map *map) 545 { 546 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 547 548 if (func_id == BPF_FUNC_sk_lookup_tcp || 549 func_id == BPF_FUNC_sk_lookup_udp || 550 func_id == BPF_FUNC_skc_lookup_tcp || 551 func_id == BPF_FUNC_ringbuf_reserve || 552 func_id == BPF_FUNC_kptr_xchg) 553 return true; 554 555 if (func_id == BPF_FUNC_map_lookup_elem && 556 (map_type == BPF_MAP_TYPE_SOCKMAP || 557 map_type == BPF_MAP_TYPE_SOCKHASH)) 558 return true; 559 560 return false; 561 } 562 563 static bool is_ptr_cast_function(enum bpf_func_id func_id) 564 { 565 return func_id == BPF_FUNC_tcp_sock || 566 func_id == BPF_FUNC_sk_fullsock || 567 func_id == BPF_FUNC_skc_to_tcp_sock || 568 func_id == BPF_FUNC_skc_to_tcp6_sock || 569 func_id == BPF_FUNC_skc_to_udp6_sock || 570 func_id == BPF_FUNC_skc_to_mptcp_sock || 571 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 572 func_id == BPF_FUNC_skc_to_tcp_request_sock; 573 } 574 575 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 576 { 577 return func_id == BPF_FUNC_dynptr_data; 578 } 579 580 static bool is_callback_calling_function(enum bpf_func_id func_id) 581 { 582 return func_id == BPF_FUNC_for_each_map_elem || 583 func_id == BPF_FUNC_timer_set_callback || 584 func_id == BPF_FUNC_find_vma || 585 func_id == BPF_FUNC_loop || 586 func_id == BPF_FUNC_user_ringbuf_drain; 587 } 588 589 static bool is_storage_get_function(enum bpf_func_id func_id) 590 { 591 return func_id == BPF_FUNC_sk_storage_get || 592 func_id == BPF_FUNC_inode_storage_get || 593 func_id == BPF_FUNC_task_storage_get || 594 func_id == BPF_FUNC_cgrp_storage_get; 595 } 596 597 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 598 const struct bpf_map *map) 599 { 600 int ref_obj_uses = 0; 601 602 if (is_ptr_cast_function(func_id)) 603 ref_obj_uses++; 604 if (is_acquire_function(func_id, map)) 605 ref_obj_uses++; 606 if (is_dynptr_ref_function(func_id)) 607 ref_obj_uses++; 608 609 return ref_obj_uses > 1; 610 } 611 612 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 613 { 614 return BPF_CLASS(insn->code) == BPF_STX && 615 BPF_MODE(insn->code) == BPF_ATOMIC && 616 insn->imm == BPF_CMPXCHG; 617 } 618 619 /* string representation of 'enum bpf_reg_type' 620 * 621 * Note that reg_type_str() can not appear more than once in a single verbose() 622 * statement. 623 */ 624 static const char *reg_type_str(struct bpf_verifier_env *env, 625 enum bpf_reg_type type) 626 { 627 char postfix[16] = {0}, prefix[64] = {0}; 628 static const char * const str[] = { 629 [NOT_INIT] = "?", 630 [SCALAR_VALUE] = "scalar", 631 [PTR_TO_CTX] = "ctx", 632 [CONST_PTR_TO_MAP] = "map_ptr", 633 [PTR_TO_MAP_VALUE] = "map_value", 634 [PTR_TO_STACK] = "fp", 635 [PTR_TO_PACKET] = "pkt", 636 [PTR_TO_PACKET_META] = "pkt_meta", 637 [PTR_TO_PACKET_END] = "pkt_end", 638 [PTR_TO_FLOW_KEYS] = "flow_keys", 639 [PTR_TO_SOCKET] = "sock", 640 [PTR_TO_SOCK_COMMON] = "sock_common", 641 [PTR_TO_TCP_SOCK] = "tcp_sock", 642 [PTR_TO_TP_BUFFER] = "tp_buffer", 643 [PTR_TO_XDP_SOCK] = "xdp_sock", 644 [PTR_TO_BTF_ID] = "ptr_", 645 [PTR_TO_MEM] = "mem", 646 [PTR_TO_BUF] = "buf", 647 [PTR_TO_FUNC] = "func", 648 [PTR_TO_MAP_KEY] = "map_key", 649 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 650 }; 651 652 if (type & PTR_MAYBE_NULL) { 653 if (base_type(type) == PTR_TO_BTF_ID) 654 strncpy(postfix, "or_null_", 16); 655 else 656 strncpy(postfix, "_or_null", 16); 657 } 658 659 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 660 type & MEM_RDONLY ? "rdonly_" : "", 661 type & MEM_RINGBUF ? "ringbuf_" : "", 662 type & MEM_USER ? "user_" : "", 663 type & MEM_PERCPU ? "percpu_" : "", 664 type & MEM_RCU ? "rcu_" : "", 665 type & PTR_UNTRUSTED ? "untrusted_" : "", 666 type & PTR_TRUSTED ? "trusted_" : "" 667 ); 668 669 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s", 670 prefix, str[base_type(type)], postfix); 671 return env->type_str_buf; 672 } 673 674 static char slot_type_char[] = { 675 [STACK_INVALID] = '?', 676 [STACK_SPILL] = 'r', 677 [STACK_MISC] = 'm', 678 [STACK_ZERO] = '0', 679 [STACK_DYNPTR] = 'd', 680 [STACK_ITER] = 'i', 681 }; 682 683 static void print_liveness(struct bpf_verifier_env *env, 684 enum bpf_reg_liveness live) 685 { 686 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 687 verbose(env, "_"); 688 if (live & REG_LIVE_READ) 689 verbose(env, "r"); 690 if (live & REG_LIVE_WRITTEN) 691 verbose(env, "w"); 692 if (live & REG_LIVE_DONE) 693 verbose(env, "D"); 694 } 695 696 static int __get_spi(s32 off) 697 { 698 return (-off - 1) / BPF_REG_SIZE; 699 } 700 701 static struct bpf_func_state *func(struct bpf_verifier_env *env, 702 const struct bpf_reg_state *reg) 703 { 704 struct bpf_verifier_state *cur = env->cur_state; 705 706 return cur->frame[reg->frameno]; 707 } 708 709 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 710 { 711 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 712 713 /* We need to check that slots between [spi - nr_slots + 1, spi] are 714 * within [0, allocated_stack). 715 * 716 * Please note that the spi grows downwards. For example, a dynptr 717 * takes the size of two stack slots; the first slot will be at 718 * spi and the second slot will be at spi - 1. 719 */ 720 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 721 } 722 723 static int stack_slot_obj_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 724 const char *obj_kind, int nr_slots) 725 { 726 int off, spi; 727 728 if (!tnum_is_const(reg->var_off)) { 729 verbose(env, "%s has to be at a constant offset\n", obj_kind); 730 return -EINVAL; 731 } 732 733 off = reg->off + reg->var_off.value; 734 if (off % BPF_REG_SIZE) { 735 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 736 return -EINVAL; 737 } 738 739 spi = __get_spi(off); 740 if (spi + 1 < nr_slots) { 741 verbose(env, "cannot pass in %s at an offset=%d\n", obj_kind, off); 742 return -EINVAL; 743 } 744 745 if (!is_spi_bounds_valid(func(env, reg), spi, nr_slots)) 746 return -ERANGE; 747 return spi; 748 } 749 750 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 751 { 752 return stack_slot_obj_get_spi(env, reg, "dynptr", BPF_DYNPTR_NR_SLOTS); 753 } 754 755 static int iter_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int nr_slots) 756 { 757 return stack_slot_obj_get_spi(env, reg, "iter", nr_slots); 758 } 759 760 static const char *btf_type_name(const struct btf *btf, u32 id) 761 { 762 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 763 } 764 765 static const char *dynptr_type_str(enum bpf_dynptr_type type) 766 { 767 switch (type) { 768 case BPF_DYNPTR_TYPE_LOCAL: 769 return "local"; 770 case BPF_DYNPTR_TYPE_RINGBUF: 771 return "ringbuf"; 772 case BPF_DYNPTR_TYPE_SKB: 773 return "skb"; 774 case BPF_DYNPTR_TYPE_XDP: 775 return "xdp"; 776 case BPF_DYNPTR_TYPE_INVALID: 777 return "<invalid>"; 778 default: 779 WARN_ONCE(1, "unknown dynptr type %d\n", type); 780 return "<unknown>"; 781 } 782 } 783 784 static const char *iter_type_str(const struct btf *btf, u32 btf_id) 785 { 786 if (!btf || btf_id == 0) 787 return "<invalid>"; 788 789 /* we already validated that type is valid and has conforming name */ 790 return btf_type_name(btf, btf_id) + sizeof(ITER_PREFIX) - 1; 791 } 792 793 static const char *iter_state_str(enum bpf_iter_state state) 794 { 795 switch (state) { 796 case BPF_ITER_STATE_ACTIVE: 797 return "active"; 798 case BPF_ITER_STATE_DRAINED: 799 return "drained"; 800 case BPF_ITER_STATE_INVALID: 801 return "<invalid>"; 802 default: 803 WARN_ONCE(1, "unknown iter state %d\n", state); 804 return "<unknown>"; 805 } 806 } 807 808 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 809 { 810 env->scratched_regs |= 1U << regno; 811 } 812 813 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 814 { 815 env->scratched_stack_slots |= 1ULL << spi; 816 } 817 818 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 819 { 820 return (env->scratched_regs >> regno) & 1; 821 } 822 823 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 824 { 825 return (env->scratched_stack_slots >> regno) & 1; 826 } 827 828 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 829 { 830 return env->scratched_regs || env->scratched_stack_slots; 831 } 832 833 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 834 { 835 env->scratched_regs = 0U; 836 env->scratched_stack_slots = 0ULL; 837 } 838 839 /* Used for printing the entire verifier state. */ 840 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 841 { 842 env->scratched_regs = ~0U; 843 env->scratched_stack_slots = ~0ULL; 844 } 845 846 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 847 { 848 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 849 case DYNPTR_TYPE_LOCAL: 850 return BPF_DYNPTR_TYPE_LOCAL; 851 case DYNPTR_TYPE_RINGBUF: 852 return BPF_DYNPTR_TYPE_RINGBUF; 853 case DYNPTR_TYPE_SKB: 854 return BPF_DYNPTR_TYPE_SKB; 855 case DYNPTR_TYPE_XDP: 856 return BPF_DYNPTR_TYPE_XDP; 857 default: 858 return BPF_DYNPTR_TYPE_INVALID; 859 } 860 } 861 862 static enum bpf_type_flag get_dynptr_type_flag(enum bpf_dynptr_type type) 863 { 864 switch (type) { 865 case BPF_DYNPTR_TYPE_LOCAL: 866 return DYNPTR_TYPE_LOCAL; 867 case BPF_DYNPTR_TYPE_RINGBUF: 868 return DYNPTR_TYPE_RINGBUF; 869 case BPF_DYNPTR_TYPE_SKB: 870 return DYNPTR_TYPE_SKB; 871 case BPF_DYNPTR_TYPE_XDP: 872 return DYNPTR_TYPE_XDP; 873 default: 874 return 0; 875 } 876 } 877 878 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 879 { 880 return type == BPF_DYNPTR_TYPE_RINGBUF; 881 } 882 883 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 884 enum bpf_dynptr_type type, 885 bool first_slot, int dynptr_id); 886 887 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 888 struct bpf_reg_state *reg); 889 890 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 891 struct bpf_reg_state *sreg1, 892 struct bpf_reg_state *sreg2, 893 enum bpf_dynptr_type type) 894 { 895 int id = ++env->id_gen; 896 897 __mark_dynptr_reg(sreg1, type, true, id); 898 __mark_dynptr_reg(sreg2, type, false, id); 899 } 900 901 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 902 struct bpf_reg_state *reg, 903 enum bpf_dynptr_type type) 904 { 905 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 906 } 907 908 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 909 struct bpf_func_state *state, int spi); 910 911 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 912 enum bpf_arg_type arg_type, int insn_idx) 913 { 914 struct bpf_func_state *state = func(env, reg); 915 enum bpf_dynptr_type type; 916 int spi, i, id, err; 917 918 spi = dynptr_get_spi(env, reg); 919 if (spi < 0) 920 return spi; 921 922 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 923 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 924 * to ensure that for the following example: 925 * [d1][d1][d2][d2] 926 * spi 3 2 1 0 927 * So marking spi = 2 should lead to destruction of both d1 and d2. In 928 * case they do belong to same dynptr, second call won't see slot_type 929 * as STACK_DYNPTR and will simply skip destruction. 930 */ 931 err = destroy_if_dynptr_stack_slot(env, state, spi); 932 if (err) 933 return err; 934 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 935 if (err) 936 return err; 937 938 for (i = 0; i < BPF_REG_SIZE; i++) { 939 state->stack[spi].slot_type[i] = STACK_DYNPTR; 940 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 941 } 942 943 type = arg_to_dynptr_type(arg_type); 944 if (type == BPF_DYNPTR_TYPE_INVALID) 945 return -EINVAL; 946 947 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 948 &state->stack[spi - 1].spilled_ptr, type); 949 950 if (dynptr_type_refcounted(type)) { 951 /* The id is used to track proper releasing */ 952 id = acquire_reference_state(env, insn_idx); 953 if (id < 0) 954 return id; 955 956 state->stack[spi].spilled_ptr.ref_obj_id = id; 957 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 958 } 959 960 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 961 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 962 963 return 0; 964 } 965 966 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 967 { 968 struct bpf_func_state *state = func(env, reg); 969 int spi, i; 970 971 spi = dynptr_get_spi(env, reg); 972 if (spi < 0) 973 return spi; 974 975 for (i = 0; i < BPF_REG_SIZE; i++) { 976 state->stack[spi].slot_type[i] = STACK_INVALID; 977 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 978 } 979 980 /* Invalidate any slices associated with this dynptr */ 981 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) 982 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id)); 983 984 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 985 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 986 987 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 988 * 989 * While we don't allow reading STACK_INVALID, it is still possible to 990 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 991 * helpers or insns can do partial read of that part without failing, 992 * but check_stack_range_initialized, check_stack_read_var_off, and 993 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 994 * the slot conservatively. Hence we need to prevent those liveness 995 * marking walks. 996 * 997 * This was not a problem before because STACK_INVALID is only set by 998 * default (where the default reg state has its reg->parent as NULL), or 999 * in clean_live_states after REG_LIVE_DONE (at which point 1000 * mark_reg_read won't walk reg->parent chain), but not randomly during 1001 * verifier state exploration (like we did above). Hence, for our case 1002 * parentage chain will still be live (i.e. reg->parent may be 1003 * non-NULL), while earlier reg->parent was NULL, so we need 1004 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 1005 * done later on reads or by mark_dynptr_read as well to unnecessary 1006 * mark registers in verifier state. 1007 */ 1008 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1009 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 1010 1011 return 0; 1012 } 1013 1014 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1015 struct bpf_reg_state *reg); 1016 1017 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1018 { 1019 if (!env->allow_ptr_leaks) 1020 __mark_reg_not_init(env, reg); 1021 else 1022 __mark_reg_unknown(env, reg); 1023 } 1024 1025 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 1026 struct bpf_func_state *state, int spi) 1027 { 1028 struct bpf_func_state *fstate; 1029 struct bpf_reg_state *dreg; 1030 int i, dynptr_id; 1031 1032 /* We always ensure that STACK_DYNPTR is never set partially, 1033 * hence just checking for slot_type[0] is enough. This is 1034 * different for STACK_SPILL, where it may be only set for 1035 * 1 byte, so code has to use is_spilled_reg. 1036 */ 1037 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 1038 return 0; 1039 1040 /* Reposition spi to first slot */ 1041 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1042 spi = spi + 1; 1043 1044 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 1045 verbose(env, "cannot overwrite referenced dynptr\n"); 1046 return -EINVAL; 1047 } 1048 1049 mark_stack_slot_scratched(env, spi); 1050 mark_stack_slot_scratched(env, spi - 1); 1051 1052 /* Writing partially to one dynptr stack slot destroys both. */ 1053 for (i = 0; i < BPF_REG_SIZE; i++) { 1054 state->stack[spi].slot_type[i] = STACK_INVALID; 1055 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 1056 } 1057 1058 dynptr_id = state->stack[spi].spilled_ptr.id; 1059 /* Invalidate any slices associated with this dynptr */ 1060 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 1061 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 1062 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 1063 continue; 1064 if (dreg->dynptr_id == dynptr_id) 1065 mark_reg_invalid(env, dreg); 1066 })); 1067 1068 /* Do not release reference state, we are destroying dynptr on stack, 1069 * not using some helper to release it. Just reset register. 1070 */ 1071 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 1072 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 1073 1074 /* Same reason as unmark_stack_slots_dynptr above */ 1075 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1076 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 1077 1078 return 0; 1079 } 1080 1081 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1082 { 1083 int spi; 1084 1085 if (reg->type == CONST_PTR_TO_DYNPTR) 1086 return false; 1087 1088 spi = dynptr_get_spi(env, reg); 1089 1090 /* -ERANGE (i.e. spi not falling into allocated stack slots) isn't an 1091 * error because this just means the stack state hasn't been updated yet. 1092 * We will do check_mem_access to check and update stack bounds later. 1093 */ 1094 if (spi < 0 && spi != -ERANGE) 1095 return false; 1096 1097 /* We don't need to check if the stack slots are marked by previous 1098 * dynptr initializations because we allow overwriting existing unreferenced 1099 * STACK_DYNPTR slots, see mark_stack_slots_dynptr which calls 1100 * destroy_if_dynptr_stack_slot to ensure dynptr objects at the slots we are 1101 * touching are completely destructed before we reinitialize them for a new 1102 * one. For referenced ones, destroy_if_dynptr_stack_slot returns an error early 1103 * instead of delaying it until the end where the user will get "Unreleased 1104 * reference" error. 1105 */ 1106 return true; 1107 } 1108 1109 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 1110 { 1111 struct bpf_func_state *state = func(env, reg); 1112 int i, spi; 1113 1114 /* This already represents first slot of initialized bpf_dynptr. 1115 * 1116 * CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 1117 * check_func_arg_reg_off's logic, so we don't need to check its 1118 * offset and alignment. 1119 */ 1120 if (reg->type == CONST_PTR_TO_DYNPTR) 1121 return true; 1122 1123 spi = dynptr_get_spi(env, reg); 1124 if (spi < 0) 1125 return false; 1126 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 1127 return false; 1128 1129 for (i = 0; i < BPF_REG_SIZE; i++) { 1130 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 1131 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 1132 return false; 1133 } 1134 1135 return true; 1136 } 1137 1138 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1139 enum bpf_arg_type arg_type) 1140 { 1141 struct bpf_func_state *state = func(env, reg); 1142 enum bpf_dynptr_type dynptr_type; 1143 int spi; 1144 1145 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1146 if (arg_type == ARG_PTR_TO_DYNPTR) 1147 return true; 1148 1149 dynptr_type = arg_to_dynptr_type(arg_type); 1150 if (reg->type == CONST_PTR_TO_DYNPTR) { 1151 return reg->dynptr.type == dynptr_type; 1152 } else { 1153 spi = dynptr_get_spi(env, reg); 1154 if (spi < 0) 1155 return false; 1156 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1157 } 1158 } 1159 1160 static void __mark_reg_known_zero(struct bpf_reg_state *reg); 1161 1162 static int mark_stack_slots_iter(struct bpf_verifier_env *env, 1163 struct bpf_reg_state *reg, int insn_idx, 1164 struct btf *btf, u32 btf_id, int nr_slots) 1165 { 1166 struct bpf_func_state *state = func(env, reg); 1167 int spi, i, j, id; 1168 1169 spi = iter_get_spi(env, reg, nr_slots); 1170 if (spi < 0) 1171 return spi; 1172 1173 id = acquire_reference_state(env, insn_idx); 1174 if (id < 0) 1175 return id; 1176 1177 for (i = 0; i < nr_slots; i++) { 1178 struct bpf_stack_state *slot = &state->stack[spi - i]; 1179 struct bpf_reg_state *st = &slot->spilled_ptr; 1180 1181 __mark_reg_known_zero(st); 1182 st->type = PTR_TO_STACK; /* we don't have dedicated reg type */ 1183 st->live |= REG_LIVE_WRITTEN; 1184 st->ref_obj_id = i == 0 ? id : 0; 1185 st->iter.btf = btf; 1186 st->iter.btf_id = btf_id; 1187 st->iter.state = BPF_ITER_STATE_ACTIVE; 1188 st->iter.depth = 0; 1189 1190 for (j = 0; j < BPF_REG_SIZE; j++) 1191 slot->slot_type[j] = STACK_ITER; 1192 1193 mark_stack_slot_scratched(env, spi - i); 1194 } 1195 1196 return 0; 1197 } 1198 1199 static int unmark_stack_slots_iter(struct bpf_verifier_env *env, 1200 struct bpf_reg_state *reg, int nr_slots) 1201 { 1202 struct bpf_func_state *state = func(env, reg); 1203 int spi, i, j; 1204 1205 spi = iter_get_spi(env, reg, nr_slots); 1206 if (spi < 0) 1207 return spi; 1208 1209 for (i = 0; i < nr_slots; i++) { 1210 struct bpf_stack_state *slot = &state->stack[spi - i]; 1211 struct bpf_reg_state *st = &slot->spilled_ptr; 1212 1213 if (i == 0) 1214 WARN_ON_ONCE(release_reference(env, st->ref_obj_id)); 1215 1216 __mark_reg_not_init(env, st); 1217 1218 /* see unmark_stack_slots_dynptr() for why we need to set REG_LIVE_WRITTEN */ 1219 st->live |= REG_LIVE_WRITTEN; 1220 1221 for (j = 0; j < BPF_REG_SIZE; j++) 1222 slot->slot_type[j] = STACK_INVALID; 1223 1224 mark_stack_slot_scratched(env, spi - i); 1225 } 1226 1227 return 0; 1228 } 1229 1230 static bool is_iter_reg_valid_uninit(struct bpf_verifier_env *env, 1231 struct bpf_reg_state *reg, int nr_slots) 1232 { 1233 struct bpf_func_state *state = func(env, reg); 1234 int spi, i, j; 1235 1236 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 1237 * will do check_mem_access to check and update stack bounds later, so 1238 * return true for that case. 1239 */ 1240 spi = iter_get_spi(env, reg, nr_slots); 1241 if (spi == -ERANGE) 1242 return true; 1243 if (spi < 0) 1244 return false; 1245 1246 for (i = 0; i < nr_slots; i++) { 1247 struct bpf_stack_state *slot = &state->stack[spi - i]; 1248 1249 for (j = 0; j < BPF_REG_SIZE; j++) 1250 if (slot->slot_type[j] == STACK_ITER) 1251 return false; 1252 } 1253 1254 return true; 1255 } 1256 1257 static bool is_iter_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1258 struct btf *btf, u32 btf_id, int nr_slots) 1259 { 1260 struct bpf_func_state *state = func(env, reg); 1261 int spi, i, j; 1262 1263 spi = iter_get_spi(env, reg, nr_slots); 1264 if (spi < 0) 1265 return false; 1266 1267 for (i = 0; i < nr_slots; i++) { 1268 struct bpf_stack_state *slot = &state->stack[spi - i]; 1269 struct bpf_reg_state *st = &slot->spilled_ptr; 1270 1271 /* only main (first) slot has ref_obj_id set */ 1272 if (i == 0 && !st->ref_obj_id) 1273 return false; 1274 if (i != 0 && st->ref_obj_id) 1275 return false; 1276 if (st->iter.btf != btf || st->iter.btf_id != btf_id) 1277 return false; 1278 1279 for (j = 0; j < BPF_REG_SIZE; j++) 1280 if (slot->slot_type[j] != STACK_ITER) 1281 return false; 1282 } 1283 1284 return true; 1285 } 1286 1287 /* Check if given stack slot is "special": 1288 * - spilled register state (STACK_SPILL); 1289 * - dynptr state (STACK_DYNPTR); 1290 * - iter state (STACK_ITER). 1291 */ 1292 static bool is_stack_slot_special(const struct bpf_stack_state *stack) 1293 { 1294 enum bpf_stack_slot_type type = stack->slot_type[BPF_REG_SIZE - 1]; 1295 1296 switch (type) { 1297 case STACK_SPILL: 1298 case STACK_DYNPTR: 1299 case STACK_ITER: 1300 return true; 1301 case STACK_INVALID: 1302 case STACK_MISC: 1303 case STACK_ZERO: 1304 return false; 1305 default: 1306 WARN_ONCE(1, "unknown stack slot type %d\n", type); 1307 return true; 1308 } 1309 } 1310 1311 /* The reg state of a pointer or a bounded scalar was saved when 1312 * it was spilled to the stack. 1313 */ 1314 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1315 { 1316 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1317 } 1318 1319 static void scrub_spilled_slot(u8 *stype) 1320 { 1321 if (*stype != STACK_INVALID) 1322 *stype = STACK_MISC; 1323 } 1324 1325 static void print_verifier_state(struct bpf_verifier_env *env, 1326 const struct bpf_func_state *state, 1327 bool print_all) 1328 { 1329 const struct bpf_reg_state *reg; 1330 enum bpf_reg_type t; 1331 int i; 1332 1333 if (state->frameno) 1334 verbose(env, " frame%d:", state->frameno); 1335 for (i = 0; i < MAX_BPF_REG; i++) { 1336 reg = &state->regs[i]; 1337 t = reg->type; 1338 if (t == NOT_INIT) 1339 continue; 1340 if (!print_all && !reg_scratched(env, i)) 1341 continue; 1342 verbose(env, " R%d", i); 1343 print_liveness(env, reg->live); 1344 verbose(env, "="); 1345 if (t == SCALAR_VALUE && reg->precise) 1346 verbose(env, "P"); 1347 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1348 tnum_is_const(reg->var_off)) { 1349 /* reg->off should be 0 for SCALAR_VALUE */ 1350 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1351 verbose(env, "%lld", reg->var_off.value + reg->off); 1352 } else { 1353 const char *sep = ""; 1354 1355 verbose(env, "%s", reg_type_str(env, t)); 1356 if (base_type(t) == PTR_TO_BTF_ID) 1357 verbose(env, "%s", btf_type_name(reg->btf, reg->btf_id)); 1358 verbose(env, "("); 1359 /* 1360 * _a stands for append, was shortened to avoid multiline statements below. 1361 * This macro is used to output a comma separated list of attributes. 1362 */ 1363 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1364 1365 if (reg->id) 1366 verbose_a("id=%d", reg->id); 1367 if (reg->ref_obj_id) 1368 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1369 if (type_is_non_owning_ref(reg->type)) 1370 verbose_a("%s", "non_own_ref"); 1371 if (t != SCALAR_VALUE) 1372 verbose_a("off=%d", reg->off); 1373 if (type_is_pkt_pointer(t)) 1374 verbose_a("r=%d", reg->range); 1375 else if (base_type(t) == CONST_PTR_TO_MAP || 1376 base_type(t) == PTR_TO_MAP_KEY || 1377 base_type(t) == PTR_TO_MAP_VALUE) 1378 verbose_a("ks=%d,vs=%d", 1379 reg->map_ptr->key_size, 1380 reg->map_ptr->value_size); 1381 if (tnum_is_const(reg->var_off)) { 1382 /* Typically an immediate SCALAR_VALUE, but 1383 * could be a pointer whose offset is too big 1384 * for reg->off 1385 */ 1386 verbose_a("imm=%llx", reg->var_off.value); 1387 } else { 1388 if (reg->smin_value != reg->umin_value && 1389 reg->smin_value != S64_MIN) 1390 verbose_a("smin=%lld", (long long)reg->smin_value); 1391 if (reg->smax_value != reg->umax_value && 1392 reg->smax_value != S64_MAX) 1393 verbose_a("smax=%lld", (long long)reg->smax_value); 1394 if (reg->umin_value != 0) 1395 verbose_a("umin=%llu", (unsigned long long)reg->umin_value); 1396 if (reg->umax_value != U64_MAX) 1397 verbose_a("umax=%llu", (unsigned long long)reg->umax_value); 1398 if (!tnum_is_unknown(reg->var_off)) { 1399 char tn_buf[48]; 1400 1401 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1402 verbose_a("var_off=%s", tn_buf); 1403 } 1404 if (reg->s32_min_value != reg->smin_value && 1405 reg->s32_min_value != S32_MIN) 1406 verbose_a("s32_min=%d", (int)(reg->s32_min_value)); 1407 if (reg->s32_max_value != reg->smax_value && 1408 reg->s32_max_value != S32_MAX) 1409 verbose_a("s32_max=%d", (int)(reg->s32_max_value)); 1410 if (reg->u32_min_value != reg->umin_value && 1411 reg->u32_min_value != U32_MIN) 1412 verbose_a("u32_min=%d", (int)(reg->u32_min_value)); 1413 if (reg->u32_max_value != reg->umax_value && 1414 reg->u32_max_value != U32_MAX) 1415 verbose_a("u32_max=%d", (int)(reg->u32_max_value)); 1416 } 1417 #undef verbose_a 1418 1419 verbose(env, ")"); 1420 } 1421 } 1422 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1423 char types_buf[BPF_REG_SIZE + 1]; 1424 bool valid = false; 1425 int j; 1426 1427 for (j = 0; j < BPF_REG_SIZE; j++) { 1428 if (state->stack[i].slot_type[j] != STACK_INVALID) 1429 valid = true; 1430 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1431 } 1432 types_buf[BPF_REG_SIZE] = 0; 1433 if (!valid) 1434 continue; 1435 if (!print_all && !stack_slot_scratched(env, i)) 1436 continue; 1437 switch (state->stack[i].slot_type[BPF_REG_SIZE - 1]) { 1438 case STACK_SPILL: 1439 reg = &state->stack[i].spilled_ptr; 1440 t = reg->type; 1441 1442 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1443 print_liveness(env, reg->live); 1444 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1445 if (t == SCALAR_VALUE && reg->precise) 1446 verbose(env, "P"); 1447 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1448 verbose(env, "%lld", reg->var_off.value + reg->off); 1449 break; 1450 case STACK_DYNPTR: 1451 i += BPF_DYNPTR_NR_SLOTS - 1; 1452 reg = &state->stack[i].spilled_ptr; 1453 1454 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1455 print_liveness(env, reg->live); 1456 verbose(env, "=dynptr_%s", dynptr_type_str(reg->dynptr.type)); 1457 if (reg->ref_obj_id) 1458 verbose(env, "(ref_id=%d)", reg->ref_obj_id); 1459 break; 1460 case STACK_ITER: 1461 /* only main slot has ref_obj_id set; skip others */ 1462 reg = &state->stack[i].spilled_ptr; 1463 if (!reg->ref_obj_id) 1464 continue; 1465 1466 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1467 print_liveness(env, reg->live); 1468 verbose(env, "=iter_%s(ref_id=%d,state=%s,depth=%u)", 1469 iter_type_str(reg->iter.btf, reg->iter.btf_id), 1470 reg->ref_obj_id, iter_state_str(reg->iter.state), 1471 reg->iter.depth); 1472 break; 1473 case STACK_MISC: 1474 case STACK_ZERO: 1475 default: 1476 reg = &state->stack[i].spilled_ptr; 1477 1478 for (j = 0; j < BPF_REG_SIZE; j++) 1479 types_buf[j] = slot_type_char[state->stack[i].slot_type[j]]; 1480 types_buf[BPF_REG_SIZE] = 0; 1481 1482 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1483 print_liveness(env, reg->live); 1484 verbose(env, "=%s", types_buf); 1485 break; 1486 } 1487 } 1488 if (state->acquired_refs && state->refs[0].id) { 1489 verbose(env, " refs=%d", state->refs[0].id); 1490 for (i = 1; i < state->acquired_refs; i++) 1491 if (state->refs[i].id) 1492 verbose(env, ",%d", state->refs[i].id); 1493 } 1494 if (state->in_callback_fn) 1495 verbose(env, " cb"); 1496 if (state->in_async_callback_fn) 1497 verbose(env, " async_cb"); 1498 verbose(env, "\n"); 1499 mark_verifier_state_clean(env); 1500 } 1501 1502 static inline u32 vlog_alignment(u32 pos) 1503 { 1504 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1505 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1506 } 1507 1508 static void print_insn_state(struct bpf_verifier_env *env, 1509 const struct bpf_func_state *state) 1510 { 1511 if (env->prev_log_len && env->prev_log_len == env->log.len_used) { 1512 /* remove new line character */ 1513 bpf_vlog_reset(&env->log, env->prev_log_len - 1); 1514 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' '); 1515 } else { 1516 verbose(env, "%d:", env->insn_idx); 1517 } 1518 print_verifier_state(env, state, false); 1519 } 1520 1521 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1522 * small to hold src. This is different from krealloc since we don't want to preserve 1523 * the contents of dst. 1524 * 1525 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1526 * not be allocated. 1527 */ 1528 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1529 { 1530 size_t alloc_bytes; 1531 void *orig = dst; 1532 size_t bytes; 1533 1534 if (ZERO_OR_NULL_PTR(src)) 1535 goto out; 1536 1537 if (unlikely(check_mul_overflow(n, size, &bytes))) 1538 return NULL; 1539 1540 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1541 dst = krealloc(orig, alloc_bytes, flags); 1542 if (!dst) { 1543 kfree(orig); 1544 return NULL; 1545 } 1546 1547 memcpy(dst, src, bytes); 1548 out: 1549 return dst ? dst : ZERO_SIZE_PTR; 1550 } 1551 1552 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1553 * small to hold new_n items. new items are zeroed out if the array grows. 1554 * 1555 * Contrary to krealloc_array, does not free arr if new_n is zero. 1556 */ 1557 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1558 { 1559 size_t alloc_size; 1560 void *new_arr; 1561 1562 if (!new_n || old_n == new_n) 1563 goto out; 1564 1565 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1566 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1567 if (!new_arr) { 1568 kfree(arr); 1569 return NULL; 1570 } 1571 arr = new_arr; 1572 1573 if (new_n > old_n) 1574 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1575 1576 out: 1577 return arr ? arr : ZERO_SIZE_PTR; 1578 } 1579 1580 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1581 { 1582 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1583 sizeof(struct bpf_reference_state), GFP_KERNEL); 1584 if (!dst->refs) 1585 return -ENOMEM; 1586 1587 dst->acquired_refs = src->acquired_refs; 1588 return 0; 1589 } 1590 1591 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1592 { 1593 size_t n = src->allocated_stack / BPF_REG_SIZE; 1594 1595 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1596 GFP_KERNEL); 1597 if (!dst->stack) 1598 return -ENOMEM; 1599 1600 dst->allocated_stack = src->allocated_stack; 1601 return 0; 1602 } 1603 1604 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1605 { 1606 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1607 sizeof(struct bpf_reference_state)); 1608 if (!state->refs) 1609 return -ENOMEM; 1610 1611 state->acquired_refs = n; 1612 return 0; 1613 } 1614 1615 static int grow_stack_state(struct bpf_func_state *state, int size) 1616 { 1617 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1618 1619 if (old_n >= n) 1620 return 0; 1621 1622 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1623 if (!state->stack) 1624 return -ENOMEM; 1625 1626 state->allocated_stack = size; 1627 return 0; 1628 } 1629 1630 /* Acquire a pointer id from the env and update the state->refs to include 1631 * this new pointer reference. 1632 * On success, returns a valid pointer id to associate with the register 1633 * On failure, returns a negative errno. 1634 */ 1635 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1636 { 1637 struct bpf_func_state *state = cur_func(env); 1638 int new_ofs = state->acquired_refs; 1639 int id, err; 1640 1641 err = resize_reference_state(state, state->acquired_refs + 1); 1642 if (err) 1643 return err; 1644 id = ++env->id_gen; 1645 state->refs[new_ofs].id = id; 1646 state->refs[new_ofs].insn_idx = insn_idx; 1647 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1648 1649 return id; 1650 } 1651 1652 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1653 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1654 { 1655 int i, last_idx; 1656 1657 last_idx = state->acquired_refs - 1; 1658 for (i = 0; i < state->acquired_refs; i++) { 1659 if (state->refs[i].id == ptr_id) { 1660 /* Cannot release caller references in callbacks */ 1661 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1662 return -EINVAL; 1663 if (last_idx && i != last_idx) 1664 memcpy(&state->refs[i], &state->refs[last_idx], 1665 sizeof(*state->refs)); 1666 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1667 state->acquired_refs--; 1668 return 0; 1669 } 1670 } 1671 return -EINVAL; 1672 } 1673 1674 static void free_func_state(struct bpf_func_state *state) 1675 { 1676 if (!state) 1677 return; 1678 kfree(state->refs); 1679 kfree(state->stack); 1680 kfree(state); 1681 } 1682 1683 static void clear_jmp_history(struct bpf_verifier_state *state) 1684 { 1685 kfree(state->jmp_history); 1686 state->jmp_history = NULL; 1687 state->jmp_history_cnt = 0; 1688 } 1689 1690 static void free_verifier_state(struct bpf_verifier_state *state, 1691 bool free_self) 1692 { 1693 int i; 1694 1695 for (i = 0; i <= state->curframe; i++) { 1696 free_func_state(state->frame[i]); 1697 state->frame[i] = NULL; 1698 } 1699 clear_jmp_history(state); 1700 if (free_self) 1701 kfree(state); 1702 } 1703 1704 /* copy verifier state from src to dst growing dst stack space 1705 * when necessary to accommodate larger src stack 1706 */ 1707 static int copy_func_state(struct bpf_func_state *dst, 1708 const struct bpf_func_state *src) 1709 { 1710 int err; 1711 1712 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1713 err = copy_reference_state(dst, src); 1714 if (err) 1715 return err; 1716 return copy_stack_state(dst, src); 1717 } 1718 1719 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1720 const struct bpf_verifier_state *src) 1721 { 1722 struct bpf_func_state *dst; 1723 int i, err; 1724 1725 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1726 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1727 GFP_USER); 1728 if (!dst_state->jmp_history) 1729 return -ENOMEM; 1730 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1731 1732 /* if dst has more stack frames then src frame, free them */ 1733 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1734 free_func_state(dst_state->frame[i]); 1735 dst_state->frame[i] = NULL; 1736 } 1737 dst_state->speculative = src->speculative; 1738 dst_state->active_rcu_lock = src->active_rcu_lock; 1739 dst_state->curframe = src->curframe; 1740 dst_state->active_lock.ptr = src->active_lock.ptr; 1741 dst_state->active_lock.id = src->active_lock.id; 1742 dst_state->branches = src->branches; 1743 dst_state->parent = src->parent; 1744 dst_state->first_insn_idx = src->first_insn_idx; 1745 dst_state->last_insn_idx = src->last_insn_idx; 1746 for (i = 0; i <= src->curframe; i++) { 1747 dst = dst_state->frame[i]; 1748 if (!dst) { 1749 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1750 if (!dst) 1751 return -ENOMEM; 1752 dst_state->frame[i] = dst; 1753 } 1754 err = copy_func_state(dst, src->frame[i]); 1755 if (err) 1756 return err; 1757 } 1758 return 0; 1759 } 1760 1761 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1762 { 1763 while (st) { 1764 u32 br = --st->branches; 1765 1766 /* WARN_ON(br > 1) technically makes sense here, 1767 * but see comment in push_stack(), hence: 1768 */ 1769 WARN_ONCE((int)br < 0, 1770 "BUG update_branch_counts:branches_to_explore=%d\n", 1771 br); 1772 if (br) 1773 break; 1774 st = st->parent; 1775 } 1776 } 1777 1778 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1779 int *insn_idx, bool pop_log) 1780 { 1781 struct bpf_verifier_state *cur = env->cur_state; 1782 struct bpf_verifier_stack_elem *elem, *head = env->head; 1783 int err; 1784 1785 if (env->head == NULL) 1786 return -ENOENT; 1787 1788 if (cur) { 1789 err = copy_verifier_state(cur, &head->st); 1790 if (err) 1791 return err; 1792 } 1793 if (pop_log) 1794 bpf_vlog_reset(&env->log, head->log_pos); 1795 if (insn_idx) 1796 *insn_idx = head->insn_idx; 1797 if (prev_insn_idx) 1798 *prev_insn_idx = head->prev_insn_idx; 1799 elem = head->next; 1800 free_verifier_state(&head->st, false); 1801 kfree(head); 1802 env->head = elem; 1803 env->stack_size--; 1804 return 0; 1805 } 1806 1807 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1808 int insn_idx, int prev_insn_idx, 1809 bool speculative) 1810 { 1811 struct bpf_verifier_state *cur = env->cur_state; 1812 struct bpf_verifier_stack_elem *elem; 1813 int err; 1814 1815 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1816 if (!elem) 1817 goto err; 1818 1819 elem->insn_idx = insn_idx; 1820 elem->prev_insn_idx = prev_insn_idx; 1821 elem->next = env->head; 1822 elem->log_pos = env->log.len_used; 1823 env->head = elem; 1824 env->stack_size++; 1825 err = copy_verifier_state(&elem->st, cur); 1826 if (err) 1827 goto err; 1828 elem->st.speculative |= speculative; 1829 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1830 verbose(env, "The sequence of %d jumps is too complex.\n", 1831 env->stack_size); 1832 goto err; 1833 } 1834 if (elem->st.parent) { 1835 ++elem->st.parent->branches; 1836 /* WARN_ON(branches > 2) technically makes sense here, 1837 * but 1838 * 1. speculative states will bump 'branches' for non-branch 1839 * instructions 1840 * 2. is_state_visited() heuristics may decide not to create 1841 * a new state for a sequence of branches and all such current 1842 * and cloned states will be pointing to a single parent state 1843 * which might have large 'branches' count. 1844 */ 1845 } 1846 return &elem->st; 1847 err: 1848 free_verifier_state(env->cur_state, true); 1849 env->cur_state = NULL; 1850 /* pop all elements and return */ 1851 while (!pop_stack(env, NULL, NULL, false)); 1852 return NULL; 1853 } 1854 1855 #define CALLER_SAVED_REGS 6 1856 static const int caller_saved[CALLER_SAVED_REGS] = { 1857 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1858 }; 1859 1860 /* This helper doesn't clear reg->id */ 1861 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1862 { 1863 reg->var_off = tnum_const(imm); 1864 reg->smin_value = (s64)imm; 1865 reg->smax_value = (s64)imm; 1866 reg->umin_value = imm; 1867 reg->umax_value = imm; 1868 1869 reg->s32_min_value = (s32)imm; 1870 reg->s32_max_value = (s32)imm; 1871 reg->u32_min_value = (u32)imm; 1872 reg->u32_max_value = (u32)imm; 1873 } 1874 1875 /* Mark the unknown part of a register (variable offset or scalar value) as 1876 * known to have the value @imm. 1877 */ 1878 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1879 { 1880 /* Clear off and union(map_ptr, range) */ 1881 memset(((u8 *)reg) + sizeof(reg->type), 0, 1882 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1883 reg->id = 0; 1884 reg->ref_obj_id = 0; 1885 ___mark_reg_known(reg, imm); 1886 } 1887 1888 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1889 { 1890 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1891 reg->s32_min_value = (s32)imm; 1892 reg->s32_max_value = (s32)imm; 1893 reg->u32_min_value = (u32)imm; 1894 reg->u32_max_value = (u32)imm; 1895 } 1896 1897 /* Mark the 'variable offset' part of a register as zero. This should be 1898 * used only on registers holding a pointer type. 1899 */ 1900 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1901 { 1902 __mark_reg_known(reg, 0); 1903 } 1904 1905 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1906 { 1907 __mark_reg_known(reg, 0); 1908 reg->type = SCALAR_VALUE; 1909 } 1910 1911 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1912 struct bpf_reg_state *regs, u32 regno) 1913 { 1914 if (WARN_ON(regno >= MAX_BPF_REG)) { 1915 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1916 /* Something bad happened, let's kill all regs */ 1917 for (regno = 0; regno < MAX_BPF_REG; regno++) 1918 __mark_reg_not_init(env, regs + regno); 1919 return; 1920 } 1921 __mark_reg_known_zero(regs + regno); 1922 } 1923 1924 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1925 bool first_slot, int dynptr_id) 1926 { 1927 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1928 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1929 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1930 */ 1931 __mark_reg_known_zero(reg); 1932 reg->type = CONST_PTR_TO_DYNPTR; 1933 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1934 reg->id = dynptr_id; 1935 reg->dynptr.type = type; 1936 reg->dynptr.first_slot = first_slot; 1937 } 1938 1939 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1940 { 1941 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1942 const struct bpf_map *map = reg->map_ptr; 1943 1944 if (map->inner_map_meta) { 1945 reg->type = CONST_PTR_TO_MAP; 1946 reg->map_ptr = map->inner_map_meta; 1947 /* transfer reg's id which is unique for every map_lookup_elem 1948 * as UID of the inner map. 1949 */ 1950 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1951 reg->map_uid = reg->id; 1952 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1953 reg->type = PTR_TO_XDP_SOCK; 1954 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1955 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1956 reg->type = PTR_TO_SOCKET; 1957 } else { 1958 reg->type = PTR_TO_MAP_VALUE; 1959 } 1960 return; 1961 } 1962 1963 reg->type &= ~PTR_MAYBE_NULL; 1964 } 1965 1966 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1967 struct btf_field_graph_root *ds_head) 1968 { 1969 __mark_reg_known_zero(®s[regno]); 1970 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1971 regs[regno].btf = ds_head->btf; 1972 regs[regno].btf_id = ds_head->value_btf_id; 1973 regs[regno].off = ds_head->node_offset; 1974 } 1975 1976 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1977 { 1978 return type_is_pkt_pointer(reg->type); 1979 } 1980 1981 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1982 { 1983 return reg_is_pkt_pointer(reg) || 1984 reg->type == PTR_TO_PACKET_END; 1985 } 1986 1987 static bool reg_is_dynptr_slice_pkt(const struct bpf_reg_state *reg) 1988 { 1989 return base_type(reg->type) == PTR_TO_MEM && 1990 (reg->type & DYNPTR_TYPE_SKB || reg->type & DYNPTR_TYPE_XDP); 1991 } 1992 1993 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1994 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1995 enum bpf_reg_type which) 1996 { 1997 /* The register can already have a range from prior markings. 1998 * This is fine as long as it hasn't been advanced from its 1999 * origin. 2000 */ 2001 return reg->type == which && 2002 reg->id == 0 && 2003 reg->off == 0 && 2004 tnum_equals_const(reg->var_off, 0); 2005 } 2006 2007 /* Reset the min/max bounds of a register */ 2008 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 2009 { 2010 reg->smin_value = S64_MIN; 2011 reg->smax_value = S64_MAX; 2012 reg->umin_value = 0; 2013 reg->umax_value = U64_MAX; 2014 2015 reg->s32_min_value = S32_MIN; 2016 reg->s32_max_value = S32_MAX; 2017 reg->u32_min_value = 0; 2018 reg->u32_max_value = U32_MAX; 2019 } 2020 2021 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 2022 { 2023 reg->smin_value = S64_MIN; 2024 reg->smax_value = S64_MAX; 2025 reg->umin_value = 0; 2026 reg->umax_value = U64_MAX; 2027 } 2028 2029 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 2030 { 2031 reg->s32_min_value = S32_MIN; 2032 reg->s32_max_value = S32_MAX; 2033 reg->u32_min_value = 0; 2034 reg->u32_max_value = U32_MAX; 2035 } 2036 2037 static void __update_reg32_bounds(struct bpf_reg_state *reg) 2038 { 2039 struct tnum var32_off = tnum_subreg(reg->var_off); 2040 2041 /* min signed is max(sign bit) | min(other bits) */ 2042 reg->s32_min_value = max_t(s32, reg->s32_min_value, 2043 var32_off.value | (var32_off.mask & S32_MIN)); 2044 /* max signed is min(sign bit) | max(other bits) */ 2045 reg->s32_max_value = min_t(s32, reg->s32_max_value, 2046 var32_off.value | (var32_off.mask & S32_MAX)); 2047 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 2048 reg->u32_max_value = min(reg->u32_max_value, 2049 (u32)(var32_off.value | var32_off.mask)); 2050 } 2051 2052 static void __update_reg64_bounds(struct bpf_reg_state *reg) 2053 { 2054 /* min signed is max(sign bit) | min(other bits) */ 2055 reg->smin_value = max_t(s64, reg->smin_value, 2056 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 2057 /* max signed is min(sign bit) | max(other bits) */ 2058 reg->smax_value = min_t(s64, reg->smax_value, 2059 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 2060 reg->umin_value = max(reg->umin_value, reg->var_off.value); 2061 reg->umax_value = min(reg->umax_value, 2062 reg->var_off.value | reg->var_off.mask); 2063 } 2064 2065 static void __update_reg_bounds(struct bpf_reg_state *reg) 2066 { 2067 __update_reg32_bounds(reg); 2068 __update_reg64_bounds(reg); 2069 } 2070 2071 /* Uses signed min/max values to inform unsigned, and vice-versa */ 2072 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 2073 { 2074 /* Learn sign from signed bounds. 2075 * If we cannot cross the sign boundary, then signed and unsigned bounds 2076 * are the same, so combine. This works even in the negative case, e.g. 2077 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2078 */ 2079 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 2080 reg->s32_min_value = reg->u32_min_value = 2081 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2082 reg->s32_max_value = reg->u32_max_value = 2083 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2084 return; 2085 } 2086 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2087 * boundary, so we must be careful. 2088 */ 2089 if ((s32)reg->u32_max_value >= 0) { 2090 /* Positive. We can't learn anything from the smin, but smax 2091 * is positive, hence safe. 2092 */ 2093 reg->s32_min_value = reg->u32_min_value; 2094 reg->s32_max_value = reg->u32_max_value = 2095 min_t(u32, reg->s32_max_value, reg->u32_max_value); 2096 } else if ((s32)reg->u32_min_value < 0) { 2097 /* Negative. We can't learn anything from the smax, but smin 2098 * is negative, hence safe. 2099 */ 2100 reg->s32_min_value = reg->u32_min_value = 2101 max_t(u32, reg->s32_min_value, reg->u32_min_value); 2102 reg->s32_max_value = reg->u32_max_value; 2103 } 2104 } 2105 2106 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 2107 { 2108 /* Learn sign from signed bounds. 2109 * If we cannot cross the sign boundary, then signed and unsigned bounds 2110 * are the same, so combine. This works even in the negative case, e.g. 2111 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 2112 */ 2113 if (reg->smin_value >= 0 || reg->smax_value < 0) { 2114 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2115 reg->umin_value); 2116 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2117 reg->umax_value); 2118 return; 2119 } 2120 /* Learn sign from unsigned bounds. Signed bounds cross the sign 2121 * boundary, so we must be careful. 2122 */ 2123 if ((s64)reg->umax_value >= 0) { 2124 /* Positive. We can't learn anything from the smin, but smax 2125 * is positive, hence safe. 2126 */ 2127 reg->smin_value = reg->umin_value; 2128 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 2129 reg->umax_value); 2130 } else if ((s64)reg->umin_value < 0) { 2131 /* Negative. We can't learn anything from the smax, but smin 2132 * is negative, hence safe. 2133 */ 2134 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 2135 reg->umin_value); 2136 reg->smax_value = reg->umax_value; 2137 } 2138 } 2139 2140 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 2141 { 2142 __reg32_deduce_bounds(reg); 2143 __reg64_deduce_bounds(reg); 2144 } 2145 2146 /* Attempts to improve var_off based on unsigned min/max information */ 2147 static void __reg_bound_offset(struct bpf_reg_state *reg) 2148 { 2149 struct tnum var64_off = tnum_intersect(reg->var_off, 2150 tnum_range(reg->umin_value, 2151 reg->umax_value)); 2152 struct tnum var32_off = tnum_intersect(tnum_subreg(var64_off), 2153 tnum_range(reg->u32_min_value, 2154 reg->u32_max_value)); 2155 2156 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 2157 } 2158 2159 static void reg_bounds_sync(struct bpf_reg_state *reg) 2160 { 2161 /* We might have learned new bounds from the var_off. */ 2162 __update_reg_bounds(reg); 2163 /* We might have learned something about the sign bit. */ 2164 __reg_deduce_bounds(reg); 2165 /* We might have learned some bits from the bounds. */ 2166 __reg_bound_offset(reg); 2167 /* Intersecting with the old var_off might have improved our bounds 2168 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 2169 * then new var_off is (0; 0x7f...fc) which improves our umax. 2170 */ 2171 __update_reg_bounds(reg); 2172 } 2173 2174 static bool __reg32_bound_s64(s32 a) 2175 { 2176 return a >= 0 && a <= S32_MAX; 2177 } 2178 2179 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 2180 { 2181 reg->umin_value = reg->u32_min_value; 2182 reg->umax_value = reg->u32_max_value; 2183 2184 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 2185 * be positive otherwise set to worse case bounds and refine later 2186 * from tnum. 2187 */ 2188 if (__reg32_bound_s64(reg->s32_min_value) && 2189 __reg32_bound_s64(reg->s32_max_value)) { 2190 reg->smin_value = reg->s32_min_value; 2191 reg->smax_value = reg->s32_max_value; 2192 } else { 2193 reg->smin_value = 0; 2194 reg->smax_value = U32_MAX; 2195 } 2196 } 2197 2198 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 2199 { 2200 /* special case when 64-bit register has upper 32-bit register 2201 * zeroed. Typically happens after zext or <<32, >>32 sequence 2202 * allowing us to use 32-bit bounds directly, 2203 */ 2204 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 2205 __reg_assign_32_into_64(reg); 2206 } else { 2207 /* Otherwise the best we can do is push lower 32bit known and 2208 * unknown bits into register (var_off set from jmp logic) 2209 * then learn as much as possible from the 64-bit tnum 2210 * known and unknown bits. The previous smin/smax bounds are 2211 * invalid here because of jmp32 compare so mark them unknown 2212 * so they do not impact tnum bounds calculation. 2213 */ 2214 __mark_reg64_unbounded(reg); 2215 } 2216 reg_bounds_sync(reg); 2217 } 2218 2219 static bool __reg64_bound_s32(s64 a) 2220 { 2221 return a >= S32_MIN && a <= S32_MAX; 2222 } 2223 2224 static bool __reg64_bound_u32(u64 a) 2225 { 2226 return a >= U32_MIN && a <= U32_MAX; 2227 } 2228 2229 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 2230 { 2231 __mark_reg32_unbounded(reg); 2232 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 2233 reg->s32_min_value = (s32)reg->smin_value; 2234 reg->s32_max_value = (s32)reg->smax_value; 2235 } 2236 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 2237 reg->u32_min_value = (u32)reg->umin_value; 2238 reg->u32_max_value = (u32)reg->umax_value; 2239 } 2240 reg_bounds_sync(reg); 2241 } 2242 2243 /* Mark a register as having a completely unknown (scalar) value. */ 2244 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 2245 struct bpf_reg_state *reg) 2246 { 2247 /* 2248 * Clear type, off, and union(map_ptr, range) and 2249 * padding between 'type' and union 2250 */ 2251 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 2252 reg->type = SCALAR_VALUE; 2253 reg->id = 0; 2254 reg->ref_obj_id = 0; 2255 reg->var_off = tnum_unknown; 2256 reg->frameno = 0; 2257 reg->precise = !env->bpf_capable; 2258 __mark_reg_unbounded(reg); 2259 } 2260 2261 static void mark_reg_unknown(struct bpf_verifier_env *env, 2262 struct bpf_reg_state *regs, u32 regno) 2263 { 2264 if (WARN_ON(regno >= MAX_BPF_REG)) { 2265 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 2266 /* Something bad happened, let's kill all regs except FP */ 2267 for (regno = 0; regno < BPF_REG_FP; regno++) 2268 __mark_reg_not_init(env, regs + regno); 2269 return; 2270 } 2271 __mark_reg_unknown(env, regs + regno); 2272 } 2273 2274 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 2275 struct bpf_reg_state *reg) 2276 { 2277 __mark_reg_unknown(env, reg); 2278 reg->type = NOT_INIT; 2279 } 2280 2281 static void mark_reg_not_init(struct bpf_verifier_env *env, 2282 struct bpf_reg_state *regs, u32 regno) 2283 { 2284 if (WARN_ON(regno >= MAX_BPF_REG)) { 2285 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 2286 /* Something bad happened, let's kill all regs except FP */ 2287 for (regno = 0; regno < BPF_REG_FP; regno++) 2288 __mark_reg_not_init(env, regs + regno); 2289 return; 2290 } 2291 __mark_reg_not_init(env, regs + regno); 2292 } 2293 2294 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 2295 struct bpf_reg_state *regs, u32 regno, 2296 enum bpf_reg_type reg_type, 2297 struct btf *btf, u32 btf_id, 2298 enum bpf_type_flag flag) 2299 { 2300 if (reg_type == SCALAR_VALUE) { 2301 mark_reg_unknown(env, regs, regno); 2302 return; 2303 } 2304 mark_reg_known_zero(env, regs, regno); 2305 regs[regno].type = PTR_TO_BTF_ID | flag; 2306 regs[regno].btf = btf; 2307 regs[regno].btf_id = btf_id; 2308 } 2309 2310 #define DEF_NOT_SUBREG (0) 2311 static void init_reg_state(struct bpf_verifier_env *env, 2312 struct bpf_func_state *state) 2313 { 2314 struct bpf_reg_state *regs = state->regs; 2315 int i; 2316 2317 for (i = 0; i < MAX_BPF_REG; i++) { 2318 mark_reg_not_init(env, regs, i); 2319 regs[i].live = REG_LIVE_NONE; 2320 regs[i].parent = NULL; 2321 regs[i].subreg_def = DEF_NOT_SUBREG; 2322 } 2323 2324 /* frame pointer */ 2325 regs[BPF_REG_FP].type = PTR_TO_STACK; 2326 mark_reg_known_zero(env, regs, BPF_REG_FP); 2327 regs[BPF_REG_FP].frameno = state->frameno; 2328 } 2329 2330 #define BPF_MAIN_FUNC (-1) 2331 static void init_func_state(struct bpf_verifier_env *env, 2332 struct bpf_func_state *state, 2333 int callsite, int frameno, int subprogno) 2334 { 2335 state->callsite = callsite; 2336 state->frameno = frameno; 2337 state->subprogno = subprogno; 2338 state->callback_ret_range = tnum_range(0, 0); 2339 init_reg_state(env, state); 2340 mark_verifier_state_scratched(env); 2341 } 2342 2343 /* Similar to push_stack(), but for async callbacks */ 2344 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2345 int insn_idx, int prev_insn_idx, 2346 int subprog) 2347 { 2348 struct bpf_verifier_stack_elem *elem; 2349 struct bpf_func_state *frame; 2350 2351 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2352 if (!elem) 2353 goto err; 2354 2355 elem->insn_idx = insn_idx; 2356 elem->prev_insn_idx = prev_insn_idx; 2357 elem->next = env->head; 2358 elem->log_pos = env->log.len_used; 2359 env->head = elem; 2360 env->stack_size++; 2361 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2362 verbose(env, 2363 "The sequence of %d jumps is too complex for async cb.\n", 2364 env->stack_size); 2365 goto err; 2366 } 2367 /* Unlike push_stack() do not copy_verifier_state(). 2368 * The caller state doesn't matter. 2369 * This is async callback. It starts in a fresh stack. 2370 * Initialize it similar to do_check_common(). 2371 */ 2372 elem->st.branches = 1; 2373 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2374 if (!frame) 2375 goto err; 2376 init_func_state(env, frame, 2377 BPF_MAIN_FUNC /* callsite */, 2378 0 /* frameno within this callchain */, 2379 subprog /* subprog number within this prog */); 2380 elem->st.frame[0] = frame; 2381 return &elem->st; 2382 err: 2383 free_verifier_state(env->cur_state, true); 2384 env->cur_state = NULL; 2385 /* pop all elements and return */ 2386 while (!pop_stack(env, NULL, NULL, false)); 2387 return NULL; 2388 } 2389 2390 2391 enum reg_arg_type { 2392 SRC_OP, /* register is used as source operand */ 2393 DST_OP, /* register is used as destination operand */ 2394 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2395 }; 2396 2397 static int cmp_subprogs(const void *a, const void *b) 2398 { 2399 return ((struct bpf_subprog_info *)a)->start - 2400 ((struct bpf_subprog_info *)b)->start; 2401 } 2402 2403 static int find_subprog(struct bpf_verifier_env *env, int off) 2404 { 2405 struct bpf_subprog_info *p; 2406 2407 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2408 sizeof(env->subprog_info[0]), cmp_subprogs); 2409 if (!p) 2410 return -ENOENT; 2411 return p - env->subprog_info; 2412 2413 } 2414 2415 static int add_subprog(struct bpf_verifier_env *env, int off) 2416 { 2417 int insn_cnt = env->prog->len; 2418 int ret; 2419 2420 if (off >= insn_cnt || off < 0) { 2421 verbose(env, "call to invalid destination\n"); 2422 return -EINVAL; 2423 } 2424 ret = find_subprog(env, off); 2425 if (ret >= 0) 2426 return ret; 2427 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2428 verbose(env, "too many subprograms\n"); 2429 return -E2BIG; 2430 } 2431 /* determine subprog starts. The end is one before the next starts */ 2432 env->subprog_info[env->subprog_cnt++].start = off; 2433 sort(env->subprog_info, env->subprog_cnt, 2434 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2435 return env->subprog_cnt - 1; 2436 } 2437 2438 #define MAX_KFUNC_DESCS 256 2439 #define MAX_KFUNC_BTFS 256 2440 2441 struct bpf_kfunc_desc { 2442 struct btf_func_model func_model; 2443 u32 func_id; 2444 s32 imm; 2445 u16 offset; 2446 }; 2447 2448 struct bpf_kfunc_btf { 2449 struct btf *btf; 2450 struct module *module; 2451 u16 offset; 2452 }; 2453 2454 struct bpf_kfunc_desc_tab { 2455 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2456 u32 nr_descs; 2457 }; 2458 2459 struct bpf_kfunc_btf_tab { 2460 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2461 u32 nr_descs; 2462 }; 2463 2464 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2465 { 2466 const struct bpf_kfunc_desc *d0 = a; 2467 const struct bpf_kfunc_desc *d1 = b; 2468 2469 /* func_id is not greater than BTF_MAX_TYPE */ 2470 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2471 } 2472 2473 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2474 { 2475 const struct bpf_kfunc_btf *d0 = a; 2476 const struct bpf_kfunc_btf *d1 = b; 2477 2478 return d0->offset - d1->offset; 2479 } 2480 2481 static const struct bpf_kfunc_desc * 2482 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2483 { 2484 struct bpf_kfunc_desc desc = { 2485 .func_id = func_id, 2486 .offset = offset, 2487 }; 2488 struct bpf_kfunc_desc_tab *tab; 2489 2490 tab = prog->aux->kfunc_tab; 2491 return bsearch(&desc, tab->descs, tab->nr_descs, 2492 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2493 } 2494 2495 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2496 s16 offset) 2497 { 2498 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2499 struct bpf_kfunc_btf_tab *tab; 2500 struct bpf_kfunc_btf *b; 2501 struct module *mod; 2502 struct btf *btf; 2503 int btf_fd; 2504 2505 tab = env->prog->aux->kfunc_btf_tab; 2506 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2507 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2508 if (!b) { 2509 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2510 verbose(env, "too many different module BTFs\n"); 2511 return ERR_PTR(-E2BIG); 2512 } 2513 2514 if (bpfptr_is_null(env->fd_array)) { 2515 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2516 return ERR_PTR(-EPROTO); 2517 } 2518 2519 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2520 offset * sizeof(btf_fd), 2521 sizeof(btf_fd))) 2522 return ERR_PTR(-EFAULT); 2523 2524 btf = btf_get_by_fd(btf_fd); 2525 if (IS_ERR(btf)) { 2526 verbose(env, "invalid module BTF fd specified\n"); 2527 return btf; 2528 } 2529 2530 if (!btf_is_module(btf)) { 2531 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2532 btf_put(btf); 2533 return ERR_PTR(-EINVAL); 2534 } 2535 2536 mod = btf_try_get_module(btf); 2537 if (!mod) { 2538 btf_put(btf); 2539 return ERR_PTR(-ENXIO); 2540 } 2541 2542 b = &tab->descs[tab->nr_descs++]; 2543 b->btf = btf; 2544 b->module = mod; 2545 b->offset = offset; 2546 2547 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2548 kfunc_btf_cmp_by_off, NULL); 2549 } 2550 return b->btf; 2551 } 2552 2553 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2554 { 2555 if (!tab) 2556 return; 2557 2558 while (tab->nr_descs--) { 2559 module_put(tab->descs[tab->nr_descs].module); 2560 btf_put(tab->descs[tab->nr_descs].btf); 2561 } 2562 kfree(tab); 2563 } 2564 2565 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2566 { 2567 if (offset) { 2568 if (offset < 0) { 2569 /* In the future, this can be allowed to increase limit 2570 * of fd index into fd_array, interpreted as u16. 2571 */ 2572 verbose(env, "negative offset disallowed for kernel module function call\n"); 2573 return ERR_PTR(-EINVAL); 2574 } 2575 2576 return __find_kfunc_desc_btf(env, offset); 2577 } 2578 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2579 } 2580 2581 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2582 { 2583 const struct btf_type *func, *func_proto; 2584 struct bpf_kfunc_btf_tab *btf_tab; 2585 struct bpf_kfunc_desc_tab *tab; 2586 struct bpf_prog_aux *prog_aux; 2587 struct bpf_kfunc_desc *desc; 2588 const char *func_name; 2589 struct btf *desc_btf; 2590 unsigned long call_imm; 2591 unsigned long addr; 2592 int err; 2593 2594 prog_aux = env->prog->aux; 2595 tab = prog_aux->kfunc_tab; 2596 btf_tab = prog_aux->kfunc_btf_tab; 2597 if (!tab) { 2598 if (!btf_vmlinux) { 2599 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2600 return -ENOTSUPP; 2601 } 2602 2603 if (!env->prog->jit_requested) { 2604 verbose(env, "JIT is required for calling kernel function\n"); 2605 return -ENOTSUPP; 2606 } 2607 2608 if (!bpf_jit_supports_kfunc_call()) { 2609 verbose(env, "JIT does not support calling kernel function\n"); 2610 return -ENOTSUPP; 2611 } 2612 2613 if (!env->prog->gpl_compatible) { 2614 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2615 return -EINVAL; 2616 } 2617 2618 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2619 if (!tab) 2620 return -ENOMEM; 2621 prog_aux->kfunc_tab = tab; 2622 } 2623 2624 /* func_id == 0 is always invalid, but instead of returning an error, be 2625 * conservative and wait until the code elimination pass before returning 2626 * error, so that invalid calls that get pruned out can be in BPF programs 2627 * loaded from userspace. It is also required that offset be untouched 2628 * for such calls. 2629 */ 2630 if (!func_id && !offset) 2631 return 0; 2632 2633 if (!btf_tab && offset) { 2634 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2635 if (!btf_tab) 2636 return -ENOMEM; 2637 prog_aux->kfunc_btf_tab = btf_tab; 2638 } 2639 2640 desc_btf = find_kfunc_desc_btf(env, offset); 2641 if (IS_ERR(desc_btf)) { 2642 verbose(env, "failed to find BTF for kernel function\n"); 2643 return PTR_ERR(desc_btf); 2644 } 2645 2646 if (find_kfunc_desc(env->prog, func_id, offset)) 2647 return 0; 2648 2649 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2650 verbose(env, "too many different kernel function calls\n"); 2651 return -E2BIG; 2652 } 2653 2654 func = btf_type_by_id(desc_btf, func_id); 2655 if (!func || !btf_type_is_func(func)) { 2656 verbose(env, "kernel btf_id %u is not a function\n", 2657 func_id); 2658 return -EINVAL; 2659 } 2660 func_proto = btf_type_by_id(desc_btf, func->type); 2661 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2662 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2663 func_id); 2664 return -EINVAL; 2665 } 2666 2667 func_name = btf_name_by_offset(desc_btf, func->name_off); 2668 addr = kallsyms_lookup_name(func_name); 2669 if (!addr) { 2670 verbose(env, "cannot find address for kernel function %s\n", 2671 func_name); 2672 return -EINVAL; 2673 } 2674 2675 call_imm = BPF_CALL_IMM(addr); 2676 /* Check whether or not the relative offset overflows desc->imm */ 2677 if ((unsigned long)(s32)call_imm != call_imm) { 2678 verbose(env, "address of kernel function %s is out of range\n", 2679 func_name); 2680 return -EINVAL; 2681 } 2682 2683 if (bpf_dev_bound_kfunc_id(func_id)) { 2684 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2685 if (err) 2686 return err; 2687 } 2688 2689 desc = &tab->descs[tab->nr_descs++]; 2690 desc->func_id = func_id; 2691 desc->imm = call_imm; 2692 desc->offset = offset; 2693 err = btf_distill_func_proto(&env->log, desc_btf, 2694 func_proto, func_name, 2695 &desc->func_model); 2696 if (!err) 2697 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2698 kfunc_desc_cmp_by_id_off, NULL); 2699 return err; 2700 } 2701 2702 static int kfunc_desc_cmp_by_imm(const void *a, const void *b) 2703 { 2704 const struct bpf_kfunc_desc *d0 = a; 2705 const struct bpf_kfunc_desc *d1 = b; 2706 2707 if (d0->imm > d1->imm) 2708 return 1; 2709 else if (d0->imm < d1->imm) 2710 return -1; 2711 return 0; 2712 } 2713 2714 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog) 2715 { 2716 struct bpf_kfunc_desc_tab *tab; 2717 2718 tab = prog->aux->kfunc_tab; 2719 if (!tab) 2720 return; 2721 2722 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2723 kfunc_desc_cmp_by_imm, NULL); 2724 } 2725 2726 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2727 { 2728 return !!prog->aux->kfunc_tab; 2729 } 2730 2731 const struct btf_func_model * 2732 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2733 const struct bpf_insn *insn) 2734 { 2735 const struct bpf_kfunc_desc desc = { 2736 .imm = insn->imm, 2737 }; 2738 const struct bpf_kfunc_desc *res; 2739 struct bpf_kfunc_desc_tab *tab; 2740 2741 tab = prog->aux->kfunc_tab; 2742 res = bsearch(&desc, tab->descs, tab->nr_descs, 2743 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm); 2744 2745 return res ? &res->func_model : NULL; 2746 } 2747 2748 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2749 { 2750 struct bpf_subprog_info *subprog = env->subprog_info; 2751 struct bpf_insn *insn = env->prog->insnsi; 2752 int i, ret, insn_cnt = env->prog->len; 2753 2754 /* Add entry function. */ 2755 ret = add_subprog(env, 0); 2756 if (ret) 2757 return ret; 2758 2759 for (i = 0; i < insn_cnt; i++, insn++) { 2760 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2761 !bpf_pseudo_kfunc_call(insn)) 2762 continue; 2763 2764 if (!env->bpf_capable) { 2765 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2766 return -EPERM; 2767 } 2768 2769 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2770 ret = add_subprog(env, i + insn->imm + 1); 2771 else 2772 ret = add_kfunc_call(env, insn->imm, insn->off); 2773 2774 if (ret < 0) 2775 return ret; 2776 } 2777 2778 /* Add a fake 'exit' subprog which could simplify subprog iteration 2779 * logic. 'subprog_cnt' should not be increased. 2780 */ 2781 subprog[env->subprog_cnt].start = insn_cnt; 2782 2783 if (env->log.level & BPF_LOG_LEVEL2) 2784 for (i = 0; i < env->subprog_cnt; i++) 2785 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2786 2787 return 0; 2788 } 2789 2790 static int check_subprogs(struct bpf_verifier_env *env) 2791 { 2792 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2793 struct bpf_subprog_info *subprog = env->subprog_info; 2794 struct bpf_insn *insn = env->prog->insnsi; 2795 int insn_cnt = env->prog->len; 2796 2797 /* now check that all jumps are within the same subprog */ 2798 subprog_start = subprog[cur_subprog].start; 2799 subprog_end = subprog[cur_subprog + 1].start; 2800 for (i = 0; i < insn_cnt; i++) { 2801 u8 code = insn[i].code; 2802 2803 if (code == (BPF_JMP | BPF_CALL) && 2804 insn[i].src_reg == 0 && 2805 insn[i].imm == BPF_FUNC_tail_call) 2806 subprog[cur_subprog].has_tail_call = true; 2807 if (BPF_CLASS(code) == BPF_LD && 2808 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2809 subprog[cur_subprog].has_ld_abs = true; 2810 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2811 goto next; 2812 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2813 goto next; 2814 off = i + insn[i].off + 1; 2815 if (off < subprog_start || off >= subprog_end) { 2816 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2817 return -EINVAL; 2818 } 2819 next: 2820 if (i == subprog_end - 1) { 2821 /* to avoid fall-through from one subprog into another 2822 * the last insn of the subprog should be either exit 2823 * or unconditional jump back 2824 */ 2825 if (code != (BPF_JMP | BPF_EXIT) && 2826 code != (BPF_JMP | BPF_JA)) { 2827 verbose(env, "last insn is not an exit or jmp\n"); 2828 return -EINVAL; 2829 } 2830 subprog_start = subprog_end; 2831 cur_subprog++; 2832 if (cur_subprog < env->subprog_cnt) 2833 subprog_end = subprog[cur_subprog + 1].start; 2834 } 2835 } 2836 return 0; 2837 } 2838 2839 /* Parentage chain of this register (or stack slot) should take care of all 2840 * issues like callee-saved registers, stack slot allocation time, etc. 2841 */ 2842 static int mark_reg_read(struct bpf_verifier_env *env, 2843 const struct bpf_reg_state *state, 2844 struct bpf_reg_state *parent, u8 flag) 2845 { 2846 bool writes = parent == state->parent; /* Observe write marks */ 2847 int cnt = 0; 2848 2849 while (parent) { 2850 /* if read wasn't screened by an earlier write ... */ 2851 if (writes && state->live & REG_LIVE_WRITTEN) 2852 break; 2853 if (parent->live & REG_LIVE_DONE) { 2854 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2855 reg_type_str(env, parent->type), 2856 parent->var_off.value, parent->off); 2857 return -EFAULT; 2858 } 2859 /* The first condition is more likely to be true than the 2860 * second, checked it first. 2861 */ 2862 if ((parent->live & REG_LIVE_READ) == flag || 2863 parent->live & REG_LIVE_READ64) 2864 /* The parentage chain never changes and 2865 * this parent was already marked as LIVE_READ. 2866 * There is no need to keep walking the chain again and 2867 * keep re-marking all parents as LIVE_READ. 2868 * This case happens when the same register is read 2869 * multiple times without writes into it in-between. 2870 * Also, if parent has the stronger REG_LIVE_READ64 set, 2871 * then no need to set the weak REG_LIVE_READ32. 2872 */ 2873 break; 2874 /* ... then we depend on parent's value */ 2875 parent->live |= flag; 2876 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 2877 if (flag == REG_LIVE_READ64) 2878 parent->live &= ~REG_LIVE_READ32; 2879 state = parent; 2880 parent = state->parent; 2881 writes = true; 2882 cnt++; 2883 } 2884 2885 if (env->longest_mark_read_walk < cnt) 2886 env->longest_mark_read_walk = cnt; 2887 return 0; 2888 } 2889 2890 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 2891 { 2892 struct bpf_func_state *state = func(env, reg); 2893 int spi, ret; 2894 2895 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 2896 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 2897 * check_kfunc_call. 2898 */ 2899 if (reg->type == CONST_PTR_TO_DYNPTR) 2900 return 0; 2901 spi = dynptr_get_spi(env, reg); 2902 if (spi < 0) 2903 return spi; 2904 /* Caller ensures dynptr is valid and initialized, which means spi is in 2905 * bounds and spi is the first dynptr slot. Simply mark stack slot as 2906 * read. 2907 */ 2908 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 2909 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 2910 if (ret) 2911 return ret; 2912 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 2913 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 2914 } 2915 2916 static int mark_iter_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 2917 int spi, int nr_slots) 2918 { 2919 struct bpf_func_state *state = func(env, reg); 2920 int err, i; 2921 2922 for (i = 0; i < nr_slots; i++) { 2923 struct bpf_reg_state *st = &state->stack[spi - i].spilled_ptr; 2924 2925 err = mark_reg_read(env, st, st->parent, REG_LIVE_READ64); 2926 if (err) 2927 return err; 2928 2929 mark_stack_slot_scratched(env, spi - i); 2930 } 2931 2932 return 0; 2933 } 2934 2935 /* This function is supposed to be used by the following 32-bit optimization 2936 * code only. It returns TRUE if the source or destination register operates 2937 * on 64-bit, otherwise return FALSE. 2938 */ 2939 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 2940 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 2941 { 2942 u8 code, class, op; 2943 2944 code = insn->code; 2945 class = BPF_CLASS(code); 2946 op = BPF_OP(code); 2947 if (class == BPF_JMP) { 2948 /* BPF_EXIT for "main" will reach here. Return TRUE 2949 * conservatively. 2950 */ 2951 if (op == BPF_EXIT) 2952 return true; 2953 if (op == BPF_CALL) { 2954 /* BPF to BPF call will reach here because of marking 2955 * caller saved clobber with DST_OP_NO_MARK for which we 2956 * don't care the register def because they are anyway 2957 * marked as NOT_INIT already. 2958 */ 2959 if (insn->src_reg == BPF_PSEUDO_CALL) 2960 return false; 2961 /* Helper call will reach here because of arg type 2962 * check, conservatively return TRUE. 2963 */ 2964 if (t == SRC_OP) 2965 return true; 2966 2967 return false; 2968 } 2969 } 2970 2971 if (class == BPF_ALU64 || class == BPF_JMP || 2972 /* BPF_END always use BPF_ALU class. */ 2973 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 2974 return true; 2975 2976 if (class == BPF_ALU || class == BPF_JMP32) 2977 return false; 2978 2979 if (class == BPF_LDX) { 2980 if (t != SRC_OP) 2981 return BPF_SIZE(code) == BPF_DW; 2982 /* LDX source must be ptr. */ 2983 return true; 2984 } 2985 2986 if (class == BPF_STX) { 2987 /* BPF_STX (including atomic variants) has multiple source 2988 * operands, one of which is a ptr. Check whether the caller is 2989 * asking about it. 2990 */ 2991 if (t == SRC_OP && reg->type != SCALAR_VALUE) 2992 return true; 2993 return BPF_SIZE(code) == BPF_DW; 2994 } 2995 2996 if (class == BPF_LD) { 2997 u8 mode = BPF_MODE(code); 2998 2999 /* LD_IMM64 */ 3000 if (mode == BPF_IMM) 3001 return true; 3002 3003 /* Both LD_IND and LD_ABS return 32-bit data. */ 3004 if (t != SRC_OP) 3005 return false; 3006 3007 /* Implicit ctx ptr. */ 3008 if (regno == BPF_REG_6) 3009 return true; 3010 3011 /* Explicit source could be any width. */ 3012 return true; 3013 } 3014 3015 if (class == BPF_ST) 3016 /* The only source register for BPF_ST is a ptr. */ 3017 return true; 3018 3019 /* Conservatively return true at default. */ 3020 return true; 3021 } 3022 3023 /* Return the regno defined by the insn, or -1. */ 3024 static int insn_def_regno(const struct bpf_insn *insn) 3025 { 3026 switch (BPF_CLASS(insn->code)) { 3027 case BPF_JMP: 3028 case BPF_JMP32: 3029 case BPF_ST: 3030 return -1; 3031 case BPF_STX: 3032 if (BPF_MODE(insn->code) == BPF_ATOMIC && 3033 (insn->imm & BPF_FETCH)) { 3034 if (insn->imm == BPF_CMPXCHG) 3035 return BPF_REG_0; 3036 else 3037 return insn->src_reg; 3038 } else { 3039 return -1; 3040 } 3041 default: 3042 return insn->dst_reg; 3043 } 3044 } 3045 3046 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 3047 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 3048 { 3049 int dst_reg = insn_def_regno(insn); 3050 3051 if (dst_reg == -1) 3052 return false; 3053 3054 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 3055 } 3056 3057 static void mark_insn_zext(struct bpf_verifier_env *env, 3058 struct bpf_reg_state *reg) 3059 { 3060 s32 def_idx = reg->subreg_def; 3061 3062 if (def_idx == DEF_NOT_SUBREG) 3063 return; 3064 3065 env->insn_aux_data[def_idx - 1].zext_dst = true; 3066 /* The dst will be zero extended, so won't be sub-register anymore. */ 3067 reg->subreg_def = DEF_NOT_SUBREG; 3068 } 3069 3070 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 3071 enum reg_arg_type t) 3072 { 3073 struct bpf_verifier_state *vstate = env->cur_state; 3074 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3075 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 3076 struct bpf_reg_state *reg, *regs = state->regs; 3077 bool rw64; 3078 3079 if (regno >= MAX_BPF_REG) { 3080 verbose(env, "R%d is invalid\n", regno); 3081 return -EINVAL; 3082 } 3083 3084 mark_reg_scratched(env, regno); 3085 3086 reg = ®s[regno]; 3087 rw64 = is_reg64(env, insn, regno, reg, t); 3088 if (t == SRC_OP) { 3089 /* check whether register used as source operand can be read */ 3090 if (reg->type == NOT_INIT) { 3091 verbose(env, "R%d !read_ok\n", regno); 3092 return -EACCES; 3093 } 3094 /* We don't need to worry about FP liveness because it's read-only */ 3095 if (regno == BPF_REG_FP) 3096 return 0; 3097 3098 if (rw64) 3099 mark_insn_zext(env, reg); 3100 3101 return mark_reg_read(env, reg, reg->parent, 3102 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 3103 } else { 3104 /* check whether register used as dest operand can be written to */ 3105 if (regno == BPF_REG_FP) { 3106 verbose(env, "frame pointer is read only\n"); 3107 return -EACCES; 3108 } 3109 reg->live |= REG_LIVE_WRITTEN; 3110 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 3111 if (t == DST_OP) 3112 mark_reg_unknown(env, regs, regno); 3113 } 3114 return 0; 3115 } 3116 3117 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 3118 { 3119 env->insn_aux_data[idx].jmp_point = true; 3120 } 3121 3122 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 3123 { 3124 return env->insn_aux_data[insn_idx].jmp_point; 3125 } 3126 3127 /* for any branch, call, exit record the history of jmps in the given state */ 3128 static int push_jmp_history(struct bpf_verifier_env *env, 3129 struct bpf_verifier_state *cur) 3130 { 3131 u32 cnt = cur->jmp_history_cnt; 3132 struct bpf_idx_pair *p; 3133 size_t alloc_size; 3134 3135 if (!is_jmp_point(env, env->insn_idx)) 3136 return 0; 3137 3138 cnt++; 3139 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 3140 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 3141 if (!p) 3142 return -ENOMEM; 3143 p[cnt - 1].idx = env->insn_idx; 3144 p[cnt - 1].prev_idx = env->prev_insn_idx; 3145 cur->jmp_history = p; 3146 cur->jmp_history_cnt = cnt; 3147 return 0; 3148 } 3149 3150 /* Backtrack one insn at a time. If idx is not at the top of recorded 3151 * history then previous instruction came from straight line execution. 3152 */ 3153 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 3154 u32 *history) 3155 { 3156 u32 cnt = *history; 3157 3158 if (cnt && st->jmp_history[cnt - 1].idx == i) { 3159 i = st->jmp_history[cnt - 1].prev_idx; 3160 (*history)--; 3161 } else { 3162 i--; 3163 } 3164 return i; 3165 } 3166 3167 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 3168 { 3169 const struct btf_type *func; 3170 struct btf *desc_btf; 3171 3172 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 3173 return NULL; 3174 3175 desc_btf = find_kfunc_desc_btf(data, insn->off); 3176 if (IS_ERR(desc_btf)) 3177 return "<error>"; 3178 3179 func = btf_type_by_id(desc_btf, insn->imm); 3180 return btf_name_by_offset(desc_btf, func->name_off); 3181 } 3182 3183 /* For given verifier state backtrack_insn() is called from the last insn to 3184 * the first insn. Its purpose is to compute a bitmask of registers and 3185 * stack slots that needs precision in the parent verifier state. 3186 */ 3187 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 3188 u32 *reg_mask, u64 *stack_mask) 3189 { 3190 const struct bpf_insn_cbs cbs = { 3191 .cb_call = disasm_kfunc_name, 3192 .cb_print = verbose, 3193 .private_data = env, 3194 }; 3195 struct bpf_insn *insn = env->prog->insnsi + idx; 3196 u8 class = BPF_CLASS(insn->code); 3197 u8 opcode = BPF_OP(insn->code); 3198 u8 mode = BPF_MODE(insn->code); 3199 u32 dreg = 1u << insn->dst_reg; 3200 u32 sreg = 1u << insn->src_reg; 3201 u32 spi; 3202 3203 if (insn->code == 0) 3204 return 0; 3205 if (env->log.level & BPF_LOG_LEVEL2) { 3206 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask); 3207 verbose(env, "%d: ", idx); 3208 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 3209 } 3210 3211 if (class == BPF_ALU || class == BPF_ALU64) { 3212 if (!(*reg_mask & dreg)) 3213 return 0; 3214 if (opcode == BPF_MOV) { 3215 if (BPF_SRC(insn->code) == BPF_X) { 3216 /* dreg = sreg 3217 * dreg needs precision after this insn 3218 * sreg needs precision before this insn 3219 */ 3220 *reg_mask &= ~dreg; 3221 *reg_mask |= sreg; 3222 } else { 3223 /* dreg = K 3224 * dreg needs precision after this insn. 3225 * Corresponding register is already marked 3226 * as precise=true in this verifier state. 3227 * No further markings in parent are necessary 3228 */ 3229 *reg_mask &= ~dreg; 3230 } 3231 } else { 3232 if (BPF_SRC(insn->code) == BPF_X) { 3233 /* dreg += sreg 3234 * both dreg and sreg need precision 3235 * before this insn 3236 */ 3237 *reg_mask |= sreg; 3238 } /* else dreg += K 3239 * dreg still needs precision before this insn 3240 */ 3241 } 3242 } else if (class == BPF_LDX) { 3243 if (!(*reg_mask & dreg)) 3244 return 0; 3245 *reg_mask &= ~dreg; 3246 3247 /* scalars can only be spilled into stack w/o losing precision. 3248 * Load from any other memory can be zero extended. 3249 * The desire to keep that precision is already indicated 3250 * by 'precise' mark in corresponding register of this state. 3251 * No further tracking necessary. 3252 */ 3253 if (insn->src_reg != BPF_REG_FP) 3254 return 0; 3255 3256 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 3257 * that [fp - off] slot contains scalar that needs to be 3258 * tracked with precision 3259 */ 3260 spi = (-insn->off - 1) / BPF_REG_SIZE; 3261 if (spi >= 64) { 3262 verbose(env, "BUG spi %d\n", spi); 3263 WARN_ONCE(1, "verifier backtracking bug"); 3264 return -EFAULT; 3265 } 3266 *stack_mask |= 1ull << spi; 3267 } else if (class == BPF_STX || class == BPF_ST) { 3268 if (*reg_mask & dreg) 3269 /* stx & st shouldn't be using _scalar_ dst_reg 3270 * to access memory. It means backtracking 3271 * encountered a case of pointer subtraction. 3272 */ 3273 return -ENOTSUPP; 3274 /* scalars can only be spilled into stack */ 3275 if (insn->dst_reg != BPF_REG_FP) 3276 return 0; 3277 spi = (-insn->off - 1) / BPF_REG_SIZE; 3278 if (spi >= 64) { 3279 verbose(env, "BUG spi %d\n", spi); 3280 WARN_ONCE(1, "verifier backtracking bug"); 3281 return -EFAULT; 3282 } 3283 if (!(*stack_mask & (1ull << spi))) 3284 return 0; 3285 *stack_mask &= ~(1ull << spi); 3286 if (class == BPF_STX) 3287 *reg_mask |= sreg; 3288 } else if (class == BPF_JMP || class == BPF_JMP32) { 3289 if (opcode == BPF_CALL) { 3290 if (insn->src_reg == BPF_PSEUDO_CALL) 3291 return -ENOTSUPP; 3292 /* BPF helpers that invoke callback subprogs are 3293 * equivalent to BPF_PSEUDO_CALL above 3294 */ 3295 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm)) 3296 return -ENOTSUPP; 3297 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 3298 * catch this error later. Make backtracking conservative 3299 * with ENOTSUPP. 3300 */ 3301 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 3302 return -ENOTSUPP; 3303 /* regular helper call sets R0 */ 3304 *reg_mask &= ~1; 3305 if (*reg_mask & 0x3f) { 3306 /* if backtracing was looking for registers R1-R5 3307 * they should have been found already. 3308 */ 3309 verbose(env, "BUG regs %x\n", *reg_mask); 3310 WARN_ONCE(1, "verifier backtracking bug"); 3311 return -EFAULT; 3312 } 3313 } else if (opcode == BPF_EXIT) { 3314 return -ENOTSUPP; 3315 } 3316 } else if (class == BPF_LD) { 3317 if (!(*reg_mask & dreg)) 3318 return 0; 3319 *reg_mask &= ~dreg; 3320 /* It's ld_imm64 or ld_abs or ld_ind. 3321 * For ld_imm64 no further tracking of precision 3322 * into parent is necessary 3323 */ 3324 if (mode == BPF_IND || mode == BPF_ABS) 3325 /* to be analyzed */ 3326 return -ENOTSUPP; 3327 } 3328 return 0; 3329 } 3330 3331 /* the scalar precision tracking algorithm: 3332 * . at the start all registers have precise=false. 3333 * . scalar ranges are tracked as normal through alu and jmp insns. 3334 * . once precise value of the scalar register is used in: 3335 * . ptr + scalar alu 3336 * . if (scalar cond K|scalar) 3337 * . helper_call(.., scalar, ...) where ARG_CONST is expected 3338 * backtrack through the verifier states and mark all registers and 3339 * stack slots with spilled constants that these scalar regisers 3340 * should be precise. 3341 * . during state pruning two registers (or spilled stack slots) 3342 * are equivalent if both are not precise. 3343 * 3344 * Note the verifier cannot simply walk register parentage chain, 3345 * since many different registers and stack slots could have been 3346 * used to compute single precise scalar. 3347 * 3348 * The approach of starting with precise=true for all registers and then 3349 * backtrack to mark a register as not precise when the verifier detects 3350 * that program doesn't care about specific value (e.g., when helper 3351 * takes register as ARG_ANYTHING parameter) is not safe. 3352 * 3353 * It's ok to walk single parentage chain of the verifier states. 3354 * It's possible that this backtracking will go all the way till 1st insn. 3355 * All other branches will be explored for needing precision later. 3356 * 3357 * The backtracking needs to deal with cases like: 3358 * 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) 3359 * r9 -= r8 3360 * r5 = r9 3361 * if r5 > 0x79f goto pc+7 3362 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3363 * r5 += 1 3364 * ... 3365 * call bpf_perf_event_output#25 3366 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3367 * 3368 * and this case: 3369 * r6 = 1 3370 * call foo // uses callee's r6 inside to compute r0 3371 * r0 += r6 3372 * if r0 == 0 goto 3373 * 3374 * to track above reg_mask/stack_mask needs to be independent for each frame. 3375 * 3376 * Also if parent's curframe > frame where backtracking started, 3377 * the verifier need to mark registers in both frames, otherwise callees 3378 * may incorrectly prune callers. This is similar to 3379 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3380 * 3381 * For now backtracking falls back into conservative marking. 3382 */ 3383 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3384 struct bpf_verifier_state *st) 3385 { 3386 struct bpf_func_state *func; 3387 struct bpf_reg_state *reg; 3388 int i, j; 3389 3390 /* big hammer: mark all scalars precise in this path. 3391 * pop_stack may still get !precise scalars. 3392 * We also skip current state and go straight to first parent state, 3393 * because precision markings in current non-checkpointed state are 3394 * not needed. See why in the comment in __mark_chain_precision below. 3395 */ 3396 for (st = st->parent; st; st = st->parent) { 3397 for (i = 0; i <= st->curframe; i++) { 3398 func = st->frame[i]; 3399 for (j = 0; j < BPF_REG_FP; j++) { 3400 reg = &func->regs[j]; 3401 if (reg->type != SCALAR_VALUE) 3402 continue; 3403 reg->precise = true; 3404 } 3405 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3406 if (!is_spilled_reg(&func->stack[j])) 3407 continue; 3408 reg = &func->stack[j].spilled_ptr; 3409 if (reg->type != SCALAR_VALUE) 3410 continue; 3411 reg->precise = true; 3412 } 3413 } 3414 } 3415 } 3416 3417 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3418 { 3419 struct bpf_func_state *func; 3420 struct bpf_reg_state *reg; 3421 int i, j; 3422 3423 for (i = 0; i <= st->curframe; i++) { 3424 func = st->frame[i]; 3425 for (j = 0; j < BPF_REG_FP; j++) { 3426 reg = &func->regs[j]; 3427 if (reg->type != SCALAR_VALUE) 3428 continue; 3429 reg->precise = false; 3430 } 3431 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3432 if (!is_spilled_reg(&func->stack[j])) 3433 continue; 3434 reg = &func->stack[j].spilled_ptr; 3435 if (reg->type != SCALAR_VALUE) 3436 continue; 3437 reg->precise = false; 3438 } 3439 } 3440 } 3441 3442 /* 3443 * __mark_chain_precision() backtracks BPF program instruction sequence and 3444 * chain of verifier states making sure that register *regno* (if regno >= 0) 3445 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 3446 * SCALARS, as well as any other registers and slots that contribute to 3447 * a tracked state of given registers/stack slots, depending on specific BPF 3448 * assembly instructions (see backtrack_insns() for exact instruction handling 3449 * logic). This backtracking relies on recorded jmp_history and is able to 3450 * traverse entire chain of parent states. This process ends only when all the 3451 * necessary registers/slots and their transitive dependencies are marked as 3452 * precise. 3453 * 3454 * One important and subtle aspect is that precise marks *do not matter* in 3455 * the currently verified state (current state). It is important to understand 3456 * why this is the case. 3457 * 3458 * First, note that current state is the state that is not yet "checkpointed", 3459 * i.e., it is not yet put into env->explored_states, and it has no children 3460 * states as well. It's ephemeral, and can end up either a) being discarded if 3461 * compatible explored state is found at some point or BPF_EXIT instruction is 3462 * reached or b) checkpointed and put into env->explored_states, branching out 3463 * into one or more children states. 3464 * 3465 * In the former case, precise markings in current state are completely 3466 * ignored by state comparison code (see regsafe() for details). Only 3467 * checkpointed ("old") state precise markings are important, and if old 3468 * state's register/slot is precise, regsafe() assumes current state's 3469 * register/slot as precise and checks value ranges exactly and precisely. If 3470 * states turn out to be compatible, current state's necessary precise 3471 * markings and any required parent states' precise markings are enforced 3472 * after the fact with propagate_precision() logic, after the fact. But it's 3473 * important to realize that in this case, even after marking current state 3474 * registers/slots as precise, we immediately discard current state. So what 3475 * actually matters is any of the precise markings propagated into current 3476 * state's parent states, which are always checkpointed (due to b) case above). 3477 * As such, for scenario a) it doesn't matter if current state has precise 3478 * markings set or not. 3479 * 3480 * Now, for the scenario b), checkpointing and forking into child(ren) 3481 * state(s). Note that before current state gets to checkpointing step, any 3482 * processed instruction always assumes precise SCALAR register/slot 3483 * knowledge: if precise value or range is useful to prune jump branch, BPF 3484 * verifier takes this opportunity enthusiastically. Similarly, when 3485 * register's value is used to calculate offset or memory address, exact 3486 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 3487 * what we mentioned above about state comparison ignoring precise markings 3488 * during state comparison, BPF verifier ignores and also assumes precise 3489 * markings *at will* during instruction verification process. But as verifier 3490 * assumes precision, it also propagates any precision dependencies across 3491 * parent states, which are not yet finalized, so can be further restricted 3492 * based on new knowledge gained from restrictions enforced by their children 3493 * states. This is so that once those parent states are finalized, i.e., when 3494 * they have no more active children state, state comparison logic in 3495 * is_state_visited() would enforce strict and precise SCALAR ranges, if 3496 * required for correctness. 3497 * 3498 * To build a bit more intuition, note also that once a state is checkpointed, 3499 * the path we took to get to that state is not important. This is crucial 3500 * property for state pruning. When state is checkpointed and finalized at 3501 * some instruction index, it can be correctly and safely used to "short 3502 * circuit" any *compatible* state that reaches exactly the same instruction 3503 * index. I.e., if we jumped to that instruction from a completely different 3504 * code path than original finalized state was derived from, it doesn't 3505 * matter, current state can be discarded because from that instruction 3506 * forward having a compatible state will ensure we will safely reach the 3507 * exit. States describe preconditions for further exploration, but completely 3508 * forget the history of how we got here. 3509 * 3510 * This also means that even if we needed precise SCALAR range to get to 3511 * finalized state, but from that point forward *that same* SCALAR register is 3512 * never used in a precise context (i.e., it's precise value is not needed for 3513 * correctness), it's correct and safe to mark such register as "imprecise" 3514 * (i.e., precise marking set to false). This is what we rely on when we do 3515 * not set precise marking in current state. If no child state requires 3516 * precision for any given SCALAR register, it's safe to dictate that it can 3517 * be imprecise. If any child state does require this register to be precise, 3518 * we'll mark it precise later retroactively during precise markings 3519 * propagation from child state to parent states. 3520 * 3521 * Skipping precise marking setting in current state is a mild version of 3522 * relying on the above observation. But we can utilize this property even 3523 * more aggressively by proactively forgetting any precise marking in the 3524 * current state (which we inherited from the parent state), right before we 3525 * checkpoint it and branch off into new child state. This is done by 3526 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 3527 * finalized states which help in short circuiting more future states. 3528 */ 3529 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno, 3530 int spi) 3531 { 3532 struct bpf_verifier_state *st = env->cur_state; 3533 int first_idx = st->first_insn_idx; 3534 int last_idx = env->insn_idx; 3535 struct bpf_func_state *func; 3536 struct bpf_reg_state *reg; 3537 u32 reg_mask = regno >= 0 ? 1u << regno : 0; 3538 u64 stack_mask = spi >= 0 ? 1ull << spi : 0; 3539 bool skip_first = true; 3540 bool new_marks = false; 3541 int i, err; 3542 3543 if (!env->bpf_capable) 3544 return 0; 3545 3546 /* Do sanity checks against current state of register and/or stack 3547 * slot, but don't set precise flag in current state, as precision 3548 * tracking in the current state is unnecessary. 3549 */ 3550 func = st->frame[frame]; 3551 if (regno >= 0) { 3552 reg = &func->regs[regno]; 3553 if (reg->type != SCALAR_VALUE) { 3554 WARN_ONCE(1, "backtracing misuse"); 3555 return -EFAULT; 3556 } 3557 new_marks = true; 3558 } 3559 3560 while (spi >= 0) { 3561 if (!is_spilled_reg(&func->stack[spi])) { 3562 stack_mask = 0; 3563 break; 3564 } 3565 reg = &func->stack[spi].spilled_ptr; 3566 if (reg->type != SCALAR_VALUE) { 3567 stack_mask = 0; 3568 break; 3569 } 3570 new_marks = true; 3571 break; 3572 } 3573 3574 if (!new_marks) 3575 return 0; 3576 if (!reg_mask && !stack_mask) 3577 return 0; 3578 3579 for (;;) { 3580 DECLARE_BITMAP(mask, 64); 3581 u32 history = st->jmp_history_cnt; 3582 3583 if (env->log.level & BPF_LOG_LEVEL2) 3584 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx); 3585 3586 if (last_idx < 0) { 3587 /* we are at the entry into subprog, which 3588 * is expected for global funcs, but only if 3589 * requested precise registers are R1-R5 3590 * (which are global func's input arguments) 3591 */ 3592 if (st->curframe == 0 && 3593 st->frame[0]->subprogno > 0 && 3594 st->frame[0]->callsite == BPF_MAIN_FUNC && 3595 stack_mask == 0 && (reg_mask & ~0x3e) == 0) { 3596 bitmap_from_u64(mask, reg_mask); 3597 for_each_set_bit(i, mask, 32) { 3598 reg = &st->frame[0]->regs[i]; 3599 if (reg->type != SCALAR_VALUE) { 3600 reg_mask &= ~(1u << i); 3601 continue; 3602 } 3603 reg->precise = true; 3604 } 3605 return 0; 3606 } 3607 3608 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n", 3609 st->frame[0]->subprogno, reg_mask, stack_mask); 3610 WARN_ONCE(1, "verifier backtracking bug"); 3611 return -EFAULT; 3612 } 3613 3614 for (i = last_idx;;) { 3615 if (skip_first) { 3616 err = 0; 3617 skip_first = false; 3618 } else { 3619 err = backtrack_insn(env, i, ®_mask, &stack_mask); 3620 } 3621 if (err == -ENOTSUPP) { 3622 mark_all_scalars_precise(env, st); 3623 return 0; 3624 } else if (err) { 3625 return err; 3626 } 3627 if (!reg_mask && !stack_mask) 3628 /* Found assignment(s) into tracked register in this state. 3629 * Since this state is already marked, just return. 3630 * Nothing to be tracked further in the parent state. 3631 */ 3632 return 0; 3633 if (i == first_idx) 3634 break; 3635 i = get_prev_insn_idx(st, i, &history); 3636 if (i >= env->prog->len) { 3637 /* This can happen if backtracking reached insn 0 3638 * and there are still reg_mask or stack_mask 3639 * to backtrack. 3640 * It means the backtracking missed the spot where 3641 * particular register was initialized with a constant. 3642 */ 3643 verbose(env, "BUG backtracking idx %d\n", i); 3644 WARN_ONCE(1, "verifier backtracking bug"); 3645 return -EFAULT; 3646 } 3647 } 3648 st = st->parent; 3649 if (!st) 3650 break; 3651 3652 new_marks = false; 3653 func = st->frame[frame]; 3654 bitmap_from_u64(mask, reg_mask); 3655 for_each_set_bit(i, mask, 32) { 3656 reg = &func->regs[i]; 3657 if (reg->type != SCALAR_VALUE) { 3658 reg_mask &= ~(1u << i); 3659 continue; 3660 } 3661 if (!reg->precise) 3662 new_marks = true; 3663 reg->precise = true; 3664 } 3665 3666 bitmap_from_u64(mask, stack_mask); 3667 for_each_set_bit(i, mask, 64) { 3668 if (i >= func->allocated_stack / BPF_REG_SIZE) { 3669 /* the sequence of instructions: 3670 * 2: (bf) r3 = r10 3671 * 3: (7b) *(u64 *)(r3 -8) = r0 3672 * 4: (79) r4 = *(u64 *)(r10 -8) 3673 * doesn't contain jmps. It's backtracked 3674 * as a single block. 3675 * During backtracking insn 3 is not recognized as 3676 * stack access, so at the end of backtracking 3677 * stack slot fp-8 is still marked in stack_mask. 3678 * However the parent state may not have accessed 3679 * fp-8 and it's "unallocated" stack space. 3680 * In such case fallback to conservative. 3681 */ 3682 mark_all_scalars_precise(env, st); 3683 return 0; 3684 } 3685 3686 if (!is_spilled_reg(&func->stack[i])) { 3687 stack_mask &= ~(1ull << i); 3688 continue; 3689 } 3690 reg = &func->stack[i].spilled_ptr; 3691 if (reg->type != SCALAR_VALUE) { 3692 stack_mask &= ~(1ull << i); 3693 continue; 3694 } 3695 if (!reg->precise) 3696 new_marks = true; 3697 reg->precise = true; 3698 } 3699 if (env->log.level & BPF_LOG_LEVEL2) { 3700 verbose(env, "parent %s regs=%x stack=%llx marks:", 3701 new_marks ? "didn't have" : "already had", 3702 reg_mask, stack_mask); 3703 print_verifier_state(env, func, true); 3704 } 3705 3706 if (!reg_mask && !stack_mask) 3707 break; 3708 if (!new_marks) 3709 break; 3710 3711 last_idx = st->last_insn_idx; 3712 first_idx = st->first_insn_idx; 3713 } 3714 return 0; 3715 } 3716 3717 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3718 { 3719 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1); 3720 } 3721 3722 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno) 3723 { 3724 return __mark_chain_precision(env, frame, regno, -1); 3725 } 3726 3727 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi) 3728 { 3729 return __mark_chain_precision(env, frame, -1, spi); 3730 } 3731 3732 static bool is_spillable_regtype(enum bpf_reg_type type) 3733 { 3734 switch (base_type(type)) { 3735 case PTR_TO_MAP_VALUE: 3736 case PTR_TO_STACK: 3737 case PTR_TO_CTX: 3738 case PTR_TO_PACKET: 3739 case PTR_TO_PACKET_META: 3740 case PTR_TO_PACKET_END: 3741 case PTR_TO_FLOW_KEYS: 3742 case CONST_PTR_TO_MAP: 3743 case PTR_TO_SOCKET: 3744 case PTR_TO_SOCK_COMMON: 3745 case PTR_TO_TCP_SOCK: 3746 case PTR_TO_XDP_SOCK: 3747 case PTR_TO_BTF_ID: 3748 case PTR_TO_BUF: 3749 case PTR_TO_MEM: 3750 case PTR_TO_FUNC: 3751 case PTR_TO_MAP_KEY: 3752 return true; 3753 default: 3754 return false; 3755 } 3756 } 3757 3758 /* Does this register contain a constant zero? */ 3759 static bool register_is_null(struct bpf_reg_state *reg) 3760 { 3761 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 3762 } 3763 3764 static bool register_is_const(struct bpf_reg_state *reg) 3765 { 3766 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 3767 } 3768 3769 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 3770 { 3771 return tnum_is_unknown(reg->var_off) && 3772 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 3773 reg->umin_value == 0 && reg->umax_value == U64_MAX && 3774 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 3775 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 3776 } 3777 3778 static bool register_is_bounded(struct bpf_reg_state *reg) 3779 { 3780 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 3781 } 3782 3783 static bool __is_pointer_value(bool allow_ptr_leaks, 3784 const struct bpf_reg_state *reg) 3785 { 3786 if (allow_ptr_leaks) 3787 return false; 3788 3789 return reg->type != SCALAR_VALUE; 3790 } 3791 3792 /* Copy src state preserving dst->parent and dst->live fields */ 3793 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 3794 { 3795 struct bpf_reg_state *parent = dst->parent; 3796 enum bpf_reg_liveness live = dst->live; 3797 3798 *dst = *src; 3799 dst->parent = parent; 3800 dst->live = live; 3801 } 3802 3803 static void save_register_state(struct bpf_func_state *state, 3804 int spi, struct bpf_reg_state *reg, 3805 int size) 3806 { 3807 int i; 3808 3809 copy_register_state(&state->stack[spi].spilled_ptr, reg); 3810 if (size == BPF_REG_SIZE) 3811 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 3812 3813 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3814 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3815 3816 /* size < 8 bytes spill */ 3817 for (; i; i--) 3818 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 3819 } 3820 3821 static bool is_bpf_st_mem(struct bpf_insn *insn) 3822 { 3823 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 3824 } 3825 3826 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3827 * stack boundary and alignment are checked in check_mem_access() 3828 */ 3829 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3830 /* stack frame we're writing to */ 3831 struct bpf_func_state *state, 3832 int off, int size, int value_regno, 3833 int insn_idx) 3834 { 3835 struct bpf_func_state *cur; /* state of the current function */ 3836 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3837 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3838 struct bpf_reg_state *reg = NULL; 3839 u32 dst_reg = insn->dst_reg; 3840 3841 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 3842 if (err) 3843 return err; 3844 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3845 * so it's aligned access and [off, off + size) are within stack limits 3846 */ 3847 if (!env->allow_ptr_leaks && 3848 state->stack[spi].slot_type[0] == STACK_SPILL && 3849 size != BPF_REG_SIZE) { 3850 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3851 return -EACCES; 3852 } 3853 3854 cur = env->cur_state->frame[env->cur_state->curframe]; 3855 if (value_regno >= 0) 3856 reg = &cur->regs[value_regno]; 3857 if (!env->bypass_spec_v4) { 3858 bool sanitize = reg && is_spillable_regtype(reg->type); 3859 3860 for (i = 0; i < size; i++) { 3861 u8 type = state->stack[spi].slot_type[i]; 3862 3863 if (type != STACK_MISC && type != STACK_ZERO) { 3864 sanitize = true; 3865 break; 3866 } 3867 } 3868 3869 if (sanitize) 3870 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 3871 } 3872 3873 err = destroy_if_dynptr_stack_slot(env, state, spi); 3874 if (err) 3875 return err; 3876 3877 mark_stack_slot_scratched(env, spi); 3878 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 3879 !register_is_null(reg) && env->bpf_capable) { 3880 if (dst_reg != BPF_REG_FP) { 3881 /* The backtracking logic can only recognize explicit 3882 * stack slot address like [fp - 8]. Other spill of 3883 * scalar via different register has to be conservative. 3884 * Backtrack from here and mark all registers as precise 3885 * that contributed into 'reg' being a constant. 3886 */ 3887 err = mark_chain_precision(env, value_regno); 3888 if (err) 3889 return err; 3890 } 3891 save_register_state(state, spi, reg, size); 3892 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 3893 insn->imm != 0 && env->bpf_capable) { 3894 struct bpf_reg_state fake_reg = {}; 3895 3896 __mark_reg_known(&fake_reg, (u32)insn->imm); 3897 fake_reg.type = SCALAR_VALUE; 3898 save_register_state(state, spi, &fake_reg, size); 3899 } else if (reg && is_spillable_regtype(reg->type)) { 3900 /* register containing pointer is being spilled into stack */ 3901 if (size != BPF_REG_SIZE) { 3902 verbose_linfo(env, insn_idx, "; "); 3903 verbose(env, "invalid size of register spill\n"); 3904 return -EACCES; 3905 } 3906 if (state != cur && reg->type == PTR_TO_STACK) { 3907 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3908 return -EINVAL; 3909 } 3910 save_register_state(state, spi, reg, size); 3911 } else { 3912 u8 type = STACK_MISC; 3913 3914 /* regular write of data into stack destroys any spilled ptr */ 3915 state->stack[spi].spilled_ptr.type = NOT_INIT; 3916 /* Mark slots as STACK_MISC if they belonged to spilled ptr/dynptr/iter. */ 3917 if (is_stack_slot_special(&state->stack[spi])) 3918 for (i = 0; i < BPF_REG_SIZE; i++) 3919 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3920 3921 /* only mark the slot as written if all 8 bytes were written 3922 * otherwise read propagation may incorrectly stop too soon 3923 * when stack slots are partially written. 3924 * This heuristic means that read propagation will be 3925 * conservative, since it will add reg_live_read marks 3926 * to stack slots all the way to first state when programs 3927 * writes+reads less than 8 bytes 3928 */ 3929 if (size == BPF_REG_SIZE) 3930 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 3931 3932 /* when we zero initialize stack slots mark them as such */ 3933 if ((reg && register_is_null(reg)) || 3934 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 3935 /* backtracking doesn't work for STACK_ZERO yet. */ 3936 err = mark_chain_precision(env, value_regno); 3937 if (err) 3938 return err; 3939 type = STACK_ZERO; 3940 } 3941 3942 /* Mark slots affected by this stack write. */ 3943 for (i = 0; i < size; i++) 3944 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 3945 type; 3946 } 3947 return 0; 3948 } 3949 3950 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 3951 * known to contain a variable offset. 3952 * This function checks whether the write is permitted and conservatively 3953 * tracks the effects of the write, considering that each stack slot in the 3954 * dynamic range is potentially written to. 3955 * 3956 * 'off' includes 'regno->off'. 3957 * 'value_regno' can be -1, meaning that an unknown value is being written to 3958 * the stack. 3959 * 3960 * Spilled pointers in range are not marked as written because we don't know 3961 * what's going to be actually written. This means that read propagation for 3962 * future reads cannot be terminated by this write. 3963 * 3964 * For privileged programs, uninitialized stack slots are considered 3965 * initialized by this write (even though we don't know exactly what offsets 3966 * are going to be written to). The idea is that we don't want the verifier to 3967 * reject future reads that access slots written to through variable offsets. 3968 */ 3969 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3970 /* func where register points to */ 3971 struct bpf_func_state *state, 3972 int ptr_regno, int off, int size, 3973 int value_regno, int insn_idx) 3974 { 3975 struct bpf_func_state *cur; /* state of the current function */ 3976 int min_off, max_off; 3977 int i, err; 3978 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 3979 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3980 bool writing_zero = false; 3981 /* set if the fact that we're writing a zero is used to let any 3982 * stack slots remain STACK_ZERO 3983 */ 3984 bool zero_used = false; 3985 3986 cur = env->cur_state->frame[env->cur_state->curframe]; 3987 ptr_reg = &cur->regs[ptr_regno]; 3988 min_off = ptr_reg->smin_value + off; 3989 max_off = ptr_reg->smax_value + off + size; 3990 if (value_regno >= 0) 3991 value_reg = &cur->regs[value_regno]; 3992 if ((value_reg && register_is_null(value_reg)) || 3993 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 3994 writing_zero = true; 3995 3996 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 3997 if (err) 3998 return err; 3999 4000 for (i = min_off; i < max_off; i++) { 4001 int spi; 4002 4003 spi = __get_spi(i); 4004 err = destroy_if_dynptr_stack_slot(env, state, spi); 4005 if (err) 4006 return err; 4007 } 4008 4009 /* Variable offset writes destroy any spilled pointers in range. */ 4010 for (i = min_off; i < max_off; i++) { 4011 u8 new_type, *stype; 4012 int slot, spi; 4013 4014 slot = -i - 1; 4015 spi = slot / BPF_REG_SIZE; 4016 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4017 mark_stack_slot_scratched(env, spi); 4018 4019 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 4020 /* Reject the write if range we may write to has not 4021 * been initialized beforehand. If we didn't reject 4022 * here, the ptr status would be erased below (even 4023 * though not all slots are actually overwritten), 4024 * possibly opening the door to leaks. 4025 * 4026 * We do however catch STACK_INVALID case below, and 4027 * only allow reading possibly uninitialized memory 4028 * later for CAP_PERFMON, as the write may not happen to 4029 * that slot. 4030 */ 4031 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 4032 insn_idx, i); 4033 return -EINVAL; 4034 } 4035 4036 /* Erase all spilled pointers. */ 4037 state->stack[spi].spilled_ptr.type = NOT_INIT; 4038 4039 /* Update the slot type. */ 4040 new_type = STACK_MISC; 4041 if (writing_zero && *stype == STACK_ZERO) { 4042 new_type = STACK_ZERO; 4043 zero_used = true; 4044 } 4045 /* If the slot is STACK_INVALID, we check whether it's OK to 4046 * pretend that it will be initialized by this write. The slot 4047 * might not actually be written to, and so if we mark it as 4048 * initialized future reads might leak uninitialized memory. 4049 * For privileged programs, we will accept such reads to slots 4050 * that may or may not be written because, if we're reject 4051 * them, the error would be too confusing. 4052 */ 4053 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 4054 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 4055 insn_idx, i); 4056 return -EINVAL; 4057 } 4058 *stype = new_type; 4059 } 4060 if (zero_used) { 4061 /* backtracking doesn't work for STACK_ZERO yet. */ 4062 err = mark_chain_precision(env, value_regno); 4063 if (err) 4064 return err; 4065 } 4066 return 0; 4067 } 4068 4069 /* When register 'dst_regno' is assigned some values from stack[min_off, 4070 * max_off), we set the register's type according to the types of the 4071 * respective stack slots. If all the stack values are known to be zeros, then 4072 * so is the destination reg. Otherwise, the register is considered to be 4073 * SCALAR. This function does not deal with register filling; the caller must 4074 * ensure that all spilled registers in the stack range have been marked as 4075 * read. 4076 */ 4077 static void mark_reg_stack_read(struct bpf_verifier_env *env, 4078 /* func where src register points to */ 4079 struct bpf_func_state *ptr_state, 4080 int min_off, int max_off, int dst_regno) 4081 { 4082 struct bpf_verifier_state *vstate = env->cur_state; 4083 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4084 int i, slot, spi; 4085 u8 *stype; 4086 int zeros = 0; 4087 4088 for (i = min_off; i < max_off; i++) { 4089 slot = -i - 1; 4090 spi = slot / BPF_REG_SIZE; 4091 stype = ptr_state->stack[spi].slot_type; 4092 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 4093 break; 4094 zeros++; 4095 } 4096 if (zeros == max_off - min_off) { 4097 /* any access_size read into register is zero extended, 4098 * so the whole register == const_zero 4099 */ 4100 __mark_reg_const_zero(&state->regs[dst_regno]); 4101 /* backtracking doesn't support STACK_ZERO yet, 4102 * so mark it precise here, so that later 4103 * backtracking can stop here. 4104 * Backtracking may not need this if this register 4105 * doesn't participate in pointer adjustment. 4106 * Forward propagation of precise flag is not 4107 * necessary either. This mark is only to stop 4108 * backtracking. Any register that contributed 4109 * to const 0 was marked precise before spill. 4110 */ 4111 state->regs[dst_regno].precise = true; 4112 } else { 4113 /* have read misc data from the stack */ 4114 mark_reg_unknown(env, state->regs, dst_regno); 4115 } 4116 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4117 } 4118 4119 /* Read the stack at 'off' and put the results into the register indicated by 4120 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 4121 * spilled reg. 4122 * 4123 * 'dst_regno' can be -1, meaning that the read value is not going to a 4124 * register. 4125 * 4126 * The access is assumed to be within the current stack bounds. 4127 */ 4128 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 4129 /* func where src register points to */ 4130 struct bpf_func_state *reg_state, 4131 int off, int size, int dst_regno) 4132 { 4133 struct bpf_verifier_state *vstate = env->cur_state; 4134 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4135 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 4136 struct bpf_reg_state *reg; 4137 u8 *stype, type; 4138 4139 stype = reg_state->stack[spi].slot_type; 4140 reg = ®_state->stack[spi].spilled_ptr; 4141 4142 if (is_spilled_reg(®_state->stack[spi])) { 4143 u8 spill_size = 1; 4144 4145 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 4146 spill_size++; 4147 4148 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 4149 if (reg->type != SCALAR_VALUE) { 4150 verbose_linfo(env, env->insn_idx, "; "); 4151 verbose(env, "invalid size of register fill\n"); 4152 return -EACCES; 4153 } 4154 4155 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4156 if (dst_regno < 0) 4157 return 0; 4158 4159 if (!(off % BPF_REG_SIZE) && size == spill_size) { 4160 /* The earlier check_reg_arg() has decided the 4161 * subreg_def for this insn. Save it first. 4162 */ 4163 s32 subreg_def = state->regs[dst_regno].subreg_def; 4164 4165 copy_register_state(&state->regs[dst_regno], reg); 4166 state->regs[dst_regno].subreg_def = subreg_def; 4167 } else { 4168 for (i = 0; i < size; i++) { 4169 type = stype[(slot - i) % BPF_REG_SIZE]; 4170 if (type == STACK_SPILL) 4171 continue; 4172 if (type == STACK_MISC) 4173 continue; 4174 if (type == STACK_INVALID && env->allow_uninit_stack) 4175 continue; 4176 verbose(env, "invalid read from stack off %d+%d size %d\n", 4177 off, i, size); 4178 return -EACCES; 4179 } 4180 mark_reg_unknown(env, state->regs, dst_regno); 4181 } 4182 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4183 return 0; 4184 } 4185 4186 if (dst_regno >= 0) { 4187 /* restore register state from stack */ 4188 copy_register_state(&state->regs[dst_regno], reg); 4189 /* mark reg as written since spilled pointer state likely 4190 * has its liveness marks cleared by is_state_visited() 4191 * which resets stack/reg liveness for state transitions 4192 */ 4193 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 4194 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 4195 /* If dst_regno==-1, the caller is asking us whether 4196 * it is acceptable to use this value as a SCALAR_VALUE 4197 * (e.g. for XADD). 4198 * We must not allow unprivileged callers to do that 4199 * with spilled pointers. 4200 */ 4201 verbose(env, "leaking pointer from stack off %d\n", 4202 off); 4203 return -EACCES; 4204 } 4205 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4206 } else { 4207 for (i = 0; i < size; i++) { 4208 type = stype[(slot - i) % BPF_REG_SIZE]; 4209 if (type == STACK_MISC) 4210 continue; 4211 if (type == STACK_ZERO) 4212 continue; 4213 if (type == STACK_INVALID && env->allow_uninit_stack) 4214 continue; 4215 verbose(env, "invalid read from stack off %d+%d size %d\n", 4216 off, i, size); 4217 return -EACCES; 4218 } 4219 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 4220 if (dst_regno >= 0) 4221 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 4222 } 4223 return 0; 4224 } 4225 4226 enum bpf_access_src { 4227 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 4228 ACCESS_HELPER = 2, /* the access is performed by a helper */ 4229 }; 4230 4231 static int check_stack_range_initialized(struct bpf_verifier_env *env, 4232 int regno, int off, int access_size, 4233 bool zero_size_allowed, 4234 enum bpf_access_src type, 4235 struct bpf_call_arg_meta *meta); 4236 4237 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 4238 { 4239 return cur_regs(env) + regno; 4240 } 4241 4242 /* Read the stack at 'ptr_regno + off' and put the result into the register 4243 * 'dst_regno'. 4244 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 4245 * but not its variable offset. 4246 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 4247 * 4248 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 4249 * filling registers (i.e. reads of spilled register cannot be detected when 4250 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 4251 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 4252 * offset; for a fixed offset check_stack_read_fixed_off should be used 4253 * instead. 4254 */ 4255 static int check_stack_read_var_off(struct bpf_verifier_env *env, 4256 int ptr_regno, int off, int size, int dst_regno) 4257 { 4258 /* The state of the source register. */ 4259 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4260 struct bpf_func_state *ptr_state = func(env, reg); 4261 int err; 4262 int min_off, max_off; 4263 4264 /* Note that we pass a NULL meta, so raw access will not be permitted. 4265 */ 4266 err = check_stack_range_initialized(env, ptr_regno, off, size, 4267 false, ACCESS_DIRECT, NULL); 4268 if (err) 4269 return err; 4270 4271 min_off = reg->smin_value + off; 4272 max_off = reg->smax_value + off; 4273 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 4274 return 0; 4275 } 4276 4277 /* check_stack_read dispatches to check_stack_read_fixed_off or 4278 * check_stack_read_var_off. 4279 * 4280 * The caller must ensure that the offset falls within the allocated stack 4281 * bounds. 4282 * 4283 * 'dst_regno' is a register which will receive the value from the stack. It 4284 * can be -1, meaning that the read value is not going to a register. 4285 */ 4286 static int check_stack_read(struct bpf_verifier_env *env, 4287 int ptr_regno, int off, int size, 4288 int dst_regno) 4289 { 4290 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4291 struct bpf_func_state *state = func(env, reg); 4292 int err; 4293 /* Some accesses are only permitted with a static offset. */ 4294 bool var_off = !tnum_is_const(reg->var_off); 4295 4296 /* The offset is required to be static when reads don't go to a 4297 * register, in order to not leak pointers (see 4298 * check_stack_read_fixed_off). 4299 */ 4300 if (dst_regno < 0 && var_off) { 4301 char tn_buf[48]; 4302 4303 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4304 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 4305 tn_buf, off, size); 4306 return -EACCES; 4307 } 4308 /* Variable offset is prohibited for unprivileged mode for simplicity 4309 * since it requires corresponding support in Spectre masking for stack 4310 * ALU. See also retrieve_ptr_limit(). The check in 4311 * check_stack_access_for_ptr_arithmetic() called by 4312 * adjust_ptr_min_max_vals() prevents users from creating stack pointers 4313 * with variable offsets, therefore no check is required here. Further, 4314 * just checking it here would be insufficient as speculative stack 4315 * writes could still lead to unsafe speculative behaviour. 4316 */ 4317 if (!var_off) { 4318 off += reg->var_off.value; 4319 err = check_stack_read_fixed_off(env, state, off, size, 4320 dst_regno); 4321 } else { 4322 /* Variable offset stack reads need more conservative handling 4323 * than fixed offset ones. Note that dst_regno >= 0 on this 4324 * branch. 4325 */ 4326 err = check_stack_read_var_off(env, ptr_regno, off, size, 4327 dst_regno); 4328 } 4329 return err; 4330 } 4331 4332 4333 /* check_stack_write dispatches to check_stack_write_fixed_off or 4334 * check_stack_write_var_off. 4335 * 4336 * 'ptr_regno' is the register used as a pointer into the stack. 4337 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4338 * 'value_regno' is the register whose value we're writing to the stack. It can 4339 * be -1, meaning that we're not writing from a register. 4340 * 4341 * The caller must ensure that the offset falls within the maximum stack size. 4342 */ 4343 static int check_stack_write(struct bpf_verifier_env *env, 4344 int ptr_regno, int off, int size, 4345 int value_regno, int insn_idx) 4346 { 4347 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4348 struct bpf_func_state *state = func(env, reg); 4349 int err; 4350 4351 if (tnum_is_const(reg->var_off)) { 4352 off += reg->var_off.value; 4353 err = check_stack_write_fixed_off(env, state, off, size, 4354 value_regno, insn_idx); 4355 } else { 4356 /* Variable offset stack reads need more conservative handling 4357 * than fixed offset ones. 4358 */ 4359 err = check_stack_write_var_off(env, state, 4360 ptr_regno, off, size, 4361 value_regno, insn_idx); 4362 } 4363 return err; 4364 } 4365 4366 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4367 int off, int size, enum bpf_access_type type) 4368 { 4369 struct bpf_reg_state *regs = cur_regs(env); 4370 struct bpf_map *map = regs[regno].map_ptr; 4371 u32 cap = bpf_map_flags_to_cap(map); 4372 4373 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4374 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 4375 map->value_size, off, size); 4376 return -EACCES; 4377 } 4378 4379 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4380 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 4381 map->value_size, off, size); 4382 return -EACCES; 4383 } 4384 4385 return 0; 4386 } 4387 4388 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4389 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 4390 int off, int size, u32 mem_size, 4391 bool zero_size_allowed) 4392 { 4393 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4394 struct bpf_reg_state *reg; 4395 4396 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4397 return 0; 4398 4399 reg = &cur_regs(env)[regno]; 4400 switch (reg->type) { 4401 case PTR_TO_MAP_KEY: 4402 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4403 mem_size, off, size); 4404 break; 4405 case PTR_TO_MAP_VALUE: 4406 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4407 mem_size, off, size); 4408 break; 4409 case PTR_TO_PACKET: 4410 case PTR_TO_PACKET_META: 4411 case PTR_TO_PACKET_END: 4412 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 4413 off, size, regno, reg->id, off, mem_size); 4414 break; 4415 case PTR_TO_MEM: 4416 default: 4417 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4418 mem_size, off, size); 4419 } 4420 4421 return -EACCES; 4422 } 4423 4424 /* check read/write into a memory region with possible variable offset */ 4425 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 4426 int off, int size, u32 mem_size, 4427 bool zero_size_allowed) 4428 { 4429 struct bpf_verifier_state *vstate = env->cur_state; 4430 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4431 struct bpf_reg_state *reg = &state->regs[regno]; 4432 int err; 4433 4434 /* We may have adjusted the register pointing to memory region, so we 4435 * need to try adding each of min_value and max_value to off 4436 * to make sure our theoretical access will be safe. 4437 * 4438 * The minimum value is only important with signed 4439 * comparisons where we can't assume the floor of a 4440 * value is 0. If we are using signed variables for our 4441 * index'es we need to make sure that whatever we use 4442 * will have a set floor within our range. 4443 */ 4444 if (reg->smin_value < 0 && 4445 (reg->smin_value == S64_MIN || 4446 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 4447 reg->smin_value + off < 0)) { 4448 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4449 regno); 4450 return -EACCES; 4451 } 4452 err = __check_mem_access(env, regno, reg->smin_value + off, size, 4453 mem_size, zero_size_allowed); 4454 if (err) { 4455 verbose(env, "R%d min value is outside of the allowed memory range\n", 4456 regno); 4457 return err; 4458 } 4459 4460 /* If we haven't set a max value then we need to bail since we can't be 4461 * sure we won't do bad things. 4462 * If reg->umax_value + off could overflow, treat that as unbounded too. 4463 */ 4464 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 4465 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 4466 regno); 4467 return -EACCES; 4468 } 4469 err = __check_mem_access(env, regno, reg->umax_value + off, size, 4470 mem_size, zero_size_allowed); 4471 if (err) { 4472 verbose(env, "R%d max value is outside of the allowed memory range\n", 4473 regno); 4474 return err; 4475 } 4476 4477 return 0; 4478 } 4479 4480 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4481 const struct bpf_reg_state *reg, int regno, 4482 bool fixed_off_ok) 4483 { 4484 /* Access to this pointer-typed register or passing it to a helper 4485 * is only allowed in its original, unmodified form. 4486 */ 4487 4488 if (reg->off < 0) { 4489 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 4490 reg_type_str(env, reg->type), regno, reg->off); 4491 return -EACCES; 4492 } 4493 4494 if (!fixed_off_ok && reg->off) { 4495 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 4496 reg_type_str(env, reg->type), regno, reg->off); 4497 return -EACCES; 4498 } 4499 4500 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4501 char tn_buf[48]; 4502 4503 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4504 verbose(env, "variable %s access var_off=%s disallowed\n", 4505 reg_type_str(env, reg->type), tn_buf); 4506 return -EACCES; 4507 } 4508 4509 return 0; 4510 } 4511 4512 int check_ptr_off_reg(struct bpf_verifier_env *env, 4513 const struct bpf_reg_state *reg, int regno) 4514 { 4515 return __check_ptr_off_reg(env, reg, regno, false); 4516 } 4517 4518 static int map_kptr_match_type(struct bpf_verifier_env *env, 4519 struct btf_field *kptr_field, 4520 struct bpf_reg_state *reg, u32 regno) 4521 { 4522 const char *targ_name = btf_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4523 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED | MEM_RCU; 4524 const char *reg_name = ""; 4525 4526 /* Only unreferenced case accepts untrusted pointers */ 4527 if (kptr_field->type == BPF_KPTR_UNREF) 4528 perm_flags |= PTR_UNTRUSTED; 4529 4530 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 4531 goto bad_type; 4532 4533 if (!btf_is_kernel(reg->btf)) { 4534 verbose(env, "R%d must point to kernel BTF\n", regno); 4535 return -EINVAL; 4536 } 4537 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4538 reg_name = btf_type_name(reg->btf, reg->btf_id); 4539 4540 /* For ref_ptr case, release function check should ensure we get one 4541 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4542 * normal store of unreferenced kptr, we must ensure var_off is zero. 4543 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 4544 * reg->off and reg->ref_obj_id are not needed here. 4545 */ 4546 if (__check_ptr_off_reg(env, reg, regno, true)) 4547 return -EACCES; 4548 4549 /* A full type match is needed, as BTF can be vmlinux or module BTF, and 4550 * we also need to take into account the reg->off. 4551 * 4552 * We want to support cases like: 4553 * 4554 * struct foo { 4555 * struct bar br; 4556 * struct baz bz; 4557 * }; 4558 * 4559 * struct foo *v; 4560 * v = func(); // PTR_TO_BTF_ID 4561 * val->foo = v; // reg->off is zero, btf and btf_id match type 4562 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 4563 * // first member type of struct after comparison fails 4564 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 4565 * // to match type 4566 * 4567 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 4568 * is zero. We must also ensure that btf_struct_ids_match does not walk 4569 * the struct to match type against first member of struct, i.e. reject 4570 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4571 * strict mode to true for type match. 4572 */ 4573 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 4574 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4575 kptr_field->type == BPF_KPTR_REF)) 4576 goto bad_type; 4577 return 0; 4578 bad_type: 4579 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4580 reg_type_str(env, reg->type), reg_name); 4581 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4582 if (kptr_field->type == BPF_KPTR_UNREF) 4583 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4584 targ_name); 4585 else 4586 verbose(env, "\n"); 4587 return -EINVAL; 4588 } 4589 4590 /* The non-sleepable programs and sleepable programs with explicit bpf_rcu_read_lock() 4591 * can dereference RCU protected pointers and result is PTR_TRUSTED. 4592 */ 4593 static bool in_rcu_cs(struct bpf_verifier_env *env) 4594 { 4595 return env->cur_state->active_rcu_lock || !env->prog->aux->sleepable; 4596 } 4597 4598 /* Once GCC supports btf_type_tag the following mechanism will be replaced with tag check */ 4599 BTF_SET_START(rcu_protected_types) 4600 BTF_ID(struct, prog_test_ref_kfunc) 4601 BTF_ID(struct, cgroup) 4602 BTF_ID(struct, bpf_cpumask) 4603 BTF_ID(struct, task_struct) 4604 BTF_SET_END(rcu_protected_types) 4605 4606 static bool rcu_protected_object(const struct btf *btf, u32 btf_id) 4607 { 4608 if (!btf_is_kernel(btf)) 4609 return false; 4610 return btf_id_set_contains(&rcu_protected_types, btf_id); 4611 } 4612 4613 static bool rcu_safe_kptr(const struct btf_field *field) 4614 { 4615 const struct btf_field_kptr *kptr = &field->kptr; 4616 4617 return field->type == BPF_KPTR_REF && rcu_protected_object(kptr->btf, kptr->btf_id); 4618 } 4619 4620 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 4621 int value_regno, int insn_idx, 4622 struct btf_field *kptr_field) 4623 { 4624 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4625 int class = BPF_CLASS(insn->code); 4626 struct bpf_reg_state *val_reg; 4627 4628 /* Things we already checked for in check_map_access and caller: 4629 * - Reject cases where variable offset may touch kptr 4630 * - size of access (must be BPF_DW) 4631 * - tnum_is_const(reg->var_off) 4632 * - kptr_field->offset == off + reg->var_off.value 4633 */ 4634 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4635 if (BPF_MODE(insn->code) != BPF_MEM) { 4636 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4637 return -EACCES; 4638 } 4639 4640 /* We only allow loading referenced kptr, since it will be marked as 4641 * untrusted, similar to unreferenced kptr. 4642 */ 4643 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) { 4644 verbose(env, "store to referenced kptr disallowed\n"); 4645 return -EACCES; 4646 } 4647 4648 if (class == BPF_LDX) { 4649 val_reg = reg_state(env, value_regno); 4650 /* We can simply mark the value_regno receiving the pointer 4651 * value from map as PTR_TO_BTF_ID, with the correct type. 4652 */ 4653 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 4654 kptr_field->kptr.btf_id, 4655 rcu_safe_kptr(kptr_field) && in_rcu_cs(env) ? 4656 PTR_MAYBE_NULL | MEM_RCU : 4657 PTR_MAYBE_NULL | PTR_UNTRUSTED); 4658 /* For mark_ptr_or_null_reg */ 4659 val_reg->id = ++env->id_gen; 4660 } else if (class == BPF_STX) { 4661 val_reg = reg_state(env, value_regno); 4662 if (!register_is_null(val_reg) && 4663 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4664 return -EACCES; 4665 } else if (class == BPF_ST) { 4666 if (insn->imm) { 4667 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4668 kptr_field->offset); 4669 return -EACCES; 4670 } 4671 } else { 4672 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4673 return -EACCES; 4674 } 4675 return 0; 4676 } 4677 4678 /* check read/write into a map element with possible variable offset */ 4679 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 4680 int off, int size, bool zero_size_allowed, 4681 enum bpf_access_src src) 4682 { 4683 struct bpf_verifier_state *vstate = env->cur_state; 4684 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4685 struct bpf_reg_state *reg = &state->regs[regno]; 4686 struct bpf_map *map = reg->map_ptr; 4687 struct btf_record *rec; 4688 int err, i; 4689 4690 err = check_mem_region_access(env, regno, off, size, map->value_size, 4691 zero_size_allowed); 4692 if (err) 4693 return err; 4694 4695 if (IS_ERR_OR_NULL(map->record)) 4696 return 0; 4697 rec = map->record; 4698 for (i = 0; i < rec->cnt; i++) { 4699 struct btf_field *field = &rec->fields[i]; 4700 u32 p = field->offset; 4701 4702 /* If any part of a field can be touched by load/store, reject 4703 * this program. To check that [x1, x2) overlaps with [y1, y2), 4704 * it is sufficient to check x1 < y2 && y1 < x2. 4705 */ 4706 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 4707 p < reg->umax_value + off + size) { 4708 switch (field->type) { 4709 case BPF_KPTR_UNREF: 4710 case BPF_KPTR_REF: 4711 if (src != ACCESS_DIRECT) { 4712 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 4713 return -EACCES; 4714 } 4715 if (!tnum_is_const(reg->var_off)) { 4716 verbose(env, "kptr access cannot have variable offset\n"); 4717 return -EACCES; 4718 } 4719 if (p != off + reg->var_off.value) { 4720 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 4721 p, off + reg->var_off.value); 4722 return -EACCES; 4723 } 4724 if (size != bpf_size_to_bytes(BPF_DW)) { 4725 verbose(env, "kptr access size must be BPF_DW\n"); 4726 return -EACCES; 4727 } 4728 break; 4729 default: 4730 verbose(env, "%s cannot be accessed directly by load/store\n", 4731 btf_field_type_name(field->type)); 4732 return -EACCES; 4733 } 4734 } 4735 } 4736 return 0; 4737 } 4738 4739 #define MAX_PACKET_OFF 0xffff 4740 4741 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4742 const struct bpf_call_arg_meta *meta, 4743 enum bpf_access_type t) 4744 { 4745 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4746 4747 switch (prog_type) { 4748 /* Program types only with direct read access go here! */ 4749 case BPF_PROG_TYPE_LWT_IN: 4750 case BPF_PROG_TYPE_LWT_OUT: 4751 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4752 case BPF_PROG_TYPE_SK_REUSEPORT: 4753 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4754 case BPF_PROG_TYPE_CGROUP_SKB: 4755 if (t == BPF_WRITE) 4756 return false; 4757 fallthrough; 4758 4759 /* Program types with direct read + write access go here! */ 4760 case BPF_PROG_TYPE_SCHED_CLS: 4761 case BPF_PROG_TYPE_SCHED_ACT: 4762 case BPF_PROG_TYPE_XDP: 4763 case BPF_PROG_TYPE_LWT_XMIT: 4764 case BPF_PROG_TYPE_SK_SKB: 4765 case BPF_PROG_TYPE_SK_MSG: 4766 if (meta) 4767 return meta->pkt_access; 4768 4769 env->seen_direct_write = true; 4770 return true; 4771 4772 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4773 if (t == BPF_WRITE) 4774 env->seen_direct_write = true; 4775 4776 return true; 4777 4778 default: 4779 return false; 4780 } 4781 } 4782 4783 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 4784 int size, bool zero_size_allowed) 4785 { 4786 struct bpf_reg_state *regs = cur_regs(env); 4787 struct bpf_reg_state *reg = ®s[regno]; 4788 int err; 4789 4790 /* We may have added a variable offset to the packet pointer; but any 4791 * reg->range we have comes after that. We are only checking the fixed 4792 * offset. 4793 */ 4794 4795 /* We don't allow negative numbers, because we aren't tracking enough 4796 * detail to prove they're safe. 4797 */ 4798 if (reg->smin_value < 0) { 4799 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4800 regno); 4801 return -EACCES; 4802 } 4803 4804 err = reg->range < 0 ? -EINVAL : 4805 __check_mem_access(env, regno, off, size, reg->range, 4806 zero_size_allowed); 4807 if (err) { 4808 verbose(env, "R%d offset is outside of the packet\n", regno); 4809 return err; 4810 } 4811 4812 /* __check_mem_access has made sure "off + size - 1" is within u16. 4813 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 4814 * otherwise find_good_pkt_pointers would have refused to set range info 4815 * that __check_mem_access would have rejected this pkt access. 4816 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 4817 */ 4818 env->prog->aux->max_pkt_offset = 4819 max_t(u32, env->prog->aux->max_pkt_offset, 4820 off + reg->umax_value + size - 1); 4821 4822 return err; 4823 } 4824 4825 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4826 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4827 enum bpf_access_type t, enum bpf_reg_type *reg_type, 4828 struct btf **btf, u32 *btf_id) 4829 { 4830 struct bpf_insn_access_aux info = { 4831 .reg_type = *reg_type, 4832 .log = &env->log, 4833 }; 4834 4835 if (env->ops->is_valid_access && 4836 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 4837 /* A non zero info.ctx_field_size indicates that this field is a 4838 * candidate for later verifier transformation to load the whole 4839 * field and then apply a mask when accessed with a narrower 4840 * access than actual ctx access size. A zero info.ctx_field_size 4841 * will only allow for whole field access and rejects any other 4842 * type of narrower access. 4843 */ 4844 *reg_type = info.reg_type; 4845 4846 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 4847 *btf = info.btf; 4848 *btf_id = info.btf_id; 4849 } else { 4850 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 4851 } 4852 /* remember the offset of last byte accessed in ctx */ 4853 if (env->prog->aux->max_ctx_offset < off + size) 4854 env->prog->aux->max_ctx_offset = off + size; 4855 return 0; 4856 } 4857 4858 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4859 return -EACCES; 4860 } 4861 4862 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 4863 int size) 4864 { 4865 if (size < 0 || off < 0 || 4866 (u64)off + size > sizeof(struct bpf_flow_keys)) { 4867 verbose(env, "invalid access to flow keys off=%d size=%d\n", 4868 off, size); 4869 return -EACCES; 4870 } 4871 return 0; 4872 } 4873 4874 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 4875 u32 regno, int off, int size, 4876 enum bpf_access_type t) 4877 { 4878 struct bpf_reg_state *regs = cur_regs(env); 4879 struct bpf_reg_state *reg = ®s[regno]; 4880 struct bpf_insn_access_aux info = {}; 4881 bool valid; 4882 4883 if (reg->smin_value < 0) { 4884 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4885 regno); 4886 return -EACCES; 4887 } 4888 4889 switch (reg->type) { 4890 case PTR_TO_SOCK_COMMON: 4891 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 4892 break; 4893 case PTR_TO_SOCKET: 4894 valid = bpf_sock_is_valid_access(off, size, t, &info); 4895 break; 4896 case PTR_TO_TCP_SOCK: 4897 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 4898 break; 4899 case PTR_TO_XDP_SOCK: 4900 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 4901 break; 4902 default: 4903 valid = false; 4904 } 4905 4906 4907 if (valid) { 4908 env->insn_aux_data[insn_idx].ctx_field_size = 4909 info.ctx_field_size; 4910 return 0; 4911 } 4912 4913 verbose(env, "R%d invalid %s access off=%d size=%d\n", 4914 regno, reg_type_str(env, reg->type), off, size); 4915 4916 return -EACCES; 4917 } 4918 4919 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 4920 { 4921 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 4922 } 4923 4924 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 4925 { 4926 const struct bpf_reg_state *reg = reg_state(env, regno); 4927 4928 return reg->type == PTR_TO_CTX; 4929 } 4930 4931 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 4932 { 4933 const struct bpf_reg_state *reg = reg_state(env, regno); 4934 4935 return type_is_sk_pointer(reg->type); 4936 } 4937 4938 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 4939 { 4940 const struct bpf_reg_state *reg = reg_state(env, regno); 4941 4942 return type_is_pkt_pointer(reg->type); 4943 } 4944 4945 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 4946 { 4947 const struct bpf_reg_state *reg = reg_state(env, regno); 4948 4949 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 4950 return reg->type == PTR_TO_FLOW_KEYS; 4951 } 4952 4953 static bool is_trusted_reg(const struct bpf_reg_state *reg) 4954 { 4955 /* A referenced register is always trusted. */ 4956 if (reg->ref_obj_id) 4957 return true; 4958 4959 /* If a register is not referenced, it is trusted if it has the 4960 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 4961 * other type modifiers may be safe, but we elect to take an opt-in 4962 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 4963 * not. 4964 * 4965 * Eventually, we should make PTR_TRUSTED the single source of truth 4966 * for whether a register is trusted. 4967 */ 4968 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 4969 !bpf_type_has_unsafe_modifiers(reg->type); 4970 } 4971 4972 static bool is_rcu_reg(const struct bpf_reg_state *reg) 4973 { 4974 return reg->type & MEM_RCU; 4975 } 4976 4977 static void clear_trusted_flags(enum bpf_type_flag *flag) 4978 { 4979 *flag &= ~(BPF_REG_TRUSTED_MODIFIERS | MEM_RCU); 4980 } 4981 4982 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 4983 const struct bpf_reg_state *reg, 4984 int off, int size, bool strict) 4985 { 4986 struct tnum reg_off; 4987 int ip_align; 4988 4989 /* Byte size accesses are always allowed. */ 4990 if (!strict || size == 1) 4991 return 0; 4992 4993 /* For platforms that do not have a Kconfig enabling 4994 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 4995 * NET_IP_ALIGN is universally set to '2'. And on platforms 4996 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 4997 * to this code only in strict mode where we want to emulate 4998 * the NET_IP_ALIGN==2 checking. Therefore use an 4999 * unconditional IP align value of '2'. 5000 */ 5001 ip_align = 2; 5002 5003 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 5004 if (!tnum_is_aligned(reg_off, size)) { 5005 char tn_buf[48]; 5006 5007 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5008 verbose(env, 5009 "misaligned packet access off %d+%s+%d+%d size %d\n", 5010 ip_align, tn_buf, reg->off, off, size); 5011 return -EACCES; 5012 } 5013 5014 return 0; 5015 } 5016 5017 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 5018 const struct bpf_reg_state *reg, 5019 const char *pointer_desc, 5020 int off, int size, bool strict) 5021 { 5022 struct tnum reg_off; 5023 5024 /* Byte size accesses are always allowed. */ 5025 if (!strict || size == 1) 5026 return 0; 5027 5028 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 5029 if (!tnum_is_aligned(reg_off, size)) { 5030 char tn_buf[48]; 5031 5032 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5033 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 5034 pointer_desc, tn_buf, reg->off, off, size); 5035 return -EACCES; 5036 } 5037 5038 return 0; 5039 } 5040 5041 static int check_ptr_alignment(struct bpf_verifier_env *env, 5042 const struct bpf_reg_state *reg, int off, 5043 int size, bool strict_alignment_once) 5044 { 5045 bool strict = env->strict_alignment || strict_alignment_once; 5046 const char *pointer_desc = ""; 5047 5048 switch (reg->type) { 5049 case PTR_TO_PACKET: 5050 case PTR_TO_PACKET_META: 5051 /* Special case, because of NET_IP_ALIGN. Given metadata sits 5052 * right in front, treat it the very same way. 5053 */ 5054 return check_pkt_ptr_alignment(env, reg, off, size, strict); 5055 case PTR_TO_FLOW_KEYS: 5056 pointer_desc = "flow keys "; 5057 break; 5058 case PTR_TO_MAP_KEY: 5059 pointer_desc = "key "; 5060 break; 5061 case PTR_TO_MAP_VALUE: 5062 pointer_desc = "value "; 5063 break; 5064 case PTR_TO_CTX: 5065 pointer_desc = "context "; 5066 break; 5067 case PTR_TO_STACK: 5068 pointer_desc = "stack "; 5069 /* The stack spill tracking logic in check_stack_write_fixed_off() 5070 * and check_stack_read_fixed_off() relies on stack accesses being 5071 * aligned. 5072 */ 5073 strict = true; 5074 break; 5075 case PTR_TO_SOCKET: 5076 pointer_desc = "sock "; 5077 break; 5078 case PTR_TO_SOCK_COMMON: 5079 pointer_desc = "sock_common "; 5080 break; 5081 case PTR_TO_TCP_SOCK: 5082 pointer_desc = "tcp_sock "; 5083 break; 5084 case PTR_TO_XDP_SOCK: 5085 pointer_desc = "xdp_sock "; 5086 break; 5087 default: 5088 break; 5089 } 5090 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 5091 strict); 5092 } 5093 5094 static int update_stack_depth(struct bpf_verifier_env *env, 5095 const struct bpf_func_state *func, 5096 int off) 5097 { 5098 u16 stack = env->subprog_info[func->subprogno].stack_depth; 5099 5100 if (stack >= -off) 5101 return 0; 5102 5103 /* update known max for given subprogram */ 5104 env->subprog_info[func->subprogno].stack_depth = -off; 5105 return 0; 5106 } 5107 5108 /* starting from main bpf function walk all instructions of the function 5109 * and recursively walk all callees that given function can call. 5110 * Ignore jump and exit insns. 5111 * Since recursion is prevented by check_cfg() this algorithm 5112 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 5113 */ 5114 static int check_max_stack_depth(struct bpf_verifier_env *env) 5115 { 5116 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 5117 struct bpf_subprog_info *subprog = env->subprog_info; 5118 struct bpf_insn *insn = env->prog->insnsi; 5119 bool tail_call_reachable = false; 5120 int ret_insn[MAX_CALL_FRAMES]; 5121 int ret_prog[MAX_CALL_FRAMES]; 5122 int j; 5123 5124 process_func: 5125 /* protect against potential stack overflow that might happen when 5126 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 5127 * depth for such case down to 256 so that the worst case scenario 5128 * would result in 8k stack size (32 which is tailcall limit * 256 = 5129 * 8k). 5130 * 5131 * To get the idea what might happen, see an example: 5132 * func1 -> sub rsp, 128 5133 * subfunc1 -> sub rsp, 256 5134 * tailcall1 -> add rsp, 256 5135 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 5136 * subfunc2 -> sub rsp, 64 5137 * subfunc22 -> sub rsp, 128 5138 * tailcall2 -> add rsp, 128 5139 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 5140 * 5141 * tailcall will unwind the current stack frame but it will not get rid 5142 * of caller's stack as shown on the example above. 5143 */ 5144 if (idx && subprog[idx].has_tail_call && depth >= 256) { 5145 verbose(env, 5146 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 5147 depth); 5148 return -EACCES; 5149 } 5150 /* round up to 32-bytes, since this is granularity 5151 * of interpreter stack size 5152 */ 5153 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5154 if (depth > MAX_BPF_STACK) { 5155 verbose(env, "combined stack size of %d calls is %d. Too large\n", 5156 frame + 1, depth); 5157 return -EACCES; 5158 } 5159 continue_func: 5160 subprog_end = subprog[idx + 1].start; 5161 for (; i < subprog_end; i++) { 5162 int next_insn; 5163 5164 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 5165 continue; 5166 /* remember insn and function to return to */ 5167 ret_insn[frame] = i + 1; 5168 ret_prog[frame] = idx; 5169 5170 /* find the callee */ 5171 next_insn = i + insn[i].imm + 1; 5172 idx = find_subprog(env, next_insn); 5173 if (idx < 0) { 5174 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5175 next_insn); 5176 return -EFAULT; 5177 } 5178 if (subprog[idx].is_async_cb) { 5179 if (subprog[idx].has_tail_call) { 5180 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 5181 return -EFAULT; 5182 } 5183 /* async callbacks don't increase bpf prog stack size */ 5184 continue; 5185 } 5186 i = next_insn; 5187 5188 if (subprog[idx].has_tail_call) 5189 tail_call_reachable = true; 5190 5191 frame++; 5192 if (frame >= MAX_CALL_FRAMES) { 5193 verbose(env, "the call stack of %d frames is too deep !\n", 5194 frame); 5195 return -E2BIG; 5196 } 5197 goto process_func; 5198 } 5199 /* if tail call got detected across bpf2bpf calls then mark each of the 5200 * currently present subprog frames as tail call reachable subprogs; 5201 * this info will be utilized by JIT so that we will be preserving the 5202 * tail call counter throughout bpf2bpf calls combined with tailcalls 5203 */ 5204 if (tail_call_reachable) 5205 for (j = 0; j < frame; j++) 5206 subprog[ret_prog[j]].tail_call_reachable = true; 5207 if (subprog[0].tail_call_reachable) 5208 env->prog->aux->tail_call_reachable = true; 5209 5210 /* end of for() loop means the last insn of the 'subprog' 5211 * was reached. Doesn't matter whether it was JA or EXIT 5212 */ 5213 if (frame == 0) 5214 return 0; 5215 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 5216 frame--; 5217 i = ret_insn[frame]; 5218 idx = ret_prog[frame]; 5219 goto continue_func; 5220 } 5221 5222 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5223 static int get_callee_stack_depth(struct bpf_verifier_env *env, 5224 const struct bpf_insn *insn, int idx) 5225 { 5226 int start = idx + insn->imm + 1, subprog; 5227 5228 subprog = find_subprog(env, start); 5229 if (subprog < 0) { 5230 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5231 start); 5232 return -EFAULT; 5233 } 5234 return env->subprog_info[subprog].stack_depth; 5235 } 5236 #endif 5237 5238 static int __check_buffer_access(struct bpf_verifier_env *env, 5239 const char *buf_info, 5240 const struct bpf_reg_state *reg, 5241 int regno, int off, int size) 5242 { 5243 if (off < 0) { 5244 verbose(env, 5245 "R%d invalid %s buffer access: off=%d, size=%d\n", 5246 regno, buf_info, off, size); 5247 return -EACCES; 5248 } 5249 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5250 char tn_buf[48]; 5251 5252 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5253 verbose(env, 5254 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 5255 regno, off, tn_buf); 5256 return -EACCES; 5257 } 5258 5259 return 0; 5260 } 5261 5262 static int check_tp_buffer_access(struct bpf_verifier_env *env, 5263 const struct bpf_reg_state *reg, 5264 int regno, int off, int size) 5265 { 5266 int err; 5267 5268 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 5269 if (err) 5270 return err; 5271 5272 if (off + size > env->prog->aux->max_tp_access) 5273 env->prog->aux->max_tp_access = off + size; 5274 5275 return 0; 5276 } 5277 5278 static int check_buffer_access(struct bpf_verifier_env *env, 5279 const struct bpf_reg_state *reg, 5280 int regno, int off, int size, 5281 bool zero_size_allowed, 5282 u32 *max_access) 5283 { 5284 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 5285 int err; 5286 5287 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 5288 if (err) 5289 return err; 5290 5291 if (off + size > *max_access) 5292 *max_access = off + size; 5293 5294 return 0; 5295 } 5296 5297 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 5298 static void zext_32_to_64(struct bpf_reg_state *reg) 5299 { 5300 reg->var_off = tnum_subreg(reg->var_off); 5301 __reg_assign_32_into_64(reg); 5302 } 5303 5304 /* truncate register to smaller size (in bytes) 5305 * must be called with size < BPF_REG_SIZE 5306 */ 5307 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 5308 { 5309 u64 mask; 5310 5311 /* clear high bits in bit representation */ 5312 reg->var_off = tnum_cast(reg->var_off, size); 5313 5314 /* fix arithmetic bounds */ 5315 mask = ((u64)1 << (size * 8)) - 1; 5316 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 5317 reg->umin_value &= mask; 5318 reg->umax_value &= mask; 5319 } else { 5320 reg->umin_value = 0; 5321 reg->umax_value = mask; 5322 } 5323 reg->smin_value = reg->umin_value; 5324 reg->smax_value = reg->umax_value; 5325 5326 /* If size is smaller than 32bit register the 32bit register 5327 * values are also truncated so we push 64-bit bounds into 5328 * 32-bit bounds. Above were truncated < 32-bits already. 5329 */ 5330 if (size >= 4) 5331 return; 5332 __reg_combine_64_into_32(reg); 5333 } 5334 5335 static bool bpf_map_is_rdonly(const struct bpf_map *map) 5336 { 5337 /* A map is considered read-only if the following condition are true: 5338 * 5339 * 1) BPF program side cannot change any of the map content. The 5340 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 5341 * and was set at map creation time. 5342 * 2) The map value(s) have been initialized from user space by a 5343 * loader and then "frozen", such that no new map update/delete 5344 * operations from syscall side are possible for the rest of 5345 * the map's lifetime from that point onwards. 5346 * 3) Any parallel/pending map update/delete operations from syscall 5347 * side have been completed. Only after that point, it's safe to 5348 * assume that map value(s) are immutable. 5349 */ 5350 return (map->map_flags & BPF_F_RDONLY_PROG) && 5351 READ_ONCE(map->frozen) && 5352 !bpf_map_write_active(map); 5353 } 5354 5355 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 5356 { 5357 void *ptr; 5358 u64 addr; 5359 int err; 5360 5361 err = map->ops->map_direct_value_addr(map, &addr, off); 5362 if (err) 5363 return err; 5364 ptr = (void *)(long)addr + off; 5365 5366 switch (size) { 5367 case sizeof(u8): 5368 *val = (u64)*(u8 *)ptr; 5369 break; 5370 case sizeof(u16): 5371 *val = (u64)*(u16 *)ptr; 5372 break; 5373 case sizeof(u32): 5374 *val = (u64)*(u32 *)ptr; 5375 break; 5376 case sizeof(u64): 5377 *val = *(u64 *)ptr; 5378 break; 5379 default: 5380 return -EINVAL; 5381 } 5382 return 0; 5383 } 5384 5385 #define BTF_TYPE_SAFE_RCU(__type) __PASTE(__type, __safe_rcu) 5386 #define BTF_TYPE_SAFE_RCU_OR_NULL(__type) __PASTE(__type, __safe_rcu_or_null) 5387 #define BTF_TYPE_SAFE_TRUSTED(__type) __PASTE(__type, __safe_trusted) 5388 5389 /* 5390 * Allow list few fields as RCU trusted or full trusted. 5391 * This logic doesn't allow mix tagging and will be removed once GCC supports 5392 * btf_type_tag. 5393 */ 5394 5395 /* RCU trusted: these fields are trusted in RCU CS and never NULL */ 5396 BTF_TYPE_SAFE_RCU(struct task_struct) { 5397 const cpumask_t *cpus_ptr; 5398 struct css_set __rcu *cgroups; 5399 struct task_struct __rcu *real_parent; 5400 struct task_struct *group_leader; 5401 }; 5402 5403 BTF_TYPE_SAFE_RCU(struct cgroup) { 5404 /* cgrp->kn is always accessible as documented in kernel/cgroup/cgroup.c */ 5405 struct kernfs_node *kn; 5406 }; 5407 5408 BTF_TYPE_SAFE_RCU(struct css_set) { 5409 struct cgroup *dfl_cgrp; 5410 }; 5411 5412 /* RCU trusted: these fields are trusted in RCU CS and can be NULL */ 5413 BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct) { 5414 struct file __rcu *exe_file; 5415 }; 5416 5417 /* skb->sk, req->sk are not RCU protected, but we mark them as such 5418 * because bpf prog accessible sockets are SOCK_RCU_FREE. 5419 */ 5420 BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff) { 5421 struct sock *sk; 5422 }; 5423 5424 BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock) { 5425 struct sock *sk; 5426 }; 5427 5428 /* full trusted: these fields are trusted even outside of RCU CS and never NULL */ 5429 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta) { 5430 struct seq_file *seq; 5431 }; 5432 5433 BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task) { 5434 struct bpf_iter_meta *meta; 5435 struct task_struct *task; 5436 }; 5437 5438 BTF_TYPE_SAFE_TRUSTED(struct linux_binprm) { 5439 struct file *file; 5440 }; 5441 5442 BTF_TYPE_SAFE_TRUSTED(struct file) { 5443 struct inode *f_inode; 5444 }; 5445 5446 BTF_TYPE_SAFE_TRUSTED(struct dentry) { 5447 /* no negative dentry-s in places where bpf can see it */ 5448 struct inode *d_inode; 5449 }; 5450 5451 BTF_TYPE_SAFE_TRUSTED(struct socket) { 5452 struct sock *sk; 5453 }; 5454 5455 static bool type_is_rcu(struct bpf_verifier_env *env, 5456 struct bpf_reg_state *reg, 5457 const char *field_name, u32 btf_id) 5458 { 5459 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct task_struct)); 5460 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct cgroup)); 5461 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU(struct css_set)); 5462 5463 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu"); 5464 } 5465 5466 static bool type_is_rcu_or_null(struct bpf_verifier_env *env, 5467 struct bpf_reg_state *reg, 5468 const char *field_name, u32 btf_id) 5469 { 5470 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct mm_struct)); 5471 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct sk_buff)); 5472 BTF_TYPE_EMIT(BTF_TYPE_SAFE_RCU_OR_NULL(struct request_sock)); 5473 5474 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_rcu_or_null"); 5475 } 5476 5477 static bool type_is_trusted(struct bpf_verifier_env *env, 5478 struct bpf_reg_state *reg, 5479 const char *field_name, u32 btf_id) 5480 { 5481 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter_meta)); 5482 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct bpf_iter__task)); 5483 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct linux_binprm)); 5484 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct file)); 5485 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct dentry)); 5486 BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket)); 5487 5488 return btf_nested_type_is_trusted(&env->log, reg, field_name, btf_id, "__safe_trusted"); 5489 } 5490 5491 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5492 struct bpf_reg_state *regs, 5493 int regno, int off, int size, 5494 enum bpf_access_type atype, 5495 int value_regno) 5496 { 5497 struct bpf_reg_state *reg = regs + regno; 5498 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5499 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5500 const char *field_name = NULL; 5501 enum bpf_type_flag flag = 0; 5502 u32 btf_id = 0; 5503 int ret; 5504 5505 if (!env->allow_ptr_leaks) { 5506 verbose(env, 5507 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5508 tname); 5509 return -EPERM; 5510 } 5511 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5512 verbose(env, 5513 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 5514 tname); 5515 return -EINVAL; 5516 } 5517 if (off < 0) { 5518 verbose(env, 5519 "R%d is ptr_%s invalid negative access: off=%d\n", 5520 regno, tname, off); 5521 return -EACCES; 5522 } 5523 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5524 char tn_buf[48]; 5525 5526 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5527 verbose(env, 5528 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5529 regno, tname, off, tn_buf); 5530 return -EACCES; 5531 } 5532 5533 if (reg->type & MEM_USER) { 5534 verbose(env, 5535 "R%d is ptr_%s access user memory: off=%d\n", 5536 regno, tname, off); 5537 return -EACCES; 5538 } 5539 5540 if (reg->type & MEM_PERCPU) { 5541 verbose(env, 5542 "R%d is ptr_%s access percpu memory: off=%d\n", 5543 regno, tname, off); 5544 return -EACCES; 5545 } 5546 5547 if (env->ops->btf_struct_access && !type_is_alloc(reg->type) && atype == BPF_WRITE) { 5548 if (!btf_is_kernel(reg->btf)) { 5549 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 5550 return -EFAULT; 5551 } 5552 ret = env->ops->btf_struct_access(&env->log, reg, off, size); 5553 } else { 5554 /* Writes are permitted with default btf_struct_access for 5555 * program allocated objects (which always have ref_obj_id > 0), 5556 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 5557 */ 5558 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 5559 verbose(env, "only read is supported\n"); 5560 return -EACCES; 5561 } 5562 5563 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 5564 !reg->ref_obj_id) { 5565 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 5566 return -EFAULT; 5567 } 5568 5569 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag, &field_name); 5570 } 5571 5572 if (ret < 0) 5573 return ret; 5574 5575 if (ret != PTR_TO_BTF_ID) { 5576 /* just mark; */ 5577 5578 } else if (type_flag(reg->type) & PTR_UNTRUSTED) { 5579 /* If this is an untrusted pointer, all pointers formed by walking it 5580 * also inherit the untrusted flag. 5581 */ 5582 flag = PTR_UNTRUSTED; 5583 5584 } else if (is_trusted_reg(reg) || is_rcu_reg(reg)) { 5585 /* By default any pointer obtained from walking a trusted pointer is no 5586 * longer trusted, unless the field being accessed has explicitly been 5587 * marked as inheriting its parent's state of trust (either full or RCU). 5588 * For example: 5589 * 'cgroups' pointer is untrusted if task->cgroups dereference 5590 * happened in a sleepable program outside of bpf_rcu_read_lock() 5591 * section. In a non-sleepable program it's trusted while in RCU CS (aka MEM_RCU). 5592 * Note bpf_rcu_read_unlock() converts MEM_RCU pointers to PTR_UNTRUSTED. 5593 * 5594 * A regular RCU-protected pointer with __rcu tag can also be deemed 5595 * trusted if we are in an RCU CS. Such pointer can be NULL. 5596 */ 5597 if (type_is_trusted(env, reg, field_name, btf_id)) { 5598 flag |= PTR_TRUSTED; 5599 } else if (in_rcu_cs(env) && !type_may_be_null(reg->type)) { 5600 if (type_is_rcu(env, reg, field_name, btf_id)) { 5601 /* ignore __rcu tag and mark it MEM_RCU */ 5602 flag |= MEM_RCU; 5603 } else if (flag & MEM_RCU || 5604 type_is_rcu_or_null(env, reg, field_name, btf_id)) { 5605 /* __rcu tagged pointers can be NULL */ 5606 flag |= MEM_RCU | PTR_MAYBE_NULL; 5607 } else if (flag & (MEM_PERCPU | MEM_USER)) { 5608 /* keep as-is */ 5609 } else { 5610 /* walking unknown pointers yields old deprecated PTR_TO_BTF_ID */ 5611 clear_trusted_flags(&flag); 5612 } 5613 } else { 5614 /* 5615 * If not in RCU CS or MEM_RCU pointer can be NULL then 5616 * aggressively mark as untrusted otherwise such 5617 * pointers will be plain PTR_TO_BTF_ID without flags 5618 * and will be allowed to be passed into helpers for 5619 * compat reasons. 5620 */ 5621 flag = PTR_UNTRUSTED; 5622 } 5623 } else { 5624 /* Old compat. Deprecated */ 5625 clear_trusted_flags(&flag); 5626 } 5627 5628 if (atype == BPF_READ && value_regno >= 0) 5629 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5630 5631 return 0; 5632 } 5633 5634 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5635 struct bpf_reg_state *regs, 5636 int regno, int off, int size, 5637 enum bpf_access_type atype, 5638 int value_regno) 5639 { 5640 struct bpf_reg_state *reg = regs + regno; 5641 struct bpf_map *map = reg->map_ptr; 5642 struct bpf_reg_state map_reg; 5643 enum bpf_type_flag flag = 0; 5644 const struct btf_type *t; 5645 const char *tname; 5646 u32 btf_id; 5647 int ret; 5648 5649 if (!btf_vmlinux) { 5650 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5651 return -ENOTSUPP; 5652 } 5653 5654 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5655 verbose(env, "map_ptr access not supported for map type %d\n", 5656 map->map_type); 5657 return -ENOTSUPP; 5658 } 5659 5660 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5661 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5662 5663 if (!env->allow_ptr_leaks) { 5664 verbose(env, 5665 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5666 tname); 5667 return -EPERM; 5668 } 5669 5670 if (off < 0) { 5671 verbose(env, "R%d is %s invalid negative access: off=%d\n", 5672 regno, tname, off); 5673 return -EACCES; 5674 } 5675 5676 if (atype != BPF_READ) { 5677 verbose(env, "only read from %s is supported\n", tname); 5678 return -EACCES; 5679 } 5680 5681 /* Simulate access to a PTR_TO_BTF_ID */ 5682 memset(&map_reg, 0, sizeof(map_reg)); 5683 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 5684 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag, NULL); 5685 if (ret < 0) 5686 return ret; 5687 5688 if (value_regno >= 0) 5689 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 5690 5691 return 0; 5692 } 5693 5694 /* Check that the stack access at the given offset is within bounds. The 5695 * maximum valid offset is -1. 5696 * 5697 * The minimum valid offset is -MAX_BPF_STACK for writes, and 5698 * -state->allocated_stack for reads. 5699 */ 5700 static int check_stack_slot_within_bounds(int off, 5701 struct bpf_func_state *state, 5702 enum bpf_access_type t) 5703 { 5704 int min_valid_off; 5705 5706 if (t == BPF_WRITE) 5707 min_valid_off = -MAX_BPF_STACK; 5708 else 5709 min_valid_off = -state->allocated_stack; 5710 5711 if (off < min_valid_off || off > -1) 5712 return -EACCES; 5713 return 0; 5714 } 5715 5716 /* Check that the stack access at 'regno + off' falls within the maximum stack 5717 * bounds. 5718 * 5719 * 'off' includes `regno->offset`, but not its dynamic part (if any). 5720 */ 5721 static int check_stack_access_within_bounds( 5722 struct bpf_verifier_env *env, 5723 int regno, int off, int access_size, 5724 enum bpf_access_src src, enum bpf_access_type type) 5725 { 5726 struct bpf_reg_state *regs = cur_regs(env); 5727 struct bpf_reg_state *reg = regs + regno; 5728 struct bpf_func_state *state = func(env, reg); 5729 int min_off, max_off; 5730 int err; 5731 char *err_extra; 5732 5733 if (src == ACCESS_HELPER) 5734 /* We don't know if helpers are reading or writing (or both). */ 5735 err_extra = " indirect access to"; 5736 else if (type == BPF_READ) 5737 err_extra = " read from"; 5738 else 5739 err_extra = " write to"; 5740 5741 if (tnum_is_const(reg->var_off)) { 5742 min_off = reg->var_off.value + off; 5743 if (access_size > 0) 5744 max_off = min_off + access_size - 1; 5745 else 5746 max_off = min_off; 5747 } else { 5748 if (reg->smax_value >= BPF_MAX_VAR_OFF || 5749 reg->smin_value <= -BPF_MAX_VAR_OFF) { 5750 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 5751 err_extra, regno); 5752 return -EACCES; 5753 } 5754 min_off = reg->smin_value + off; 5755 if (access_size > 0) 5756 max_off = reg->smax_value + off + access_size - 1; 5757 else 5758 max_off = min_off; 5759 } 5760 5761 err = check_stack_slot_within_bounds(min_off, state, type); 5762 if (!err) 5763 err = check_stack_slot_within_bounds(max_off, state, type); 5764 5765 if (err) { 5766 if (tnum_is_const(reg->var_off)) { 5767 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 5768 err_extra, regno, off, access_size); 5769 } else { 5770 char tn_buf[48]; 5771 5772 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5773 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 5774 err_extra, regno, tn_buf, access_size); 5775 } 5776 } 5777 return err; 5778 } 5779 5780 /* check whether memory at (regno + off) is accessible for t = (read | write) 5781 * if t==write, value_regno is a register which value is stored into memory 5782 * if t==read, value_regno is a register which will receive the value from memory 5783 * if t==write && value_regno==-1, some unknown value is stored into memory 5784 * if t==read && value_regno==-1, don't care what we read from memory 5785 */ 5786 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 5787 int off, int bpf_size, enum bpf_access_type t, 5788 int value_regno, bool strict_alignment_once) 5789 { 5790 struct bpf_reg_state *regs = cur_regs(env); 5791 struct bpf_reg_state *reg = regs + regno; 5792 struct bpf_func_state *state; 5793 int size, err = 0; 5794 5795 size = bpf_size_to_bytes(bpf_size); 5796 if (size < 0) 5797 return size; 5798 5799 /* alignment checks will add in reg->off themselves */ 5800 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 5801 if (err) 5802 return err; 5803 5804 /* for access checks, reg->off is just part of off */ 5805 off += reg->off; 5806 5807 if (reg->type == PTR_TO_MAP_KEY) { 5808 if (t == BPF_WRITE) { 5809 verbose(env, "write to change key R%d not allowed\n", regno); 5810 return -EACCES; 5811 } 5812 5813 err = check_mem_region_access(env, regno, off, size, 5814 reg->map_ptr->key_size, false); 5815 if (err) 5816 return err; 5817 if (value_regno >= 0) 5818 mark_reg_unknown(env, regs, value_regno); 5819 } else if (reg->type == PTR_TO_MAP_VALUE) { 5820 struct btf_field *kptr_field = NULL; 5821 5822 if (t == BPF_WRITE && value_regno >= 0 && 5823 is_pointer_value(env, value_regno)) { 5824 verbose(env, "R%d leaks addr into map\n", value_regno); 5825 return -EACCES; 5826 } 5827 err = check_map_access_type(env, regno, off, size, t); 5828 if (err) 5829 return err; 5830 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 5831 if (err) 5832 return err; 5833 if (tnum_is_const(reg->var_off)) 5834 kptr_field = btf_record_find(reg->map_ptr->record, 5835 off + reg->var_off.value, BPF_KPTR); 5836 if (kptr_field) { 5837 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 5838 } else if (t == BPF_READ && value_regno >= 0) { 5839 struct bpf_map *map = reg->map_ptr; 5840 5841 /* if map is read-only, track its contents as scalars */ 5842 if (tnum_is_const(reg->var_off) && 5843 bpf_map_is_rdonly(map) && 5844 map->ops->map_direct_value_addr) { 5845 int map_off = off + reg->var_off.value; 5846 u64 val = 0; 5847 5848 err = bpf_map_direct_read(map, map_off, size, 5849 &val); 5850 if (err) 5851 return err; 5852 5853 regs[value_regno].type = SCALAR_VALUE; 5854 __mark_reg_known(®s[value_regno], val); 5855 } else { 5856 mark_reg_unknown(env, regs, value_regno); 5857 } 5858 } 5859 } else if (base_type(reg->type) == PTR_TO_MEM) { 5860 bool rdonly_mem = type_is_rdonly_mem(reg->type); 5861 5862 if (type_may_be_null(reg->type)) { 5863 verbose(env, "R%d invalid mem access '%s'\n", regno, 5864 reg_type_str(env, reg->type)); 5865 return -EACCES; 5866 } 5867 5868 if (t == BPF_WRITE && rdonly_mem) { 5869 verbose(env, "R%d cannot write into %s\n", 5870 regno, reg_type_str(env, reg->type)); 5871 return -EACCES; 5872 } 5873 5874 if (t == BPF_WRITE && value_regno >= 0 && 5875 is_pointer_value(env, value_regno)) { 5876 verbose(env, "R%d leaks addr into mem\n", value_regno); 5877 return -EACCES; 5878 } 5879 5880 err = check_mem_region_access(env, regno, off, size, 5881 reg->mem_size, false); 5882 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 5883 mark_reg_unknown(env, regs, value_regno); 5884 } else if (reg->type == PTR_TO_CTX) { 5885 enum bpf_reg_type reg_type = SCALAR_VALUE; 5886 struct btf *btf = NULL; 5887 u32 btf_id = 0; 5888 5889 if (t == BPF_WRITE && value_regno >= 0 && 5890 is_pointer_value(env, value_regno)) { 5891 verbose(env, "R%d leaks addr into ctx\n", value_regno); 5892 return -EACCES; 5893 } 5894 5895 err = check_ptr_off_reg(env, reg, regno); 5896 if (err < 0) 5897 return err; 5898 5899 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 5900 &btf_id); 5901 if (err) 5902 verbose_linfo(env, insn_idx, "; "); 5903 if (!err && t == BPF_READ && value_regno >= 0) { 5904 /* ctx access returns either a scalar, or a 5905 * PTR_TO_PACKET[_META,_END]. In the latter 5906 * case, we know the offset is zero. 5907 */ 5908 if (reg_type == SCALAR_VALUE) { 5909 mark_reg_unknown(env, regs, value_regno); 5910 } else { 5911 mark_reg_known_zero(env, regs, 5912 value_regno); 5913 if (type_may_be_null(reg_type)) 5914 regs[value_regno].id = ++env->id_gen; 5915 /* A load of ctx field could have different 5916 * actual load size with the one encoded in the 5917 * insn. When the dst is PTR, it is for sure not 5918 * a sub-register. 5919 */ 5920 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 5921 if (base_type(reg_type) == PTR_TO_BTF_ID) { 5922 regs[value_regno].btf = btf; 5923 regs[value_regno].btf_id = btf_id; 5924 } 5925 } 5926 regs[value_regno].type = reg_type; 5927 } 5928 5929 } else if (reg->type == PTR_TO_STACK) { 5930 /* Basic bounds checks. */ 5931 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 5932 if (err) 5933 return err; 5934 5935 state = func(env, reg); 5936 err = update_stack_depth(env, state, off); 5937 if (err) 5938 return err; 5939 5940 if (t == BPF_READ) 5941 err = check_stack_read(env, regno, off, size, 5942 value_regno); 5943 else 5944 err = check_stack_write(env, regno, off, size, 5945 value_regno, insn_idx); 5946 } else if (reg_is_pkt_pointer(reg)) { 5947 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 5948 verbose(env, "cannot write into packet\n"); 5949 return -EACCES; 5950 } 5951 if (t == BPF_WRITE && value_regno >= 0 && 5952 is_pointer_value(env, value_regno)) { 5953 verbose(env, "R%d leaks addr into packet\n", 5954 value_regno); 5955 return -EACCES; 5956 } 5957 err = check_packet_access(env, regno, off, size, false); 5958 if (!err && t == BPF_READ && value_regno >= 0) 5959 mark_reg_unknown(env, regs, value_regno); 5960 } else if (reg->type == PTR_TO_FLOW_KEYS) { 5961 if (t == BPF_WRITE && value_regno >= 0 && 5962 is_pointer_value(env, value_regno)) { 5963 verbose(env, "R%d leaks addr into flow keys\n", 5964 value_regno); 5965 return -EACCES; 5966 } 5967 5968 err = check_flow_keys_access(env, off, size); 5969 if (!err && t == BPF_READ && value_regno >= 0) 5970 mark_reg_unknown(env, regs, value_regno); 5971 } else if (type_is_sk_pointer(reg->type)) { 5972 if (t == BPF_WRITE) { 5973 verbose(env, "R%d cannot write into %s\n", 5974 regno, reg_type_str(env, reg->type)); 5975 return -EACCES; 5976 } 5977 err = check_sock_access(env, insn_idx, regno, off, size, t); 5978 if (!err && value_regno >= 0) 5979 mark_reg_unknown(env, regs, value_regno); 5980 } else if (reg->type == PTR_TO_TP_BUFFER) { 5981 err = check_tp_buffer_access(env, reg, regno, off, size); 5982 if (!err && t == BPF_READ && value_regno >= 0) 5983 mark_reg_unknown(env, regs, value_regno); 5984 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 5985 !type_may_be_null(reg->type)) { 5986 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 5987 value_regno); 5988 } else if (reg->type == CONST_PTR_TO_MAP) { 5989 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 5990 value_regno); 5991 } else if (base_type(reg->type) == PTR_TO_BUF) { 5992 bool rdonly_mem = type_is_rdonly_mem(reg->type); 5993 u32 *max_access; 5994 5995 if (rdonly_mem) { 5996 if (t == BPF_WRITE) { 5997 verbose(env, "R%d cannot write into %s\n", 5998 regno, reg_type_str(env, reg->type)); 5999 return -EACCES; 6000 } 6001 max_access = &env->prog->aux->max_rdonly_access; 6002 } else { 6003 max_access = &env->prog->aux->max_rdwr_access; 6004 } 6005 6006 err = check_buffer_access(env, reg, regno, off, size, false, 6007 max_access); 6008 6009 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 6010 mark_reg_unknown(env, regs, value_regno); 6011 } else { 6012 verbose(env, "R%d invalid mem access '%s'\n", regno, 6013 reg_type_str(env, reg->type)); 6014 return -EACCES; 6015 } 6016 6017 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 6018 regs[value_regno].type == SCALAR_VALUE) { 6019 /* b/h/w load zero-extends, mark upper bits as known 0 */ 6020 coerce_reg_to_size(®s[value_regno], size); 6021 } 6022 return err; 6023 } 6024 6025 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 6026 { 6027 int load_reg; 6028 int err; 6029 6030 switch (insn->imm) { 6031 case BPF_ADD: 6032 case BPF_ADD | BPF_FETCH: 6033 case BPF_AND: 6034 case BPF_AND | BPF_FETCH: 6035 case BPF_OR: 6036 case BPF_OR | BPF_FETCH: 6037 case BPF_XOR: 6038 case BPF_XOR | BPF_FETCH: 6039 case BPF_XCHG: 6040 case BPF_CMPXCHG: 6041 break; 6042 default: 6043 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 6044 return -EINVAL; 6045 } 6046 6047 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 6048 verbose(env, "invalid atomic operand size\n"); 6049 return -EINVAL; 6050 } 6051 6052 /* check src1 operand */ 6053 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6054 if (err) 6055 return err; 6056 6057 /* check src2 operand */ 6058 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6059 if (err) 6060 return err; 6061 6062 if (insn->imm == BPF_CMPXCHG) { 6063 /* Check comparison of R0 with memory location */ 6064 const u32 aux_reg = BPF_REG_0; 6065 6066 err = check_reg_arg(env, aux_reg, SRC_OP); 6067 if (err) 6068 return err; 6069 6070 if (is_pointer_value(env, aux_reg)) { 6071 verbose(env, "R%d leaks addr into mem\n", aux_reg); 6072 return -EACCES; 6073 } 6074 } 6075 6076 if (is_pointer_value(env, insn->src_reg)) { 6077 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 6078 return -EACCES; 6079 } 6080 6081 if (is_ctx_reg(env, insn->dst_reg) || 6082 is_pkt_reg(env, insn->dst_reg) || 6083 is_flow_key_reg(env, insn->dst_reg) || 6084 is_sk_reg(env, insn->dst_reg)) { 6085 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 6086 insn->dst_reg, 6087 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 6088 return -EACCES; 6089 } 6090 6091 if (insn->imm & BPF_FETCH) { 6092 if (insn->imm == BPF_CMPXCHG) 6093 load_reg = BPF_REG_0; 6094 else 6095 load_reg = insn->src_reg; 6096 6097 /* check and record load of old value */ 6098 err = check_reg_arg(env, load_reg, DST_OP); 6099 if (err) 6100 return err; 6101 } else { 6102 /* This instruction accesses a memory location but doesn't 6103 * actually load it into a register. 6104 */ 6105 load_reg = -1; 6106 } 6107 6108 /* Check whether we can read the memory, with second call for fetch 6109 * case to simulate the register fill. 6110 */ 6111 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6112 BPF_SIZE(insn->code), BPF_READ, -1, true); 6113 if (!err && load_reg >= 0) 6114 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6115 BPF_SIZE(insn->code), BPF_READ, load_reg, 6116 true); 6117 if (err) 6118 return err; 6119 6120 /* Check whether we can write into the same memory. */ 6121 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 6122 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 6123 if (err) 6124 return err; 6125 6126 return 0; 6127 } 6128 6129 /* When register 'regno' is used to read the stack (either directly or through 6130 * a helper function) make sure that it's within stack boundary and, depending 6131 * on the access type, that all elements of the stack are initialized. 6132 * 6133 * 'off' includes 'regno->off', but not its dynamic part (if any). 6134 * 6135 * All registers that have been spilled on the stack in the slots within the 6136 * read offsets are marked as read. 6137 */ 6138 static int check_stack_range_initialized( 6139 struct bpf_verifier_env *env, int regno, int off, 6140 int access_size, bool zero_size_allowed, 6141 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 6142 { 6143 struct bpf_reg_state *reg = reg_state(env, regno); 6144 struct bpf_func_state *state = func(env, reg); 6145 int err, min_off, max_off, i, j, slot, spi; 6146 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 6147 enum bpf_access_type bounds_check_type; 6148 /* Some accesses can write anything into the stack, others are 6149 * read-only. 6150 */ 6151 bool clobber = false; 6152 6153 if (access_size == 0 && !zero_size_allowed) { 6154 verbose(env, "invalid zero-sized read\n"); 6155 return -EACCES; 6156 } 6157 6158 if (type == ACCESS_HELPER) { 6159 /* The bounds checks for writes are more permissive than for 6160 * reads. However, if raw_mode is not set, we'll do extra 6161 * checks below. 6162 */ 6163 bounds_check_type = BPF_WRITE; 6164 clobber = true; 6165 } else { 6166 bounds_check_type = BPF_READ; 6167 } 6168 err = check_stack_access_within_bounds(env, regno, off, access_size, 6169 type, bounds_check_type); 6170 if (err) 6171 return err; 6172 6173 6174 if (tnum_is_const(reg->var_off)) { 6175 min_off = max_off = reg->var_off.value + off; 6176 } else { 6177 /* Variable offset is prohibited for unprivileged mode for 6178 * simplicity since it requires corresponding support in 6179 * Spectre masking for stack ALU. 6180 * See also retrieve_ptr_limit(). 6181 */ 6182 if (!env->bypass_spec_v1) { 6183 char tn_buf[48]; 6184 6185 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6186 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 6187 regno, err_extra, tn_buf); 6188 return -EACCES; 6189 } 6190 /* Only initialized buffer on stack is allowed to be accessed 6191 * with variable offset. With uninitialized buffer it's hard to 6192 * guarantee that whole memory is marked as initialized on 6193 * helper return since specific bounds are unknown what may 6194 * cause uninitialized stack leaking. 6195 */ 6196 if (meta && meta->raw_mode) 6197 meta = NULL; 6198 6199 min_off = reg->smin_value + off; 6200 max_off = reg->smax_value + off; 6201 } 6202 6203 if (meta && meta->raw_mode) { 6204 /* Ensure we won't be overwriting dynptrs when simulating byte 6205 * by byte access in check_helper_call using meta.access_size. 6206 * This would be a problem if we have a helper in the future 6207 * which takes: 6208 * 6209 * helper(uninit_mem, len, dynptr) 6210 * 6211 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 6212 * may end up writing to dynptr itself when touching memory from 6213 * arg 1. This can be relaxed on a case by case basis for known 6214 * safe cases, but reject due to the possibilitiy of aliasing by 6215 * default. 6216 */ 6217 for (i = min_off; i < max_off + access_size; i++) { 6218 int stack_off = -i - 1; 6219 6220 spi = __get_spi(i); 6221 /* raw_mode may write past allocated_stack */ 6222 if (state->allocated_stack <= stack_off) 6223 continue; 6224 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 6225 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 6226 return -EACCES; 6227 } 6228 } 6229 meta->access_size = access_size; 6230 meta->regno = regno; 6231 return 0; 6232 } 6233 6234 for (i = min_off; i < max_off + access_size; i++) { 6235 u8 *stype; 6236 6237 slot = -i - 1; 6238 spi = slot / BPF_REG_SIZE; 6239 if (state->allocated_stack <= slot) 6240 goto err; 6241 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 6242 if (*stype == STACK_MISC) 6243 goto mark; 6244 if ((*stype == STACK_ZERO) || 6245 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 6246 if (clobber) { 6247 /* helper can write anything into the stack */ 6248 *stype = STACK_MISC; 6249 } 6250 goto mark; 6251 } 6252 6253 if (is_spilled_reg(&state->stack[spi]) && 6254 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 6255 env->allow_ptr_leaks)) { 6256 if (clobber) { 6257 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 6258 for (j = 0; j < BPF_REG_SIZE; j++) 6259 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 6260 } 6261 goto mark; 6262 } 6263 6264 err: 6265 if (tnum_is_const(reg->var_off)) { 6266 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 6267 err_extra, regno, min_off, i - min_off, access_size); 6268 } else { 6269 char tn_buf[48]; 6270 6271 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6272 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 6273 err_extra, regno, tn_buf, i - min_off, access_size); 6274 } 6275 return -EACCES; 6276 mark: 6277 /* reading any byte out of 8-byte 'spill_slot' will cause 6278 * the whole slot to be marked as 'read' 6279 */ 6280 mark_reg_read(env, &state->stack[spi].spilled_ptr, 6281 state->stack[spi].spilled_ptr.parent, 6282 REG_LIVE_READ64); 6283 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 6284 * be sure that whether stack slot is written to or not. Hence, 6285 * we must still conservatively propagate reads upwards even if 6286 * helper may write to the entire memory range. 6287 */ 6288 } 6289 return update_stack_depth(env, state, min_off); 6290 } 6291 6292 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 6293 int access_size, bool zero_size_allowed, 6294 struct bpf_call_arg_meta *meta) 6295 { 6296 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6297 u32 *max_access; 6298 6299 switch (base_type(reg->type)) { 6300 case PTR_TO_PACKET: 6301 case PTR_TO_PACKET_META: 6302 return check_packet_access(env, regno, reg->off, access_size, 6303 zero_size_allowed); 6304 case PTR_TO_MAP_KEY: 6305 if (meta && meta->raw_mode) { 6306 verbose(env, "R%d cannot write into %s\n", regno, 6307 reg_type_str(env, reg->type)); 6308 return -EACCES; 6309 } 6310 return check_mem_region_access(env, regno, reg->off, access_size, 6311 reg->map_ptr->key_size, false); 6312 case PTR_TO_MAP_VALUE: 6313 if (check_map_access_type(env, regno, reg->off, access_size, 6314 meta && meta->raw_mode ? BPF_WRITE : 6315 BPF_READ)) 6316 return -EACCES; 6317 return check_map_access(env, regno, reg->off, access_size, 6318 zero_size_allowed, ACCESS_HELPER); 6319 case PTR_TO_MEM: 6320 if (type_is_rdonly_mem(reg->type)) { 6321 if (meta && meta->raw_mode) { 6322 verbose(env, "R%d cannot write into %s\n", regno, 6323 reg_type_str(env, reg->type)); 6324 return -EACCES; 6325 } 6326 } 6327 return check_mem_region_access(env, regno, reg->off, 6328 access_size, reg->mem_size, 6329 zero_size_allowed); 6330 case PTR_TO_BUF: 6331 if (type_is_rdonly_mem(reg->type)) { 6332 if (meta && meta->raw_mode) { 6333 verbose(env, "R%d cannot write into %s\n", regno, 6334 reg_type_str(env, reg->type)); 6335 return -EACCES; 6336 } 6337 6338 max_access = &env->prog->aux->max_rdonly_access; 6339 } else { 6340 max_access = &env->prog->aux->max_rdwr_access; 6341 } 6342 return check_buffer_access(env, reg, regno, reg->off, 6343 access_size, zero_size_allowed, 6344 max_access); 6345 case PTR_TO_STACK: 6346 return check_stack_range_initialized( 6347 env, 6348 regno, reg->off, access_size, 6349 zero_size_allowed, ACCESS_HELPER, meta); 6350 case PTR_TO_BTF_ID: 6351 return check_ptr_to_btf_access(env, regs, regno, reg->off, 6352 access_size, BPF_READ, -1); 6353 case PTR_TO_CTX: 6354 /* in case the function doesn't know how to access the context, 6355 * (because we are in a program of type SYSCALL for example), we 6356 * can not statically check its size. 6357 * Dynamically check it now. 6358 */ 6359 if (!env->ops->convert_ctx_access) { 6360 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 6361 int offset = access_size - 1; 6362 6363 /* Allow zero-byte read from PTR_TO_CTX */ 6364 if (access_size == 0) 6365 return zero_size_allowed ? 0 : -EACCES; 6366 6367 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 6368 atype, -1, false); 6369 } 6370 6371 fallthrough; 6372 default: /* scalar_value or invalid ptr */ 6373 /* Allow zero-byte read from NULL, regardless of pointer type */ 6374 if (zero_size_allowed && access_size == 0 && 6375 register_is_null(reg)) 6376 return 0; 6377 6378 verbose(env, "R%d type=%s ", regno, 6379 reg_type_str(env, reg->type)); 6380 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 6381 return -EACCES; 6382 } 6383 } 6384 6385 static int check_mem_size_reg(struct bpf_verifier_env *env, 6386 struct bpf_reg_state *reg, u32 regno, 6387 bool zero_size_allowed, 6388 struct bpf_call_arg_meta *meta) 6389 { 6390 int err; 6391 6392 /* This is used to refine r0 return value bounds for helpers 6393 * that enforce this value as an upper bound on return values. 6394 * See do_refine_retval_range() for helpers that can refine 6395 * the return value. C type of helper is u32 so we pull register 6396 * bound from umax_value however, if negative verifier errors 6397 * out. Only upper bounds can be learned because retval is an 6398 * int type and negative retvals are allowed. 6399 */ 6400 meta->msize_max_value = reg->umax_value; 6401 6402 /* The register is SCALAR_VALUE; the access check 6403 * happens using its boundaries. 6404 */ 6405 if (!tnum_is_const(reg->var_off)) 6406 /* For unprivileged variable accesses, disable raw 6407 * mode so that the program is required to 6408 * initialize all the memory that the helper could 6409 * just partially fill up. 6410 */ 6411 meta = NULL; 6412 6413 if (reg->smin_value < 0) { 6414 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 6415 regno); 6416 return -EACCES; 6417 } 6418 6419 if (reg->umin_value == 0) { 6420 err = check_helper_mem_access(env, regno - 1, 0, 6421 zero_size_allowed, 6422 meta); 6423 if (err) 6424 return err; 6425 } 6426 6427 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 6428 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 6429 regno); 6430 return -EACCES; 6431 } 6432 err = check_helper_mem_access(env, regno - 1, 6433 reg->umax_value, 6434 zero_size_allowed, meta); 6435 if (!err) 6436 err = mark_chain_precision(env, regno); 6437 return err; 6438 } 6439 6440 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6441 u32 regno, u32 mem_size) 6442 { 6443 bool may_be_null = type_may_be_null(reg->type); 6444 struct bpf_reg_state saved_reg; 6445 struct bpf_call_arg_meta meta; 6446 int err; 6447 6448 if (register_is_null(reg)) 6449 return 0; 6450 6451 memset(&meta, 0, sizeof(meta)); 6452 /* Assuming that the register contains a value check if the memory 6453 * access is safe. Temporarily save and restore the register's state as 6454 * the conversion shouldn't be visible to a caller. 6455 */ 6456 if (may_be_null) { 6457 saved_reg = *reg; 6458 mark_ptr_not_null_reg(reg); 6459 } 6460 6461 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 6462 /* Check access for BPF_WRITE */ 6463 meta.raw_mode = true; 6464 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 6465 6466 if (may_be_null) 6467 *reg = saved_reg; 6468 6469 return err; 6470 } 6471 6472 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 6473 u32 regno) 6474 { 6475 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 6476 bool may_be_null = type_may_be_null(mem_reg->type); 6477 struct bpf_reg_state saved_reg; 6478 struct bpf_call_arg_meta meta; 6479 int err; 6480 6481 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 6482 6483 memset(&meta, 0, sizeof(meta)); 6484 6485 if (may_be_null) { 6486 saved_reg = *mem_reg; 6487 mark_ptr_not_null_reg(mem_reg); 6488 } 6489 6490 err = check_mem_size_reg(env, reg, regno, true, &meta); 6491 /* Check access for BPF_WRITE */ 6492 meta.raw_mode = true; 6493 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 6494 6495 if (may_be_null) 6496 *mem_reg = saved_reg; 6497 return err; 6498 } 6499 6500 /* Implementation details: 6501 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 6502 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 6503 * Two bpf_map_lookups (even with the same key) will have different reg->id. 6504 * Two separate bpf_obj_new will also have different reg->id. 6505 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 6506 * clears reg->id after value_or_null->value transition, since the verifier only 6507 * cares about the range of access to valid map value pointer and doesn't care 6508 * about actual address of the map element. 6509 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 6510 * reg->id > 0 after value_or_null->value transition. By doing so 6511 * two bpf_map_lookups will be considered two different pointers that 6512 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 6513 * returned from bpf_obj_new. 6514 * The verifier allows taking only one bpf_spin_lock at a time to avoid 6515 * dead-locks. 6516 * Since only one bpf_spin_lock is allowed the checks are simpler than 6517 * reg_is_refcounted() logic. The verifier needs to remember only 6518 * one spin_lock instead of array of acquired_refs. 6519 * cur_state->active_lock remembers which map value element or allocated 6520 * object got locked and clears it after bpf_spin_unlock. 6521 */ 6522 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 6523 bool is_lock) 6524 { 6525 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6526 struct bpf_verifier_state *cur = env->cur_state; 6527 bool is_const = tnum_is_const(reg->var_off); 6528 u64 val = reg->var_off.value; 6529 struct bpf_map *map = NULL; 6530 struct btf *btf = NULL; 6531 struct btf_record *rec; 6532 6533 if (!is_const) { 6534 verbose(env, 6535 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 6536 regno); 6537 return -EINVAL; 6538 } 6539 if (reg->type == PTR_TO_MAP_VALUE) { 6540 map = reg->map_ptr; 6541 if (!map->btf) { 6542 verbose(env, 6543 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 6544 map->name); 6545 return -EINVAL; 6546 } 6547 } else { 6548 btf = reg->btf; 6549 } 6550 6551 rec = reg_btf_record(reg); 6552 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 6553 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 6554 map ? map->name : "kptr"); 6555 return -EINVAL; 6556 } 6557 if (rec->spin_lock_off != val + reg->off) { 6558 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 6559 val + reg->off, rec->spin_lock_off); 6560 return -EINVAL; 6561 } 6562 if (is_lock) { 6563 if (cur->active_lock.ptr) { 6564 verbose(env, 6565 "Locking two bpf_spin_locks are not allowed\n"); 6566 return -EINVAL; 6567 } 6568 if (map) 6569 cur->active_lock.ptr = map; 6570 else 6571 cur->active_lock.ptr = btf; 6572 cur->active_lock.id = reg->id; 6573 } else { 6574 void *ptr; 6575 6576 if (map) 6577 ptr = map; 6578 else 6579 ptr = btf; 6580 6581 if (!cur->active_lock.ptr) { 6582 verbose(env, "bpf_spin_unlock without taking a lock\n"); 6583 return -EINVAL; 6584 } 6585 if (cur->active_lock.ptr != ptr || 6586 cur->active_lock.id != reg->id) { 6587 verbose(env, "bpf_spin_unlock of different lock\n"); 6588 return -EINVAL; 6589 } 6590 6591 invalidate_non_owning_refs(env); 6592 6593 cur->active_lock.ptr = NULL; 6594 cur->active_lock.id = 0; 6595 } 6596 return 0; 6597 } 6598 6599 static int process_timer_func(struct bpf_verifier_env *env, int regno, 6600 struct bpf_call_arg_meta *meta) 6601 { 6602 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6603 bool is_const = tnum_is_const(reg->var_off); 6604 struct bpf_map *map = reg->map_ptr; 6605 u64 val = reg->var_off.value; 6606 6607 if (!is_const) { 6608 verbose(env, 6609 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 6610 regno); 6611 return -EINVAL; 6612 } 6613 if (!map->btf) { 6614 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 6615 map->name); 6616 return -EINVAL; 6617 } 6618 if (!btf_record_has_field(map->record, BPF_TIMER)) { 6619 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 6620 return -EINVAL; 6621 } 6622 if (map->record->timer_off != val + reg->off) { 6623 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 6624 val + reg->off, map->record->timer_off); 6625 return -EINVAL; 6626 } 6627 if (meta->map_ptr) { 6628 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 6629 return -EFAULT; 6630 } 6631 meta->map_uid = reg->map_uid; 6632 meta->map_ptr = map; 6633 return 0; 6634 } 6635 6636 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 6637 struct bpf_call_arg_meta *meta) 6638 { 6639 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6640 struct bpf_map *map_ptr = reg->map_ptr; 6641 struct btf_field *kptr_field; 6642 u32 kptr_off; 6643 6644 if (!tnum_is_const(reg->var_off)) { 6645 verbose(env, 6646 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 6647 regno); 6648 return -EINVAL; 6649 } 6650 if (!map_ptr->btf) { 6651 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 6652 map_ptr->name); 6653 return -EINVAL; 6654 } 6655 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 6656 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 6657 return -EINVAL; 6658 } 6659 6660 meta->map_ptr = map_ptr; 6661 kptr_off = reg->off + reg->var_off.value; 6662 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 6663 if (!kptr_field) { 6664 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 6665 return -EACCES; 6666 } 6667 if (kptr_field->type != BPF_KPTR_REF) { 6668 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 6669 return -EACCES; 6670 } 6671 meta->kptr_field = kptr_field; 6672 return 0; 6673 } 6674 6675 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 6676 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 6677 * 6678 * In both cases we deal with the first 8 bytes, but need to mark the next 8 6679 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 6680 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 6681 * 6682 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 6683 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 6684 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 6685 * mutate the view of the dynptr and also possibly destroy it. In the latter 6686 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 6687 * memory that dynptr points to. 6688 * 6689 * The verifier will keep track both levels of mutation (bpf_dynptr's in 6690 * reg->type and the memory's in reg->dynptr.type), but there is no support for 6691 * readonly dynptr view yet, hence only the first case is tracked and checked. 6692 * 6693 * This is consistent with how C applies the const modifier to a struct object, 6694 * where the pointer itself inside bpf_dynptr becomes const but not what it 6695 * points to. 6696 * 6697 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 6698 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 6699 */ 6700 static int process_dynptr_func(struct bpf_verifier_env *env, int regno, int insn_idx, 6701 enum bpf_arg_type arg_type) 6702 { 6703 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6704 int err; 6705 6706 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 6707 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 6708 */ 6709 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 6710 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 6711 return -EFAULT; 6712 } 6713 6714 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 6715 * constructing a mutable bpf_dynptr object. 6716 * 6717 * Currently, this is only possible with PTR_TO_STACK 6718 * pointing to a region of at least 16 bytes which doesn't 6719 * contain an existing bpf_dynptr. 6720 * 6721 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 6722 * mutated or destroyed. However, the memory it points to 6723 * may be mutated. 6724 * 6725 * None - Points to a initialized dynptr that can be mutated and 6726 * destroyed, including mutation of the memory it points 6727 * to. 6728 */ 6729 if (arg_type & MEM_UNINIT) { 6730 int i; 6731 6732 if (!is_dynptr_reg_valid_uninit(env, reg)) { 6733 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 6734 return -EINVAL; 6735 } 6736 6737 /* we write BPF_DW bits (8 bytes) at a time */ 6738 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 6739 err = check_mem_access(env, insn_idx, regno, 6740 i, BPF_DW, BPF_WRITE, -1, false); 6741 if (err) 6742 return err; 6743 } 6744 6745 err = mark_stack_slots_dynptr(env, reg, arg_type, insn_idx); 6746 } else /* MEM_RDONLY and None case from above */ { 6747 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 6748 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 6749 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 6750 return -EINVAL; 6751 } 6752 6753 if (!is_dynptr_reg_valid_init(env, reg)) { 6754 verbose(env, 6755 "Expected an initialized dynptr as arg #%d\n", 6756 regno); 6757 return -EINVAL; 6758 } 6759 6760 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 6761 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 6762 verbose(env, 6763 "Expected a dynptr of type %s as arg #%d\n", 6764 dynptr_type_str(arg_to_dynptr_type(arg_type)), regno); 6765 return -EINVAL; 6766 } 6767 6768 err = mark_dynptr_read(env, reg); 6769 } 6770 return err; 6771 } 6772 6773 static u32 iter_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg, int spi) 6774 { 6775 struct bpf_func_state *state = func(env, reg); 6776 6777 return state->stack[spi].spilled_ptr.ref_obj_id; 6778 } 6779 6780 static bool is_iter_kfunc(struct bpf_kfunc_call_arg_meta *meta) 6781 { 6782 return meta->kfunc_flags & (KF_ITER_NEW | KF_ITER_NEXT | KF_ITER_DESTROY); 6783 } 6784 6785 static bool is_iter_new_kfunc(struct bpf_kfunc_call_arg_meta *meta) 6786 { 6787 return meta->kfunc_flags & KF_ITER_NEW; 6788 } 6789 6790 static bool is_iter_next_kfunc(struct bpf_kfunc_call_arg_meta *meta) 6791 { 6792 return meta->kfunc_flags & KF_ITER_NEXT; 6793 } 6794 6795 static bool is_iter_destroy_kfunc(struct bpf_kfunc_call_arg_meta *meta) 6796 { 6797 return meta->kfunc_flags & KF_ITER_DESTROY; 6798 } 6799 6800 static bool is_kfunc_arg_iter(struct bpf_kfunc_call_arg_meta *meta, int arg) 6801 { 6802 /* btf_check_iter_kfuncs() guarantees that first argument of any iter 6803 * kfunc is iter state pointer 6804 */ 6805 return arg == 0 && is_iter_kfunc(meta); 6806 } 6807 6808 static int process_iter_arg(struct bpf_verifier_env *env, int regno, int insn_idx, 6809 struct bpf_kfunc_call_arg_meta *meta) 6810 { 6811 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6812 const struct btf_type *t; 6813 const struct btf_param *arg; 6814 int spi, err, i, nr_slots; 6815 u32 btf_id; 6816 6817 /* btf_check_iter_kfuncs() ensures we don't need to validate anything here */ 6818 arg = &btf_params(meta->func_proto)[0]; 6819 t = btf_type_skip_modifiers(meta->btf, arg->type, NULL); /* PTR */ 6820 t = btf_type_skip_modifiers(meta->btf, t->type, &btf_id); /* STRUCT */ 6821 nr_slots = t->size / BPF_REG_SIZE; 6822 6823 if (is_iter_new_kfunc(meta)) { 6824 /* bpf_iter_<type>_new() expects pointer to uninit iter state */ 6825 if (!is_iter_reg_valid_uninit(env, reg, nr_slots)) { 6826 verbose(env, "expected uninitialized iter_%s as arg #%d\n", 6827 iter_type_str(meta->btf, btf_id), regno); 6828 return -EINVAL; 6829 } 6830 6831 for (i = 0; i < nr_slots * 8; i += BPF_REG_SIZE) { 6832 err = check_mem_access(env, insn_idx, regno, 6833 i, BPF_DW, BPF_WRITE, -1, false); 6834 if (err) 6835 return err; 6836 } 6837 6838 err = mark_stack_slots_iter(env, reg, insn_idx, meta->btf, btf_id, nr_slots); 6839 if (err) 6840 return err; 6841 } else { 6842 /* iter_next() or iter_destroy() expect initialized iter state*/ 6843 if (!is_iter_reg_valid_init(env, reg, meta->btf, btf_id, nr_slots)) { 6844 verbose(env, "expected an initialized iter_%s as arg #%d\n", 6845 iter_type_str(meta->btf, btf_id), regno); 6846 return -EINVAL; 6847 } 6848 6849 spi = iter_get_spi(env, reg, nr_slots); 6850 if (spi < 0) 6851 return spi; 6852 6853 err = mark_iter_read(env, reg, spi, nr_slots); 6854 if (err) 6855 return err; 6856 6857 /* remember meta->iter info for process_iter_next_call() */ 6858 meta->iter.spi = spi; 6859 meta->iter.frameno = reg->frameno; 6860 meta->ref_obj_id = iter_ref_obj_id(env, reg, spi); 6861 6862 if (is_iter_destroy_kfunc(meta)) { 6863 err = unmark_stack_slots_iter(env, reg, nr_slots); 6864 if (err) 6865 return err; 6866 } 6867 } 6868 6869 return 0; 6870 } 6871 6872 /* process_iter_next_call() is called when verifier gets to iterator's next 6873 * "method" (e.g., bpf_iter_num_next() for numbers iterator) call. We'll refer 6874 * to it as just "iter_next()" in comments below. 6875 * 6876 * BPF verifier relies on a crucial contract for any iter_next() 6877 * implementation: it should *eventually* return NULL, and once that happens 6878 * it should keep returning NULL. That is, once iterator exhausts elements to 6879 * iterate, it should never reset or spuriously return new elements. 6880 * 6881 * With the assumption of such contract, process_iter_next_call() simulates 6882 * a fork in the verifier state to validate loop logic correctness and safety 6883 * without having to simulate infinite amount of iterations. 6884 * 6885 * In current state, we first assume that iter_next() returned NULL and 6886 * iterator state is set to DRAINED (BPF_ITER_STATE_DRAINED). In such 6887 * conditions we should not form an infinite loop and should eventually reach 6888 * exit. 6889 * 6890 * Besides that, we also fork current state and enqueue it for later 6891 * verification. In a forked state we keep iterator state as ACTIVE 6892 * (BPF_ITER_STATE_ACTIVE) and assume non-NULL return from iter_next(). We 6893 * also bump iteration depth to prevent erroneous infinite loop detection 6894 * later on (see iter_active_depths_differ() comment for details). In this 6895 * state we assume that we'll eventually loop back to another iter_next() 6896 * calls (it could be in exactly same location or in some other instruction, 6897 * it doesn't matter, we don't make any unnecessary assumptions about this, 6898 * everything revolves around iterator state in a stack slot, not which 6899 * instruction is calling iter_next()). When that happens, we either will come 6900 * to iter_next() with equivalent state and can conclude that next iteration 6901 * will proceed in exactly the same way as we just verified, so it's safe to 6902 * assume that loop converges. If not, we'll go on another iteration 6903 * simulation with a different input state, until all possible starting states 6904 * are validated or we reach maximum number of instructions limit. 6905 * 6906 * This way, we will either exhaustively discover all possible input states 6907 * that iterator loop can start with and eventually will converge, or we'll 6908 * effectively regress into bounded loop simulation logic and either reach 6909 * maximum number of instructions if loop is not provably convergent, or there 6910 * is some statically known limit on number of iterations (e.g., if there is 6911 * an explicit `if n > 100 then break;` statement somewhere in the loop). 6912 * 6913 * One very subtle but very important aspect is that we *always* simulate NULL 6914 * condition first (as the current state) before we simulate non-NULL case. 6915 * This has to do with intricacies of scalar precision tracking. By simulating 6916 * "exit condition" of iter_next() returning NULL first, we make sure all the 6917 * relevant precision marks *that will be set **after** we exit iterator loop* 6918 * are propagated backwards to common parent state of NULL and non-NULL 6919 * branches. Thanks to that, state equivalence checks done later in forked 6920 * state, when reaching iter_next() for ACTIVE iterator, can assume that 6921 * precision marks are finalized and won't change. Because simulating another 6922 * ACTIVE iterator iteration won't change them (because given same input 6923 * states we'll end up with exactly same output states which we are currently 6924 * comparing; and verification after the loop already propagated back what 6925 * needs to be **additionally** tracked as precise). It's subtle, grok 6926 * precision tracking for more intuitive understanding. 6927 */ 6928 static int process_iter_next_call(struct bpf_verifier_env *env, int insn_idx, 6929 struct bpf_kfunc_call_arg_meta *meta) 6930 { 6931 struct bpf_verifier_state *cur_st = env->cur_state, *queued_st; 6932 struct bpf_func_state *cur_fr = cur_st->frame[cur_st->curframe], *queued_fr; 6933 struct bpf_reg_state *cur_iter, *queued_iter; 6934 int iter_frameno = meta->iter.frameno; 6935 int iter_spi = meta->iter.spi; 6936 6937 BTF_TYPE_EMIT(struct bpf_iter); 6938 6939 cur_iter = &env->cur_state->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 6940 6941 if (cur_iter->iter.state != BPF_ITER_STATE_ACTIVE && 6942 cur_iter->iter.state != BPF_ITER_STATE_DRAINED) { 6943 verbose(env, "verifier internal error: unexpected iterator state %d (%s)\n", 6944 cur_iter->iter.state, iter_state_str(cur_iter->iter.state)); 6945 return -EFAULT; 6946 } 6947 6948 if (cur_iter->iter.state == BPF_ITER_STATE_ACTIVE) { 6949 /* branch out active iter state */ 6950 queued_st = push_stack(env, insn_idx + 1, insn_idx, false); 6951 if (!queued_st) 6952 return -ENOMEM; 6953 6954 queued_iter = &queued_st->frame[iter_frameno]->stack[iter_spi].spilled_ptr; 6955 queued_iter->iter.state = BPF_ITER_STATE_ACTIVE; 6956 queued_iter->iter.depth++; 6957 6958 queued_fr = queued_st->frame[queued_st->curframe]; 6959 mark_ptr_not_null_reg(&queued_fr->regs[BPF_REG_0]); 6960 } 6961 6962 /* switch to DRAINED state, but keep the depth unchanged */ 6963 /* mark current iter state as drained and assume returned NULL */ 6964 cur_iter->iter.state = BPF_ITER_STATE_DRAINED; 6965 __mark_reg_const_zero(&cur_fr->regs[BPF_REG_0]); 6966 6967 return 0; 6968 } 6969 6970 static bool arg_type_is_mem_size(enum bpf_arg_type type) 6971 { 6972 return type == ARG_CONST_SIZE || 6973 type == ARG_CONST_SIZE_OR_ZERO; 6974 } 6975 6976 static bool arg_type_is_release(enum bpf_arg_type type) 6977 { 6978 return type & OBJ_RELEASE; 6979 } 6980 6981 static bool arg_type_is_dynptr(enum bpf_arg_type type) 6982 { 6983 return base_type(type) == ARG_PTR_TO_DYNPTR; 6984 } 6985 6986 static int int_ptr_type_to_size(enum bpf_arg_type type) 6987 { 6988 if (type == ARG_PTR_TO_INT) 6989 return sizeof(u32); 6990 else if (type == ARG_PTR_TO_LONG) 6991 return sizeof(u64); 6992 6993 return -EINVAL; 6994 } 6995 6996 static int resolve_map_arg_type(struct bpf_verifier_env *env, 6997 const struct bpf_call_arg_meta *meta, 6998 enum bpf_arg_type *arg_type) 6999 { 7000 if (!meta->map_ptr) { 7001 /* kernel subsystem misconfigured verifier */ 7002 verbose(env, "invalid map_ptr to access map->type\n"); 7003 return -EACCES; 7004 } 7005 7006 switch (meta->map_ptr->map_type) { 7007 case BPF_MAP_TYPE_SOCKMAP: 7008 case BPF_MAP_TYPE_SOCKHASH: 7009 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 7010 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 7011 } else { 7012 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 7013 return -EINVAL; 7014 } 7015 break; 7016 case BPF_MAP_TYPE_BLOOM_FILTER: 7017 if (meta->func_id == BPF_FUNC_map_peek_elem) 7018 *arg_type = ARG_PTR_TO_MAP_VALUE; 7019 break; 7020 default: 7021 break; 7022 } 7023 return 0; 7024 } 7025 7026 struct bpf_reg_types { 7027 const enum bpf_reg_type types[10]; 7028 u32 *btf_id; 7029 }; 7030 7031 static const struct bpf_reg_types sock_types = { 7032 .types = { 7033 PTR_TO_SOCK_COMMON, 7034 PTR_TO_SOCKET, 7035 PTR_TO_TCP_SOCK, 7036 PTR_TO_XDP_SOCK, 7037 }, 7038 }; 7039 7040 #ifdef CONFIG_NET 7041 static const struct bpf_reg_types btf_id_sock_common_types = { 7042 .types = { 7043 PTR_TO_SOCK_COMMON, 7044 PTR_TO_SOCKET, 7045 PTR_TO_TCP_SOCK, 7046 PTR_TO_XDP_SOCK, 7047 PTR_TO_BTF_ID, 7048 PTR_TO_BTF_ID | PTR_TRUSTED, 7049 }, 7050 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 7051 }; 7052 #endif 7053 7054 static const struct bpf_reg_types mem_types = { 7055 .types = { 7056 PTR_TO_STACK, 7057 PTR_TO_PACKET, 7058 PTR_TO_PACKET_META, 7059 PTR_TO_MAP_KEY, 7060 PTR_TO_MAP_VALUE, 7061 PTR_TO_MEM, 7062 PTR_TO_MEM | MEM_RINGBUF, 7063 PTR_TO_BUF, 7064 PTR_TO_BTF_ID | PTR_TRUSTED, 7065 }, 7066 }; 7067 7068 static const struct bpf_reg_types int_ptr_types = { 7069 .types = { 7070 PTR_TO_STACK, 7071 PTR_TO_PACKET, 7072 PTR_TO_PACKET_META, 7073 PTR_TO_MAP_KEY, 7074 PTR_TO_MAP_VALUE, 7075 }, 7076 }; 7077 7078 static const struct bpf_reg_types spin_lock_types = { 7079 .types = { 7080 PTR_TO_MAP_VALUE, 7081 PTR_TO_BTF_ID | MEM_ALLOC, 7082 } 7083 }; 7084 7085 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 7086 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 7087 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 7088 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 7089 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 7090 static const struct bpf_reg_types btf_ptr_types = { 7091 .types = { 7092 PTR_TO_BTF_ID, 7093 PTR_TO_BTF_ID | PTR_TRUSTED, 7094 PTR_TO_BTF_ID | MEM_RCU, 7095 }, 7096 }; 7097 static const struct bpf_reg_types percpu_btf_ptr_types = { 7098 .types = { 7099 PTR_TO_BTF_ID | MEM_PERCPU, 7100 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 7101 } 7102 }; 7103 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 7104 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 7105 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7106 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 7107 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 7108 static const struct bpf_reg_types dynptr_types = { 7109 .types = { 7110 PTR_TO_STACK, 7111 CONST_PTR_TO_DYNPTR, 7112 } 7113 }; 7114 7115 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 7116 [ARG_PTR_TO_MAP_KEY] = &mem_types, 7117 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 7118 [ARG_CONST_SIZE] = &scalar_types, 7119 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 7120 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 7121 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 7122 [ARG_PTR_TO_CTX] = &context_types, 7123 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 7124 #ifdef CONFIG_NET 7125 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 7126 #endif 7127 [ARG_PTR_TO_SOCKET] = &fullsock_types, 7128 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 7129 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 7130 [ARG_PTR_TO_MEM] = &mem_types, 7131 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 7132 [ARG_PTR_TO_INT] = &int_ptr_types, 7133 [ARG_PTR_TO_LONG] = &int_ptr_types, 7134 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 7135 [ARG_PTR_TO_FUNC] = &func_ptr_types, 7136 [ARG_PTR_TO_STACK] = &stack_ptr_types, 7137 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 7138 [ARG_PTR_TO_TIMER] = &timer_types, 7139 [ARG_PTR_TO_KPTR] = &kptr_types, 7140 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 7141 }; 7142 7143 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 7144 enum bpf_arg_type arg_type, 7145 const u32 *arg_btf_id, 7146 struct bpf_call_arg_meta *meta) 7147 { 7148 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7149 enum bpf_reg_type expected, type = reg->type; 7150 const struct bpf_reg_types *compatible; 7151 int i, j; 7152 7153 compatible = compatible_reg_types[base_type(arg_type)]; 7154 if (!compatible) { 7155 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 7156 return -EFAULT; 7157 } 7158 7159 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 7160 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 7161 * 7162 * Same for MAYBE_NULL: 7163 * 7164 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 7165 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 7166 * 7167 * Therefore we fold these flags depending on the arg_type before comparison. 7168 */ 7169 if (arg_type & MEM_RDONLY) 7170 type &= ~MEM_RDONLY; 7171 if (arg_type & PTR_MAYBE_NULL) 7172 type &= ~PTR_MAYBE_NULL; 7173 7174 if (meta->func_id == BPF_FUNC_kptr_xchg && type & MEM_ALLOC) 7175 type &= ~MEM_ALLOC; 7176 7177 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 7178 expected = compatible->types[i]; 7179 if (expected == NOT_INIT) 7180 break; 7181 7182 if (type == expected) 7183 goto found; 7184 } 7185 7186 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 7187 for (j = 0; j + 1 < i; j++) 7188 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 7189 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 7190 return -EACCES; 7191 7192 found: 7193 if (base_type(reg->type) != PTR_TO_BTF_ID) 7194 return 0; 7195 7196 if (compatible == &mem_types) { 7197 if (!(arg_type & MEM_RDONLY)) { 7198 verbose(env, 7199 "%s() may write into memory pointed by R%d type=%s\n", 7200 func_id_name(meta->func_id), 7201 regno, reg_type_str(env, reg->type)); 7202 return -EACCES; 7203 } 7204 return 0; 7205 } 7206 7207 switch ((int)reg->type) { 7208 case PTR_TO_BTF_ID: 7209 case PTR_TO_BTF_ID | PTR_TRUSTED: 7210 case PTR_TO_BTF_ID | MEM_RCU: 7211 case PTR_TO_BTF_ID | PTR_MAYBE_NULL: 7212 case PTR_TO_BTF_ID | PTR_MAYBE_NULL | MEM_RCU: 7213 { 7214 /* For bpf_sk_release, it needs to match against first member 7215 * 'struct sock_common', hence make an exception for it. This 7216 * allows bpf_sk_release to work for multiple socket types. 7217 */ 7218 bool strict_type_match = arg_type_is_release(arg_type) && 7219 meta->func_id != BPF_FUNC_sk_release; 7220 7221 if (type_may_be_null(reg->type) && 7222 (!type_may_be_null(arg_type) || arg_type_is_release(arg_type))) { 7223 verbose(env, "Possibly NULL pointer passed to helper arg%d\n", regno); 7224 return -EACCES; 7225 } 7226 7227 if (!arg_btf_id) { 7228 if (!compatible->btf_id) { 7229 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 7230 return -EFAULT; 7231 } 7232 arg_btf_id = compatible->btf_id; 7233 } 7234 7235 if (meta->func_id == BPF_FUNC_kptr_xchg) { 7236 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 7237 return -EACCES; 7238 } else { 7239 if (arg_btf_id == BPF_PTR_POISON) { 7240 verbose(env, "verifier internal error:"); 7241 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 7242 regno); 7243 return -EACCES; 7244 } 7245 7246 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 7247 btf_vmlinux, *arg_btf_id, 7248 strict_type_match)) { 7249 verbose(env, "R%d is of type %s but %s is expected\n", 7250 regno, btf_type_name(reg->btf, reg->btf_id), 7251 btf_type_name(btf_vmlinux, *arg_btf_id)); 7252 return -EACCES; 7253 } 7254 } 7255 break; 7256 } 7257 case PTR_TO_BTF_ID | MEM_ALLOC: 7258 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock && 7259 meta->func_id != BPF_FUNC_kptr_xchg) { 7260 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 7261 return -EFAULT; 7262 } 7263 /* Handled by helper specific checks */ 7264 break; 7265 case PTR_TO_BTF_ID | MEM_PERCPU: 7266 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 7267 /* Handled by helper specific checks */ 7268 break; 7269 default: 7270 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 7271 return -EFAULT; 7272 } 7273 return 0; 7274 } 7275 7276 static struct btf_field * 7277 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 7278 { 7279 struct btf_field *field; 7280 struct btf_record *rec; 7281 7282 rec = reg_btf_record(reg); 7283 if (!rec) 7284 return NULL; 7285 7286 field = btf_record_find(rec, off, fields); 7287 if (!field) 7288 return NULL; 7289 7290 return field; 7291 } 7292 7293 int check_func_arg_reg_off(struct bpf_verifier_env *env, 7294 const struct bpf_reg_state *reg, int regno, 7295 enum bpf_arg_type arg_type) 7296 { 7297 u32 type = reg->type; 7298 7299 /* When referenced register is passed to release function, its fixed 7300 * offset must be 0. 7301 * 7302 * We will check arg_type_is_release reg has ref_obj_id when storing 7303 * meta->release_regno. 7304 */ 7305 if (arg_type_is_release(arg_type)) { 7306 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 7307 * may not directly point to the object being released, but to 7308 * dynptr pointing to such object, which might be at some offset 7309 * on the stack. In that case, we simply to fallback to the 7310 * default handling. 7311 */ 7312 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 7313 return 0; 7314 7315 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) { 7316 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT)) 7317 return __check_ptr_off_reg(env, reg, regno, true); 7318 7319 verbose(env, "R%d must have zero offset when passed to release func\n", 7320 regno); 7321 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno, 7322 btf_type_name(reg->btf, reg->btf_id), reg->off); 7323 return -EINVAL; 7324 } 7325 7326 /* Doing check_ptr_off_reg check for the offset will catch this 7327 * because fixed_off_ok is false, but checking here allows us 7328 * to give the user a better error message. 7329 */ 7330 if (reg->off) { 7331 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 7332 regno); 7333 return -EINVAL; 7334 } 7335 return __check_ptr_off_reg(env, reg, regno, false); 7336 } 7337 7338 switch (type) { 7339 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 7340 case PTR_TO_STACK: 7341 case PTR_TO_PACKET: 7342 case PTR_TO_PACKET_META: 7343 case PTR_TO_MAP_KEY: 7344 case PTR_TO_MAP_VALUE: 7345 case PTR_TO_MEM: 7346 case PTR_TO_MEM | MEM_RDONLY: 7347 case PTR_TO_MEM | MEM_RINGBUF: 7348 case PTR_TO_BUF: 7349 case PTR_TO_BUF | MEM_RDONLY: 7350 case SCALAR_VALUE: 7351 return 0; 7352 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 7353 * fixed offset. 7354 */ 7355 case PTR_TO_BTF_ID: 7356 case PTR_TO_BTF_ID | MEM_ALLOC: 7357 case PTR_TO_BTF_ID | PTR_TRUSTED: 7358 case PTR_TO_BTF_ID | MEM_RCU: 7359 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 7360 /* When referenced PTR_TO_BTF_ID is passed to release function, 7361 * its fixed offset must be 0. In the other cases, fixed offset 7362 * can be non-zero. This was already checked above. So pass 7363 * fixed_off_ok as true to allow fixed offset for all other 7364 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 7365 * still need to do checks instead of returning. 7366 */ 7367 return __check_ptr_off_reg(env, reg, regno, true); 7368 default: 7369 return __check_ptr_off_reg(env, reg, regno, false); 7370 } 7371 } 7372 7373 static struct bpf_reg_state *get_dynptr_arg_reg(struct bpf_verifier_env *env, 7374 const struct bpf_func_proto *fn, 7375 struct bpf_reg_state *regs) 7376 { 7377 struct bpf_reg_state *state = NULL; 7378 int i; 7379 7380 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) 7381 if (arg_type_is_dynptr(fn->arg_type[i])) { 7382 if (state) { 7383 verbose(env, "verifier internal error: multiple dynptr args\n"); 7384 return NULL; 7385 } 7386 state = ®s[BPF_REG_1 + i]; 7387 } 7388 7389 if (!state) 7390 verbose(env, "verifier internal error: no dynptr arg found\n"); 7391 7392 return state; 7393 } 7394 7395 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 7396 { 7397 struct bpf_func_state *state = func(env, reg); 7398 int spi; 7399 7400 if (reg->type == CONST_PTR_TO_DYNPTR) 7401 return reg->id; 7402 spi = dynptr_get_spi(env, reg); 7403 if (spi < 0) 7404 return spi; 7405 return state->stack[spi].spilled_ptr.id; 7406 } 7407 7408 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 7409 { 7410 struct bpf_func_state *state = func(env, reg); 7411 int spi; 7412 7413 if (reg->type == CONST_PTR_TO_DYNPTR) 7414 return reg->ref_obj_id; 7415 spi = dynptr_get_spi(env, reg); 7416 if (spi < 0) 7417 return spi; 7418 return state->stack[spi].spilled_ptr.ref_obj_id; 7419 } 7420 7421 static enum bpf_dynptr_type dynptr_get_type(struct bpf_verifier_env *env, 7422 struct bpf_reg_state *reg) 7423 { 7424 struct bpf_func_state *state = func(env, reg); 7425 int spi; 7426 7427 if (reg->type == CONST_PTR_TO_DYNPTR) 7428 return reg->dynptr.type; 7429 7430 spi = __get_spi(reg->off); 7431 if (spi < 0) { 7432 verbose(env, "verifier internal error: invalid spi when querying dynptr type\n"); 7433 return BPF_DYNPTR_TYPE_INVALID; 7434 } 7435 7436 return state->stack[spi].spilled_ptr.dynptr.type; 7437 } 7438 7439 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 7440 struct bpf_call_arg_meta *meta, 7441 const struct bpf_func_proto *fn, 7442 int insn_idx) 7443 { 7444 u32 regno = BPF_REG_1 + arg; 7445 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 7446 enum bpf_arg_type arg_type = fn->arg_type[arg]; 7447 enum bpf_reg_type type = reg->type; 7448 u32 *arg_btf_id = NULL; 7449 int err = 0; 7450 7451 if (arg_type == ARG_DONTCARE) 7452 return 0; 7453 7454 err = check_reg_arg(env, regno, SRC_OP); 7455 if (err) 7456 return err; 7457 7458 if (arg_type == ARG_ANYTHING) { 7459 if (is_pointer_value(env, regno)) { 7460 verbose(env, "R%d leaks addr into helper function\n", 7461 regno); 7462 return -EACCES; 7463 } 7464 return 0; 7465 } 7466 7467 if (type_is_pkt_pointer(type) && 7468 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 7469 verbose(env, "helper access to the packet is not allowed\n"); 7470 return -EACCES; 7471 } 7472 7473 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 7474 err = resolve_map_arg_type(env, meta, &arg_type); 7475 if (err) 7476 return err; 7477 } 7478 7479 if (register_is_null(reg) && type_may_be_null(arg_type)) 7480 /* A NULL register has a SCALAR_VALUE type, so skip 7481 * type checking. 7482 */ 7483 goto skip_type_check; 7484 7485 /* arg_btf_id and arg_size are in a union. */ 7486 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 7487 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 7488 arg_btf_id = fn->arg_btf_id[arg]; 7489 7490 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 7491 if (err) 7492 return err; 7493 7494 err = check_func_arg_reg_off(env, reg, regno, arg_type); 7495 if (err) 7496 return err; 7497 7498 skip_type_check: 7499 if (arg_type_is_release(arg_type)) { 7500 if (arg_type_is_dynptr(arg_type)) { 7501 struct bpf_func_state *state = func(env, reg); 7502 int spi; 7503 7504 /* Only dynptr created on stack can be released, thus 7505 * the get_spi and stack state checks for spilled_ptr 7506 * should only be done before process_dynptr_func for 7507 * PTR_TO_STACK. 7508 */ 7509 if (reg->type == PTR_TO_STACK) { 7510 spi = dynptr_get_spi(env, reg); 7511 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 7512 verbose(env, "arg %d is an unacquired reference\n", regno); 7513 return -EINVAL; 7514 } 7515 } else { 7516 verbose(env, "cannot release unowned const bpf_dynptr\n"); 7517 return -EINVAL; 7518 } 7519 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 7520 verbose(env, "R%d must be referenced when passed to release function\n", 7521 regno); 7522 return -EINVAL; 7523 } 7524 if (meta->release_regno) { 7525 verbose(env, "verifier internal error: more than one release argument\n"); 7526 return -EFAULT; 7527 } 7528 meta->release_regno = regno; 7529 } 7530 7531 if (reg->ref_obj_id) { 7532 if (meta->ref_obj_id) { 7533 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 7534 regno, reg->ref_obj_id, 7535 meta->ref_obj_id); 7536 return -EFAULT; 7537 } 7538 meta->ref_obj_id = reg->ref_obj_id; 7539 } 7540 7541 switch (base_type(arg_type)) { 7542 case ARG_CONST_MAP_PTR: 7543 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 7544 if (meta->map_ptr) { 7545 /* Use map_uid (which is unique id of inner map) to reject: 7546 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 7547 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 7548 * if (inner_map1 && inner_map2) { 7549 * timer = bpf_map_lookup_elem(inner_map1); 7550 * if (timer) 7551 * // mismatch would have been allowed 7552 * bpf_timer_init(timer, inner_map2); 7553 * } 7554 * 7555 * Comparing map_ptr is enough to distinguish normal and outer maps. 7556 */ 7557 if (meta->map_ptr != reg->map_ptr || 7558 meta->map_uid != reg->map_uid) { 7559 verbose(env, 7560 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 7561 meta->map_uid, reg->map_uid); 7562 return -EINVAL; 7563 } 7564 } 7565 meta->map_ptr = reg->map_ptr; 7566 meta->map_uid = reg->map_uid; 7567 break; 7568 case ARG_PTR_TO_MAP_KEY: 7569 /* bpf_map_xxx(..., map_ptr, ..., key) call: 7570 * check that [key, key + map->key_size) are within 7571 * stack limits and initialized 7572 */ 7573 if (!meta->map_ptr) { 7574 /* in function declaration map_ptr must come before 7575 * map_key, so that it's verified and known before 7576 * we have to check map_key here. Otherwise it means 7577 * that kernel subsystem misconfigured verifier 7578 */ 7579 verbose(env, "invalid map_ptr to access map->key\n"); 7580 return -EACCES; 7581 } 7582 err = check_helper_mem_access(env, regno, 7583 meta->map_ptr->key_size, false, 7584 NULL); 7585 break; 7586 case ARG_PTR_TO_MAP_VALUE: 7587 if (type_may_be_null(arg_type) && register_is_null(reg)) 7588 return 0; 7589 7590 /* bpf_map_xxx(..., map_ptr, ..., value) call: 7591 * check [value, value + map->value_size) validity 7592 */ 7593 if (!meta->map_ptr) { 7594 /* kernel subsystem misconfigured verifier */ 7595 verbose(env, "invalid map_ptr to access map->value\n"); 7596 return -EACCES; 7597 } 7598 meta->raw_mode = arg_type & MEM_UNINIT; 7599 err = check_helper_mem_access(env, regno, 7600 meta->map_ptr->value_size, false, 7601 meta); 7602 break; 7603 case ARG_PTR_TO_PERCPU_BTF_ID: 7604 if (!reg->btf_id) { 7605 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 7606 return -EACCES; 7607 } 7608 meta->ret_btf = reg->btf; 7609 meta->ret_btf_id = reg->btf_id; 7610 break; 7611 case ARG_PTR_TO_SPIN_LOCK: 7612 if (in_rbtree_lock_required_cb(env)) { 7613 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 7614 return -EACCES; 7615 } 7616 if (meta->func_id == BPF_FUNC_spin_lock) { 7617 err = process_spin_lock(env, regno, true); 7618 if (err) 7619 return err; 7620 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 7621 err = process_spin_lock(env, regno, false); 7622 if (err) 7623 return err; 7624 } else { 7625 verbose(env, "verifier internal error\n"); 7626 return -EFAULT; 7627 } 7628 break; 7629 case ARG_PTR_TO_TIMER: 7630 err = process_timer_func(env, regno, meta); 7631 if (err) 7632 return err; 7633 break; 7634 case ARG_PTR_TO_FUNC: 7635 meta->subprogno = reg->subprogno; 7636 break; 7637 case ARG_PTR_TO_MEM: 7638 /* The access to this pointer is only checked when we hit the 7639 * next is_mem_size argument below. 7640 */ 7641 meta->raw_mode = arg_type & MEM_UNINIT; 7642 if (arg_type & MEM_FIXED_SIZE) { 7643 err = check_helper_mem_access(env, regno, 7644 fn->arg_size[arg], false, 7645 meta); 7646 } 7647 break; 7648 case ARG_CONST_SIZE: 7649 err = check_mem_size_reg(env, reg, regno, false, meta); 7650 break; 7651 case ARG_CONST_SIZE_OR_ZERO: 7652 err = check_mem_size_reg(env, reg, regno, true, meta); 7653 break; 7654 case ARG_PTR_TO_DYNPTR: 7655 err = process_dynptr_func(env, regno, insn_idx, arg_type); 7656 if (err) 7657 return err; 7658 break; 7659 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 7660 if (!tnum_is_const(reg->var_off)) { 7661 verbose(env, "R%d is not a known constant'\n", 7662 regno); 7663 return -EACCES; 7664 } 7665 meta->mem_size = reg->var_off.value; 7666 err = mark_chain_precision(env, regno); 7667 if (err) 7668 return err; 7669 break; 7670 case ARG_PTR_TO_INT: 7671 case ARG_PTR_TO_LONG: 7672 { 7673 int size = int_ptr_type_to_size(arg_type); 7674 7675 err = check_helper_mem_access(env, regno, size, false, meta); 7676 if (err) 7677 return err; 7678 err = check_ptr_alignment(env, reg, 0, size, true); 7679 break; 7680 } 7681 case ARG_PTR_TO_CONST_STR: 7682 { 7683 struct bpf_map *map = reg->map_ptr; 7684 int map_off; 7685 u64 map_addr; 7686 char *str_ptr; 7687 7688 if (!bpf_map_is_rdonly(map)) { 7689 verbose(env, "R%d does not point to a readonly map'\n", regno); 7690 return -EACCES; 7691 } 7692 7693 if (!tnum_is_const(reg->var_off)) { 7694 verbose(env, "R%d is not a constant address'\n", regno); 7695 return -EACCES; 7696 } 7697 7698 if (!map->ops->map_direct_value_addr) { 7699 verbose(env, "no direct value access support for this map type\n"); 7700 return -EACCES; 7701 } 7702 7703 err = check_map_access(env, regno, reg->off, 7704 map->value_size - reg->off, false, 7705 ACCESS_HELPER); 7706 if (err) 7707 return err; 7708 7709 map_off = reg->off + reg->var_off.value; 7710 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 7711 if (err) { 7712 verbose(env, "direct value access on string failed\n"); 7713 return err; 7714 } 7715 7716 str_ptr = (char *)(long)(map_addr); 7717 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 7718 verbose(env, "string is not zero-terminated\n"); 7719 return -EINVAL; 7720 } 7721 break; 7722 } 7723 case ARG_PTR_TO_KPTR: 7724 err = process_kptr_func(env, regno, meta); 7725 if (err) 7726 return err; 7727 break; 7728 } 7729 7730 return err; 7731 } 7732 7733 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 7734 { 7735 enum bpf_attach_type eatype = env->prog->expected_attach_type; 7736 enum bpf_prog_type type = resolve_prog_type(env->prog); 7737 7738 if (func_id != BPF_FUNC_map_update_elem) 7739 return false; 7740 7741 /* It's not possible to get access to a locked struct sock in these 7742 * contexts, so updating is safe. 7743 */ 7744 switch (type) { 7745 case BPF_PROG_TYPE_TRACING: 7746 if (eatype == BPF_TRACE_ITER) 7747 return true; 7748 break; 7749 case BPF_PROG_TYPE_SOCKET_FILTER: 7750 case BPF_PROG_TYPE_SCHED_CLS: 7751 case BPF_PROG_TYPE_SCHED_ACT: 7752 case BPF_PROG_TYPE_XDP: 7753 case BPF_PROG_TYPE_SK_REUSEPORT: 7754 case BPF_PROG_TYPE_FLOW_DISSECTOR: 7755 case BPF_PROG_TYPE_SK_LOOKUP: 7756 return true; 7757 default: 7758 break; 7759 } 7760 7761 verbose(env, "cannot update sockmap in this context\n"); 7762 return false; 7763 } 7764 7765 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 7766 { 7767 return env->prog->jit_requested && 7768 bpf_jit_supports_subprog_tailcalls(); 7769 } 7770 7771 static int check_map_func_compatibility(struct bpf_verifier_env *env, 7772 struct bpf_map *map, int func_id) 7773 { 7774 if (!map) 7775 return 0; 7776 7777 /* We need a two way check, first is from map perspective ... */ 7778 switch (map->map_type) { 7779 case BPF_MAP_TYPE_PROG_ARRAY: 7780 if (func_id != BPF_FUNC_tail_call) 7781 goto error; 7782 break; 7783 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 7784 if (func_id != BPF_FUNC_perf_event_read && 7785 func_id != BPF_FUNC_perf_event_output && 7786 func_id != BPF_FUNC_skb_output && 7787 func_id != BPF_FUNC_perf_event_read_value && 7788 func_id != BPF_FUNC_xdp_output) 7789 goto error; 7790 break; 7791 case BPF_MAP_TYPE_RINGBUF: 7792 if (func_id != BPF_FUNC_ringbuf_output && 7793 func_id != BPF_FUNC_ringbuf_reserve && 7794 func_id != BPF_FUNC_ringbuf_query && 7795 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 7796 func_id != BPF_FUNC_ringbuf_submit_dynptr && 7797 func_id != BPF_FUNC_ringbuf_discard_dynptr) 7798 goto error; 7799 break; 7800 case BPF_MAP_TYPE_USER_RINGBUF: 7801 if (func_id != BPF_FUNC_user_ringbuf_drain) 7802 goto error; 7803 break; 7804 case BPF_MAP_TYPE_STACK_TRACE: 7805 if (func_id != BPF_FUNC_get_stackid) 7806 goto error; 7807 break; 7808 case BPF_MAP_TYPE_CGROUP_ARRAY: 7809 if (func_id != BPF_FUNC_skb_under_cgroup && 7810 func_id != BPF_FUNC_current_task_under_cgroup) 7811 goto error; 7812 break; 7813 case BPF_MAP_TYPE_CGROUP_STORAGE: 7814 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 7815 if (func_id != BPF_FUNC_get_local_storage) 7816 goto error; 7817 break; 7818 case BPF_MAP_TYPE_DEVMAP: 7819 case BPF_MAP_TYPE_DEVMAP_HASH: 7820 if (func_id != BPF_FUNC_redirect_map && 7821 func_id != BPF_FUNC_map_lookup_elem) 7822 goto error; 7823 break; 7824 /* Restrict bpf side of cpumap and xskmap, open when use-cases 7825 * appear. 7826 */ 7827 case BPF_MAP_TYPE_CPUMAP: 7828 if (func_id != BPF_FUNC_redirect_map) 7829 goto error; 7830 break; 7831 case BPF_MAP_TYPE_XSKMAP: 7832 if (func_id != BPF_FUNC_redirect_map && 7833 func_id != BPF_FUNC_map_lookup_elem) 7834 goto error; 7835 break; 7836 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 7837 case BPF_MAP_TYPE_HASH_OF_MAPS: 7838 if (func_id != BPF_FUNC_map_lookup_elem) 7839 goto error; 7840 break; 7841 case BPF_MAP_TYPE_SOCKMAP: 7842 if (func_id != BPF_FUNC_sk_redirect_map && 7843 func_id != BPF_FUNC_sock_map_update && 7844 func_id != BPF_FUNC_map_delete_elem && 7845 func_id != BPF_FUNC_msg_redirect_map && 7846 func_id != BPF_FUNC_sk_select_reuseport && 7847 func_id != BPF_FUNC_map_lookup_elem && 7848 !may_update_sockmap(env, func_id)) 7849 goto error; 7850 break; 7851 case BPF_MAP_TYPE_SOCKHASH: 7852 if (func_id != BPF_FUNC_sk_redirect_hash && 7853 func_id != BPF_FUNC_sock_hash_update && 7854 func_id != BPF_FUNC_map_delete_elem && 7855 func_id != BPF_FUNC_msg_redirect_hash && 7856 func_id != BPF_FUNC_sk_select_reuseport && 7857 func_id != BPF_FUNC_map_lookup_elem && 7858 !may_update_sockmap(env, func_id)) 7859 goto error; 7860 break; 7861 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 7862 if (func_id != BPF_FUNC_sk_select_reuseport) 7863 goto error; 7864 break; 7865 case BPF_MAP_TYPE_QUEUE: 7866 case BPF_MAP_TYPE_STACK: 7867 if (func_id != BPF_FUNC_map_peek_elem && 7868 func_id != BPF_FUNC_map_pop_elem && 7869 func_id != BPF_FUNC_map_push_elem) 7870 goto error; 7871 break; 7872 case BPF_MAP_TYPE_SK_STORAGE: 7873 if (func_id != BPF_FUNC_sk_storage_get && 7874 func_id != BPF_FUNC_sk_storage_delete && 7875 func_id != BPF_FUNC_kptr_xchg) 7876 goto error; 7877 break; 7878 case BPF_MAP_TYPE_INODE_STORAGE: 7879 if (func_id != BPF_FUNC_inode_storage_get && 7880 func_id != BPF_FUNC_inode_storage_delete && 7881 func_id != BPF_FUNC_kptr_xchg) 7882 goto error; 7883 break; 7884 case BPF_MAP_TYPE_TASK_STORAGE: 7885 if (func_id != BPF_FUNC_task_storage_get && 7886 func_id != BPF_FUNC_task_storage_delete && 7887 func_id != BPF_FUNC_kptr_xchg) 7888 goto error; 7889 break; 7890 case BPF_MAP_TYPE_CGRP_STORAGE: 7891 if (func_id != BPF_FUNC_cgrp_storage_get && 7892 func_id != BPF_FUNC_cgrp_storage_delete && 7893 func_id != BPF_FUNC_kptr_xchg) 7894 goto error; 7895 break; 7896 case BPF_MAP_TYPE_BLOOM_FILTER: 7897 if (func_id != BPF_FUNC_map_peek_elem && 7898 func_id != BPF_FUNC_map_push_elem) 7899 goto error; 7900 break; 7901 default: 7902 break; 7903 } 7904 7905 /* ... and second from the function itself. */ 7906 switch (func_id) { 7907 case BPF_FUNC_tail_call: 7908 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 7909 goto error; 7910 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 7911 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 7912 return -EINVAL; 7913 } 7914 break; 7915 case BPF_FUNC_perf_event_read: 7916 case BPF_FUNC_perf_event_output: 7917 case BPF_FUNC_perf_event_read_value: 7918 case BPF_FUNC_skb_output: 7919 case BPF_FUNC_xdp_output: 7920 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 7921 goto error; 7922 break; 7923 case BPF_FUNC_ringbuf_output: 7924 case BPF_FUNC_ringbuf_reserve: 7925 case BPF_FUNC_ringbuf_query: 7926 case BPF_FUNC_ringbuf_reserve_dynptr: 7927 case BPF_FUNC_ringbuf_submit_dynptr: 7928 case BPF_FUNC_ringbuf_discard_dynptr: 7929 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 7930 goto error; 7931 break; 7932 case BPF_FUNC_user_ringbuf_drain: 7933 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 7934 goto error; 7935 break; 7936 case BPF_FUNC_get_stackid: 7937 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 7938 goto error; 7939 break; 7940 case BPF_FUNC_current_task_under_cgroup: 7941 case BPF_FUNC_skb_under_cgroup: 7942 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 7943 goto error; 7944 break; 7945 case BPF_FUNC_redirect_map: 7946 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 7947 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 7948 map->map_type != BPF_MAP_TYPE_CPUMAP && 7949 map->map_type != BPF_MAP_TYPE_XSKMAP) 7950 goto error; 7951 break; 7952 case BPF_FUNC_sk_redirect_map: 7953 case BPF_FUNC_msg_redirect_map: 7954 case BPF_FUNC_sock_map_update: 7955 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 7956 goto error; 7957 break; 7958 case BPF_FUNC_sk_redirect_hash: 7959 case BPF_FUNC_msg_redirect_hash: 7960 case BPF_FUNC_sock_hash_update: 7961 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 7962 goto error; 7963 break; 7964 case BPF_FUNC_get_local_storage: 7965 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 7966 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 7967 goto error; 7968 break; 7969 case BPF_FUNC_sk_select_reuseport: 7970 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 7971 map->map_type != BPF_MAP_TYPE_SOCKMAP && 7972 map->map_type != BPF_MAP_TYPE_SOCKHASH) 7973 goto error; 7974 break; 7975 case BPF_FUNC_map_pop_elem: 7976 if (map->map_type != BPF_MAP_TYPE_QUEUE && 7977 map->map_type != BPF_MAP_TYPE_STACK) 7978 goto error; 7979 break; 7980 case BPF_FUNC_map_peek_elem: 7981 case BPF_FUNC_map_push_elem: 7982 if (map->map_type != BPF_MAP_TYPE_QUEUE && 7983 map->map_type != BPF_MAP_TYPE_STACK && 7984 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 7985 goto error; 7986 break; 7987 case BPF_FUNC_map_lookup_percpu_elem: 7988 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 7989 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 7990 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 7991 goto error; 7992 break; 7993 case BPF_FUNC_sk_storage_get: 7994 case BPF_FUNC_sk_storage_delete: 7995 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 7996 goto error; 7997 break; 7998 case BPF_FUNC_inode_storage_get: 7999 case BPF_FUNC_inode_storage_delete: 8000 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 8001 goto error; 8002 break; 8003 case BPF_FUNC_task_storage_get: 8004 case BPF_FUNC_task_storage_delete: 8005 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 8006 goto error; 8007 break; 8008 case BPF_FUNC_cgrp_storage_get: 8009 case BPF_FUNC_cgrp_storage_delete: 8010 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 8011 goto error; 8012 break; 8013 default: 8014 break; 8015 } 8016 8017 return 0; 8018 error: 8019 verbose(env, "cannot pass map_type %d into func %s#%d\n", 8020 map->map_type, func_id_name(func_id), func_id); 8021 return -EINVAL; 8022 } 8023 8024 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 8025 { 8026 int count = 0; 8027 8028 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 8029 count++; 8030 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 8031 count++; 8032 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 8033 count++; 8034 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 8035 count++; 8036 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 8037 count++; 8038 8039 /* We only support one arg being in raw mode at the moment, 8040 * which is sufficient for the helper functions we have 8041 * right now. 8042 */ 8043 return count <= 1; 8044 } 8045 8046 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 8047 { 8048 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 8049 bool has_size = fn->arg_size[arg] != 0; 8050 bool is_next_size = false; 8051 8052 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 8053 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 8054 8055 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 8056 return is_next_size; 8057 8058 return has_size == is_next_size || is_next_size == is_fixed; 8059 } 8060 8061 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 8062 { 8063 /* bpf_xxx(..., buf, len) call will access 'len' 8064 * bytes from memory 'buf'. Both arg types need 8065 * to be paired, so make sure there's no buggy 8066 * helper function specification. 8067 */ 8068 if (arg_type_is_mem_size(fn->arg1_type) || 8069 check_args_pair_invalid(fn, 0) || 8070 check_args_pair_invalid(fn, 1) || 8071 check_args_pair_invalid(fn, 2) || 8072 check_args_pair_invalid(fn, 3) || 8073 check_args_pair_invalid(fn, 4)) 8074 return false; 8075 8076 return true; 8077 } 8078 8079 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 8080 { 8081 int i; 8082 8083 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 8084 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 8085 return !!fn->arg_btf_id[i]; 8086 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 8087 return fn->arg_btf_id[i] == BPF_PTR_POISON; 8088 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 8089 /* arg_btf_id and arg_size are in a union. */ 8090 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 8091 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 8092 return false; 8093 } 8094 8095 return true; 8096 } 8097 8098 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 8099 { 8100 return check_raw_mode_ok(fn) && 8101 check_arg_pair_ok(fn) && 8102 check_btf_id_ok(fn) ? 0 : -EINVAL; 8103 } 8104 8105 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 8106 * are now invalid, so turn them into unknown SCALAR_VALUE. 8107 * 8108 * This also applies to dynptr slices belonging to skb and xdp dynptrs, 8109 * since these slices point to packet data. 8110 */ 8111 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 8112 { 8113 struct bpf_func_state *state; 8114 struct bpf_reg_state *reg; 8115 8116 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8117 if (reg_is_pkt_pointer_any(reg) || reg_is_dynptr_slice_pkt(reg)) 8118 mark_reg_invalid(env, reg); 8119 })); 8120 } 8121 8122 enum { 8123 AT_PKT_END = -1, 8124 BEYOND_PKT_END = -2, 8125 }; 8126 8127 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 8128 { 8129 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8130 struct bpf_reg_state *reg = &state->regs[regn]; 8131 8132 if (reg->type != PTR_TO_PACKET) 8133 /* PTR_TO_PACKET_META is not supported yet */ 8134 return; 8135 8136 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 8137 * How far beyond pkt_end it goes is unknown. 8138 * if (!range_open) it's the case of pkt >= pkt_end 8139 * if (range_open) it's the case of pkt > pkt_end 8140 * hence this pointer is at least 1 byte bigger than pkt_end 8141 */ 8142 if (range_open) 8143 reg->range = BEYOND_PKT_END; 8144 else 8145 reg->range = AT_PKT_END; 8146 } 8147 8148 /* The pointer with the specified id has released its reference to kernel 8149 * resources. Identify all copies of the same pointer and clear the reference. 8150 */ 8151 static int release_reference(struct bpf_verifier_env *env, 8152 int ref_obj_id) 8153 { 8154 struct bpf_func_state *state; 8155 struct bpf_reg_state *reg; 8156 int err; 8157 8158 err = release_reference_state(cur_func(env), ref_obj_id); 8159 if (err) 8160 return err; 8161 8162 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8163 if (reg->ref_obj_id == ref_obj_id) 8164 mark_reg_invalid(env, reg); 8165 })); 8166 8167 return 0; 8168 } 8169 8170 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 8171 { 8172 struct bpf_func_state *unused; 8173 struct bpf_reg_state *reg; 8174 8175 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 8176 if (type_is_non_owning_ref(reg->type)) 8177 mark_reg_invalid(env, reg); 8178 })); 8179 } 8180 8181 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 8182 struct bpf_reg_state *regs) 8183 { 8184 int i; 8185 8186 /* after the call registers r0 - r5 were scratched */ 8187 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8188 mark_reg_not_init(env, regs, caller_saved[i]); 8189 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8190 } 8191 } 8192 8193 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 8194 struct bpf_func_state *caller, 8195 struct bpf_func_state *callee, 8196 int insn_idx); 8197 8198 static int set_callee_state(struct bpf_verifier_env *env, 8199 struct bpf_func_state *caller, 8200 struct bpf_func_state *callee, int insn_idx); 8201 8202 static bool is_callback_calling_kfunc(u32 btf_id); 8203 8204 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8205 int *insn_idx, int subprog, 8206 set_callee_state_fn set_callee_state_cb) 8207 { 8208 struct bpf_verifier_state *state = env->cur_state; 8209 struct bpf_func_info_aux *func_info_aux; 8210 struct bpf_func_state *caller, *callee; 8211 int err; 8212 bool is_global = false; 8213 8214 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 8215 verbose(env, "the call stack of %d frames is too deep\n", 8216 state->curframe + 2); 8217 return -E2BIG; 8218 } 8219 8220 caller = state->frame[state->curframe]; 8221 if (state->frame[state->curframe + 1]) { 8222 verbose(env, "verifier bug. Frame %d already allocated\n", 8223 state->curframe + 1); 8224 return -EFAULT; 8225 } 8226 8227 func_info_aux = env->prog->aux->func_info_aux; 8228 if (func_info_aux) 8229 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 8230 err = btf_check_subprog_call(env, subprog, caller->regs); 8231 if (err == -EFAULT) 8232 return err; 8233 if (is_global) { 8234 if (err) { 8235 verbose(env, "Caller passes invalid args into func#%d\n", 8236 subprog); 8237 return err; 8238 } else { 8239 if (env->log.level & BPF_LOG_LEVEL) 8240 verbose(env, 8241 "Func#%d is global and valid. Skipping.\n", 8242 subprog); 8243 clear_caller_saved_regs(env, caller->regs); 8244 8245 /* All global functions return a 64-bit SCALAR_VALUE */ 8246 mark_reg_unknown(env, caller->regs, BPF_REG_0); 8247 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8248 8249 /* continue with next insn after call */ 8250 return 0; 8251 } 8252 } 8253 8254 /* set_callee_state is used for direct subprog calls, but we are 8255 * interested in validating only BPF helpers that can call subprogs as 8256 * callbacks 8257 */ 8258 if (set_callee_state_cb != set_callee_state) { 8259 if (bpf_pseudo_kfunc_call(insn) && 8260 !is_callback_calling_kfunc(insn->imm)) { 8261 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 8262 func_id_name(insn->imm), insn->imm); 8263 return -EFAULT; 8264 } else if (!bpf_pseudo_kfunc_call(insn) && 8265 !is_callback_calling_function(insn->imm)) { /* helper */ 8266 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 8267 func_id_name(insn->imm), insn->imm); 8268 return -EFAULT; 8269 } 8270 } 8271 8272 if (insn->code == (BPF_JMP | BPF_CALL) && 8273 insn->src_reg == 0 && 8274 insn->imm == BPF_FUNC_timer_set_callback) { 8275 struct bpf_verifier_state *async_cb; 8276 8277 /* there is no real recursion here. timer callbacks are async */ 8278 env->subprog_info[subprog].is_async_cb = true; 8279 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 8280 *insn_idx, subprog); 8281 if (!async_cb) 8282 return -EFAULT; 8283 callee = async_cb->frame[0]; 8284 callee->async_entry_cnt = caller->async_entry_cnt + 1; 8285 8286 /* Convert bpf_timer_set_callback() args into timer callback args */ 8287 err = set_callee_state_cb(env, caller, callee, *insn_idx); 8288 if (err) 8289 return err; 8290 8291 clear_caller_saved_regs(env, caller->regs); 8292 mark_reg_unknown(env, caller->regs, BPF_REG_0); 8293 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8294 /* continue with next insn after call */ 8295 return 0; 8296 } 8297 8298 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 8299 if (!callee) 8300 return -ENOMEM; 8301 state->frame[state->curframe + 1] = callee; 8302 8303 /* callee cannot access r0, r6 - r9 for reading and has to write 8304 * into its own stack before reading from it. 8305 * callee can read/write into caller's stack 8306 */ 8307 init_func_state(env, callee, 8308 /* remember the callsite, it will be used by bpf_exit */ 8309 *insn_idx /* callsite */, 8310 state->curframe + 1 /* frameno within this callchain */, 8311 subprog /* subprog number within this prog */); 8312 8313 /* Transfer references to the callee */ 8314 err = copy_reference_state(callee, caller); 8315 if (err) 8316 goto err_out; 8317 8318 err = set_callee_state_cb(env, caller, callee, *insn_idx); 8319 if (err) 8320 goto err_out; 8321 8322 clear_caller_saved_regs(env, caller->regs); 8323 8324 /* only increment it after check_reg_arg() finished */ 8325 state->curframe++; 8326 8327 /* and go analyze first insn of the callee */ 8328 *insn_idx = env->subprog_info[subprog].start - 1; 8329 8330 if (env->log.level & BPF_LOG_LEVEL) { 8331 verbose(env, "caller:\n"); 8332 print_verifier_state(env, caller, true); 8333 verbose(env, "callee:\n"); 8334 print_verifier_state(env, callee, true); 8335 } 8336 return 0; 8337 8338 err_out: 8339 free_func_state(callee); 8340 state->frame[state->curframe + 1] = NULL; 8341 return err; 8342 } 8343 8344 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 8345 struct bpf_func_state *caller, 8346 struct bpf_func_state *callee) 8347 { 8348 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 8349 * void *callback_ctx, u64 flags); 8350 * callback_fn(struct bpf_map *map, void *key, void *value, 8351 * void *callback_ctx); 8352 */ 8353 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 8354 8355 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 8356 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 8357 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 8358 8359 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 8360 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 8361 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 8362 8363 /* pointer to stack or null */ 8364 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 8365 8366 /* unused */ 8367 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8368 return 0; 8369 } 8370 8371 static int set_callee_state(struct bpf_verifier_env *env, 8372 struct bpf_func_state *caller, 8373 struct bpf_func_state *callee, int insn_idx) 8374 { 8375 int i; 8376 8377 /* copy r1 - r5 args that callee can access. The copy includes parent 8378 * pointers, which connects us up to the liveness chain 8379 */ 8380 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 8381 callee->regs[i] = caller->regs[i]; 8382 return 0; 8383 } 8384 8385 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8386 int *insn_idx) 8387 { 8388 int subprog, target_insn; 8389 8390 target_insn = *insn_idx + insn->imm + 1; 8391 subprog = find_subprog(env, target_insn); 8392 if (subprog < 0) { 8393 verbose(env, "verifier bug. No program starts at insn %d\n", 8394 target_insn); 8395 return -EFAULT; 8396 } 8397 8398 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 8399 } 8400 8401 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 8402 struct bpf_func_state *caller, 8403 struct bpf_func_state *callee, 8404 int insn_idx) 8405 { 8406 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 8407 struct bpf_map *map; 8408 int err; 8409 8410 if (bpf_map_ptr_poisoned(insn_aux)) { 8411 verbose(env, "tail_call abusing map_ptr\n"); 8412 return -EINVAL; 8413 } 8414 8415 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 8416 if (!map->ops->map_set_for_each_callback_args || 8417 !map->ops->map_for_each_callback) { 8418 verbose(env, "callback function not allowed for map\n"); 8419 return -ENOTSUPP; 8420 } 8421 8422 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 8423 if (err) 8424 return err; 8425 8426 callee->in_callback_fn = true; 8427 callee->callback_ret_range = tnum_range(0, 1); 8428 return 0; 8429 } 8430 8431 static int set_loop_callback_state(struct bpf_verifier_env *env, 8432 struct bpf_func_state *caller, 8433 struct bpf_func_state *callee, 8434 int insn_idx) 8435 { 8436 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 8437 * u64 flags); 8438 * callback_fn(u32 index, void *callback_ctx); 8439 */ 8440 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 8441 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 8442 8443 /* unused */ 8444 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 8445 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8446 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8447 8448 callee->in_callback_fn = true; 8449 callee->callback_ret_range = tnum_range(0, 1); 8450 return 0; 8451 } 8452 8453 static int set_timer_callback_state(struct bpf_verifier_env *env, 8454 struct bpf_func_state *caller, 8455 struct bpf_func_state *callee, 8456 int insn_idx) 8457 { 8458 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 8459 8460 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 8461 * callback_fn(struct bpf_map *map, void *key, void *value); 8462 */ 8463 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 8464 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 8465 callee->regs[BPF_REG_1].map_ptr = map_ptr; 8466 8467 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 8468 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 8469 callee->regs[BPF_REG_2].map_ptr = map_ptr; 8470 8471 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 8472 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 8473 callee->regs[BPF_REG_3].map_ptr = map_ptr; 8474 8475 /* unused */ 8476 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8477 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8478 callee->in_async_callback_fn = true; 8479 callee->callback_ret_range = tnum_range(0, 1); 8480 return 0; 8481 } 8482 8483 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 8484 struct bpf_func_state *caller, 8485 struct bpf_func_state *callee, 8486 int insn_idx) 8487 { 8488 /* bpf_find_vma(struct task_struct *task, u64 addr, 8489 * void *callback_fn, void *callback_ctx, u64 flags) 8490 * (callback_fn)(struct task_struct *task, 8491 * struct vm_area_struct *vma, void *callback_ctx); 8492 */ 8493 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 8494 8495 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 8496 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 8497 callee->regs[BPF_REG_2].btf = btf_vmlinux; 8498 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 8499 8500 /* pointer to stack or null */ 8501 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 8502 8503 /* unused */ 8504 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8505 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8506 callee->in_callback_fn = true; 8507 callee->callback_ret_range = tnum_range(0, 1); 8508 return 0; 8509 } 8510 8511 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 8512 struct bpf_func_state *caller, 8513 struct bpf_func_state *callee, 8514 int insn_idx) 8515 { 8516 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 8517 * callback_ctx, u64 flags); 8518 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 8519 */ 8520 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 8521 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 8522 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 8523 8524 /* unused */ 8525 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 8526 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8527 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8528 8529 callee->in_callback_fn = true; 8530 callee->callback_ret_range = tnum_range(0, 1); 8531 return 0; 8532 } 8533 8534 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 8535 struct bpf_func_state *caller, 8536 struct bpf_func_state *callee, 8537 int insn_idx) 8538 { 8539 /* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node, 8540 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 8541 * 8542 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset 8543 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 8544 * by this point, so look at 'root' 8545 */ 8546 struct btf_field *field; 8547 8548 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 8549 BPF_RB_ROOT); 8550 if (!field || !field->graph_root.value_btf_id) 8551 return -EFAULT; 8552 8553 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 8554 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 8555 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 8556 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 8557 8558 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 8559 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 8560 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 8561 callee->in_callback_fn = true; 8562 callee->callback_ret_range = tnum_range(0, 1); 8563 return 0; 8564 } 8565 8566 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 8567 8568 /* Are we currently verifying the callback for a rbtree helper that must 8569 * be called with lock held? If so, no need to complain about unreleased 8570 * lock 8571 */ 8572 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 8573 { 8574 struct bpf_verifier_state *state = env->cur_state; 8575 struct bpf_insn *insn = env->prog->insnsi; 8576 struct bpf_func_state *callee; 8577 int kfunc_btf_id; 8578 8579 if (!state->curframe) 8580 return false; 8581 8582 callee = state->frame[state->curframe]; 8583 8584 if (!callee->in_callback_fn) 8585 return false; 8586 8587 kfunc_btf_id = insn[callee->callsite].imm; 8588 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 8589 } 8590 8591 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 8592 { 8593 struct bpf_verifier_state *state = env->cur_state; 8594 struct bpf_func_state *caller, *callee; 8595 struct bpf_reg_state *r0; 8596 int err; 8597 8598 callee = state->frame[state->curframe]; 8599 r0 = &callee->regs[BPF_REG_0]; 8600 if (r0->type == PTR_TO_STACK) { 8601 /* technically it's ok to return caller's stack pointer 8602 * (or caller's caller's pointer) back to the caller, 8603 * since these pointers are valid. Only current stack 8604 * pointer will be invalid as soon as function exits, 8605 * but let's be conservative 8606 */ 8607 verbose(env, "cannot return stack pointer to the caller\n"); 8608 return -EINVAL; 8609 } 8610 8611 caller = state->frame[state->curframe - 1]; 8612 if (callee->in_callback_fn) { 8613 /* enforce R0 return value range [0, 1]. */ 8614 struct tnum range = callee->callback_ret_range; 8615 8616 if (r0->type != SCALAR_VALUE) { 8617 verbose(env, "R0 not a scalar value\n"); 8618 return -EACCES; 8619 } 8620 if (!tnum_in(range, r0->var_off)) { 8621 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 8622 return -EINVAL; 8623 } 8624 } else { 8625 /* return to the caller whatever r0 had in the callee */ 8626 caller->regs[BPF_REG_0] = *r0; 8627 } 8628 8629 /* callback_fn frame should have released its own additions to parent's 8630 * reference state at this point, or check_reference_leak would 8631 * complain, hence it must be the same as the caller. There is no need 8632 * to copy it back. 8633 */ 8634 if (!callee->in_callback_fn) { 8635 /* Transfer references to the caller */ 8636 err = copy_reference_state(caller, callee); 8637 if (err) 8638 return err; 8639 } 8640 8641 *insn_idx = callee->callsite + 1; 8642 if (env->log.level & BPF_LOG_LEVEL) { 8643 verbose(env, "returning from callee:\n"); 8644 print_verifier_state(env, callee, true); 8645 verbose(env, "to caller at %d:\n", *insn_idx); 8646 print_verifier_state(env, caller, true); 8647 } 8648 /* clear everything in the callee */ 8649 free_func_state(callee); 8650 state->frame[state->curframe--] = NULL; 8651 return 0; 8652 } 8653 8654 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 8655 int func_id, 8656 struct bpf_call_arg_meta *meta) 8657 { 8658 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 8659 8660 if (ret_type != RET_INTEGER || 8661 (func_id != BPF_FUNC_get_stack && 8662 func_id != BPF_FUNC_get_task_stack && 8663 func_id != BPF_FUNC_probe_read_str && 8664 func_id != BPF_FUNC_probe_read_kernel_str && 8665 func_id != BPF_FUNC_probe_read_user_str)) 8666 return; 8667 8668 ret_reg->smax_value = meta->msize_max_value; 8669 ret_reg->s32_max_value = meta->msize_max_value; 8670 ret_reg->smin_value = -MAX_ERRNO; 8671 ret_reg->s32_min_value = -MAX_ERRNO; 8672 reg_bounds_sync(ret_reg); 8673 } 8674 8675 static int 8676 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 8677 int func_id, int insn_idx) 8678 { 8679 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 8680 struct bpf_map *map = meta->map_ptr; 8681 8682 if (func_id != BPF_FUNC_tail_call && 8683 func_id != BPF_FUNC_map_lookup_elem && 8684 func_id != BPF_FUNC_map_update_elem && 8685 func_id != BPF_FUNC_map_delete_elem && 8686 func_id != BPF_FUNC_map_push_elem && 8687 func_id != BPF_FUNC_map_pop_elem && 8688 func_id != BPF_FUNC_map_peek_elem && 8689 func_id != BPF_FUNC_for_each_map_elem && 8690 func_id != BPF_FUNC_redirect_map && 8691 func_id != BPF_FUNC_map_lookup_percpu_elem) 8692 return 0; 8693 8694 if (map == NULL) { 8695 verbose(env, "kernel subsystem misconfigured verifier\n"); 8696 return -EINVAL; 8697 } 8698 8699 /* In case of read-only, some additional restrictions 8700 * need to be applied in order to prevent altering the 8701 * state of the map from program side. 8702 */ 8703 if ((map->map_flags & BPF_F_RDONLY_PROG) && 8704 (func_id == BPF_FUNC_map_delete_elem || 8705 func_id == BPF_FUNC_map_update_elem || 8706 func_id == BPF_FUNC_map_push_elem || 8707 func_id == BPF_FUNC_map_pop_elem)) { 8708 verbose(env, "write into map forbidden\n"); 8709 return -EACCES; 8710 } 8711 8712 if (!BPF_MAP_PTR(aux->map_ptr_state)) 8713 bpf_map_ptr_store(aux, meta->map_ptr, 8714 !meta->map_ptr->bypass_spec_v1); 8715 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 8716 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 8717 !meta->map_ptr->bypass_spec_v1); 8718 return 0; 8719 } 8720 8721 static int 8722 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 8723 int func_id, int insn_idx) 8724 { 8725 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 8726 struct bpf_reg_state *regs = cur_regs(env), *reg; 8727 struct bpf_map *map = meta->map_ptr; 8728 u64 val, max; 8729 int err; 8730 8731 if (func_id != BPF_FUNC_tail_call) 8732 return 0; 8733 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 8734 verbose(env, "kernel subsystem misconfigured verifier\n"); 8735 return -EINVAL; 8736 } 8737 8738 reg = ®s[BPF_REG_3]; 8739 val = reg->var_off.value; 8740 max = map->max_entries; 8741 8742 if (!(register_is_const(reg) && val < max)) { 8743 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 8744 return 0; 8745 } 8746 8747 err = mark_chain_precision(env, BPF_REG_3); 8748 if (err) 8749 return err; 8750 if (bpf_map_key_unseen(aux)) 8751 bpf_map_key_store(aux, val); 8752 else if (!bpf_map_key_poisoned(aux) && 8753 bpf_map_key_immediate(aux) != val) 8754 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 8755 return 0; 8756 } 8757 8758 static int check_reference_leak(struct bpf_verifier_env *env) 8759 { 8760 struct bpf_func_state *state = cur_func(env); 8761 bool refs_lingering = false; 8762 int i; 8763 8764 if (state->frameno && !state->in_callback_fn) 8765 return 0; 8766 8767 for (i = 0; i < state->acquired_refs; i++) { 8768 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 8769 continue; 8770 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 8771 state->refs[i].id, state->refs[i].insn_idx); 8772 refs_lingering = true; 8773 } 8774 return refs_lingering ? -EINVAL : 0; 8775 } 8776 8777 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 8778 struct bpf_reg_state *regs) 8779 { 8780 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 8781 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 8782 struct bpf_map *fmt_map = fmt_reg->map_ptr; 8783 struct bpf_bprintf_data data = {}; 8784 int err, fmt_map_off, num_args; 8785 u64 fmt_addr; 8786 char *fmt; 8787 8788 /* data must be an array of u64 */ 8789 if (data_len_reg->var_off.value % 8) 8790 return -EINVAL; 8791 num_args = data_len_reg->var_off.value / 8; 8792 8793 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 8794 * and map_direct_value_addr is set. 8795 */ 8796 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 8797 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 8798 fmt_map_off); 8799 if (err) { 8800 verbose(env, "verifier bug\n"); 8801 return -EFAULT; 8802 } 8803 fmt = (char *)(long)fmt_addr + fmt_map_off; 8804 8805 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 8806 * can focus on validating the format specifiers. 8807 */ 8808 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 8809 if (err < 0) 8810 verbose(env, "Invalid format string\n"); 8811 8812 return err; 8813 } 8814 8815 static int check_get_func_ip(struct bpf_verifier_env *env) 8816 { 8817 enum bpf_prog_type type = resolve_prog_type(env->prog); 8818 int func_id = BPF_FUNC_get_func_ip; 8819 8820 if (type == BPF_PROG_TYPE_TRACING) { 8821 if (!bpf_prog_has_trampoline(env->prog)) { 8822 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 8823 func_id_name(func_id), func_id); 8824 return -ENOTSUPP; 8825 } 8826 return 0; 8827 } else if (type == BPF_PROG_TYPE_KPROBE) { 8828 return 0; 8829 } 8830 8831 verbose(env, "func %s#%d not supported for program type %d\n", 8832 func_id_name(func_id), func_id, type); 8833 return -ENOTSUPP; 8834 } 8835 8836 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 8837 { 8838 return &env->insn_aux_data[env->insn_idx]; 8839 } 8840 8841 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 8842 { 8843 struct bpf_reg_state *regs = cur_regs(env); 8844 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 8845 bool reg_is_null = register_is_null(reg); 8846 8847 if (reg_is_null) 8848 mark_chain_precision(env, BPF_REG_4); 8849 8850 return reg_is_null; 8851 } 8852 8853 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 8854 { 8855 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 8856 8857 if (!state->initialized) { 8858 state->initialized = 1; 8859 state->fit_for_inline = loop_flag_is_zero(env); 8860 state->callback_subprogno = subprogno; 8861 return; 8862 } 8863 8864 if (!state->fit_for_inline) 8865 return; 8866 8867 state->fit_for_inline = (loop_flag_is_zero(env) && 8868 state->callback_subprogno == subprogno); 8869 } 8870 8871 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8872 int *insn_idx_p) 8873 { 8874 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 8875 const struct bpf_func_proto *fn = NULL; 8876 enum bpf_return_type ret_type; 8877 enum bpf_type_flag ret_flag; 8878 struct bpf_reg_state *regs; 8879 struct bpf_call_arg_meta meta; 8880 int insn_idx = *insn_idx_p; 8881 bool changes_data; 8882 int i, err, func_id; 8883 8884 /* find function prototype */ 8885 func_id = insn->imm; 8886 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 8887 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 8888 func_id); 8889 return -EINVAL; 8890 } 8891 8892 if (env->ops->get_func_proto) 8893 fn = env->ops->get_func_proto(func_id, env->prog); 8894 if (!fn) { 8895 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 8896 func_id); 8897 return -EINVAL; 8898 } 8899 8900 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 8901 if (!env->prog->gpl_compatible && fn->gpl_only) { 8902 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 8903 return -EINVAL; 8904 } 8905 8906 if (fn->allowed && !fn->allowed(env->prog)) { 8907 verbose(env, "helper call is not allowed in probe\n"); 8908 return -EINVAL; 8909 } 8910 8911 if (!env->prog->aux->sleepable && fn->might_sleep) { 8912 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 8913 return -EINVAL; 8914 } 8915 8916 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 8917 changes_data = bpf_helper_changes_pkt_data(fn->func); 8918 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 8919 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 8920 func_id_name(func_id), func_id); 8921 return -EINVAL; 8922 } 8923 8924 memset(&meta, 0, sizeof(meta)); 8925 meta.pkt_access = fn->pkt_access; 8926 8927 err = check_func_proto(fn, func_id); 8928 if (err) { 8929 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 8930 func_id_name(func_id), func_id); 8931 return err; 8932 } 8933 8934 if (env->cur_state->active_rcu_lock) { 8935 if (fn->might_sleep) { 8936 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 8937 func_id_name(func_id), func_id); 8938 return -EINVAL; 8939 } 8940 8941 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 8942 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 8943 } 8944 8945 meta.func_id = func_id; 8946 /* check args */ 8947 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 8948 err = check_func_arg(env, i, &meta, fn, insn_idx); 8949 if (err) 8950 return err; 8951 } 8952 8953 err = record_func_map(env, &meta, func_id, insn_idx); 8954 if (err) 8955 return err; 8956 8957 err = record_func_key(env, &meta, func_id, insn_idx); 8958 if (err) 8959 return err; 8960 8961 /* Mark slots with STACK_MISC in case of raw mode, stack offset 8962 * is inferred from register state. 8963 */ 8964 for (i = 0; i < meta.access_size; i++) { 8965 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 8966 BPF_WRITE, -1, false); 8967 if (err) 8968 return err; 8969 } 8970 8971 regs = cur_regs(env); 8972 8973 if (meta.release_regno) { 8974 err = -EINVAL; 8975 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 8976 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 8977 * is safe to do directly. 8978 */ 8979 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 8980 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 8981 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 8982 return -EFAULT; 8983 } 8984 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 8985 } else if (meta.ref_obj_id) { 8986 err = release_reference(env, meta.ref_obj_id); 8987 } else if (register_is_null(®s[meta.release_regno])) { 8988 /* meta.ref_obj_id can only be 0 if register that is meant to be 8989 * released is NULL, which must be > R0. 8990 */ 8991 err = 0; 8992 } 8993 if (err) { 8994 verbose(env, "func %s#%d reference has not been acquired before\n", 8995 func_id_name(func_id), func_id); 8996 return err; 8997 } 8998 } 8999 9000 switch (func_id) { 9001 case BPF_FUNC_tail_call: 9002 err = check_reference_leak(env); 9003 if (err) { 9004 verbose(env, "tail_call would lead to reference leak\n"); 9005 return err; 9006 } 9007 break; 9008 case BPF_FUNC_get_local_storage: 9009 /* check that flags argument in get_local_storage(map, flags) is 0, 9010 * this is required because get_local_storage() can't return an error. 9011 */ 9012 if (!register_is_null(®s[BPF_REG_2])) { 9013 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 9014 return -EINVAL; 9015 } 9016 break; 9017 case BPF_FUNC_for_each_map_elem: 9018 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9019 set_map_elem_callback_state); 9020 break; 9021 case BPF_FUNC_timer_set_callback: 9022 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9023 set_timer_callback_state); 9024 break; 9025 case BPF_FUNC_find_vma: 9026 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9027 set_find_vma_callback_state); 9028 break; 9029 case BPF_FUNC_snprintf: 9030 err = check_bpf_snprintf_call(env, regs); 9031 break; 9032 case BPF_FUNC_loop: 9033 update_loop_inline_state(env, meta.subprogno); 9034 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9035 set_loop_callback_state); 9036 break; 9037 case BPF_FUNC_dynptr_from_mem: 9038 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 9039 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 9040 reg_type_str(env, regs[BPF_REG_1].type)); 9041 return -EACCES; 9042 } 9043 break; 9044 case BPF_FUNC_set_retval: 9045 if (prog_type == BPF_PROG_TYPE_LSM && 9046 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 9047 if (!env->prog->aux->attach_func_proto->type) { 9048 /* Make sure programs that attach to void 9049 * hooks don't try to modify return value. 9050 */ 9051 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 9052 return -EINVAL; 9053 } 9054 } 9055 break; 9056 case BPF_FUNC_dynptr_data: 9057 { 9058 struct bpf_reg_state *reg; 9059 int id, ref_obj_id; 9060 9061 reg = get_dynptr_arg_reg(env, fn, regs); 9062 if (!reg) 9063 return -EFAULT; 9064 9065 9066 if (meta.dynptr_id) { 9067 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 9068 return -EFAULT; 9069 } 9070 if (meta.ref_obj_id) { 9071 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 9072 return -EFAULT; 9073 } 9074 9075 id = dynptr_id(env, reg); 9076 if (id < 0) { 9077 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 9078 return id; 9079 } 9080 9081 ref_obj_id = dynptr_ref_obj_id(env, reg); 9082 if (ref_obj_id < 0) { 9083 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 9084 return ref_obj_id; 9085 } 9086 9087 meta.dynptr_id = id; 9088 meta.ref_obj_id = ref_obj_id; 9089 9090 break; 9091 } 9092 case BPF_FUNC_dynptr_write: 9093 { 9094 enum bpf_dynptr_type dynptr_type; 9095 struct bpf_reg_state *reg; 9096 9097 reg = get_dynptr_arg_reg(env, fn, regs); 9098 if (!reg) 9099 return -EFAULT; 9100 9101 dynptr_type = dynptr_get_type(env, reg); 9102 if (dynptr_type == BPF_DYNPTR_TYPE_INVALID) 9103 return -EFAULT; 9104 9105 if (dynptr_type == BPF_DYNPTR_TYPE_SKB) 9106 /* this will trigger clear_all_pkt_pointers(), which will 9107 * invalidate all dynptr slices associated with the skb 9108 */ 9109 changes_data = true; 9110 9111 break; 9112 } 9113 case BPF_FUNC_user_ringbuf_drain: 9114 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9115 set_user_ringbuf_callback_state); 9116 break; 9117 } 9118 9119 if (err) 9120 return err; 9121 9122 /* reset caller saved regs */ 9123 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9124 mark_reg_not_init(env, regs, caller_saved[i]); 9125 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9126 } 9127 9128 /* helper call returns 64-bit value. */ 9129 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 9130 9131 /* update return register (already marked as written above) */ 9132 ret_type = fn->ret_type; 9133 ret_flag = type_flag(ret_type); 9134 9135 switch (base_type(ret_type)) { 9136 case RET_INTEGER: 9137 /* sets type to SCALAR_VALUE */ 9138 mark_reg_unknown(env, regs, BPF_REG_0); 9139 break; 9140 case RET_VOID: 9141 regs[BPF_REG_0].type = NOT_INIT; 9142 break; 9143 case RET_PTR_TO_MAP_VALUE: 9144 /* There is no offset yet applied, variable or fixed */ 9145 mark_reg_known_zero(env, regs, BPF_REG_0); 9146 /* remember map_ptr, so that check_map_access() 9147 * can check 'value_size' boundary of memory access 9148 * to map element returned from bpf_map_lookup_elem() 9149 */ 9150 if (meta.map_ptr == NULL) { 9151 verbose(env, 9152 "kernel subsystem misconfigured verifier\n"); 9153 return -EINVAL; 9154 } 9155 regs[BPF_REG_0].map_ptr = meta.map_ptr; 9156 regs[BPF_REG_0].map_uid = meta.map_uid; 9157 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 9158 if (!type_may_be_null(ret_type) && 9159 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 9160 regs[BPF_REG_0].id = ++env->id_gen; 9161 } 9162 break; 9163 case RET_PTR_TO_SOCKET: 9164 mark_reg_known_zero(env, regs, BPF_REG_0); 9165 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 9166 break; 9167 case RET_PTR_TO_SOCK_COMMON: 9168 mark_reg_known_zero(env, regs, BPF_REG_0); 9169 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 9170 break; 9171 case RET_PTR_TO_TCP_SOCK: 9172 mark_reg_known_zero(env, regs, BPF_REG_0); 9173 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 9174 break; 9175 case RET_PTR_TO_MEM: 9176 mark_reg_known_zero(env, regs, BPF_REG_0); 9177 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 9178 regs[BPF_REG_0].mem_size = meta.mem_size; 9179 break; 9180 case RET_PTR_TO_MEM_OR_BTF_ID: 9181 { 9182 const struct btf_type *t; 9183 9184 mark_reg_known_zero(env, regs, BPF_REG_0); 9185 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 9186 if (!btf_type_is_struct(t)) { 9187 u32 tsize; 9188 const struct btf_type *ret; 9189 const char *tname; 9190 9191 /* resolve the type size of ksym. */ 9192 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 9193 if (IS_ERR(ret)) { 9194 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 9195 verbose(env, "unable to resolve the size of type '%s': %ld\n", 9196 tname, PTR_ERR(ret)); 9197 return -EINVAL; 9198 } 9199 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 9200 regs[BPF_REG_0].mem_size = tsize; 9201 } else { 9202 /* MEM_RDONLY may be carried from ret_flag, but it 9203 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 9204 * it will confuse the check of PTR_TO_BTF_ID in 9205 * check_mem_access(). 9206 */ 9207 ret_flag &= ~MEM_RDONLY; 9208 9209 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 9210 regs[BPF_REG_0].btf = meta.ret_btf; 9211 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 9212 } 9213 break; 9214 } 9215 case RET_PTR_TO_BTF_ID: 9216 { 9217 struct btf *ret_btf; 9218 int ret_btf_id; 9219 9220 mark_reg_known_zero(env, regs, BPF_REG_0); 9221 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 9222 if (func_id == BPF_FUNC_kptr_xchg) { 9223 ret_btf = meta.kptr_field->kptr.btf; 9224 ret_btf_id = meta.kptr_field->kptr.btf_id; 9225 if (!btf_is_kernel(ret_btf)) 9226 regs[BPF_REG_0].type |= MEM_ALLOC; 9227 } else { 9228 if (fn->ret_btf_id == BPF_PTR_POISON) { 9229 verbose(env, "verifier internal error:"); 9230 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 9231 func_id_name(func_id)); 9232 return -EINVAL; 9233 } 9234 ret_btf = btf_vmlinux; 9235 ret_btf_id = *fn->ret_btf_id; 9236 } 9237 if (ret_btf_id == 0) { 9238 verbose(env, "invalid return type %u of func %s#%d\n", 9239 base_type(ret_type), func_id_name(func_id), 9240 func_id); 9241 return -EINVAL; 9242 } 9243 regs[BPF_REG_0].btf = ret_btf; 9244 regs[BPF_REG_0].btf_id = ret_btf_id; 9245 break; 9246 } 9247 default: 9248 verbose(env, "unknown return type %u of func %s#%d\n", 9249 base_type(ret_type), func_id_name(func_id), func_id); 9250 return -EINVAL; 9251 } 9252 9253 if (type_may_be_null(regs[BPF_REG_0].type)) 9254 regs[BPF_REG_0].id = ++env->id_gen; 9255 9256 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 9257 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 9258 func_id_name(func_id), func_id); 9259 return -EFAULT; 9260 } 9261 9262 if (is_dynptr_ref_function(func_id)) 9263 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 9264 9265 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 9266 /* For release_reference() */ 9267 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 9268 } else if (is_acquire_function(func_id, meta.map_ptr)) { 9269 int id = acquire_reference_state(env, insn_idx); 9270 9271 if (id < 0) 9272 return id; 9273 /* For mark_ptr_or_null_reg() */ 9274 regs[BPF_REG_0].id = id; 9275 /* For release_reference() */ 9276 regs[BPF_REG_0].ref_obj_id = id; 9277 } 9278 9279 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 9280 9281 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 9282 if (err) 9283 return err; 9284 9285 if ((func_id == BPF_FUNC_get_stack || 9286 func_id == BPF_FUNC_get_task_stack) && 9287 !env->prog->has_callchain_buf) { 9288 const char *err_str; 9289 9290 #ifdef CONFIG_PERF_EVENTS 9291 err = get_callchain_buffers(sysctl_perf_event_max_stack); 9292 err_str = "cannot get callchain buffer for func %s#%d\n"; 9293 #else 9294 err = -ENOTSUPP; 9295 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 9296 #endif 9297 if (err) { 9298 verbose(env, err_str, func_id_name(func_id), func_id); 9299 return err; 9300 } 9301 9302 env->prog->has_callchain_buf = true; 9303 } 9304 9305 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 9306 env->prog->call_get_stack = true; 9307 9308 if (func_id == BPF_FUNC_get_func_ip) { 9309 if (check_get_func_ip(env)) 9310 return -ENOTSUPP; 9311 env->prog->call_get_func_ip = true; 9312 } 9313 9314 if (changes_data) 9315 clear_all_pkt_pointers(env); 9316 return 0; 9317 } 9318 9319 /* mark_btf_func_reg_size() is used when the reg size is determined by 9320 * the BTF func_proto's return value size and argument. 9321 */ 9322 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 9323 size_t reg_size) 9324 { 9325 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 9326 9327 if (regno == BPF_REG_0) { 9328 /* Function return value */ 9329 reg->live |= REG_LIVE_WRITTEN; 9330 reg->subreg_def = reg_size == sizeof(u64) ? 9331 DEF_NOT_SUBREG : env->insn_idx + 1; 9332 } else { 9333 /* Function argument */ 9334 if (reg_size == sizeof(u64)) { 9335 mark_insn_zext(env, reg); 9336 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 9337 } else { 9338 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 9339 } 9340 } 9341 } 9342 9343 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 9344 { 9345 return meta->kfunc_flags & KF_ACQUIRE; 9346 } 9347 9348 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 9349 { 9350 return meta->kfunc_flags & KF_RET_NULL; 9351 } 9352 9353 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 9354 { 9355 return meta->kfunc_flags & KF_RELEASE; 9356 } 9357 9358 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 9359 { 9360 return (meta->kfunc_flags & KF_TRUSTED_ARGS) || is_kfunc_release(meta); 9361 } 9362 9363 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 9364 { 9365 return meta->kfunc_flags & KF_SLEEPABLE; 9366 } 9367 9368 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 9369 { 9370 return meta->kfunc_flags & KF_DESTRUCTIVE; 9371 } 9372 9373 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 9374 { 9375 return meta->kfunc_flags & KF_RCU; 9376 } 9377 9378 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg) 9379 { 9380 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET); 9381 } 9382 9383 static bool __kfunc_param_match_suffix(const struct btf *btf, 9384 const struct btf_param *arg, 9385 const char *suffix) 9386 { 9387 int suffix_len = strlen(suffix), len; 9388 const char *param_name; 9389 9390 /* In the future, this can be ported to use BTF tagging */ 9391 param_name = btf_name_by_offset(btf, arg->name_off); 9392 if (str_is_empty(param_name)) 9393 return false; 9394 len = strlen(param_name); 9395 if (len < suffix_len) 9396 return false; 9397 param_name += len - suffix_len; 9398 return !strncmp(param_name, suffix, suffix_len); 9399 } 9400 9401 static bool is_kfunc_arg_mem_size(const struct btf *btf, 9402 const struct btf_param *arg, 9403 const struct bpf_reg_state *reg) 9404 { 9405 const struct btf_type *t; 9406 9407 t = btf_type_skip_modifiers(btf, arg->type, NULL); 9408 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 9409 return false; 9410 9411 return __kfunc_param_match_suffix(btf, arg, "__sz"); 9412 } 9413 9414 static bool is_kfunc_arg_const_mem_size(const struct btf *btf, 9415 const struct btf_param *arg, 9416 const struct bpf_reg_state *reg) 9417 { 9418 const struct btf_type *t; 9419 9420 t = btf_type_skip_modifiers(btf, arg->type, NULL); 9421 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 9422 return false; 9423 9424 return __kfunc_param_match_suffix(btf, arg, "__szk"); 9425 } 9426 9427 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 9428 { 9429 return __kfunc_param_match_suffix(btf, arg, "__k"); 9430 } 9431 9432 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 9433 { 9434 return __kfunc_param_match_suffix(btf, arg, "__ign"); 9435 } 9436 9437 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 9438 { 9439 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 9440 } 9441 9442 static bool is_kfunc_arg_uninit(const struct btf *btf, const struct btf_param *arg) 9443 { 9444 return __kfunc_param_match_suffix(btf, arg, "__uninit"); 9445 } 9446 9447 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 9448 const struct btf_param *arg, 9449 const char *name) 9450 { 9451 int len, target_len = strlen(name); 9452 const char *param_name; 9453 9454 param_name = btf_name_by_offset(btf, arg->name_off); 9455 if (str_is_empty(param_name)) 9456 return false; 9457 len = strlen(param_name); 9458 if (len != target_len) 9459 return false; 9460 if (strcmp(param_name, name)) 9461 return false; 9462 9463 return true; 9464 } 9465 9466 enum { 9467 KF_ARG_DYNPTR_ID, 9468 KF_ARG_LIST_HEAD_ID, 9469 KF_ARG_LIST_NODE_ID, 9470 KF_ARG_RB_ROOT_ID, 9471 KF_ARG_RB_NODE_ID, 9472 }; 9473 9474 BTF_ID_LIST(kf_arg_btf_ids) 9475 BTF_ID(struct, bpf_dynptr_kern) 9476 BTF_ID(struct, bpf_list_head) 9477 BTF_ID(struct, bpf_list_node) 9478 BTF_ID(struct, bpf_rb_root) 9479 BTF_ID(struct, bpf_rb_node) 9480 9481 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 9482 const struct btf_param *arg, int type) 9483 { 9484 const struct btf_type *t; 9485 u32 res_id; 9486 9487 t = btf_type_skip_modifiers(btf, arg->type, NULL); 9488 if (!t) 9489 return false; 9490 if (!btf_type_is_ptr(t)) 9491 return false; 9492 t = btf_type_skip_modifiers(btf, t->type, &res_id); 9493 if (!t) 9494 return false; 9495 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 9496 } 9497 9498 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 9499 { 9500 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 9501 } 9502 9503 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 9504 { 9505 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 9506 } 9507 9508 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 9509 { 9510 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 9511 } 9512 9513 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 9514 { 9515 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 9516 } 9517 9518 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 9519 { 9520 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 9521 } 9522 9523 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 9524 const struct btf_param *arg) 9525 { 9526 const struct btf_type *t; 9527 9528 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 9529 if (!t) 9530 return false; 9531 9532 return true; 9533 } 9534 9535 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 9536 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 9537 const struct btf *btf, 9538 const struct btf_type *t, int rec) 9539 { 9540 const struct btf_type *member_type; 9541 const struct btf_member *member; 9542 u32 i; 9543 9544 if (!btf_type_is_struct(t)) 9545 return false; 9546 9547 for_each_member(i, t, member) { 9548 const struct btf_array *array; 9549 9550 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 9551 if (btf_type_is_struct(member_type)) { 9552 if (rec >= 3) { 9553 verbose(env, "max struct nesting depth exceeded\n"); 9554 return false; 9555 } 9556 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 9557 return false; 9558 continue; 9559 } 9560 if (btf_type_is_array(member_type)) { 9561 array = btf_array(member_type); 9562 if (!array->nelems) 9563 return false; 9564 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 9565 if (!btf_type_is_scalar(member_type)) 9566 return false; 9567 continue; 9568 } 9569 if (!btf_type_is_scalar(member_type)) 9570 return false; 9571 } 9572 return true; 9573 } 9574 9575 9576 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 9577 #ifdef CONFIG_NET 9578 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 9579 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 9580 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 9581 #endif 9582 }; 9583 9584 enum kfunc_ptr_arg_type { 9585 KF_ARG_PTR_TO_CTX, 9586 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 9587 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */ 9588 KF_ARG_PTR_TO_DYNPTR, 9589 KF_ARG_PTR_TO_ITER, 9590 KF_ARG_PTR_TO_LIST_HEAD, 9591 KF_ARG_PTR_TO_LIST_NODE, 9592 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 9593 KF_ARG_PTR_TO_MEM, 9594 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 9595 KF_ARG_PTR_TO_CALLBACK, 9596 KF_ARG_PTR_TO_RB_ROOT, 9597 KF_ARG_PTR_TO_RB_NODE, 9598 }; 9599 9600 enum special_kfunc_type { 9601 KF_bpf_obj_new_impl, 9602 KF_bpf_obj_drop_impl, 9603 KF_bpf_list_push_front, 9604 KF_bpf_list_push_back, 9605 KF_bpf_list_pop_front, 9606 KF_bpf_list_pop_back, 9607 KF_bpf_cast_to_kern_ctx, 9608 KF_bpf_rdonly_cast, 9609 KF_bpf_rcu_read_lock, 9610 KF_bpf_rcu_read_unlock, 9611 KF_bpf_rbtree_remove, 9612 KF_bpf_rbtree_add, 9613 KF_bpf_rbtree_first, 9614 KF_bpf_dynptr_from_skb, 9615 KF_bpf_dynptr_from_xdp, 9616 KF_bpf_dynptr_slice, 9617 KF_bpf_dynptr_slice_rdwr, 9618 }; 9619 9620 BTF_SET_START(special_kfunc_set) 9621 BTF_ID(func, bpf_obj_new_impl) 9622 BTF_ID(func, bpf_obj_drop_impl) 9623 BTF_ID(func, bpf_list_push_front) 9624 BTF_ID(func, bpf_list_push_back) 9625 BTF_ID(func, bpf_list_pop_front) 9626 BTF_ID(func, bpf_list_pop_back) 9627 BTF_ID(func, bpf_cast_to_kern_ctx) 9628 BTF_ID(func, bpf_rdonly_cast) 9629 BTF_ID(func, bpf_rbtree_remove) 9630 BTF_ID(func, bpf_rbtree_add) 9631 BTF_ID(func, bpf_rbtree_first) 9632 BTF_ID(func, bpf_dynptr_from_skb) 9633 BTF_ID(func, bpf_dynptr_from_xdp) 9634 BTF_ID(func, bpf_dynptr_slice) 9635 BTF_ID(func, bpf_dynptr_slice_rdwr) 9636 BTF_SET_END(special_kfunc_set) 9637 9638 BTF_ID_LIST(special_kfunc_list) 9639 BTF_ID(func, bpf_obj_new_impl) 9640 BTF_ID(func, bpf_obj_drop_impl) 9641 BTF_ID(func, bpf_list_push_front) 9642 BTF_ID(func, bpf_list_push_back) 9643 BTF_ID(func, bpf_list_pop_front) 9644 BTF_ID(func, bpf_list_pop_back) 9645 BTF_ID(func, bpf_cast_to_kern_ctx) 9646 BTF_ID(func, bpf_rdonly_cast) 9647 BTF_ID(func, bpf_rcu_read_lock) 9648 BTF_ID(func, bpf_rcu_read_unlock) 9649 BTF_ID(func, bpf_rbtree_remove) 9650 BTF_ID(func, bpf_rbtree_add) 9651 BTF_ID(func, bpf_rbtree_first) 9652 BTF_ID(func, bpf_dynptr_from_skb) 9653 BTF_ID(func, bpf_dynptr_from_xdp) 9654 BTF_ID(func, bpf_dynptr_slice) 9655 BTF_ID(func, bpf_dynptr_slice_rdwr) 9656 9657 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 9658 { 9659 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 9660 } 9661 9662 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 9663 { 9664 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 9665 } 9666 9667 static enum kfunc_ptr_arg_type 9668 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 9669 struct bpf_kfunc_call_arg_meta *meta, 9670 const struct btf_type *t, const struct btf_type *ref_t, 9671 const char *ref_tname, const struct btf_param *args, 9672 int argno, int nargs) 9673 { 9674 u32 regno = argno + 1; 9675 struct bpf_reg_state *regs = cur_regs(env); 9676 struct bpf_reg_state *reg = ®s[regno]; 9677 bool arg_mem_size = false; 9678 9679 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 9680 return KF_ARG_PTR_TO_CTX; 9681 9682 /* In this function, we verify the kfunc's BTF as per the argument type, 9683 * leaving the rest of the verification with respect to the register 9684 * type to our caller. When a set of conditions hold in the BTF type of 9685 * arguments, we resolve it to a known kfunc_ptr_arg_type. 9686 */ 9687 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 9688 return KF_ARG_PTR_TO_CTX; 9689 9690 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 9691 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 9692 9693 if (is_kfunc_arg_kptr_get(meta, argno)) { 9694 if (!btf_type_is_ptr(ref_t)) { 9695 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n"); 9696 return -EINVAL; 9697 } 9698 ref_t = btf_type_by_id(meta->btf, ref_t->type); 9699 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off); 9700 if (!btf_type_is_struct(ref_t)) { 9701 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n", 9702 meta->func_name, btf_type_str(ref_t), ref_tname); 9703 return -EINVAL; 9704 } 9705 return KF_ARG_PTR_TO_KPTR; 9706 } 9707 9708 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 9709 return KF_ARG_PTR_TO_DYNPTR; 9710 9711 if (is_kfunc_arg_iter(meta, argno)) 9712 return KF_ARG_PTR_TO_ITER; 9713 9714 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 9715 return KF_ARG_PTR_TO_LIST_HEAD; 9716 9717 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 9718 return KF_ARG_PTR_TO_LIST_NODE; 9719 9720 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 9721 return KF_ARG_PTR_TO_RB_ROOT; 9722 9723 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 9724 return KF_ARG_PTR_TO_RB_NODE; 9725 9726 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 9727 if (!btf_type_is_struct(ref_t)) { 9728 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 9729 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 9730 return -EINVAL; 9731 } 9732 return KF_ARG_PTR_TO_BTF_ID; 9733 } 9734 9735 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 9736 return KF_ARG_PTR_TO_CALLBACK; 9737 9738 9739 if (argno + 1 < nargs && 9740 (is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]) || 9741 is_kfunc_arg_const_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1]))) 9742 arg_mem_size = true; 9743 9744 /* This is the catch all argument type of register types supported by 9745 * check_helper_mem_access. However, we only allow when argument type is 9746 * pointer to scalar, or struct composed (recursively) of scalars. When 9747 * arg_mem_size is true, the pointer can be void *. 9748 */ 9749 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 9750 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 9751 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 9752 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 9753 return -EINVAL; 9754 } 9755 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 9756 } 9757 9758 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 9759 struct bpf_reg_state *reg, 9760 const struct btf_type *ref_t, 9761 const char *ref_tname, u32 ref_id, 9762 struct bpf_kfunc_call_arg_meta *meta, 9763 int argno) 9764 { 9765 const struct btf_type *reg_ref_t; 9766 bool strict_type_match = false; 9767 const struct btf *reg_btf; 9768 const char *reg_ref_tname; 9769 u32 reg_ref_id; 9770 9771 if (base_type(reg->type) == PTR_TO_BTF_ID) { 9772 reg_btf = reg->btf; 9773 reg_ref_id = reg->btf_id; 9774 } else { 9775 reg_btf = btf_vmlinux; 9776 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 9777 } 9778 9779 /* Enforce strict type matching for calls to kfuncs that are acquiring 9780 * or releasing a reference, or are no-cast aliases. We do _not_ 9781 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 9782 * as we want to enable BPF programs to pass types that are bitwise 9783 * equivalent without forcing them to explicitly cast with something 9784 * like bpf_cast_to_kern_ctx(). 9785 * 9786 * For example, say we had a type like the following: 9787 * 9788 * struct bpf_cpumask { 9789 * cpumask_t cpumask; 9790 * refcount_t usage; 9791 * }; 9792 * 9793 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 9794 * to a struct cpumask, so it would be safe to pass a struct 9795 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 9796 * 9797 * The philosophy here is similar to how we allow scalars of different 9798 * types to be passed to kfuncs as long as the size is the same. The 9799 * only difference here is that we're simply allowing 9800 * btf_struct_ids_match() to walk the struct at the 0th offset, and 9801 * resolve types. 9802 */ 9803 if (is_kfunc_acquire(meta) || 9804 (is_kfunc_release(meta) && reg->ref_obj_id) || 9805 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 9806 strict_type_match = true; 9807 9808 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 9809 9810 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 9811 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 9812 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 9813 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 9814 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 9815 btf_type_str(reg_ref_t), reg_ref_tname); 9816 return -EINVAL; 9817 } 9818 return 0; 9819 } 9820 9821 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env, 9822 struct bpf_reg_state *reg, 9823 const struct btf_type *ref_t, 9824 const char *ref_tname, 9825 struct bpf_kfunc_call_arg_meta *meta, 9826 int argno) 9827 { 9828 struct btf_field *kptr_field; 9829 9830 /* check_func_arg_reg_off allows var_off for 9831 * PTR_TO_MAP_VALUE, but we need fixed offset to find 9832 * off_desc. 9833 */ 9834 if (!tnum_is_const(reg->var_off)) { 9835 verbose(env, "arg#0 must have constant offset\n"); 9836 return -EINVAL; 9837 } 9838 9839 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR); 9840 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) { 9841 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n", 9842 reg->off + reg->var_off.value); 9843 return -EINVAL; 9844 } 9845 9846 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf, 9847 kptr_field->kptr.btf_id, true)) { 9848 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n", 9849 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 9850 return -EINVAL; 9851 } 9852 return 0; 9853 } 9854 9855 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 9856 { 9857 struct bpf_verifier_state *state = env->cur_state; 9858 9859 if (!state->active_lock.ptr) { 9860 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 9861 return -EFAULT; 9862 } 9863 9864 if (type_flag(reg->type) & NON_OWN_REF) { 9865 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 9866 return -EFAULT; 9867 } 9868 9869 reg->type |= NON_OWN_REF; 9870 return 0; 9871 } 9872 9873 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 9874 { 9875 struct bpf_func_state *state, *unused; 9876 struct bpf_reg_state *reg; 9877 int i; 9878 9879 state = cur_func(env); 9880 9881 if (!ref_obj_id) { 9882 verbose(env, "verifier internal error: ref_obj_id is zero for " 9883 "owning -> non-owning conversion\n"); 9884 return -EFAULT; 9885 } 9886 9887 for (i = 0; i < state->acquired_refs; i++) { 9888 if (state->refs[i].id != ref_obj_id) 9889 continue; 9890 9891 /* Clear ref_obj_id here so release_reference doesn't clobber 9892 * the whole reg 9893 */ 9894 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9895 if (reg->ref_obj_id == ref_obj_id) { 9896 reg->ref_obj_id = 0; 9897 ref_set_non_owning(env, reg); 9898 } 9899 })); 9900 return 0; 9901 } 9902 9903 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 9904 return -EFAULT; 9905 } 9906 9907 /* Implementation details: 9908 * 9909 * Each register points to some region of memory, which we define as an 9910 * allocation. Each allocation may embed a bpf_spin_lock which protects any 9911 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 9912 * allocation. The lock and the data it protects are colocated in the same 9913 * memory region. 9914 * 9915 * Hence, everytime a register holds a pointer value pointing to such 9916 * allocation, the verifier preserves a unique reg->id for it. 9917 * 9918 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 9919 * bpf_spin_lock is called. 9920 * 9921 * To enable this, lock state in the verifier captures two values: 9922 * active_lock.ptr = Register's type specific pointer 9923 * active_lock.id = A unique ID for each register pointer value 9924 * 9925 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 9926 * supported register types. 9927 * 9928 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 9929 * allocated objects is the reg->btf pointer. 9930 * 9931 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 9932 * can establish the provenance of the map value statically for each distinct 9933 * lookup into such maps. They always contain a single map value hence unique 9934 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 9935 * 9936 * So, in case of global variables, they use array maps with max_entries = 1, 9937 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 9938 * into the same map value as max_entries is 1, as described above). 9939 * 9940 * In case of inner map lookups, the inner map pointer has same map_ptr as the 9941 * outer map pointer (in verifier context), but each lookup into an inner map 9942 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 9943 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 9944 * will get different reg->id assigned to each lookup, hence different 9945 * active_lock.id. 9946 * 9947 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 9948 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 9949 * returned from bpf_obj_new. Each allocation receives a new reg->id. 9950 */ 9951 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 9952 { 9953 void *ptr; 9954 u32 id; 9955 9956 switch ((int)reg->type) { 9957 case PTR_TO_MAP_VALUE: 9958 ptr = reg->map_ptr; 9959 break; 9960 case PTR_TO_BTF_ID | MEM_ALLOC: 9961 ptr = reg->btf; 9962 break; 9963 default: 9964 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 9965 return -EFAULT; 9966 } 9967 id = reg->id; 9968 9969 if (!env->cur_state->active_lock.ptr) 9970 return -EINVAL; 9971 if (env->cur_state->active_lock.ptr != ptr || 9972 env->cur_state->active_lock.id != id) { 9973 verbose(env, "held lock and object are not in the same allocation\n"); 9974 return -EINVAL; 9975 } 9976 return 0; 9977 } 9978 9979 static bool is_bpf_list_api_kfunc(u32 btf_id) 9980 { 9981 return btf_id == special_kfunc_list[KF_bpf_list_push_front] || 9982 btf_id == special_kfunc_list[KF_bpf_list_push_back] || 9983 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 9984 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 9985 } 9986 9987 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 9988 { 9989 return btf_id == special_kfunc_list[KF_bpf_rbtree_add] || 9990 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 9991 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 9992 } 9993 9994 static bool is_bpf_graph_api_kfunc(u32 btf_id) 9995 { 9996 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id); 9997 } 9998 9999 static bool is_callback_calling_kfunc(u32 btf_id) 10000 { 10001 return btf_id == special_kfunc_list[KF_bpf_rbtree_add]; 10002 } 10003 10004 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 10005 { 10006 return is_bpf_rbtree_api_kfunc(btf_id); 10007 } 10008 10009 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 10010 enum btf_field_type head_field_type, 10011 u32 kfunc_btf_id) 10012 { 10013 bool ret; 10014 10015 switch (head_field_type) { 10016 case BPF_LIST_HEAD: 10017 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 10018 break; 10019 case BPF_RB_ROOT: 10020 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 10021 break; 10022 default: 10023 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 10024 btf_field_type_name(head_field_type)); 10025 return false; 10026 } 10027 10028 if (!ret) 10029 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 10030 btf_field_type_name(head_field_type)); 10031 return ret; 10032 } 10033 10034 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 10035 enum btf_field_type node_field_type, 10036 u32 kfunc_btf_id) 10037 { 10038 bool ret; 10039 10040 switch (node_field_type) { 10041 case BPF_LIST_NODE: 10042 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] || 10043 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]); 10044 break; 10045 case BPF_RB_NODE: 10046 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10047 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]); 10048 break; 10049 default: 10050 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 10051 btf_field_type_name(node_field_type)); 10052 return false; 10053 } 10054 10055 if (!ret) 10056 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 10057 btf_field_type_name(node_field_type)); 10058 return ret; 10059 } 10060 10061 static int 10062 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 10063 struct bpf_reg_state *reg, u32 regno, 10064 struct bpf_kfunc_call_arg_meta *meta, 10065 enum btf_field_type head_field_type, 10066 struct btf_field **head_field) 10067 { 10068 const char *head_type_name; 10069 struct btf_field *field; 10070 struct btf_record *rec; 10071 u32 head_off; 10072 10073 if (meta->btf != btf_vmlinux) { 10074 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10075 return -EFAULT; 10076 } 10077 10078 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 10079 return -EFAULT; 10080 10081 head_type_name = btf_field_type_name(head_field_type); 10082 if (!tnum_is_const(reg->var_off)) { 10083 verbose(env, 10084 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10085 regno, head_type_name); 10086 return -EINVAL; 10087 } 10088 10089 rec = reg_btf_record(reg); 10090 head_off = reg->off + reg->var_off.value; 10091 field = btf_record_find(rec, head_off, head_field_type); 10092 if (!field) { 10093 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 10094 return -EINVAL; 10095 } 10096 10097 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 10098 if (check_reg_allocation_locked(env, reg)) { 10099 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 10100 rec->spin_lock_off, head_type_name); 10101 return -EINVAL; 10102 } 10103 10104 if (*head_field) { 10105 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 10106 return -EFAULT; 10107 } 10108 *head_field = field; 10109 return 0; 10110 } 10111 10112 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 10113 struct bpf_reg_state *reg, u32 regno, 10114 struct bpf_kfunc_call_arg_meta *meta) 10115 { 10116 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 10117 &meta->arg_list_head.field); 10118 } 10119 10120 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 10121 struct bpf_reg_state *reg, u32 regno, 10122 struct bpf_kfunc_call_arg_meta *meta) 10123 { 10124 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 10125 &meta->arg_rbtree_root.field); 10126 } 10127 10128 static int 10129 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 10130 struct bpf_reg_state *reg, u32 regno, 10131 struct bpf_kfunc_call_arg_meta *meta, 10132 enum btf_field_type head_field_type, 10133 enum btf_field_type node_field_type, 10134 struct btf_field **node_field) 10135 { 10136 const char *node_type_name; 10137 const struct btf_type *et, *t; 10138 struct btf_field *field; 10139 u32 node_off; 10140 10141 if (meta->btf != btf_vmlinux) { 10142 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 10143 return -EFAULT; 10144 } 10145 10146 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 10147 return -EFAULT; 10148 10149 node_type_name = btf_field_type_name(node_field_type); 10150 if (!tnum_is_const(reg->var_off)) { 10151 verbose(env, 10152 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 10153 regno, node_type_name); 10154 return -EINVAL; 10155 } 10156 10157 node_off = reg->off + reg->var_off.value; 10158 field = reg_find_field_offset(reg, node_off, node_field_type); 10159 if (!field || field->offset != node_off) { 10160 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 10161 return -EINVAL; 10162 } 10163 10164 field = *node_field; 10165 10166 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 10167 t = btf_type_by_id(reg->btf, reg->btf_id); 10168 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 10169 field->graph_root.value_btf_id, true)) { 10170 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 10171 "in struct %s, but arg is at offset=%d in struct %s\n", 10172 btf_field_type_name(head_field_type), 10173 btf_field_type_name(node_field_type), 10174 field->graph_root.node_offset, 10175 btf_name_by_offset(field->graph_root.btf, et->name_off), 10176 node_off, btf_name_by_offset(reg->btf, t->name_off)); 10177 return -EINVAL; 10178 } 10179 10180 if (node_off != field->graph_root.node_offset) { 10181 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 10182 node_off, btf_field_type_name(node_field_type), 10183 field->graph_root.node_offset, 10184 btf_name_by_offset(field->graph_root.btf, et->name_off)); 10185 return -EINVAL; 10186 } 10187 10188 return 0; 10189 } 10190 10191 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 10192 struct bpf_reg_state *reg, u32 regno, 10193 struct bpf_kfunc_call_arg_meta *meta) 10194 { 10195 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 10196 BPF_LIST_HEAD, BPF_LIST_NODE, 10197 &meta->arg_list_head.field); 10198 } 10199 10200 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 10201 struct bpf_reg_state *reg, u32 regno, 10202 struct bpf_kfunc_call_arg_meta *meta) 10203 { 10204 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 10205 BPF_RB_ROOT, BPF_RB_NODE, 10206 &meta->arg_rbtree_root.field); 10207 } 10208 10209 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta, 10210 int insn_idx) 10211 { 10212 const char *func_name = meta->func_name, *ref_tname; 10213 const struct btf *btf = meta->btf; 10214 const struct btf_param *args; 10215 u32 i, nargs; 10216 int ret; 10217 10218 args = (const struct btf_param *)(meta->func_proto + 1); 10219 nargs = btf_type_vlen(meta->func_proto); 10220 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 10221 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 10222 MAX_BPF_FUNC_REG_ARGS); 10223 return -EINVAL; 10224 } 10225 10226 /* Check that BTF function arguments match actual types that the 10227 * verifier sees. 10228 */ 10229 for (i = 0; i < nargs; i++) { 10230 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 10231 const struct btf_type *t, *ref_t, *resolve_ret; 10232 enum bpf_arg_type arg_type = ARG_DONTCARE; 10233 u32 regno = i + 1, ref_id, type_size; 10234 bool is_ret_buf_sz = false; 10235 int kf_arg_type; 10236 10237 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 10238 10239 if (is_kfunc_arg_ignore(btf, &args[i])) 10240 continue; 10241 10242 if (btf_type_is_scalar(t)) { 10243 if (reg->type != SCALAR_VALUE) { 10244 verbose(env, "R%d is not a scalar\n", regno); 10245 return -EINVAL; 10246 } 10247 10248 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 10249 if (meta->arg_constant.found) { 10250 verbose(env, "verifier internal error: only one constant argument permitted\n"); 10251 return -EFAULT; 10252 } 10253 if (!tnum_is_const(reg->var_off)) { 10254 verbose(env, "R%d must be a known constant\n", regno); 10255 return -EINVAL; 10256 } 10257 ret = mark_chain_precision(env, regno); 10258 if (ret < 0) 10259 return ret; 10260 meta->arg_constant.found = true; 10261 meta->arg_constant.value = reg->var_off.value; 10262 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 10263 meta->r0_rdonly = true; 10264 is_ret_buf_sz = true; 10265 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 10266 is_ret_buf_sz = true; 10267 } 10268 10269 if (is_ret_buf_sz) { 10270 if (meta->r0_size) { 10271 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 10272 return -EINVAL; 10273 } 10274 10275 if (!tnum_is_const(reg->var_off)) { 10276 verbose(env, "R%d is not a const\n", regno); 10277 return -EINVAL; 10278 } 10279 10280 meta->r0_size = reg->var_off.value; 10281 ret = mark_chain_precision(env, regno); 10282 if (ret) 10283 return ret; 10284 } 10285 continue; 10286 } 10287 10288 if (!btf_type_is_ptr(t)) { 10289 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 10290 return -EINVAL; 10291 } 10292 10293 if ((is_kfunc_trusted_args(meta) || is_kfunc_rcu(meta)) && 10294 (register_is_null(reg) || type_may_be_null(reg->type))) { 10295 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 10296 return -EACCES; 10297 } 10298 10299 if (reg->ref_obj_id) { 10300 if (is_kfunc_release(meta) && meta->ref_obj_id) { 10301 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 10302 regno, reg->ref_obj_id, 10303 meta->ref_obj_id); 10304 return -EFAULT; 10305 } 10306 meta->ref_obj_id = reg->ref_obj_id; 10307 if (is_kfunc_release(meta)) 10308 meta->release_regno = regno; 10309 } 10310 10311 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 10312 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 10313 10314 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 10315 if (kf_arg_type < 0) 10316 return kf_arg_type; 10317 10318 switch (kf_arg_type) { 10319 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 10320 case KF_ARG_PTR_TO_BTF_ID: 10321 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 10322 break; 10323 10324 if (!is_trusted_reg(reg)) { 10325 if (!is_kfunc_rcu(meta)) { 10326 verbose(env, "R%d must be referenced or trusted\n", regno); 10327 return -EINVAL; 10328 } 10329 if (!is_rcu_reg(reg)) { 10330 verbose(env, "R%d must be a rcu pointer\n", regno); 10331 return -EINVAL; 10332 } 10333 } 10334 10335 fallthrough; 10336 case KF_ARG_PTR_TO_CTX: 10337 /* Trusted arguments have the same offset checks as release arguments */ 10338 arg_type |= OBJ_RELEASE; 10339 break; 10340 case KF_ARG_PTR_TO_KPTR: 10341 case KF_ARG_PTR_TO_DYNPTR: 10342 case KF_ARG_PTR_TO_ITER: 10343 case KF_ARG_PTR_TO_LIST_HEAD: 10344 case KF_ARG_PTR_TO_LIST_NODE: 10345 case KF_ARG_PTR_TO_RB_ROOT: 10346 case KF_ARG_PTR_TO_RB_NODE: 10347 case KF_ARG_PTR_TO_MEM: 10348 case KF_ARG_PTR_TO_MEM_SIZE: 10349 case KF_ARG_PTR_TO_CALLBACK: 10350 /* Trusted by default */ 10351 break; 10352 default: 10353 WARN_ON_ONCE(1); 10354 return -EFAULT; 10355 } 10356 10357 if (is_kfunc_release(meta) && reg->ref_obj_id) 10358 arg_type |= OBJ_RELEASE; 10359 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 10360 if (ret < 0) 10361 return ret; 10362 10363 switch (kf_arg_type) { 10364 case KF_ARG_PTR_TO_CTX: 10365 if (reg->type != PTR_TO_CTX) { 10366 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 10367 return -EINVAL; 10368 } 10369 10370 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 10371 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 10372 if (ret < 0) 10373 return -EINVAL; 10374 meta->ret_btf_id = ret; 10375 } 10376 break; 10377 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 10378 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10379 verbose(env, "arg#%d expected pointer to allocated object\n", i); 10380 return -EINVAL; 10381 } 10382 if (!reg->ref_obj_id) { 10383 verbose(env, "allocated object must be referenced\n"); 10384 return -EINVAL; 10385 } 10386 if (meta->btf == btf_vmlinux && 10387 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 10388 meta->arg_obj_drop.btf = reg->btf; 10389 meta->arg_obj_drop.btf_id = reg->btf_id; 10390 } 10391 break; 10392 case KF_ARG_PTR_TO_KPTR: 10393 if (reg->type != PTR_TO_MAP_VALUE) { 10394 verbose(env, "arg#0 expected pointer to map value\n"); 10395 return -EINVAL; 10396 } 10397 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i); 10398 if (ret < 0) 10399 return ret; 10400 break; 10401 case KF_ARG_PTR_TO_DYNPTR: 10402 { 10403 enum bpf_arg_type dynptr_arg_type = ARG_PTR_TO_DYNPTR; 10404 10405 if (reg->type != PTR_TO_STACK && 10406 reg->type != CONST_PTR_TO_DYNPTR) { 10407 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 10408 return -EINVAL; 10409 } 10410 10411 if (reg->type == CONST_PTR_TO_DYNPTR) 10412 dynptr_arg_type |= MEM_RDONLY; 10413 10414 if (is_kfunc_arg_uninit(btf, &args[i])) 10415 dynptr_arg_type |= MEM_UNINIT; 10416 10417 if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) 10418 dynptr_arg_type |= DYNPTR_TYPE_SKB; 10419 else if (meta->func_id == special_kfunc_list[KF_bpf_dynptr_from_xdp]) 10420 dynptr_arg_type |= DYNPTR_TYPE_XDP; 10421 10422 ret = process_dynptr_func(env, regno, insn_idx, dynptr_arg_type); 10423 if (ret < 0) 10424 return ret; 10425 10426 if (!(dynptr_arg_type & MEM_UNINIT)) { 10427 int id = dynptr_id(env, reg); 10428 10429 if (id < 0) { 10430 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 10431 return id; 10432 } 10433 meta->initialized_dynptr.id = id; 10434 meta->initialized_dynptr.type = dynptr_get_type(env, reg); 10435 } 10436 10437 break; 10438 } 10439 case KF_ARG_PTR_TO_ITER: 10440 ret = process_iter_arg(env, regno, insn_idx, meta); 10441 if (ret < 0) 10442 return ret; 10443 break; 10444 case KF_ARG_PTR_TO_LIST_HEAD: 10445 if (reg->type != PTR_TO_MAP_VALUE && 10446 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10447 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 10448 return -EINVAL; 10449 } 10450 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 10451 verbose(env, "allocated object must be referenced\n"); 10452 return -EINVAL; 10453 } 10454 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 10455 if (ret < 0) 10456 return ret; 10457 break; 10458 case KF_ARG_PTR_TO_RB_ROOT: 10459 if (reg->type != PTR_TO_MAP_VALUE && 10460 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10461 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 10462 return -EINVAL; 10463 } 10464 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 10465 verbose(env, "allocated object must be referenced\n"); 10466 return -EINVAL; 10467 } 10468 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 10469 if (ret < 0) 10470 return ret; 10471 break; 10472 case KF_ARG_PTR_TO_LIST_NODE: 10473 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10474 verbose(env, "arg#%d expected pointer to allocated object\n", i); 10475 return -EINVAL; 10476 } 10477 if (!reg->ref_obj_id) { 10478 verbose(env, "allocated object must be referenced\n"); 10479 return -EINVAL; 10480 } 10481 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 10482 if (ret < 0) 10483 return ret; 10484 break; 10485 case KF_ARG_PTR_TO_RB_NODE: 10486 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 10487 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 10488 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 10489 return -EINVAL; 10490 } 10491 if (in_rbtree_lock_required_cb(env)) { 10492 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 10493 return -EINVAL; 10494 } 10495 } else { 10496 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 10497 verbose(env, "arg#%d expected pointer to allocated object\n", i); 10498 return -EINVAL; 10499 } 10500 if (!reg->ref_obj_id) { 10501 verbose(env, "allocated object must be referenced\n"); 10502 return -EINVAL; 10503 } 10504 } 10505 10506 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 10507 if (ret < 0) 10508 return ret; 10509 break; 10510 case KF_ARG_PTR_TO_BTF_ID: 10511 /* Only base_type is checked, further checks are done here */ 10512 if ((base_type(reg->type) != PTR_TO_BTF_ID || 10513 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 10514 !reg2btf_ids[base_type(reg->type)]) { 10515 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 10516 verbose(env, "expected %s or socket\n", 10517 reg_type_str(env, base_type(reg->type) | 10518 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 10519 return -EINVAL; 10520 } 10521 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 10522 if (ret < 0) 10523 return ret; 10524 break; 10525 case KF_ARG_PTR_TO_MEM: 10526 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 10527 if (IS_ERR(resolve_ret)) { 10528 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 10529 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 10530 return -EINVAL; 10531 } 10532 ret = check_mem_reg(env, reg, regno, type_size); 10533 if (ret < 0) 10534 return ret; 10535 break; 10536 case KF_ARG_PTR_TO_MEM_SIZE: 10537 { 10538 struct bpf_reg_state *size_reg = ®s[regno + 1]; 10539 const struct btf_param *size_arg = &args[i + 1]; 10540 10541 ret = check_kfunc_mem_size_reg(env, size_reg, regno + 1); 10542 if (ret < 0) { 10543 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 10544 return ret; 10545 } 10546 10547 if (is_kfunc_arg_const_mem_size(meta->btf, size_arg, size_reg)) { 10548 if (meta->arg_constant.found) { 10549 verbose(env, "verifier internal error: only one constant argument permitted\n"); 10550 return -EFAULT; 10551 } 10552 if (!tnum_is_const(size_reg->var_off)) { 10553 verbose(env, "R%d must be a known constant\n", regno + 1); 10554 return -EINVAL; 10555 } 10556 meta->arg_constant.found = true; 10557 meta->arg_constant.value = size_reg->var_off.value; 10558 } 10559 10560 /* Skip next '__sz' or '__szk' argument */ 10561 i++; 10562 break; 10563 } 10564 case KF_ARG_PTR_TO_CALLBACK: 10565 meta->subprogno = reg->subprogno; 10566 break; 10567 } 10568 } 10569 10570 if (is_kfunc_release(meta) && !meta->release_regno) { 10571 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 10572 func_name); 10573 return -EINVAL; 10574 } 10575 10576 return 0; 10577 } 10578 10579 static int fetch_kfunc_meta(struct bpf_verifier_env *env, 10580 struct bpf_insn *insn, 10581 struct bpf_kfunc_call_arg_meta *meta, 10582 const char **kfunc_name) 10583 { 10584 const struct btf_type *func, *func_proto; 10585 u32 func_id, *kfunc_flags; 10586 const char *func_name; 10587 struct btf *desc_btf; 10588 10589 if (kfunc_name) 10590 *kfunc_name = NULL; 10591 10592 if (!insn->imm) 10593 return -EINVAL; 10594 10595 desc_btf = find_kfunc_desc_btf(env, insn->off); 10596 if (IS_ERR(desc_btf)) 10597 return PTR_ERR(desc_btf); 10598 10599 func_id = insn->imm; 10600 func = btf_type_by_id(desc_btf, func_id); 10601 func_name = btf_name_by_offset(desc_btf, func->name_off); 10602 if (kfunc_name) 10603 *kfunc_name = func_name; 10604 func_proto = btf_type_by_id(desc_btf, func->type); 10605 10606 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id); 10607 if (!kfunc_flags) { 10608 return -EACCES; 10609 } 10610 10611 memset(meta, 0, sizeof(*meta)); 10612 meta->btf = desc_btf; 10613 meta->func_id = func_id; 10614 meta->kfunc_flags = *kfunc_flags; 10615 meta->func_proto = func_proto; 10616 meta->func_name = func_name; 10617 10618 return 0; 10619 } 10620 10621 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 10622 int *insn_idx_p) 10623 { 10624 const struct btf_type *t, *ptr_type; 10625 u32 i, nargs, ptr_type_id, release_ref_obj_id; 10626 struct bpf_reg_state *regs = cur_regs(env); 10627 const char *func_name, *ptr_type_name; 10628 bool sleepable, rcu_lock, rcu_unlock; 10629 struct bpf_kfunc_call_arg_meta meta; 10630 struct bpf_insn_aux_data *insn_aux; 10631 int err, insn_idx = *insn_idx_p; 10632 const struct btf_param *args; 10633 const struct btf_type *ret_t; 10634 struct btf *desc_btf; 10635 10636 /* skip for now, but return error when we find this in fixup_kfunc_call */ 10637 if (!insn->imm) 10638 return 0; 10639 10640 err = fetch_kfunc_meta(env, insn, &meta, &func_name); 10641 if (err == -EACCES && func_name) 10642 verbose(env, "calling kernel function %s is not allowed\n", func_name); 10643 if (err) 10644 return err; 10645 desc_btf = meta.btf; 10646 insn_aux = &env->insn_aux_data[insn_idx]; 10647 10648 insn_aux->is_iter_next = is_iter_next_kfunc(&meta); 10649 10650 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 10651 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 10652 return -EACCES; 10653 } 10654 10655 sleepable = is_kfunc_sleepable(&meta); 10656 if (sleepable && !env->prog->aux->sleepable) { 10657 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 10658 return -EACCES; 10659 } 10660 10661 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 10662 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 10663 10664 if (env->cur_state->active_rcu_lock) { 10665 struct bpf_func_state *state; 10666 struct bpf_reg_state *reg; 10667 10668 if (rcu_lock) { 10669 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 10670 return -EINVAL; 10671 } else if (rcu_unlock) { 10672 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 10673 if (reg->type & MEM_RCU) { 10674 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 10675 reg->type |= PTR_UNTRUSTED; 10676 } 10677 })); 10678 env->cur_state->active_rcu_lock = false; 10679 } else if (sleepable) { 10680 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 10681 return -EACCES; 10682 } 10683 } else if (rcu_lock) { 10684 env->cur_state->active_rcu_lock = true; 10685 } else if (rcu_unlock) { 10686 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 10687 return -EINVAL; 10688 } 10689 10690 /* Check the arguments */ 10691 err = check_kfunc_args(env, &meta, insn_idx); 10692 if (err < 0) 10693 return err; 10694 /* In case of release function, we get register number of refcounted 10695 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 10696 */ 10697 if (meta.release_regno) { 10698 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 10699 if (err) { 10700 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 10701 func_name, meta.func_id); 10702 return err; 10703 } 10704 } 10705 10706 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] || 10707 meta.func_id == special_kfunc_list[KF_bpf_list_push_back] || 10708 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) { 10709 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 10710 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 10711 if (err) { 10712 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 10713 func_name, meta.func_id); 10714 return err; 10715 } 10716 10717 err = release_reference(env, release_ref_obj_id); 10718 if (err) { 10719 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 10720 func_name, meta.func_id); 10721 return err; 10722 } 10723 } 10724 10725 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) { 10726 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 10727 set_rbtree_add_callback_state); 10728 if (err) { 10729 verbose(env, "kfunc %s#%d failed callback verification\n", 10730 func_name, meta.func_id); 10731 return err; 10732 } 10733 } 10734 10735 for (i = 0; i < CALLER_SAVED_REGS; i++) 10736 mark_reg_not_init(env, regs, caller_saved[i]); 10737 10738 /* Check return type */ 10739 t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL); 10740 10741 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 10742 /* Only exception is bpf_obj_new_impl */ 10743 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) { 10744 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 10745 return -EINVAL; 10746 } 10747 } 10748 10749 if (btf_type_is_scalar(t)) { 10750 mark_reg_unknown(env, regs, BPF_REG_0); 10751 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 10752 } else if (btf_type_is_ptr(t)) { 10753 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 10754 10755 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 10756 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 10757 struct btf *ret_btf; 10758 u32 ret_btf_id; 10759 10760 if (unlikely(!bpf_global_ma_set)) 10761 return -ENOMEM; 10762 10763 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 10764 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 10765 return -EINVAL; 10766 } 10767 10768 ret_btf = env->prog->aux->btf; 10769 ret_btf_id = meta.arg_constant.value; 10770 10771 /* This may be NULL due to user not supplying a BTF */ 10772 if (!ret_btf) { 10773 verbose(env, "bpf_obj_new requires prog BTF\n"); 10774 return -EINVAL; 10775 } 10776 10777 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 10778 if (!ret_t || !__btf_type_is_struct(ret_t)) { 10779 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 10780 return -EINVAL; 10781 } 10782 10783 mark_reg_known_zero(env, regs, BPF_REG_0); 10784 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 10785 regs[BPF_REG_0].btf = ret_btf; 10786 regs[BPF_REG_0].btf_id = ret_btf_id; 10787 10788 insn_aux->obj_new_size = ret_t->size; 10789 insn_aux->kptr_struct_meta = 10790 btf_find_struct_meta(ret_btf, ret_btf_id); 10791 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 10792 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 10793 struct btf_field *field = meta.arg_list_head.field; 10794 10795 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 10796 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 10797 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 10798 struct btf_field *field = meta.arg_rbtree_root.field; 10799 10800 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 10801 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 10802 mark_reg_known_zero(env, regs, BPF_REG_0); 10803 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 10804 regs[BPF_REG_0].btf = desc_btf; 10805 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10806 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 10807 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 10808 if (!ret_t || !btf_type_is_struct(ret_t)) { 10809 verbose(env, 10810 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 10811 return -EINVAL; 10812 } 10813 10814 mark_reg_known_zero(env, regs, BPF_REG_0); 10815 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 10816 regs[BPF_REG_0].btf = desc_btf; 10817 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 10818 } else if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice] || 10819 meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice_rdwr]) { 10820 enum bpf_type_flag type_flag = get_dynptr_type_flag(meta.initialized_dynptr.type); 10821 10822 mark_reg_known_zero(env, regs, BPF_REG_0); 10823 10824 if (!meta.arg_constant.found) { 10825 verbose(env, "verifier internal error: bpf_dynptr_slice(_rdwr) no constant size\n"); 10826 return -EFAULT; 10827 } 10828 10829 regs[BPF_REG_0].mem_size = meta.arg_constant.value; 10830 10831 /* PTR_MAYBE_NULL will be added when is_kfunc_ret_null is checked */ 10832 regs[BPF_REG_0].type = PTR_TO_MEM | type_flag; 10833 10834 if (meta.func_id == special_kfunc_list[KF_bpf_dynptr_slice]) { 10835 regs[BPF_REG_0].type |= MEM_RDONLY; 10836 } else { 10837 /* this will set env->seen_direct_write to true */ 10838 if (!may_access_direct_pkt_data(env, NULL, BPF_WRITE)) { 10839 verbose(env, "the prog does not allow writes to packet data\n"); 10840 return -EINVAL; 10841 } 10842 } 10843 10844 if (!meta.initialized_dynptr.id) { 10845 verbose(env, "verifier internal error: no dynptr id\n"); 10846 return -EFAULT; 10847 } 10848 regs[BPF_REG_0].dynptr_id = meta.initialized_dynptr.id; 10849 10850 /* we don't need to set BPF_REG_0's ref obj id 10851 * because packet slices are not refcounted (see 10852 * dynptr_type_refcounted) 10853 */ 10854 } else { 10855 verbose(env, "kernel function %s unhandled dynamic return type\n", 10856 meta.func_name); 10857 return -EFAULT; 10858 } 10859 } else if (!__btf_type_is_struct(ptr_type)) { 10860 if (!meta.r0_size) { 10861 __u32 sz; 10862 10863 if (!IS_ERR(btf_resolve_size(desc_btf, ptr_type, &sz))) { 10864 meta.r0_size = sz; 10865 meta.r0_rdonly = true; 10866 } 10867 } 10868 if (!meta.r0_size) { 10869 ptr_type_name = btf_name_by_offset(desc_btf, 10870 ptr_type->name_off); 10871 verbose(env, 10872 "kernel function %s returns pointer type %s %s is not supported\n", 10873 func_name, 10874 btf_type_str(ptr_type), 10875 ptr_type_name); 10876 return -EINVAL; 10877 } 10878 10879 mark_reg_known_zero(env, regs, BPF_REG_0); 10880 regs[BPF_REG_0].type = PTR_TO_MEM; 10881 regs[BPF_REG_0].mem_size = meta.r0_size; 10882 10883 if (meta.r0_rdonly) 10884 regs[BPF_REG_0].type |= MEM_RDONLY; 10885 10886 /* Ensures we don't access the memory after a release_reference() */ 10887 if (meta.ref_obj_id) 10888 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10889 } else { 10890 mark_reg_known_zero(env, regs, BPF_REG_0); 10891 regs[BPF_REG_0].btf = desc_btf; 10892 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 10893 regs[BPF_REG_0].btf_id = ptr_type_id; 10894 } 10895 10896 if (is_kfunc_ret_null(&meta)) { 10897 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 10898 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 10899 regs[BPF_REG_0].id = ++env->id_gen; 10900 } 10901 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 10902 if (is_kfunc_acquire(&meta)) { 10903 int id = acquire_reference_state(env, insn_idx); 10904 10905 if (id < 0) 10906 return id; 10907 if (is_kfunc_ret_null(&meta)) 10908 regs[BPF_REG_0].id = id; 10909 regs[BPF_REG_0].ref_obj_id = id; 10910 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 10911 ref_set_non_owning(env, ®s[BPF_REG_0]); 10912 } 10913 10914 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove]) 10915 invalidate_non_owning_refs(env); 10916 10917 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 10918 regs[BPF_REG_0].id = ++env->id_gen; 10919 } else if (btf_type_is_void(t)) { 10920 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 10921 if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 10922 insn_aux->kptr_struct_meta = 10923 btf_find_struct_meta(meta.arg_obj_drop.btf, 10924 meta.arg_obj_drop.btf_id); 10925 } 10926 } 10927 } 10928 10929 nargs = btf_type_vlen(meta.func_proto); 10930 args = (const struct btf_param *)(meta.func_proto + 1); 10931 for (i = 0; i < nargs; i++) { 10932 u32 regno = i + 1; 10933 10934 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 10935 if (btf_type_is_ptr(t)) 10936 mark_btf_func_reg_size(env, regno, sizeof(void *)); 10937 else 10938 /* scalar. ensured by btf_check_kfunc_arg_match() */ 10939 mark_btf_func_reg_size(env, regno, t->size); 10940 } 10941 10942 if (is_iter_next_kfunc(&meta)) { 10943 err = process_iter_next_call(env, insn_idx, &meta); 10944 if (err) 10945 return err; 10946 } 10947 10948 return 0; 10949 } 10950 10951 static bool signed_add_overflows(s64 a, s64 b) 10952 { 10953 /* Do the add in u64, where overflow is well-defined */ 10954 s64 res = (s64)((u64)a + (u64)b); 10955 10956 if (b < 0) 10957 return res > a; 10958 return res < a; 10959 } 10960 10961 static bool signed_add32_overflows(s32 a, s32 b) 10962 { 10963 /* Do the add in u32, where overflow is well-defined */ 10964 s32 res = (s32)((u32)a + (u32)b); 10965 10966 if (b < 0) 10967 return res > a; 10968 return res < a; 10969 } 10970 10971 static bool signed_sub_overflows(s64 a, s64 b) 10972 { 10973 /* Do the sub in u64, where overflow is well-defined */ 10974 s64 res = (s64)((u64)a - (u64)b); 10975 10976 if (b < 0) 10977 return res < a; 10978 return res > a; 10979 } 10980 10981 static bool signed_sub32_overflows(s32 a, s32 b) 10982 { 10983 /* Do the sub in u32, where overflow is well-defined */ 10984 s32 res = (s32)((u32)a - (u32)b); 10985 10986 if (b < 0) 10987 return res < a; 10988 return res > a; 10989 } 10990 10991 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 10992 const struct bpf_reg_state *reg, 10993 enum bpf_reg_type type) 10994 { 10995 bool known = tnum_is_const(reg->var_off); 10996 s64 val = reg->var_off.value; 10997 s64 smin = reg->smin_value; 10998 10999 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 11000 verbose(env, "math between %s pointer and %lld is not allowed\n", 11001 reg_type_str(env, type), val); 11002 return false; 11003 } 11004 11005 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 11006 verbose(env, "%s pointer offset %d is not allowed\n", 11007 reg_type_str(env, type), reg->off); 11008 return false; 11009 } 11010 11011 if (smin == S64_MIN) { 11012 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 11013 reg_type_str(env, type)); 11014 return false; 11015 } 11016 11017 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 11018 verbose(env, "value %lld makes %s pointer be out of bounds\n", 11019 smin, reg_type_str(env, type)); 11020 return false; 11021 } 11022 11023 return true; 11024 } 11025 11026 enum { 11027 REASON_BOUNDS = -1, 11028 REASON_TYPE = -2, 11029 REASON_PATHS = -3, 11030 REASON_LIMIT = -4, 11031 REASON_STACK = -5, 11032 }; 11033 11034 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 11035 u32 *alu_limit, bool mask_to_left) 11036 { 11037 u32 max = 0, ptr_limit = 0; 11038 11039 switch (ptr_reg->type) { 11040 case PTR_TO_STACK: 11041 /* Offset 0 is out-of-bounds, but acceptable start for the 11042 * left direction, see BPF_REG_FP. Also, unknown scalar 11043 * offset where we would need to deal with min/max bounds is 11044 * currently prohibited for unprivileged. 11045 */ 11046 max = MAX_BPF_STACK + mask_to_left; 11047 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 11048 break; 11049 case PTR_TO_MAP_VALUE: 11050 max = ptr_reg->map_ptr->value_size; 11051 ptr_limit = (mask_to_left ? 11052 ptr_reg->smin_value : 11053 ptr_reg->umax_value) + ptr_reg->off; 11054 break; 11055 default: 11056 return REASON_TYPE; 11057 } 11058 11059 if (ptr_limit >= max) 11060 return REASON_LIMIT; 11061 *alu_limit = ptr_limit; 11062 return 0; 11063 } 11064 11065 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 11066 const struct bpf_insn *insn) 11067 { 11068 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 11069 } 11070 11071 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 11072 u32 alu_state, u32 alu_limit) 11073 { 11074 /* If we arrived here from different branches with different 11075 * state or limits to sanitize, then this won't work. 11076 */ 11077 if (aux->alu_state && 11078 (aux->alu_state != alu_state || 11079 aux->alu_limit != alu_limit)) 11080 return REASON_PATHS; 11081 11082 /* Corresponding fixup done in do_misc_fixups(). */ 11083 aux->alu_state = alu_state; 11084 aux->alu_limit = alu_limit; 11085 return 0; 11086 } 11087 11088 static int sanitize_val_alu(struct bpf_verifier_env *env, 11089 struct bpf_insn *insn) 11090 { 11091 struct bpf_insn_aux_data *aux = cur_aux(env); 11092 11093 if (can_skip_alu_sanitation(env, insn)) 11094 return 0; 11095 11096 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 11097 } 11098 11099 static bool sanitize_needed(u8 opcode) 11100 { 11101 return opcode == BPF_ADD || opcode == BPF_SUB; 11102 } 11103 11104 struct bpf_sanitize_info { 11105 struct bpf_insn_aux_data aux; 11106 bool mask_to_left; 11107 }; 11108 11109 static struct bpf_verifier_state * 11110 sanitize_speculative_path(struct bpf_verifier_env *env, 11111 const struct bpf_insn *insn, 11112 u32 next_idx, u32 curr_idx) 11113 { 11114 struct bpf_verifier_state *branch; 11115 struct bpf_reg_state *regs; 11116 11117 branch = push_stack(env, next_idx, curr_idx, true); 11118 if (branch && insn) { 11119 regs = branch->frame[branch->curframe]->regs; 11120 if (BPF_SRC(insn->code) == BPF_K) { 11121 mark_reg_unknown(env, regs, insn->dst_reg); 11122 } else if (BPF_SRC(insn->code) == BPF_X) { 11123 mark_reg_unknown(env, regs, insn->dst_reg); 11124 mark_reg_unknown(env, regs, insn->src_reg); 11125 } 11126 } 11127 return branch; 11128 } 11129 11130 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 11131 struct bpf_insn *insn, 11132 const struct bpf_reg_state *ptr_reg, 11133 const struct bpf_reg_state *off_reg, 11134 struct bpf_reg_state *dst_reg, 11135 struct bpf_sanitize_info *info, 11136 const bool commit_window) 11137 { 11138 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 11139 struct bpf_verifier_state *vstate = env->cur_state; 11140 bool off_is_imm = tnum_is_const(off_reg->var_off); 11141 bool off_is_neg = off_reg->smin_value < 0; 11142 bool ptr_is_dst_reg = ptr_reg == dst_reg; 11143 u8 opcode = BPF_OP(insn->code); 11144 u32 alu_state, alu_limit; 11145 struct bpf_reg_state tmp; 11146 bool ret; 11147 int err; 11148 11149 if (can_skip_alu_sanitation(env, insn)) 11150 return 0; 11151 11152 /* We already marked aux for masking from non-speculative 11153 * paths, thus we got here in the first place. We only care 11154 * to explore bad access from here. 11155 */ 11156 if (vstate->speculative) 11157 goto do_sim; 11158 11159 if (!commit_window) { 11160 if (!tnum_is_const(off_reg->var_off) && 11161 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 11162 return REASON_BOUNDS; 11163 11164 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 11165 (opcode == BPF_SUB && !off_is_neg); 11166 } 11167 11168 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 11169 if (err < 0) 11170 return err; 11171 11172 if (commit_window) { 11173 /* In commit phase we narrow the masking window based on 11174 * the observed pointer move after the simulated operation. 11175 */ 11176 alu_state = info->aux.alu_state; 11177 alu_limit = abs(info->aux.alu_limit - alu_limit); 11178 } else { 11179 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 11180 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 11181 alu_state |= ptr_is_dst_reg ? 11182 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 11183 11184 /* Limit pruning on unknown scalars to enable deep search for 11185 * potential masking differences from other program paths. 11186 */ 11187 if (!off_is_imm) 11188 env->explore_alu_limits = true; 11189 } 11190 11191 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 11192 if (err < 0) 11193 return err; 11194 do_sim: 11195 /* If we're in commit phase, we're done here given we already 11196 * pushed the truncated dst_reg into the speculative verification 11197 * stack. 11198 * 11199 * Also, when register is a known constant, we rewrite register-based 11200 * operation to immediate-based, and thus do not need masking (and as 11201 * a consequence, do not need to simulate the zero-truncation either). 11202 */ 11203 if (commit_window || off_is_imm) 11204 return 0; 11205 11206 /* Simulate and find potential out-of-bounds access under 11207 * speculative execution from truncation as a result of 11208 * masking when off was not within expected range. If off 11209 * sits in dst, then we temporarily need to move ptr there 11210 * to simulate dst (== 0) +/-= ptr. Needed, for example, 11211 * for cases where we use K-based arithmetic in one direction 11212 * and truncated reg-based in the other in order to explore 11213 * bad access. 11214 */ 11215 if (!ptr_is_dst_reg) { 11216 tmp = *dst_reg; 11217 copy_register_state(dst_reg, ptr_reg); 11218 } 11219 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 11220 env->insn_idx); 11221 if (!ptr_is_dst_reg && ret) 11222 *dst_reg = tmp; 11223 return !ret ? REASON_STACK : 0; 11224 } 11225 11226 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 11227 { 11228 struct bpf_verifier_state *vstate = env->cur_state; 11229 11230 /* If we simulate paths under speculation, we don't update the 11231 * insn as 'seen' such that when we verify unreachable paths in 11232 * the non-speculative domain, sanitize_dead_code() can still 11233 * rewrite/sanitize them. 11234 */ 11235 if (!vstate->speculative) 11236 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 11237 } 11238 11239 static int sanitize_err(struct bpf_verifier_env *env, 11240 const struct bpf_insn *insn, int reason, 11241 const struct bpf_reg_state *off_reg, 11242 const struct bpf_reg_state *dst_reg) 11243 { 11244 static const char *err = "pointer arithmetic with it prohibited for !root"; 11245 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 11246 u32 dst = insn->dst_reg, src = insn->src_reg; 11247 11248 switch (reason) { 11249 case REASON_BOUNDS: 11250 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 11251 off_reg == dst_reg ? dst : src, err); 11252 break; 11253 case REASON_TYPE: 11254 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 11255 off_reg == dst_reg ? src : dst, err); 11256 break; 11257 case REASON_PATHS: 11258 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 11259 dst, op, err); 11260 break; 11261 case REASON_LIMIT: 11262 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 11263 dst, op, err); 11264 break; 11265 case REASON_STACK: 11266 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 11267 dst, err); 11268 break; 11269 default: 11270 verbose(env, "verifier internal error: unknown reason (%d)\n", 11271 reason); 11272 break; 11273 } 11274 11275 return -EACCES; 11276 } 11277 11278 /* check that stack access falls within stack limits and that 'reg' doesn't 11279 * have a variable offset. 11280 * 11281 * Variable offset is prohibited for unprivileged mode for simplicity since it 11282 * requires corresponding support in Spectre masking for stack ALU. See also 11283 * retrieve_ptr_limit(). 11284 * 11285 * 11286 * 'off' includes 'reg->off'. 11287 */ 11288 static int check_stack_access_for_ptr_arithmetic( 11289 struct bpf_verifier_env *env, 11290 int regno, 11291 const struct bpf_reg_state *reg, 11292 int off) 11293 { 11294 if (!tnum_is_const(reg->var_off)) { 11295 char tn_buf[48]; 11296 11297 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 11298 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 11299 regno, tn_buf, off); 11300 return -EACCES; 11301 } 11302 11303 if (off >= 0 || off < -MAX_BPF_STACK) { 11304 verbose(env, "R%d stack pointer arithmetic goes out of range, " 11305 "prohibited for !root; off=%d\n", regno, off); 11306 return -EACCES; 11307 } 11308 11309 return 0; 11310 } 11311 11312 static int sanitize_check_bounds(struct bpf_verifier_env *env, 11313 const struct bpf_insn *insn, 11314 const struct bpf_reg_state *dst_reg) 11315 { 11316 u32 dst = insn->dst_reg; 11317 11318 /* For unprivileged we require that resulting offset must be in bounds 11319 * in order to be able to sanitize access later on. 11320 */ 11321 if (env->bypass_spec_v1) 11322 return 0; 11323 11324 switch (dst_reg->type) { 11325 case PTR_TO_STACK: 11326 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 11327 dst_reg->off + dst_reg->var_off.value)) 11328 return -EACCES; 11329 break; 11330 case PTR_TO_MAP_VALUE: 11331 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 11332 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 11333 "prohibited for !root\n", dst); 11334 return -EACCES; 11335 } 11336 break; 11337 default: 11338 break; 11339 } 11340 11341 return 0; 11342 } 11343 11344 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 11345 * Caller should also handle BPF_MOV case separately. 11346 * If we return -EACCES, caller may want to try again treating pointer as a 11347 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 11348 */ 11349 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 11350 struct bpf_insn *insn, 11351 const struct bpf_reg_state *ptr_reg, 11352 const struct bpf_reg_state *off_reg) 11353 { 11354 struct bpf_verifier_state *vstate = env->cur_state; 11355 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 11356 struct bpf_reg_state *regs = state->regs, *dst_reg; 11357 bool known = tnum_is_const(off_reg->var_off); 11358 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 11359 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 11360 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 11361 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 11362 struct bpf_sanitize_info info = {}; 11363 u8 opcode = BPF_OP(insn->code); 11364 u32 dst = insn->dst_reg; 11365 int ret; 11366 11367 dst_reg = ®s[dst]; 11368 11369 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 11370 smin_val > smax_val || umin_val > umax_val) { 11371 /* Taint dst register if offset had invalid bounds derived from 11372 * e.g. dead branches. 11373 */ 11374 __mark_reg_unknown(env, dst_reg); 11375 return 0; 11376 } 11377 11378 if (BPF_CLASS(insn->code) != BPF_ALU64) { 11379 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 11380 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 11381 __mark_reg_unknown(env, dst_reg); 11382 return 0; 11383 } 11384 11385 verbose(env, 11386 "R%d 32-bit pointer arithmetic prohibited\n", 11387 dst); 11388 return -EACCES; 11389 } 11390 11391 if (ptr_reg->type & PTR_MAYBE_NULL) { 11392 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 11393 dst, reg_type_str(env, ptr_reg->type)); 11394 return -EACCES; 11395 } 11396 11397 switch (base_type(ptr_reg->type)) { 11398 case CONST_PTR_TO_MAP: 11399 /* smin_val represents the known value */ 11400 if (known && smin_val == 0 && opcode == BPF_ADD) 11401 break; 11402 fallthrough; 11403 case PTR_TO_PACKET_END: 11404 case PTR_TO_SOCKET: 11405 case PTR_TO_SOCK_COMMON: 11406 case PTR_TO_TCP_SOCK: 11407 case PTR_TO_XDP_SOCK: 11408 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 11409 dst, reg_type_str(env, ptr_reg->type)); 11410 return -EACCES; 11411 default: 11412 break; 11413 } 11414 11415 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 11416 * The id may be overwritten later if we create a new variable offset. 11417 */ 11418 dst_reg->type = ptr_reg->type; 11419 dst_reg->id = ptr_reg->id; 11420 11421 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 11422 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 11423 return -EINVAL; 11424 11425 /* pointer types do not carry 32-bit bounds at the moment. */ 11426 __mark_reg32_unbounded(dst_reg); 11427 11428 if (sanitize_needed(opcode)) { 11429 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 11430 &info, false); 11431 if (ret < 0) 11432 return sanitize_err(env, insn, ret, off_reg, dst_reg); 11433 } 11434 11435 switch (opcode) { 11436 case BPF_ADD: 11437 /* We can take a fixed offset as long as it doesn't overflow 11438 * the s32 'off' field 11439 */ 11440 if (known && (ptr_reg->off + smin_val == 11441 (s64)(s32)(ptr_reg->off + smin_val))) { 11442 /* pointer += K. Accumulate it into fixed offset */ 11443 dst_reg->smin_value = smin_ptr; 11444 dst_reg->smax_value = smax_ptr; 11445 dst_reg->umin_value = umin_ptr; 11446 dst_reg->umax_value = umax_ptr; 11447 dst_reg->var_off = ptr_reg->var_off; 11448 dst_reg->off = ptr_reg->off + smin_val; 11449 dst_reg->raw = ptr_reg->raw; 11450 break; 11451 } 11452 /* A new variable offset is created. Note that off_reg->off 11453 * == 0, since it's a scalar. 11454 * dst_reg gets the pointer type and since some positive 11455 * integer value was added to the pointer, give it a new 'id' 11456 * if it's a PTR_TO_PACKET. 11457 * this creates a new 'base' pointer, off_reg (variable) gets 11458 * added into the variable offset, and we copy the fixed offset 11459 * from ptr_reg. 11460 */ 11461 if (signed_add_overflows(smin_ptr, smin_val) || 11462 signed_add_overflows(smax_ptr, smax_val)) { 11463 dst_reg->smin_value = S64_MIN; 11464 dst_reg->smax_value = S64_MAX; 11465 } else { 11466 dst_reg->smin_value = smin_ptr + smin_val; 11467 dst_reg->smax_value = smax_ptr + smax_val; 11468 } 11469 if (umin_ptr + umin_val < umin_ptr || 11470 umax_ptr + umax_val < umax_ptr) { 11471 dst_reg->umin_value = 0; 11472 dst_reg->umax_value = U64_MAX; 11473 } else { 11474 dst_reg->umin_value = umin_ptr + umin_val; 11475 dst_reg->umax_value = umax_ptr + umax_val; 11476 } 11477 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 11478 dst_reg->off = ptr_reg->off; 11479 dst_reg->raw = ptr_reg->raw; 11480 if (reg_is_pkt_pointer(ptr_reg)) { 11481 dst_reg->id = ++env->id_gen; 11482 /* something was added to pkt_ptr, set range to zero */ 11483 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 11484 } 11485 break; 11486 case BPF_SUB: 11487 if (dst_reg == off_reg) { 11488 /* scalar -= pointer. Creates an unknown scalar */ 11489 verbose(env, "R%d tried to subtract pointer from scalar\n", 11490 dst); 11491 return -EACCES; 11492 } 11493 /* We don't allow subtraction from FP, because (according to 11494 * test_verifier.c test "invalid fp arithmetic", JITs might not 11495 * be able to deal with it. 11496 */ 11497 if (ptr_reg->type == PTR_TO_STACK) { 11498 verbose(env, "R%d subtraction from stack pointer prohibited\n", 11499 dst); 11500 return -EACCES; 11501 } 11502 if (known && (ptr_reg->off - smin_val == 11503 (s64)(s32)(ptr_reg->off - smin_val))) { 11504 /* pointer -= K. Subtract it from fixed offset */ 11505 dst_reg->smin_value = smin_ptr; 11506 dst_reg->smax_value = smax_ptr; 11507 dst_reg->umin_value = umin_ptr; 11508 dst_reg->umax_value = umax_ptr; 11509 dst_reg->var_off = ptr_reg->var_off; 11510 dst_reg->id = ptr_reg->id; 11511 dst_reg->off = ptr_reg->off - smin_val; 11512 dst_reg->raw = ptr_reg->raw; 11513 break; 11514 } 11515 /* A new variable offset is created. If the subtrahend is known 11516 * nonnegative, then any reg->range we had before is still good. 11517 */ 11518 if (signed_sub_overflows(smin_ptr, smax_val) || 11519 signed_sub_overflows(smax_ptr, smin_val)) { 11520 /* Overflow possible, we know nothing */ 11521 dst_reg->smin_value = S64_MIN; 11522 dst_reg->smax_value = S64_MAX; 11523 } else { 11524 dst_reg->smin_value = smin_ptr - smax_val; 11525 dst_reg->smax_value = smax_ptr - smin_val; 11526 } 11527 if (umin_ptr < umax_val) { 11528 /* Overflow possible, we know nothing */ 11529 dst_reg->umin_value = 0; 11530 dst_reg->umax_value = U64_MAX; 11531 } else { 11532 /* Cannot overflow (as long as bounds are consistent) */ 11533 dst_reg->umin_value = umin_ptr - umax_val; 11534 dst_reg->umax_value = umax_ptr - umin_val; 11535 } 11536 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 11537 dst_reg->off = ptr_reg->off; 11538 dst_reg->raw = ptr_reg->raw; 11539 if (reg_is_pkt_pointer(ptr_reg)) { 11540 dst_reg->id = ++env->id_gen; 11541 /* something was added to pkt_ptr, set range to zero */ 11542 if (smin_val < 0) 11543 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 11544 } 11545 break; 11546 case BPF_AND: 11547 case BPF_OR: 11548 case BPF_XOR: 11549 /* bitwise ops on pointers are troublesome, prohibit. */ 11550 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 11551 dst, bpf_alu_string[opcode >> 4]); 11552 return -EACCES; 11553 default: 11554 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 11555 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 11556 dst, bpf_alu_string[opcode >> 4]); 11557 return -EACCES; 11558 } 11559 11560 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 11561 return -EINVAL; 11562 reg_bounds_sync(dst_reg); 11563 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 11564 return -EACCES; 11565 if (sanitize_needed(opcode)) { 11566 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 11567 &info, true); 11568 if (ret < 0) 11569 return sanitize_err(env, insn, ret, off_reg, dst_reg); 11570 } 11571 11572 return 0; 11573 } 11574 11575 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 11576 struct bpf_reg_state *src_reg) 11577 { 11578 s32 smin_val = src_reg->s32_min_value; 11579 s32 smax_val = src_reg->s32_max_value; 11580 u32 umin_val = src_reg->u32_min_value; 11581 u32 umax_val = src_reg->u32_max_value; 11582 11583 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 11584 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 11585 dst_reg->s32_min_value = S32_MIN; 11586 dst_reg->s32_max_value = S32_MAX; 11587 } else { 11588 dst_reg->s32_min_value += smin_val; 11589 dst_reg->s32_max_value += smax_val; 11590 } 11591 if (dst_reg->u32_min_value + umin_val < umin_val || 11592 dst_reg->u32_max_value + umax_val < umax_val) { 11593 dst_reg->u32_min_value = 0; 11594 dst_reg->u32_max_value = U32_MAX; 11595 } else { 11596 dst_reg->u32_min_value += umin_val; 11597 dst_reg->u32_max_value += umax_val; 11598 } 11599 } 11600 11601 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 11602 struct bpf_reg_state *src_reg) 11603 { 11604 s64 smin_val = src_reg->smin_value; 11605 s64 smax_val = src_reg->smax_value; 11606 u64 umin_val = src_reg->umin_value; 11607 u64 umax_val = src_reg->umax_value; 11608 11609 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 11610 signed_add_overflows(dst_reg->smax_value, smax_val)) { 11611 dst_reg->smin_value = S64_MIN; 11612 dst_reg->smax_value = S64_MAX; 11613 } else { 11614 dst_reg->smin_value += smin_val; 11615 dst_reg->smax_value += smax_val; 11616 } 11617 if (dst_reg->umin_value + umin_val < umin_val || 11618 dst_reg->umax_value + umax_val < umax_val) { 11619 dst_reg->umin_value = 0; 11620 dst_reg->umax_value = U64_MAX; 11621 } else { 11622 dst_reg->umin_value += umin_val; 11623 dst_reg->umax_value += umax_val; 11624 } 11625 } 11626 11627 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 11628 struct bpf_reg_state *src_reg) 11629 { 11630 s32 smin_val = src_reg->s32_min_value; 11631 s32 smax_val = src_reg->s32_max_value; 11632 u32 umin_val = src_reg->u32_min_value; 11633 u32 umax_val = src_reg->u32_max_value; 11634 11635 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 11636 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 11637 /* Overflow possible, we know nothing */ 11638 dst_reg->s32_min_value = S32_MIN; 11639 dst_reg->s32_max_value = S32_MAX; 11640 } else { 11641 dst_reg->s32_min_value -= smax_val; 11642 dst_reg->s32_max_value -= smin_val; 11643 } 11644 if (dst_reg->u32_min_value < umax_val) { 11645 /* Overflow possible, we know nothing */ 11646 dst_reg->u32_min_value = 0; 11647 dst_reg->u32_max_value = U32_MAX; 11648 } else { 11649 /* Cannot overflow (as long as bounds are consistent) */ 11650 dst_reg->u32_min_value -= umax_val; 11651 dst_reg->u32_max_value -= umin_val; 11652 } 11653 } 11654 11655 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 11656 struct bpf_reg_state *src_reg) 11657 { 11658 s64 smin_val = src_reg->smin_value; 11659 s64 smax_val = src_reg->smax_value; 11660 u64 umin_val = src_reg->umin_value; 11661 u64 umax_val = src_reg->umax_value; 11662 11663 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 11664 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 11665 /* Overflow possible, we know nothing */ 11666 dst_reg->smin_value = S64_MIN; 11667 dst_reg->smax_value = S64_MAX; 11668 } else { 11669 dst_reg->smin_value -= smax_val; 11670 dst_reg->smax_value -= smin_val; 11671 } 11672 if (dst_reg->umin_value < umax_val) { 11673 /* Overflow possible, we know nothing */ 11674 dst_reg->umin_value = 0; 11675 dst_reg->umax_value = U64_MAX; 11676 } else { 11677 /* Cannot overflow (as long as bounds are consistent) */ 11678 dst_reg->umin_value -= umax_val; 11679 dst_reg->umax_value -= umin_val; 11680 } 11681 } 11682 11683 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 11684 struct bpf_reg_state *src_reg) 11685 { 11686 s32 smin_val = src_reg->s32_min_value; 11687 u32 umin_val = src_reg->u32_min_value; 11688 u32 umax_val = src_reg->u32_max_value; 11689 11690 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 11691 /* Ain't nobody got time to multiply that sign */ 11692 __mark_reg32_unbounded(dst_reg); 11693 return; 11694 } 11695 /* Both values are positive, so we can work with unsigned and 11696 * copy the result to signed (unless it exceeds S32_MAX). 11697 */ 11698 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 11699 /* Potential overflow, we know nothing */ 11700 __mark_reg32_unbounded(dst_reg); 11701 return; 11702 } 11703 dst_reg->u32_min_value *= umin_val; 11704 dst_reg->u32_max_value *= umax_val; 11705 if (dst_reg->u32_max_value > S32_MAX) { 11706 /* Overflow possible, we know nothing */ 11707 dst_reg->s32_min_value = S32_MIN; 11708 dst_reg->s32_max_value = S32_MAX; 11709 } else { 11710 dst_reg->s32_min_value = dst_reg->u32_min_value; 11711 dst_reg->s32_max_value = dst_reg->u32_max_value; 11712 } 11713 } 11714 11715 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 11716 struct bpf_reg_state *src_reg) 11717 { 11718 s64 smin_val = src_reg->smin_value; 11719 u64 umin_val = src_reg->umin_value; 11720 u64 umax_val = src_reg->umax_value; 11721 11722 if (smin_val < 0 || dst_reg->smin_value < 0) { 11723 /* Ain't nobody got time to multiply that sign */ 11724 __mark_reg64_unbounded(dst_reg); 11725 return; 11726 } 11727 /* Both values are positive, so we can work with unsigned and 11728 * copy the result to signed (unless it exceeds S64_MAX). 11729 */ 11730 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 11731 /* Potential overflow, we know nothing */ 11732 __mark_reg64_unbounded(dst_reg); 11733 return; 11734 } 11735 dst_reg->umin_value *= umin_val; 11736 dst_reg->umax_value *= umax_val; 11737 if (dst_reg->umax_value > S64_MAX) { 11738 /* Overflow possible, we know nothing */ 11739 dst_reg->smin_value = S64_MIN; 11740 dst_reg->smax_value = S64_MAX; 11741 } else { 11742 dst_reg->smin_value = dst_reg->umin_value; 11743 dst_reg->smax_value = dst_reg->umax_value; 11744 } 11745 } 11746 11747 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 11748 struct bpf_reg_state *src_reg) 11749 { 11750 bool src_known = tnum_subreg_is_const(src_reg->var_off); 11751 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 11752 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 11753 s32 smin_val = src_reg->s32_min_value; 11754 u32 umax_val = src_reg->u32_max_value; 11755 11756 if (src_known && dst_known) { 11757 __mark_reg32_known(dst_reg, var32_off.value); 11758 return; 11759 } 11760 11761 /* We get our minimum from the var_off, since that's inherently 11762 * bitwise. Our maximum is the minimum of the operands' maxima. 11763 */ 11764 dst_reg->u32_min_value = var32_off.value; 11765 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 11766 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 11767 /* Lose signed bounds when ANDing negative numbers, 11768 * ain't nobody got time for that. 11769 */ 11770 dst_reg->s32_min_value = S32_MIN; 11771 dst_reg->s32_max_value = S32_MAX; 11772 } else { 11773 /* ANDing two positives gives a positive, so safe to 11774 * cast result into s64. 11775 */ 11776 dst_reg->s32_min_value = dst_reg->u32_min_value; 11777 dst_reg->s32_max_value = dst_reg->u32_max_value; 11778 } 11779 } 11780 11781 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 11782 struct bpf_reg_state *src_reg) 11783 { 11784 bool src_known = tnum_is_const(src_reg->var_off); 11785 bool dst_known = tnum_is_const(dst_reg->var_off); 11786 s64 smin_val = src_reg->smin_value; 11787 u64 umax_val = src_reg->umax_value; 11788 11789 if (src_known && dst_known) { 11790 __mark_reg_known(dst_reg, dst_reg->var_off.value); 11791 return; 11792 } 11793 11794 /* We get our minimum from the var_off, since that's inherently 11795 * bitwise. Our maximum is the minimum of the operands' maxima. 11796 */ 11797 dst_reg->umin_value = dst_reg->var_off.value; 11798 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 11799 if (dst_reg->smin_value < 0 || smin_val < 0) { 11800 /* Lose signed bounds when ANDing negative numbers, 11801 * ain't nobody got time for that. 11802 */ 11803 dst_reg->smin_value = S64_MIN; 11804 dst_reg->smax_value = S64_MAX; 11805 } else { 11806 /* ANDing two positives gives a positive, so safe to 11807 * cast result into s64. 11808 */ 11809 dst_reg->smin_value = dst_reg->umin_value; 11810 dst_reg->smax_value = dst_reg->umax_value; 11811 } 11812 /* We may learn something more from the var_off */ 11813 __update_reg_bounds(dst_reg); 11814 } 11815 11816 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 11817 struct bpf_reg_state *src_reg) 11818 { 11819 bool src_known = tnum_subreg_is_const(src_reg->var_off); 11820 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 11821 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 11822 s32 smin_val = src_reg->s32_min_value; 11823 u32 umin_val = src_reg->u32_min_value; 11824 11825 if (src_known && dst_known) { 11826 __mark_reg32_known(dst_reg, var32_off.value); 11827 return; 11828 } 11829 11830 /* We get our maximum from the var_off, and our minimum is the 11831 * maximum of the operands' minima 11832 */ 11833 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 11834 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 11835 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 11836 /* Lose signed bounds when ORing negative numbers, 11837 * ain't nobody got time for that. 11838 */ 11839 dst_reg->s32_min_value = S32_MIN; 11840 dst_reg->s32_max_value = S32_MAX; 11841 } else { 11842 /* ORing two positives gives a positive, so safe to 11843 * cast result into s64. 11844 */ 11845 dst_reg->s32_min_value = dst_reg->u32_min_value; 11846 dst_reg->s32_max_value = dst_reg->u32_max_value; 11847 } 11848 } 11849 11850 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 11851 struct bpf_reg_state *src_reg) 11852 { 11853 bool src_known = tnum_is_const(src_reg->var_off); 11854 bool dst_known = tnum_is_const(dst_reg->var_off); 11855 s64 smin_val = src_reg->smin_value; 11856 u64 umin_val = src_reg->umin_value; 11857 11858 if (src_known && dst_known) { 11859 __mark_reg_known(dst_reg, dst_reg->var_off.value); 11860 return; 11861 } 11862 11863 /* We get our maximum from the var_off, and our minimum is the 11864 * maximum of the operands' minima 11865 */ 11866 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 11867 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 11868 if (dst_reg->smin_value < 0 || smin_val < 0) { 11869 /* Lose signed bounds when ORing negative numbers, 11870 * ain't nobody got time for that. 11871 */ 11872 dst_reg->smin_value = S64_MIN; 11873 dst_reg->smax_value = S64_MAX; 11874 } else { 11875 /* ORing two positives gives a positive, so safe to 11876 * cast result into s64. 11877 */ 11878 dst_reg->smin_value = dst_reg->umin_value; 11879 dst_reg->smax_value = dst_reg->umax_value; 11880 } 11881 /* We may learn something more from the var_off */ 11882 __update_reg_bounds(dst_reg); 11883 } 11884 11885 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 11886 struct bpf_reg_state *src_reg) 11887 { 11888 bool src_known = tnum_subreg_is_const(src_reg->var_off); 11889 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 11890 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 11891 s32 smin_val = src_reg->s32_min_value; 11892 11893 if (src_known && dst_known) { 11894 __mark_reg32_known(dst_reg, var32_off.value); 11895 return; 11896 } 11897 11898 /* We get both minimum and maximum from the var32_off. */ 11899 dst_reg->u32_min_value = var32_off.value; 11900 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 11901 11902 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 11903 /* XORing two positive sign numbers gives a positive, 11904 * so safe to cast u32 result into s32. 11905 */ 11906 dst_reg->s32_min_value = dst_reg->u32_min_value; 11907 dst_reg->s32_max_value = dst_reg->u32_max_value; 11908 } else { 11909 dst_reg->s32_min_value = S32_MIN; 11910 dst_reg->s32_max_value = S32_MAX; 11911 } 11912 } 11913 11914 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 11915 struct bpf_reg_state *src_reg) 11916 { 11917 bool src_known = tnum_is_const(src_reg->var_off); 11918 bool dst_known = tnum_is_const(dst_reg->var_off); 11919 s64 smin_val = src_reg->smin_value; 11920 11921 if (src_known && dst_known) { 11922 /* dst_reg->var_off.value has been updated earlier */ 11923 __mark_reg_known(dst_reg, dst_reg->var_off.value); 11924 return; 11925 } 11926 11927 /* We get both minimum and maximum from the var_off. */ 11928 dst_reg->umin_value = dst_reg->var_off.value; 11929 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 11930 11931 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 11932 /* XORing two positive sign numbers gives a positive, 11933 * so safe to cast u64 result into s64. 11934 */ 11935 dst_reg->smin_value = dst_reg->umin_value; 11936 dst_reg->smax_value = dst_reg->umax_value; 11937 } else { 11938 dst_reg->smin_value = S64_MIN; 11939 dst_reg->smax_value = S64_MAX; 11940 } 11941 11942 __update_reg_bounds(dst_reg); 11943 } 11944 11945 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 11946 u64 umin_val, u64 umax_val) 11947 { 11948 /* We lose all sign bit information (except what we can pick 11949 * up from var_off) 11950 */ 11951 dst_reg->s32_min_value = S32_MIN; 11952 dst_reg->s32_max_value = S32_MAX; 11953 /* If we might shift our top bit out, then we know nothing */ 11954 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 11955 dst_reg->u32_min_value = 0; 11956 dst_reg->u32_max_value = U32_MAX; 11957 } else { 11958 dst_reg->u32_min_value <<= umin_val; 11959 dst_reg->u32_max_value <<= umax_val; 11960 } 11961 } 11962 11963 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 11964 struct bpf_reg_state *src_reg) 11965 { 11966 u32 umax_val = src_reg->u32_max_value; 11967 u32 umin_val = src_reg->u32_min_value; 11968 /* u32 alu operation will zext upper bits */ 11969 struct tnum subreg = tnum_subreg(dst_reg->var_off); 11970 11971 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 11972 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 11973 /* Not required but being careful mark reg64 bounds as unknown so 11974 * that we are forced to pick them up from tnum and zext later and 11975 * if some path skips this step we are still safe. 11976 */ 11977 __mark_reg64_unbounded(dst_reg); 11978 __update_reg32_bounds(dst_reg); 11979 } 11980 11981 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 11982 u64 umin_val, u64 umax_val) 11983 { 11984 /* Special case <<32 because it is a common compiler pattern to sign 11985 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 11986 * positive we know this shift will also be positive so we can track 11987 * bounds correctly. Otherwise we lose all sign bit information except 11988 * what we can pick up from var_off. Perhaps we can generalize this 11989 * later to shifts of any length. 11990 */ 11991 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 11992 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 11993 else 11994 dst_reg->smax_value = S64_MAX; 11995 11996 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 11997 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 11998 else 11999 dst_reg->smin_value = S64_MIN; 12000 12001 /* If we might shift our top bit out, then we know nothing */ 12002 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 12003 dst_reg->umin_value = 0; 12004 dst_reg->umax_value = U64_MAX; 12005 } else { 12006 dst_reg->umin_value <<= umin_val; 12007 dst_reg->umax_value <<= umax_val; 12008 } 12009 } 12010 12011 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 12012 struct bpf_reg_state *src_reg) 12013 { 12014 u64 umax_val = src_reg->umax_value; 12015 u64 umin_val = src_reg->umin_value; 12016 12017 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 12018 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 12019 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 12020 12021 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 12022 /* We may learn something more from the var_off */ 12023 __update_reg_bounds(dst_reg); 12024 } 12025 12026 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 12027 struct bpf_reg_state *src_reg) 12028 { 12029 struct tnum subreg = tnum_subreg(dst_reg->var_off); 12030 u32 umax_val = src_reg->u32_max_value; 12031 u32 umin_val = src_reg->u32_min_value; 12032 12033 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12034 * be negative, then either: 12035 * 1) src_reg might be zero, so the sign bit of the result is 12036 * unknown, so we lose our signed bounds 12037 * 2) it's known negative, thus the unsigned bounds capture the 12038 * signed bounds 12039 * 3) the signed bounds cross zero, so they tell us nothing 12040 * about the result 12041 * If the value in dst_reg is known nonnegative, then again the 12042 * unsigned bounds capture the signed bounds. 12043 * Thus, in all cases it suffices to blow away our signed bounds 12044 * and rely on inferring new ones from the unsigned bounds and 12045 * var_off of the result. 12046 */ 12047 dst_reg->s32_min_value = S32_MIN; 12048 dst_reg->s32_max_value = S32_MAX; 12049 12050 dst_reg->var_off = tnum_rshift(subreg, umin_val); 12051 dst_reg->u32_min_value >>= umax_val; 12052 dst_reg->u32_max_value >>= umin_val; 12053 12054 __mark_reg64_unbounded(dst_reg); 12055 __update_reg32_bounds(dst_reg); 12056 } 12057 12058 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 12059 struct bpf_reg_state *src_reg) 12060 { 12061 u64 umax_val = src_reg->umax_value; 12062 u64 umin_val = src_reg->umin_value; 12063 12064 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 12065 * be negative, then either: 12066 * 1) src_reg might be zero, so the sign bit of the result is 12067 * unknown, so we lose our signed bounds 12068 * 2) it's known negative, thus the unsigned bounds capture the 12069 * signed bounds 12070 * 3) the signed bounds cross zero, so they tell us nothing 12071 * about the result 12072 * If the value in dst_reg is known nonnegative, then again the 12073 * unsigned bounds capture the signed bounds. 12074 * Thus, in all cases it suffices to blow away our signed bounds 12075 * and rely on inferring new ones from the unsigned bounds and 12076 * var_off of the result. 12077 */ 12078 dst_reg->smin_value = S64_MIN; 12079 dst_reg->smax_value = S64_MAX; 12080 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 12081 dst_reg->umin_value >>= umax_val; 12082 dst_reg->umax_value >>= umin_val; 12083 12084 /* Its not easy to operate on alu32 bounds here because it depends 12085 * on bits being shifted in. Take easy way out and mark unbounded 12086 * so we can recalculate later from tnum. 12087 */ 12088 __mark_reg32_unbounded(dst_reg); 12089 __update_reg_bounds(dst_reg); 12090 } 12091 12092 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 12093 struct bpf_reg_state *src_reg) 12094 { 12095 u64 umin_val = src_reg->u32_min_value; 12096 12097 /* Upon reaching here, src_known is true and 12098 * umax_val is equal to umin_val. 12099 */ 12100 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 12101 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 12102 12103 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 12104 12105 /* blow away the dst_reg umin_value/umax_value and rely on 12106 * dst_reg var_off to refine the result. 12107 */ 12108 dst_reg->u32_min_value = 0; 12109 dst_reg->u32_max_value = U32_MAX; 12110 12111 __mark_reg64_unbounded(dst_reg); 12112 __update_reg32_bounds(dst_reg); 12113 } 12114 12115 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 12116 struct bpf_reg_state *src_reg) 12117 { 12118 u64 umin_val = src_reg->umin_value; 12119 12120 /* Upon reaching here, src_known is true and umax_val is equal 12121 * to umin_val. 12122 */ 12123 dst_reg->smin_value >>= umin_val; 12124 dst_reg->smax_value >>= umin_val; 12125 12126 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 12127 12128 /* blow away the dst_reg umin_value/umax_value and rely on 12129 * dst_reg var_off to refine the result. 12130 */ 12131 dst_reg->umin_value = 0; 12132 dst_reg->umax_value = U64_MAX; 12133 12134 /* Its not easy to operate on alu32 bounds here because it depends 12135 * on bits being shifted in from upper 32-bits. Take easy way out 12136 * and mark unbounded so we can recalculate later from tnum. 12137 */ 12138 __mark_reg32_unbounded(dst_reg); 12139 __update_reg_bounds(dst_reg); 12140 } 12141 12142 /* WARNING: This function does calculations on 64-bit values, but the actual 12143 * execution may occur on 32-bit values. Therefore, things like bitshifts 12144 * need extra checks in the 32-bit case. 12145 */ 12146 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 12147 struct bpf_insn *insn, 12148 struct bpf_reg_state *dst_reg, 12149 struct bpf_reg_state src_reg) 12150 { 12151 struct bpf_reg_state *regs = cur_regs(env); 12152 u8 opcode = BPF_OP(insn->code); 12153 bool src_known; 12154 s64 smin_val, smax_val; 12155 u64 umin_val, umax_val; 12156 s32 s32_min_val, s32_max_val; 12157 u32 u32_min_val, u32_max_val; 12158 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 12159 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 12160 int ret; 12161 12162 smin_val = src_reg.smin_value; 12163 smax_val = src_reg.smax_value; 12164 umin_val = src_reg.umin_value; 12165 umax_val = src_reg.umax_value; 12166 12167 s32_min_val = src_reg.s32_min_value; 12168 s32_max_val = src_reg.s32_max_value; 12169 u32_min_val = src_reg.u32_min_value; 12170 u32_max_val = src_reg.u32_max_value; 12171 12172 if (alu32) { 12173 src_known = tnum_subreg_is_const(src_reg.var_off); 12174 if ((src_known && 12175 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 12176 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 12177 /* Taint dst register if offset had invalid bounds 12178 * derived from e.g. dead branches. 12179 */ 12180 __mark_reg_unknown(env, dst_reg); 12181 return 0; 12182 } 12183 } else { 12184 src_known = tnum_is_const(src_reg.var_off); 12185 if ((src_known && 12186 (smin_val != smax_val || umin_val != umax_val)) || 12187 smin_val > smax_val || umin_val > umax_val) { 12188 /* Taint dst register if offset had invalid bounds 12189 * derived from e.g. dead branches. 12190 */ 12191 __mark_reg_unknown(env, dst_reg); 12192 return 0; 12193 } 12194 } 12195 12196 if (!src_known && 12197 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 12198 __mark_reg_unknown(env, dst_reg); 12199 return 0; 12200 } 12201 12202 if (sanitize_needed(opcode)) { 12203 ret = sanitize_val_alu(env, insn); 12204 if (ret < 0) 12205 return sanitize_err(env, insn, ret, NULL, NULL); 12206 } 12207 12208 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 12209 * There are two classes of instructions: The first class we track both 12210 * alu32 and alu64 sign/unsigned bounds independently this provides the 12211 * greatest amount of precision when alu operations are mixed with jmp32 12212 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 12213 * and BPF_OR. This is possible because these ops have fairly easy to 12214 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 12215 * See alu32 verifier tests for examples. The second class of 12216 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 12217 * with regards to tracking sign/unsigned bounds because the bits may 12218 * cross subreg boundaries in the alu64 case. When this happens we mark 12219 * the reg unbounded in the subreg bound space and use the resulting 12220 * tnum to calculate an approximation of the sign/unsigned bounds. 12221 */ 12222 switch (opcode) { 12223 case BPF_ADD: 12224 scalar32_min_max_add(dst_reg, &src_reg); 12225 scalar_min_max_add(dst_reg, &src_reg); 12226 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 12227 break; 12228 case BPF_SUB: 12229 scalar32_min_max_sub(dst_reg, &src_reg); 12230 scalar_min_max_sub(dst_reg, &src_reg); 12231 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 12232 break; 12233 case BPF_MUL: 12234 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 12235 scalar32_min_max_mul(dst_reg, &src_reg); 12236 scalar_min_max_mul(dst_reg, &src_reg); 12237 break; 12238 case BPF_AND: 12239 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 12240 scalar32_min_max_and(dst_reg, &src_reg); 12241 scalar_min_max_and(dst_reg, &src_reg); 12242 break; 12243 case BPF_OR: 12244 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 12245 scalar32_min_max_or(dst_reg, &src_reg); 12246 scalar_min_max_or(dst_reg, &src_reg); 12247 break; 12248 case BPF_XOR: 12249 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 12250 scalar32_min_max_xor(dst_reg, &src_reg); 12251 scalar_min_max_xor(dst_reg, &src_reg); 12252 break; 12253 case BPF_LSH: 12254 if (umax_val >= insn_bitness) { 12255 /* Shifts greater than 31 or 63 are undefined. 12256 * This includes shifts by a negative number. 12257 */ 12258 mark_reg_unknown(env, regs, insn->dst_reg); 12259 break; 12260 } 12261 if (alu32) 12262 scalar32_min_max_lsh(dst_reg, &src_reg); 12263 else 12264 scalar_min_max_lsh(dst_reg, &src_reg); 12265 break; 12266 case BPF_RSH: 12267 if (umax_val >= insn_bitness) { 12268 /* Shifts greater than 31 or 63 are undefined. 12269 * This includes shifts by a negative number. 12270 */ 12271 mark_reg_unknown(env, regs, insn->dst_reg); 12272 break; 12273 } 12274 if (alu32) 12275 scalar32_min_max_rsh(dst_reg, &src_reg); 12276 else 12277 scalar_min_max_rsh(dst_reg, &src_reg); 12278 break; 12279 case BPF_ARSH: 12280 if (umax_val >= insn_bitness) { 12281 /* Shifts greater than 31 or 63 are undefined. 12282 * This includes shifts by a negative number. 12283 */ 12284 mark_reg_unknown(env, regs, insn->dst_reg); 12285 break; 12286 } 12287 if (alu32) 12288 scalar32_min_max_arsh(dst_reg, &src_reg); 12289 else 12290 scalar_min_max_arsh(dst_reg, &src_reg); 12291 break; 12292 default: 12293 mark_reg_unknown(env, regs, insn->dst_reg); 12294 break; 12295 } 12296 12297 /* ALU32 ops are zero extended into 64bit register */ 12298 if (alu32) 12299 zext_32_to_64(dst_reg); 12300 reg_bounds_sync(dst_reg); 12301 return 0; 12302 } 12303 12304 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 12305 * and var_off. 12306 */ 12307 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 12308 struct bpf_insn *insn) 12309 { 12310 struct bpf_verifier_state *vstate = env->cur_state; 12311 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12312 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 12313 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 12314 u8 opcode = BPF_OP(insn->code); 12315 int err; 12316 12317 dst_reg = ®s[insn->dst_reg]; 12318 src_reg = NULL; 12319 if (dst_reg->type != SCALAR_VALUE) 12320 ptr_reg = dst_reg; 12321 else 12322 /* Make sure ID is cleared otherwise dst_reg min/max could be 12323 * incorrectly propagated into other registers by find_equal_scalars() 12324 */ 12325 dst_reg->id = 0; 12326 if (BPF_SRC(insn->code) == BPF_X) { 12327 src_reg = ®s[insn->src_reg]; 12328 if (src_reg->type != SCALAR_VALUE) { 12329 if (dst_reg->type != SCALAR_VALUE) { 12330 /* Combining two pointers by any ALU op yields 12331 * an arbitrary scalar. Disallow all math except 12332 * pointer subtraction 12333 */ 12334 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 12335 mark_reg_unknown(env, regs, insn->dst_reg); 12336 return 0; 12337 } 12338 verbose(env, "R%d pointer %s pointer prohibited\n", 12339 insn->dst_reg, 12340 bpf_alu_string[opcode >> 4]); 12341 return -EACCES; 12342 } else { 12343 /* scalar += pointer 12344 * This is legal, but we have to reverse our 12345 * src/dest handling in computing the range 12346 */ 12347 err = mark_chain_precision(env, insn->dst_reg); 12348 if (err) 12349 return err; 12350 return adjust_ptr_min_max_vals(env, insn, 12351 src_reg, dst_reg); 12352 } 12353 } else if (ptr_reg) { 12354 /* pointer += scalar */ 12355 err = mark_chain_precision(env, insn->src_reg); 12356 if (err) 12357 return err; 12358 return adjust_ptr_min_max_vals(env, insn, 12359 dst_reg, src_reg); 12360 } else if (dst_reg->precise) { 12361 /* if dst_reg is precise, src_reg should be precise as well */ 12362 err = mark_chain_precision(env, insn->src_reg); 12363 if (err) 12364 return err; 12365 } 12366 } else { 12367 /* Pretend the src is a reg with a known value, since we only 12368 * need to be able to read from this state. 12369 */ 12370 off_reg.type = SCALAR_VALUE; 12371 __mark_reg_known(&off_reg, insn->imm); 12372 src_reg = &off_reg; 12373 if (ptr_reg) /* pointer += K */ 12374 return adjust_ptr_min_max_vals(env, insn, 12375 ptr_reg, src_reg); 12376 } 12377 12378 /* Got here implies adding two SCALAR_VALUEs */ 12379 if (WARN_ON_ONCE(ptr_reg)) { 12380 print_verifier_state(env, state, true); 12381 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 12382 return -EINVAL; 12383 } 12384 if (WARN_ON(!src_reg)) { 12385 print_verifier_state(env, state, true); 12386 verbose(env, "verifier internal error: no src_reg\n"); 12387 return -EINVAL; 12388 } 12389 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 12390 } 12391 12392 /* check validity of 32-bit and 64-bit arithmetic operations */ 12393 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 12394 { 12395 struct bpf_reg_state *regs = cur_regs(env); 12396 u8 opcode = BPF_OP(insn->code); 12397 int err; 12398 12399 if (opcode == BPF_END || opcode == BPF_NEG) { 12400 if (opcode == BPF_NEG) { 12401 if (BPF_SRC(insn->code) != BPF_K || 12402 insn->src_reg != BPF_REG_0 || 12403 insn->off != 0 || insn->imm != 0) { 12404 verbose(env, "BPF_NEG uses reserved fields\n"); 12405 return -EINVAL; 12406 } 12407 } else { 12408 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 12409 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 12410 BPF_CLASS(insn->code) == BPF_ALU64) { 12411 verbose(env, "BPF_END uses reserved fields\n"); 12412 return -EINVAL; 12413 } 12414 } 12415 12416 /* check src operand */ 12417 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 12418 if (err) 12419 return err; 12420 12421 if (is_pointer_value(env, insn->dst_reg)) { 12422 verbose(env, "R%d pointer arithmetic prohibited\n", 12423 insn->dst_reg); 12424 return -EACCES; 12425 } 12426 12427 /* check dest operand */ 12428 err = check_reg_arg(env, insn->dst_reg, DST_OP); 12429 if (err) 12430 return err; 12431 12432 } else if (opcode == BPF_MOV) { 12433 12434 if (BPF_SRC(insn->code) == BPF_X) { 12435 if (insn->imm != 0 || insn->off != 0) { 12436 verbose(env, "BPF_MOV uses reserved fields\n"); 12437 return -EINVAL; 12438 } 12439 12440 /* check src operand */ 12441 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12442 if (err) 12443 return err; 12444 } else { 12445 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 12446 verbose(env, "BPF_MOV uses reserved fields\n"); 12447 return -EINVAL; 12448 } 12449 } 12450 12451 /* check dest operand, mark as required later */ 12452 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 12453 if (err) 12454 return err; 12455 12456 if (BPF_SRC(insn->code) == BPF_X) { 12457 struct bpf_reg_state *src_reg = regs + insn->src_reg; 12458 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 12459 12460 if (BPF_CLASS(insn->code) == BPF_ALU64) { 12461 /* case: R1 = R2 12462 * copy register state to dest reg 12463 */ 12464 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 12465 /* Assign src and dst registers the same ID 12466 * that will be used by find_equal_scalars() 12467 * to propagate min/max range. 12468 */ 12469 src_reg->id = ++env->id_gen; 12470 copy_register_state(dst_reg, src_reg); 12471 dst_reg->live |= REG_LIVE_WRITTEN; 12472 dst_reg->subreg_def = DEF_NOT_SUBREG; 12473 } else { 12474 /* R1 = (u32) R2 */ 12475 if (is_pointer_value(env, insn->src_reg)) { 12476 verbose(env, 12477 "R%d partial copy of pointer\n", 12478 insn->src_reg); 12479 return -EACCES; 12480 } else if (src_reg->type == SCALAR_VALUE) { 12481 copy_register_state(dst_reg, src_reg); 12482 /* Make sure ID is cleared otherwise 12483 * dst_reg min/max could be incorrectly 12484 * propagated into src_reg by find_equal_scalars() 12485 */ 12486 dst_reg->id = 0; 12487 dst_reg->live |= REG_LIVE_WRITTEN; 12488 dst_reg->subreg_def = env->insn_idx + 1; 12489 } else { 12490 mark_reg_unknown(env, regs, 12491 insn->dst_reg); 12492 } 12493 zext_32_to_64(dst_reg); 12494 reg_bounds_sync(dst_reg); 12495 } 12496 } else { 12497 /* case: R = imm 12498 * remember the value we stored into this reg 12499 */ 12500 /* clear any state __mark_reg_known doesn't set */ 12501 mark_reg_unknown(env, regs, insn->dst_reg); 12502 regs[insn->dst_reg].type = SCALAR_VALUE; 12503 if (BPF_CLASS(insn->code) == BPF_ALU64) { 12504 __mark_reg_known(regs + insn->dst_reg, 12505 insn->imm); 12506 } else { 12507 __mark_reg_known(regs + insn->dst_reg, 12508 (u32)insn->imm); 12509 } 12510 } 12511 12512 } else if (opcode > BPF_END) { 12513 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 12514 return -EINVAL; 12515 12516 } else { /* all other ALU ops: and, sub, xor, add, ... */ 12517 12518 if (BPF_SRC(insn->code) == BPF_X) { 12519 if (insn->imm != 0 || insn->off != 0) { 12520 verbose(env, "BPF_ALU uses reserved fields\n"); 12521 return -EINVAL; 12522 } 12523 /* check src1 operand */ 12524 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12525 if (err) 12526 return err; 12527 } else { 12528 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 12529 verbose(env, "BPF_ALU uses reserved fields\n"); 12530 return -EINVAL; 12531 } 12532 } 12533 12534 /* check src2 operand */ 12535 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 12536 if (err) 12537 return err; 12538 12539 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 12540 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 12541 verbose(env, "div by zero\n"); 12542 return -EINVAL; 12543 } 12544 12545 if ((opcode == BPF_LSH || opcode == BPF_RSH || 12546 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 12547 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 12548 12549 if (insn->imm < 0 || insn->imm >= size) { 12550 verbose(env, "invalid shift %d\n", insn->imm); 12551 return -EINVAL; 12552 } 12553 } 12554 12555 /* check dest operand */ 12556 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 12557 if (err) 12558 return err; 12559 12560 return adjust_reg_min_max_vals(env, insn); 12561 } 12562 12563 return 0; 12564 } 12565 12566 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 12567 struct bpf_reg_state *dst_reg, 12568 enum bpf_reg_type type, 12569 bool range_right_open) 12570 { 12571 struct bpf_func_state *state; 12572 struct bpf_reg_state *reg; 12573 int new_range; 12574 12575 if (dst_reg->off < 0 || 12576 (dst_reg->off == 0 && range_right_open)) 12577 /* This doesn't give us any range */ 12578 return; 12579 12580 if (dst_reg->umax_value > MAX_PACKET_OFF || 12581 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 12582 /* Risk of overflow. For instance, ptr + (1<<63) may be less 12583 * than pkt_end, but that's because it's also less than pkt. 12584 */ 12585 return; 12586 12587 new_range = dst_reg->off; 12588 if (range_right_open) 12589 new_range++; 12590 12591 /* Examples for register markings: 12592 * 12593 * pkt_data in dst register: 12594 * 12595 * r2 = r3; 12596 * r2 += 8; 12597 * if (r2 > pkt_end) goto <handle exception> 12598 * <access okay> 12599 * 12600 * r2 = r3; 12601 * r2 += 8; 12602 * if (r2 < pkt_end) goto <access okay> 12603 * <handle exception> 12604 * 12605 * Where: 12606 * r2 == dst_reg, pkt_end == src_reg 12607 * r2=pkt(id=n,off=8,r=0) 12608 * r3=pkt(id=n,off=0,r=0) 12609 * 12610 * pkt_data in src register: 12611 * 12612 * r2 = r3; 12613 * r2 += 8; 12614 * if (pkt_end >= r2) goto <access okay> 12615 * <handle exception> 12616 * 12617 * r2 = r3; 12618 * r2 += 8; 12619 * if (pkt_end <= r2) goto <handle exception> 12620 * <access okay> 12621 * 12622 * Where: 12623 * pkt_end == dst_reg, r2 == src_reg 12624 * r2=pkt(id=n,off=8,r=0) 12625 * r3=pkt(id=n,off=0,r=0) 12626 * 12627 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 12628 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 12629 * and [r3, r3 + 8-1) respectively is safe to access depending on 12630 * the check. 12631 */ 12632 12633 /* If our ids match, then we must have the same max_value. And we 12634 * don't care about the other reg's fixed offset, since if it's too big 12635 * the range won't allow anything. 12636 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 12637 */ 12638 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 12639 if (reg->type == type && reg->id == dst_reg->id) 12640 /* keep the maximum range already checked */ 12641 reg->range = max(reg->range, new_range); 12642 })); 12643 } 12644 12645 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 12646 { 12647 struct tnum subreg = tnum_subreg(reg->var_off); 12648 s32 sval = (s32)val; 12649 12650 switch (opcode) { 12651 case BPF_JEQ: 12652 if (tnum_is_const(subreg)) 12653 return !!tnum_equals_const(subreg, val); 12654 break; 12655 case BPF_JNE: 12656 if (tnum_is_const(subreg)) 12657 return !tnum_equals_const(subreg, val); 12658 break; 12659 case BPF_JSET: 12660 if ((~subreg.mask & subreg.value) & val) 12661 return 1; 12662 if (!((subreg.mask | subreg.value) & val)) 12663 return 0; 12664 break; 12665 case BPF_JGT: 12666 if (reg->u32_min_value > val) 12667 return 1; 12668 else if (reg->u32_max_value <= val) 12669 return 0; 12670 break; 12671 case BPF_JSGT: 12672 if (reg->s32_min_value > sval) 12673 return 1; 12674 else if (reg->s32_max_value <= sval) 12675 return 0; 12676 break; 12677 case BPF_JLT: 12678 if (reg->u32_max_value < val) 12679 return 1; 12680 else if (reg->u32_min_value >= val) 12681 return 0; 12682 break; 12683 case BPF_JSLT: 12684 if (reg->s32_max_value < sval) 12685 return 1; 12686 else if (reg->s32_min_value >= sval) 12687 return 0; 12688 break; 12689 case BPF_JGE: 12690 if (reg->u32_min_value >= val) 12691 return 1; 12692 else if (reg->u32_max_value < val) 12693 return 0; 12694 break; 12695 case BPF_JSGE: 12696 if (reg->s32_min_value >= sval) 12697 return 1; 12698 else if (reg->s32_max_value < sval) 12699 return 0; 12700 break; 12701 case BPF_JLE: 12702 if (reg->u32_max_value <= val) 12703 return 1; 12704 else if (reg->u32_min_value > val) 12705 return 0; 12706 break; 12707 case BPF_JSLE: 12708 if (reg->s32_max_value <= sval) 12709 return 1; 12710 else if (reg->s32_min_value > sval) 12711 return 0; 12712 break; 12713 } 12714 12715 return -1; 12716 } 12717 12718 12719 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 12720 { 12721 s64 sval = (s64)val; 12722 12723 switch (opcode) { 12724 case BPF_JEQ: 12725 if (tnum_is_const(reg->var_off)) 12726 return !!tnum_equals_const(reg->var_off, val); 12727 break; 12728 case BPF_JNE: 12729 if (tnum_is_const(reg->var_off)) 12730 return !tnum_equals_const(reg->var_off, val); 12731 break; 12732 case BPF_JSET: 12733 if ((~reg->var_off.mask & reg->var_off.value) & val) 12734 return 1; 12735 if (!((reg->var_off.mask | reg->var_off.value) & val)) 12736 return 0; 12737 break; 12738 case BPF_JGT: 12739 if (reg->umin_value > val) 12740 return 1; 12741 else if (reg->umax_value <= val) 12742 return 0; 12743 break; 12744 case BPF_JSGT: 12745 if (reg->smin_value > sval) 12746 return 1; 12747 else if (reg->smax_value <= sval) 12748 return 0; 12749 break; 12750 case BPF_JLT: 12751 if (reg->umax_value < val) 12752 return 1; 12753 else if (reg->umin_value >= val) 12754 return 0; 12755 break; 12756 case BPF_JSLT: 12757 if (reg->smax_value < sval) 12758 return 1; 12759 else if (reg->smin_value >= sval) 12760 return 0; 12761 break; 12762 case BPF_JGE: 12763 if (reg->umin_value >= val) 12764 return 1; 12765 else if (reg->umax_value < val) 12766 return 0; 12767 break; 12768 case BPF_JSGE: 12769 if (reg->smin_value >= sval) 12770 return 1; 12771 else if (reg->smax_value < sval) 12772 return 0; 12773 break; 12774 case BPF_JLE: 12775 if (reg->umax_value <= val) 12776 return 1; 12777 else if (reg->umin_value > val) 12778 return 0; 12779 break; 12780 case BPF_JSLE: 12781 if (reg->smax_value <= sval) 12782 return 1; 12783 else if (reg->smin_value > sval) 12784 return 0; 12785 break; 12786 } 12787 12788 return -1; 12789 } 12790 12791 /* compute branch direction of the expression "if (reg opcode val) goto target;" 12792 * and return: 12793 * 1 - branch will be taken and "goto target" will be executed 12794 * 0 - branch will not be taken and fall-through to next insn 12795 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 12796 * range [0,10] 12797 */ 12798 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 12799 bool is_jmp32) 12800 { 12801 if (__is_pointer_value(false, reg)) { 12802 if (!reg_type_not_null(reg->type)) 12803 return -1; 12804 12805 /* If pointer is valid tests against zero will fail so we can 12806 * use this to direct branch taken. 12807 */ 12808 if (val != 0) 12809 return -1; 12810 12811 switch (opcode) { 12812 case BPF_JEQ: 12813 return 0; 12814 case BPF_JNE: 12815 return 1; 12816 default: 12817 return -1; 12818 } 12819 } 12820 12821 if (is_jmp32) 12822 return is_branch32_taken(reg, val, opcode); 12823 return is_branch64_taken(reg, val, opcode); 12824 } 12825 12826 static int flip_opcode(u32 opcode) 12827 { 12828 /* How can we transform "a <op> b" into "b <op> a"? */ 12829 static const u8 opcode_flip[16] = { 12830 /* these stay the same */ 12831 [BPF_JEQ >> 4] = BPF_JEQ, 12832 [BPF_JNE >> 4] = BPF_JNE, 12833 [BPF_JSET >> 4] = BPF_JSET, 12834 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 12835 [BPF_JGE >> 4] = BPF_JLE, 12836 [BPF_JGT >> 4] = BPF_JLT, 12837 [BPF_JLE >> 4] = BPF_JGE, 12838 [BPF_JLT >> 4] = BPF_JGT, 12839 [BPF_JSGE >> 4] = BPF_JSLE, 12840 [BPF_JSGT >> 4] = BPF_JSLT, 12841 [BPF_JSLE >> 4] = BPF_JSGE, 12842 [BPF_JSLT >> 4] = BPF_JSGT 12843 }; 12844 return opcode_flip[opcode >> 4]; 12845 } 12846 12847 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 12848 struct bpf_reg_state *src_reg, 12849 u8 opcode) 12850 { 12851 struct bpf_reg_state *pkt; 12852 12853 if (src_reg->type == PTR_TO_PACKET_END) { 12854 pkt = dst_reg; 12855 } else if (dst_reg->type == PTR_TO_PACKET_END) { 12856 pkt = src_reg; 12857 opcode = flip_opcode(opcode); 12858 } else { 12859 return -1; 12860 } 12861 12862 if (pkt->range >= 0) 12863 return -1; 12864 12865 switch (opcode) { 12866 case BPF_JLE: 12867 /* pkt <= pkt_end */ 12868 fallthrough; 12869 case BPF_JGT: 12870 /* pkt > pkt_end */ 12871 if (pkt->range == BEYOND_PKT_END) 12872 /* pkt has at last one extra byte beyond pkt_end */ 12873 return opcode == BPF_JGT; 12874 break; 12875 case BPF_JLT: 12876 /* pkt < pkt_end */ 12877 fallthrough; 12878 case BPF_JGE: 12879 /* pkt >= pkt_end */ 12880 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 12881 return opcode == BPF_JGE; 12882 break; 12883 } 12884 return -1; 12885 } 12886 12887 /* Adjusts the register min/max values in the case that the dst_reg is the 12888 * variable register that we are working on, and src_reg is a constant or we're 12889 * simply doing a BPF_K check. 12890 * In JEQ/JNE cases we also adjust the var_off values. 12891 */ 12892 static void reg_set_min_max(struct bpf_reg_state *true_reg, 12893 struct bpf_reg_state *false_reg, 12894 u64 val, u32 val32, 12895 u8 opcode, bool is_jmp32) 12896 { 12897 struct tnum false_32off = tnum_subreg(false_reg->var_off); 12898 struct tnum false_64off = false_reg->var_off; 12899 struct tnum true_32off = tnum_subreg(true_reg->var_off); 12900 struct tnum true_64off = true_reg->var_off; 12901 s64 sval = (s64)val; 12902 s32 sval32 = (s32)val32; 12903 12904 /* If the dst_reg is a pointer, we can't learn anything about its 12905 * variable offset from the compare (unless src_reg were a pointer into 12906 * the same object, but we don't bother with that. 12907 * Since false_reg and true_reg have the same type by construction, we 12908 * only need to check one of them for pointerness. 12909 */ 12910 if (__is_pointer_value(false, false_reg)) 12911 return; 12912 12913 switch (opcode) { 12914 /* JEQ/JNE comparison doesn't change the register equivalence. 12915 * 12916 * r1 = r2; 12917 * if (r1 == 42) goto label; 12918 * ... 12919 * label: // here both r1 and r2 are known to be 42. 12920 * 12921 * Hence when marking register as known preserve it's ID. 12922 */ 12923 case BPF_JEQ: 12924 if (is_jmp32) { 12925 __mark_reg32_known(true_reg, val32); 12926 true_32off = tnum_subreg(true_reg->var_off); 12927 } else { 12928 ___mark_reg_known(true_reg, val); 12929 true_64off = true_reg->var_off; 12930 } 12931 break; 12932 case BPF_JNE: 12933 if (is_jmp32) { 12934 __mark_reg32_known(false_reg, val32); 12935 false_32off = tnum_subreg(false_reg->var_off); 12936 } else { 12937 ___mark_reg_known(false_reg, val); 12938 false_64off = false_reg->var_off; 12939 } 12940 break; 12941 case BPF_JSET: 12942 if (is_jmp32) { 12943 false_32off = tnum_and(false_32off, tnum_const(~val32)); 12944 if (is_power_of_2(val32)) 12945 true_32off = tnum_or(true_32off, 12946 tnum_const(val32)); 12947 } else { 12948 false_64off = tnum_and(false_64off, tnum_const(~val)); 12949 if (is_power_of_2(val)) 12950 true_64off = tnum_or(true_64off, 12951 tnum_const(val)); 12952 } 12953 break; 12954 case BPF_JGE: 12955 case BPF_JGT: 12956 { 12957 if (is_jmp32) { 12958 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 12959 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 12960 12961 false_reg->u32_max_value = min(false_reg->u32_max_value, 12962 false_umax); 12963 true_reg->u32_min_value = max(true_reg->u32_min_value, 12964 true_umin); 12965 } else { 12966 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 12967 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 12968 12969 false_reg->umax_value = min(false_reg->umax_value, false_umax); 12970 true_reg->umin_value = max(true_reg->umin_value, true_umin); 12971 } 12972 break; 12973 } 12974 case BPF_JSGE: 12975 case BPF_JSGT: 12976 { 12977 if (is_jmp32) { 12978 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 12979 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 12980 12981 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 12982 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 12983 } else { 12984 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 12985 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 12986 12987 false_reg->smax_value = min(false_reg->smax_value, false_smax); 12988 true_reg->smin_value = max(true_reg->smin_value, true_smin); 12989 } 12990 break; 12991 } 12992 case BPF_JLE: 12993 case BPF_JLT: 12994 { 12995 if (is_jmp32) { 12996 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 12997 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 12998 12999 false_reg->u32_min_value = max(false_reg->u32_min_value, 13000 false_umin); 13001 true_reg->u32_max_value = min(true_reg->u32_max_value, 13002 true_umax); 13003 } else { 13004 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 13005 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 13006 13007 false_reg->umin_value = max(false_reg->umin_value, false_umin); 13008 true_reg->umax_value = min(true_reg->umax_value, true_umax); 13009 } 13010 break; 13011 } 13012 case BPF_JSLE: 13013 case BPF_JSLT: 13014 { 13015 if (is_jmp32) { 13016 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 13017 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 13018 13019 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 13020 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 13021 } else { 13022 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 13023 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 13024 13025 false_reg->smin_value = max(false_reg->smin_value, false_smin); 13026 true_reg->smax_value = min(true_reg->smax_value, true_smax); 13027 } 13028 break; 13029 } 13030 default: 13031 return; 13032 } 13033 13034 if (is_jmp32) { 13035 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 13036 tnum_subreg(false_32off)); 13037 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 13038 tnum_subreg(true_32off)); 13039 __reg_combine_32_into_64(false_reg); 13040 __reg_combine_32_into_64(true_reg); 13041 } else { 13042 false_reg->var_off = false_64off; 13043 true_reg->var_off = true_64off; 13044 __reg_combine_64_into_32(false_reg); 13045 __reg_combine_64_into_32(true_reg); 13046 } 13047 } 13048 13049 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 13050 * the variable reg. 13051 */ 13052 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 13053 struct bpf_reg_state *false_reg, 13054 u64 val, u32 val32, 13055 u8 opcode, bool is_jmp32) 13056 { 13057 opcode = flip_opcode(opcode); 13058 /* This uses zero as "not present in table"; luckily the zero opcode, 13059 * BPF_JA, can't get here. 13060 */ 13061 if (opcode) 13062 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 13063 } 13064 13065 /* Regs are known to be equal, so intersect their min/max/var_off */ 13066 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 13067 struct bpf_reg_state *dst_reg) 13068 { 13069 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 13070 dst_reg->umin_value); 13071 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 13072 dst_reg->umax_value); 13073 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 13074 dst_reg->smin_value); 13075 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 13076 dst_reg->smax_value); 13077 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 13078 dst_reg->var_off); 13079 reg_bounds_sync(src_reg); 13080 reg_bounds_sync(dst_reg); 13081 } 13082 13083 static void reg_combine_min_max(struct bpf_reg_state *true_src, 13084 struct bpf_reg_state *true_dst, 13085 struct bpf_reg_state *false_src, 13086 struct bpf_reg_state *false_dst, 13087 u8 opcode) 13088 { 13089 switch (opcode) { 13090 case BPF_JEQ: 13091 __reg_combine_min_max(true_src, true_dst); 13092 break; 13093 case BPF_JNE: 13094 __reg_combine_min_max(false_src, false_dst); 13095 break; 13096 } 13097 } 13098 13099 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 13100 struct bpf_reg_state *reg, u32 id, 13101 bool is_null) 13102 { 13103 if (type_may_be_null(reg->type) && reg->id == id && 13104 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 13105 /* Old offset (both fixed and variable parts) should have been 13106 * known-zero, because we don't allow pointer arithmetic on 13107 * pointers that might be NULL. If we see this happening, don't 13108 * convert the register. 13109 * 13110 * But in some cases, some helpers that return local kptrs 13111 * advance offset for the returned pointer. In those cases, it 13112 * is fine to expect to see reg->off. 13113 */ 13114 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 13115 return; 13116 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 13117 WARN_ON_ONCE(reg->off)) 13118 return; 13119 13120 if (is_null) { 13121 reg->type = SCALAR_VALUE; 13122 /* We don't need id and ref_obj_id from this point 13123 * onwards anymore, thus we should better reset it, 13124 * so that state pruning has chances to take effect. 13125 */ 13126 reg->id = 0; 13127 reg->ref_obj_id = 0; 13128 13129 return; 13130 } 13131 13132 mark_ptr_not_null_reg(reg); 13133 13134 if (!reg_may_point_to_spin_lock(reg)) { 13135 /* For not-NULL ptr, reg->ref_obj_id will be reset 13136 * in release_reference(). 13137 * 13138 * reg->id is still used by spin_lock ptr. Other 13139 * than spin_lock ptr type, reg->id can be reset. 13140 */ 13141 reg->id = 0; 13142 } 13143 } 13144 } 13145 13146 /* The logic is similar to find_good_pkt_pointers(), both could eventually 13147 * be folded together at some point. 13148 */ 13149 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 13150 bool is_null) 13151 { 13152 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 13153 struct bpf_reg_state *regs = state->regs, *reg; 13154 u32 ref_obj_id = regs[regno].ref_obj_id; 13155 u32 id = regs[regno].id; 13156 13157 if (ref_obj_id && ref_obj_id == id && is_null) 13158 /* regs[regno] is in the " == NULL" branch. 13159 * No one could have freed the reference state before 13160 * doing the NULL check. 13161 */ 13162 WARN_ON_ONCE(release_reference_state(state, id)); 13163 13164 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13165 mark_ptr_or_null_reg(state, reg, id, is_null); 13166 })); 13167 } 13168 13169 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 13170 struct bpf_reg_state *dst_reg, 13171 struct bpf_reg_state *src_reg, 13172 struct bpf_verifier_state *this_branch, 13173 struct bpf_verifier_state *other_branch) 13174 { 13175 if (BPF_SRC(insn->code) != BPF_X) 13176 return false; 13177 13178 /* Pointers are always 64-bit. */ 13179 if (BPF_CLASS(insn->code) == BPF_JMP32) 13180 return false; 13181 13182 switch (BPF_OP(insn->code)) { 13183 case BPF_JGT: 13184 if ((dst_reg->type == PTR_TO_PACKET && 13185 src_reg->type == PTR_TO_PACKET_END) || 13186 (dst_reg->type == PTR_TO_PACKET_META && 13187 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13188 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 13189 find_good_pkt_pointers(this_branch, dst_reg, 13190 dst_reg->type, false); 13191 mark_pkt_end(other_branch, insn->dst_reg, true); 13192 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13193 src_reg->type == PTR_TO_PACKET) || 13194 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13195 src_reg->type == PTR_TO_PACKET_META)) { 13196 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 13197 find_good_pkt_pointers(other_branch, src_reg, 13198 src_reg->type, true); 13199 mark_pkt_end(this_branch, insn->src_reg, false); 13200 } else { 13201 return false; 13202 } 13203 break; 13204 case BPF_JLT: 13205 if ((dst_reg->type == PTR_TO_PACKET && 13206 src_reg->type == PTR_TO_PACKET_END) || 13207 (dst_reg->type == PTR_TO_PACKET_META && 13208 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13209 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 13210 find_good_pkt_pointers(other_branch, dst_reg, 13211 dst_reg->type, true); 13212 mark_pkt_end(this_branch, insn->dst_reg, false); 13213 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13214 src_reg->type == PTR_TO_PACKET) || 13215 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13216 src_reg->type == PTR_TO_PACKET_META)) { 13217 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 13218 find_good_pkt_pointers(this_branch, src_reg, 13219 src_reg->type, false); 13220 mark_pkt_end(other_branch, insn->src_reg, true); 13221 } else { 13222 return false; 13223 } 13224 break; 13225 case BPF_JGE: 13226 if ((dst_reg->type == PTR_TO_PACKET && 13227 src_reg->type == PTR_TO_PACKET_END) || 13228 (dst_reg->type == PTR_TO_PACKET_META && 13229 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13230 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 13231 find_good_pkt_pointers(this_branch, dst_reg, 13232 dst_reg->type, true); 13233 mark_pkt_end(other_branch, insn->dst_reg, false); 13234 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13235 src_reg->type == PTR_TO_PACKET) || 13236 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13237 src_reg->type == PTR_TO_PACKET_META)) { 13238 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 13239 find_good_pkt_pointers(other_branch, src_reg, 13240 src_reg->type, false); 13241 mark_pkt_end(this_branch, insn->src_reg, true); 13242 } else { 13243 return false; 13244 } 13245 break; 13246 case BPF_JLE: 13247 if ((dst_reg->type == PTR_TO_PACKET && 13248 src_reg->type == PTR_TO_PACKET_END) || 13249 (dst_reg->type == PTR_TO_PACKET_META && 13250 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 13251 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 13252 find_good_pkt_pointers(other_branch, dst_reg, 13253 dst_reg->type, false); 13254 mark_pkt_end(this_branch, insn->dst_reg, true); 13255 } else if ((dst_reg->type == PTR_TO_PACKET_END && 13256 src_reg->type == PTR_TO_PACKET) || 13257 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 13258 src_reg->type == PTR_TO_PACKET_META)) { 13259 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 13260 find_good_pkt_pointers(this_branch, src_reg, 13261 src_reg->type, true); 13262 mark_pkt_end(other_branch, insn->src_reg, false); 13263 } else { 13264 return false; 13265 } 13266 break; 13267 default: 13268 return false; 13269 } 13270 13271 return true; 13272 } 13273 13274 static void find_equal_scalars(struct bpf_verifier_state *vstate, 13275 struct bpf_reg_state *known_reg) 13276 { 13277 struct bpf_func_state *state; 13278 struct bpf_reg_state *reg; 13279 13280 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 13281 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 13282 copy_register_state(reg, known_reg); 13283 })); 13284 } 13285 13286 static int check_cond_jmp_op(struct bpf_verifier_env *env, 13287 struct bpf_insn *insn, int *insn_idx) 13288 { 13289 struct bpf_verifier_state *this_branch = env->cur_state; 13290 struct bpf_verifier_state *other_branch; 13291 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 13292 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 13293 struct bpf_reg_state *eq_branch_regs; 13294 u8 opcode = BPF_OP(insn->code); 13295 bool is_jmp32; 13296 int pred = -1; 13297 int err; 13298 13299 /* Only conditional jumps are expected to reach here. */ 13300 if (opcode == BPF_JA || opcode > BPF_JSLE) { 13301 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 13302 return -EINVAL; 13303 } 13304 13305 if (BPF_SRC(insn->code) == BPF_X) { 13306 if (insn->imm != 0) { 13307 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 13308 return -EINVAL; 13309 } 13310 13311 /* check src1 operand */ 13312 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13313 if (err) 13314 return err; 13315 13316 if (is_pointer_value(env, insn->src_reg)) { 13317 verbose(env, "R%d pointer comparison prohibited\n", 13318 insn->src_reg); 13319 return -EACCES; 13320 } 13321 src_reg = ®s[insn->src_reg]; 13322 } else { 13323 if (insn->src_reg != BPF_REG_0) { 13324 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 13325 return -EINVAL; 13326 } 13327 } 13328 13329 /* check src2 operand */ 13330 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13331 if (err) 13332 return err; 13333 13334 dst_reg = ®s[insn->dst_reg]; 13335 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 13336 13337 if (BPF_SRC(insn->code) == BPF_K) { 13338 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 13339 } else if (src_reg->type == SCALAR_VALUE && 13340 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 13341 pred = is_branch_taken(dst_reg, 13342 tnum_subreg(src_reg->var_off).value, 13343 opcode, 13344 is_jmp32); 13345 } else if (src_reg->type == SCALAR_VALUE && 13346 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 13347 pred = is_branch_taken(dst_reg, 13348 src_reg->var_off.value, 13349 opcode, 13350 is_jmp32); 13351 } else if (reg_is_pkt_pointer_any(dst_reg) && 13352 reg_is_pkt_pointer_any(src_reg) && 13353 !is_jmp32) { 13354 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 13355 } 13356 13357 if (pred >= 0) { 13358 /* If we get here with a dst_reg pointer type it is because 13359 * above is_branch_taken() special cased the 0 comparison. 13360 */ 13361 if (!__is_pointer_value(false, dst_reg)) 13362 err = mark_chain_precision(env, insn->dst_reg); 13363 if (BPF_SRC(insn->code) == BPF_X && !err && 13364 !__is_pointer_value(false, src_reg)) 13365 err = mark_chain_precision(env, insn->src_reg); 13366 if (err) 13367 return err; 13368 } 13369 13370 if (pred == 1) { 13371 /* Only follow the goto, ignore fall-through. If needed, push 13372 * the fall-through branch for simulation under speculative 13373 * execution. 13374 */ 13375 if (!env->bypass_spec_v1 && 13376 !sanitize_speculative_path(env, insn, *insn_idx + 1, 13377 *insn_idx)) 13378 return -EFAULT; 13379 *insn_idx += insn->off; 13380 return 0; 13381 } else if (pred == 0) { 13382 /* Only follow the fall-through branch, since that's where the 13383 * program will go. If needed, push the goto branch for 13384 * simulation under speculative execution. 13385 */ 13386 if (!env->bypass_spec_v1 && 13387 !sanitize_speculative_path(env, insn, 13388 *insn_idx + insn->off + 1, 13389 *insn_idx)) 13390 return -EFAULT; 13391 return 0; 13392 } 13393 13394 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 13395 false); 13396 if (!other_branch) 13397 return -EFAULT; 13398 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 13399 13400 /* detect if we are comparing against a constant value so we can adjust 13401 * our min/max values for our dst register. 13402 * this is only legit if both are scalars (or pointers to the same 13403 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 13404 * because otherwise the different base pointers mean the offsets aren't 13405 * comparable. 13406 */ 13407 if (BPF_SRC(insn->code) == BPF_X) { 13408 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 13409 13410 if (dst_reg->type == SCALAR_VALUE && 13411 src_reg->type == SCALAR_VALUE) { 13412 if (tnum_is_const(src_reg->var_off) || 13413 (is_jmp32 && 13414 tnum_is_const(tnum_subreg(src_reg->var_off)))) 13415 reg_set_min_max(&other_branch_regs[insn->dst_reg], 13416 dst_reg, 13417 src_reg->var_off.value, 13418 tnum_subreg(src_reg->var_off).value, 13419 opcode, is_jmp32); 13420 else if (tnum_is_const(dst_reg->var_off) || 13421 (is_jmp32 && 13422 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 13423 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 13424 src_reg, 13425 dst_reg->var_off.value, 13426 tnum_subreg(dst_reg->var_off).value, 13427 opcode, is_jmp32); 13428 else if (!is_jmp32 && 13429 (opcode == BPF_JEQ || opcode == BPF_JNE)) 13430 /* Comparing for equality, we can combine knowledge */ 13431 reg_combine_min_max(&other_branch_regs[insn->src_reg], 13432 &other_branch_regs[insn->dst_reg], 13433 src_reg, dst_reg, opcode); 13434 if (src_reg->id && 13435 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 13436 find_equal_scalars(this_branch, src_reg); 13437 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 13438 } 13439 13440 } 13441 } else if (dst_reg->type == SCALAR_VALUE) { 13442 reg_set_min_max(&other_branch_regs[insn->dst_reg], 13443 dst_reg, insn->imm, (u32)insn->imm, 13444 opcode, is_jmp32); 13445 } 13446 13447 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 13448 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 13449 find_equal_scalars(this_branch, dst_reg); 13450 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 13451 } 13452 13453 /* if one pointer register is compared to another pointer 13454 * register check if PTR_MAYBE_NULL could be lifted. 13455 * E.g. register A - maybe null 13456 * register B - not null 13457 * for JNE A, B, ... - A is not null in the false branch; 13458 * for JEQ A, B, ... - A is not null in the true branch. 13459 * 13460 * Since PTR_TO_BTF_ID points to a kernel struct that does 13461 * not need to be null checked by the BPF program, i.e., 13462 * could be null even without PTR_MAYBE_NULL marking, so 13463 * only propagate nullness when neither reg is that type. 13464 */ 13465 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 13466 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 13467 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 13468 base_type(src_reg->type) != PTR_TO_BTF_ID && 13469 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 13470 eq_branch_regs = NULL; 13471 switch (opcode) { 13472 case BPF_JEQ: 13473 eq_branch_regs = other_branch_regs; 13474 break; 13475 case BPF_JNE: 13476 eq_branch_regs = regs; 13477 break; 13478 default: 13479 /* do nothing */ 13480 break; 13481 } 13482 if (eq_branch_regs) { 13483 if (type_may_be_null(src_reg->type)) 13484 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 13485 else 13486 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 13487 } 13488 } 13489 13490 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 13491 * NOTE: these optimizations below are related with pointer comparison 13492 * which will never be JMP32. 13493 */ 13494 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 13495 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 13496 type_may_be_null(dst_reg->type)) { 13497 /* Mark all identical registers in each branch as either 13498 * safe or unknown depending R == 0 or R != 0 conditional. 13499 */ 13500 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 13501 opcode == BPF_JNE); 13502 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 13503 opcode == BPF_JEQ); 13504 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 13505 this_branch, other_branch) && 13506 is_pointer_value(env, insn->dst_reg)) { 13507 verbose(env, "R%d pointer comparison prohibited\n", 13508 insn->dst_reg); 13509 return -EACCES; 13510 } 13511 if (env->log.level & BPF_LOG_LEVEL) 13512 print_insn_state(env, this_branch->frame[this_branch->curframe]); 13513 return 0; 13514 } 13515 13516 /* verify BPF_LD_IMM64 instruction */ 13517 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 13518 { 13519 struct bpf_insn_aux_data *aux = cur_aux(env); 13520 struct bpf_reg_state *regs = cur_regs(env); 13521 struct bpf_reg_state *dst_reg; 13522 struct bpf_map *map; 13523 int err; 13524 13525 if (BPF_SIZE(insn->code) != BPF_DW) { 13526 verbose(env, "invalid BPF_LD_IMM insn\n"); 13527 return -EINVAL; 13528 } 13529 if (insn->off != 0) { 13530 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 13531 return -EINVAL; 13532 } 13533 13534 err = check_reg_arg(env, insn->dst_reg, DST_OP); 13535 if (err) 13536 return err; 13537 13538 dst_reg = ®s[insn->dst_reg]; 13539 if (insn->src_reg == 0) { 13540 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 13541 13542 dst_reg->type = SCALAR_VALUE; 13543 __mark_reg_known(®s[insn->dst_reg], imm); 13544 return 0; 13545 } 13546 13547 /* All special src_reg cases are listed below. From this point onwards 13548 * we either succeed and assign a corresponding dst_reg->type after 13549 * zeroing the offset, or fail and reject the program. 13550 */ 13551 mark_reg_known_zero(env, regs, insn->dst_reg); 13552 13553 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 13554 dst_reg->type = aux->btf_var.reg_type; 13555 switch (base_type(dst_reg->type)) { 13556 case PTR_TO_MEM: 13557 dst_reg->mem_size = aux->btf_var.mem_size; 13558 break; 13559 case PTR_TO_BTF_ID: 13560 dst_reg->btf = aux->btf_var.btf; 13561 dst_reg->btf_id = aux->btf_var.btf_id; 13562 break; 13563 default: 13564 verbose(env, "bpf verifier is misconfigured\n"); 13565 return -EFAULT; 13566 } 13567 return 0; 13568 } 13569 13570 if (insn->src_reg == BPF_PSEUDO_FUNC) { 13571 struct bpf_prog_aux *aux = env->prog->aux; 13572 u32 subprogno = find_subprog(env, 13573 env->insn_idx + insn->imm + 1); 13574 13575 if (!aux->func_info) { 13576 verbose(env, "missing btf func_info\n"); 13577 return -EINVAL; 13578 } 13579 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 13580 verbose(env, "callback function not static\n"); 13581 return -EINVAL; 13582 } 13583 13584 dst_reg->type = PTR_TO_FUNC; 13585 dst_reg->subprogno = subprogno; 13586 return 0; 13587 } 13588 13589 map = env->used_maps[aux->map_index]; 13590 dst_reg->map_ptr = map; 13591 13592 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 13593 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 13594 dst_reg->type = PTR_TO_MAP_VALUE; 13595 dst_reg->off = aux->map_off; 13596 WARN_ON_ONCE(map->max_entries != 1); 13597 /* We want reg->id to be same (0) as map_value is not distinct */ 13598 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 13599 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 13600 dst_reg->type = CONST_PTR_TO_MAP; 13601 } else { 13602 verbose(env, "bpf verifier is misconfigured\n"); 13603 return -EINVAL; 13604 } 13605 13606 return 0; 13607 } 13608 13609 static bool may_access_skb(enum bpf_prog_type type) 13610 { 13611 switch (type) { 13612 case BPF_PROG_TYPE_SOCKET_FILTER: 13613 case BPF_PROG_TYPE_SCHED_CLS: 13614 case BPF_PROG_TYPE_SCHED_ACT: 13615 return true; 13616 default: 13617 return false; 13618 } 13619 } 13620 13621 /* verify safety of LD_ABS|LD_IND instructions: 13622 * - they can only appear in the programs where ctx == skb 13623 * - since they are wrappers of function calls, they scratch R1-R5 registers, 13624 * preserve R6-R9, and store return value into R0 13625 * 13626 * Implicit input: 13627 * ctx == skb == R6 == CTX 13628 * 13629 * Explicit input: 13630 * SRC == any register 13631 * IMM == 32-bit immediate 13632 * 13633 * Output: 13634 * R0 - 8/16/32-bit skb data converted to cpu endianness 13635 */ 13636 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 13637 { 13638 struct bpf_reg_state *regs = cur_regs(env); 13639 static const int ctx_reg = BPF_REG_6; 13640 u8 mode = BPF_MODE(insn->code); 13641 int i, err; 13642 13643 if (!may_access_skb(resolve_prog_type(env->prog))) { 13644 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 13645 return -EINVAL; 13646 } 13647 13648 if (!env->ops->gen_ld_abs) { 13649 verbose(env, "bpf verifier is misconfigured\n"); 13650 return -EINVAL; 13651 } 13652 13653 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 13654 BPF_SIZE(insn->code) == BPF_DW || 13655 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 13656 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 13657 return -EINVAL; 13658 } 13659 13660 /* check whether implicit source operand (register R6) is readable */ 13661 err = check_reg_arg(env, ctx_reg, SRC_OP); 13662 if (err) 13663 return err; 13664 13665 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 13666 * gen_ld_abs() may terminate the program at runtime, leading to 13667 * reference leak. 13668 */ 13669 err = check_reference_leak(env); 13670 if (err) { 13671 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 13672 return err; 13673 } 13674 13675 if (env->cur_state->active_lock.ptr) { 13676 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 13677 return -EINVAL; 13678 } 13679 13680 if (env->cur_state->active_rcu_lock) { 13681 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 13682 return -EINVAL; 13683 } 13684 13685 if (regs[ctx_reg].type != PTR_TO_CTX) { 13686 verbose(env, 13687 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 13688 return -EINVAL; 13689 } 13690 13691 if (mode == BPF_IND) { 13692 /* check explicit source operand */ 13693 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13694 if (err) 13695 return err; 13696 } 13697 13698 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 13699 if (err < 0) 13700 return err; 13701 13702 /* reset caller saved regs to unreadable */ 13703 for (i = 0; i < CALLER_SAVED_REGS; i++) { 13704 mark_reg_not_init(env, regs, caller_saved[i]); 13705 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 13706 } 13707 13708 /* mark destination R0 register as readable, since it contains 13709 * the value fetched from the packet. 13710 * Already marked as written above. 13711 */ 13712 mark_reg_unknown(env, regs, BPF_REG_0); 13713 /* ld_abs load up to 32-bit skb data. */ 13714 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 13715 return 0; 13716 } 13717 13718 static int check_return_code(struct bpf_verifier_env *env) 13719 { 13720 struct tnum enforce_attach_type_range = tnum_unknown; 13721 const struct bpf_prog *prog = env->prog; 13722 struct bpf_reg_state *reg; 13723 struct tnum range = tnum_range(0, 1); 13724 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 13725 int err; 13726 struct bpf_func_state *frame = env->cur_state->frame[0]; 13727 const bool is_subprog = frame->subprogno; 13728 13729 /* LSM and struct_ops func-ptr's return type could be "void" */ 13730 if (!is_subprog) { 13731 switch (prog_type) { 13732 case BPF_PROG_TYPE_LSM: 13733 if (prog->expected_attach_type == BPF_LSM_CGROUP) 13734 /* See below, can be 0 or 0-1 depending on hook. */ 13735 break; 13736 fallthrough; 13737 case BPF_PROG_TYPE_STRUCT_OPS: 13738 if (!prog->aux->attach_func_proto->type) 13739 return 0; 13740 break; 13741 default: 13742 break; 13743 } 13744 } 13745 13746 /* eBPF calling convention is such that R0 is used 13747 * to return the value from eBPF program. 13748 * Make sure that it's readable at this time 13749 * of bpf_exit, which means that program wrote 13750 * something into it earlier 13751 */ 13752 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 13753 if (err) 13754 return err; 13755 13756 if (is_pointer_value(env, BPF_REG_0)) { 13757 verbose(env, "R0 leaks addr as return value\n"); 13758 return -EACCES; 13759 } 13760 13761 reg = cur_regs(env) + BPF_REG_0; 13762 13763 if (frame->in_async_callback_fn) { 13764 /* enforce return zero from async callbacks like timer */ 13765 if (reg->type != SCALAR_VALUE) { 13766 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 13767 reg_type_str(env, reg->type)); 13768 return -EINVAL; 13769 } 13770 13771 if (!tnum_in(tnum_const(0), reg->var_off)) { 13772 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 13773 return -EINVAL; 13774 } 13775 return 0; 13776 } 13777 13778 if (is_subprog) { 13779 if (reg->type != SCALAR_VALUE) { 13780 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 13781 reg_type_str(env, reg->type)); 13782 return -EINVAL; 13783 } 13784 return 0; 13785 } 13786 13787 switch (prog_type) { 13788 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 13789 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 13790 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 13791 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 13792 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 13793 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 13794 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 13795 range = tnum_range(1, 1); 13796 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 13797 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 13798 range = tnum_range(0, 3); 13799 break; 13800 case BPF_PROG_TYPE_CGROUP_SKB: 13801 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 13802 range = tnum_range(0, 3); 13803 enforce_attach_type_range = tnum_range(2, 3); 13804 } 13805 break; 13806 case BPF_PROG_TYPE_CGROUP_SOCK: 13807 case BPF_PROG_TYPE_SOCK_OPS: 13808 case BPF_PROG_TYPE_CGROUP_DEVICE: 13809 case BPF_PROG_TYPE_CGROUP_SYSCTL: 13810 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 13811 break; 13812 case BPF_PROG_TYPE_RAW_TRACEPOINT: 13813 if (!env->prog->aux->attach_btf_id) 13814 return 0; 13815 range = tnum_const(0); 13816 break; 13817 case BPF_PROG_TYPE_TRACING: 13818 switch (env->prog->expected_attach_type) { 13819 case BPF_TRACE_FENTRY: 13820 case BPF_TRACE_FEXIT: 13821 range = tnum_const(0); 13822 break; 13823 case BPF_TRACE_RAW_TP: 13824 case BPF_MODIFY_RETURN: 13825 return 0; 13826 case BPF_TRACE_ITER: 13827 break; 13828 default: 13829 return -ENOTSUPP; 13830 } 13831 break; 13832 case BPF_PROG_TYPE_SK_LOOKUP: 13833 range = tnum_range(SK_DROP, SK_PASS); 13834 break; 13835 13836 case BPF_PROG_TYPE_LSM: 13837 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 13838 /* Regular BPF_PROG_TYPE_LSM programs can return 13839 * any value. 13840 */ 13841 return 0; 13842 } 13843 if (!env->prog->aux->attach_func_proto->type) { 13844 /* Make sure programs that attach to void 13845 * hooks don't try to modify return value. 13846 */ 13847 range = tnum_range(1, 1); 13848 } 13849 break; 13850 13851 case BPF_PROG_TYPE_EXT: 13852 /* freplace program can return anything as its return value 13853 * depends on the to-be-replaced kernel func or bpf program. 13854 */ 13855 default: 13856 return 0; 13857 } 13858 13859 if (reg->type != SCALAR_VALUE) { 13860 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 13861 reg_type_str(env, reg->type)); 13862 return -EINVAL; 13863 } 13864 13865 if (!tnum_in(range, reg->var_off)) { 13866 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 13867 if (prog->expected_attach_type == BPF_LSM_CGROUP && 13868 prog_type == BPF_PROG_TYPE_LSM && 13869 !prog->aux->attach_func_proto->type) 13870 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 13871 return -EINVAL; 13872 } 13873 13874 if (!tnum_is_unknown(enforce_attach_type_range) && 13875 tnum_in(enforce_attach_type_range, reg->var_off)) 13876 env->prog->enforce_expected_attach_type = 1; 13877 return 0; 13878 } 13879 13880 /* non-recursive DFS pseudo code 13881 * 1 procedure DFS-iterative(G,v): 13882 * 2 label v as discovered 13883 * 3 let S be a stack 13884 * 4 S.push(v) 13885 * 5 while S is not empty 13886 * 6 t <- S.peek() 13887 * 7 if t is what we're looking for: 13888 * 8 return t 13889 * 9 for all edges e in G.adjacentEdges(t) do 13890 * 10 if edge e is already labelled 13891 * 11 continue with the next edge 13892 * 12 w <- G.adjacentVertex(t,e) 13893 * 13 if vertex w is not discovered and not explored 13894 * 14 label e as tree-edge 13895 * 15 label w as discovered 13896 * 16 S.push(w) 13897 * 17 continue at 5 13898 * 18 else if vertex w is discovered 13899 * 19 label e as back-edge 13900 * 20 else 13901 * 21 // vertex w is explored 13902 * 22 label e as forward- or cross-edge 13903 * 23 label t as explored 13904 * 24 S.pop() 13905 * 13906 * convention: 13907 * 0x10 - discovered 13908 * 0x11 - discovered and fall-through edge labelled 13909 * 0x12 - discovered and fall-through and branch edges labelled 13910 * 0x20 - explored 13911 */ 13912 13913 enum { 13914 DISCOVERED = 0x10, 13915 EXPLORED = 0x20, 13916 FALLTHROUGH = 1, 13917 BRANCH = 2, 13918 }; 13919 13920 static u32 state_htab_size(struct bpf_verifier_env *env) 13921 { 13922 return env->prog->len; 13923 } 13924 13925 static struct bpf_verifier_state_list **explored_state( 13926 struct bpf_verifier_env *env, 13927 int idx) 13928 { 13929 struct bpf_verifier_state *cur = env->cur_state; 13930 struct bpf_func_state *state = cur->frame[cur->curframe]; 13931 13932 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 13933 } 13934 13935 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 13936 { 13937 env->insn_aux_data[idx].prune_point = true; 13938 } 13939 13940 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 13941 { 13942 return env->insn_aux_data[insn_idx].prune_point; 13943 } 13944 13945 static void mark_force_checkpoint(struct bpf_verifier_env *env, int idx) 13946 { 13947 env->insn_aux_data[idx].force_checkpoint = true; 13948 } 13949 13950 static bool is_force_checkpoint(struct bpf_verifier_env *env, int insn_idx) 13951 { 13952 return env->insn_aux_data[insn_idx].force_checkpoint; 13953 } 13954 13955 13956 enum { 13957 DONE_EXPLORING = 0, 13958 KEEP_EXPLORING = 1, 13959 }; 13960 13961 /* t, w, e - match pseudo-code above: 13962 * t - index of current instruction 13963 * w - next instruction 13964 * e - edge 13965 */ 13966 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 13967 bool loop_ok) 13968 { 13969 int *insn_stack = env->cfg.insn_stack; 13970 int *insn_state = env->cfg.insn_state; 13971 13972 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 13973 return DONE_EXPLORING; 13974 13975 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 13976 return DONE_EXPLORING; 13977 13978 if (w < 0 || w >= env->prog->len) { 13979 verbose_linfo(env, t, "%d: ", t); 13980 verbose(env, "jump out of range from insn %d to %d\n", t, w); 13981 return -EINVAL; 13982 } 13983 13984 if (e == BRANCH) { 13985 /* mark branch target for state pruning */ 13986 mark_prune_point(env, w); 13987 mark_jmp_point(env, w); 13988 } 13989 13990 if (insn_state[w] == 0) { 13991 /* tree-edge */ 13992 insn_state[t] = DISCOVERED | e; 13993 insn_state[w] = DISCOVERED; 13994 if (env->cfg.cur_stack >= env->prog->len) 13995 return -E2BIG; 13996 insn_stack[env->cfg.cur_stack++] = w; 13997 return KEEP_EXPLORING; 13998 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 13999 if (loop_ok && env->bpf_capable) 14000 return DONE_EXPLORING; 14001 verbose_linfo(env, t, "%d: ", t); 14002 verbose_linfo(env, w, "%d: ", w); 14003 verbose(env, "back-edge from insn %d to %d\n", t, w); 14004 return -EINVAL; 14005 } else if (insn_state[w] == EXPLORED) { 14006 /* forward- or cross-edge */ 14007 insn_state[t] = DISCOVERED | e; 14008 } else { 14009 verbose(env, "insn state internal bug\n"); 14010 return -EFAULT; 14011 } 14012 return DONE_EXPLORING; 14013 } 14014 14015 static int visit_func_call_insn(int t, struct bpf_insn *insns, 14016 struct bpf_verifier_env *env, 14017 bool visit_callee) 14018 { 14019 int ret; 14020 14021 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 14022 if (ret) 14023 return ret; 14024 14025 mark_prune_point(env, t + 1); 14026 /* when we exit from subprog, we need to record non-linear history */ 14027 mark_jmp_point(env, t + 1); 14028 14029 if (visit_callee) { 14030 mark_prune_point(env, t); 14031 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 14032 /* It's ok to allow recursion from CFG point of 14033 * view. __check_func_call() will do the actual 14034 * check. 14035 */ 14036 bpf_pseudo_func(insns + t)); 14037 } 14038 return ret; 14039 } 14040 14041 /* Visits the instruction at index t and returns one of the following: 14042 * < 0 - an error occurred 14043 * DONE_EXPLORING - the instruction was fully explored 14044 * KEEP_EXPLORING - there is still work to be done before it is fully explored 14045 */ 14046 static int visit_insn(int t, struct bpf_verifier_env *env) 14047 { 14048 struct bpf_insn *insns = env->prog->insnsi, *insn = &insns[t]; 14049 int ret; 14050 14051 if (bpf_pseudo_func(insn)) 14052 return visit_func_call_insn(t, insns, env, true); 14053 14054 /* All non-branch instructions have a single fall-through edge. */ 14055 if (BPF_CLASS(insn->code) != BPF_JMP && 14056 BPF_CLASS(insn->code) != BPF_JMP32) 14057 return push_insn(t, t + 1, FALLTHROUGH, env, false); 14058 14059 switch (BPF_OP(insn->code)) { 14060 case BPF_EXIT: 14061 return DONE_EXPLORING; 14062 14063 case BPF_CALL: 14064 if (insn->src_reg == 0 && insn->imm == BPF_FUNC_timer_set_callback) 14065 /* Mark this call insn as a prune point to trigger 14066 * is_state_visited() check before call itself is 14067 * processed by __check_func_call(). Otherwise new 14068 * async state will be pushed for further exploration. 14069 */ 14070 mark_prune_point(env, t); 14071 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 14072 struct bpf_kfunc_call_arg_meta meta; 14073 14074 ret = fetch_kfunc_meta(env, insn, &meta, NULL); 14075 if (ret == 0 && is_iter_next_kfunc(&meta)) { 14076 mark_prune_point(env, t); 14077 /* Checking and saving state checkpoints at iter_next() call 14078 * is crucial for fast convergence of open-coded iterator loop 14079 * logic, so we need to force it. If we don't do that, 14080 * is_state_visited() might skip saving a checkpoint, causing 14081 * unnecessarily long sequence of not checkpointed 14082 * instructions and jumps, leading to exhaustion of jump 14083 * history buffer, and potentially other undesired outcomes. 14084 * It is expected that with correct open-coded iterators 14085 * convergence will happen quickly, so we don't run a risk of 14086 * exhausting memory. 14087 */ 14088 mark_force_checkpoint(env, t); 14089 } 14090 } 14091 return visit_func_call_insn(t, insns, env, insn->src_reg == BPF_PSEUDO_CALL); 14092 14093 case BPF_JA: 14094 if (BPF_SRC(insn->code) != BPF_K) 14095 return -EINVAL; 14096 14097 /* unconditional jump with single edge */ 14098 ret = push_insn(t, t + insn->off + 1, FALLTHROUGH, env, 14099 true); 14100 if (ret) 14101 return ret; 14102 14103 mark_prune_point(env, t + insn->off + 1); 14104 mark_jmp_point(env, t + insn->off + 1); 14105 14106 return ret; 14107 14108 default: 14109 /* conditional jump with two edges */ 14110 mark_prune_point(env, t); 14111 14112 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 14113 if (ret) 14114 return ret; 14115 14116 return push_insn(t, t + insn->off + 1, BRANCH, env, true); 14117 } 14118 } 14119 14120 /* non-recursive depth-first-search to detect loops in BPF program 14121 * loop == back-edge in directed graph 14122 */ 14123 static int check_cfg(struct bpf_verifier_env *env) 14124 { 14125 int insn_cnt = env->prog->len; 14126 int *insn_stack, *insn_state; 14127 int ret = 0; 14128 int i; 14129 14130 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 14131 if (!insn_state) 14132 return -ENOMEM; 14133 14134 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 14135 if (!insn_stack) { 14136 kvfree(insn_state); 14137 return -ENOMEM; 14138 } 14139 14140 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 14141 insn_stack[0] = 0; /* 0 is the first instruction */ 14142 env->cfg.cur_stack = 1; 14143 14144 while (env->cfg.cur_stack > 0) { 14145 int t = insn_stack[env->cfg.cur_stack - 1]; 14146 14147 ret = visit_insn(t, env); 14148 switch (ret) { 14149 case DONE_EXPLORING: 14150 insn_state[t] = EXPLORED; 14151 env->cfg.cur_stack--; 14152 break; 14153 case KEEP_EXPLORING: 14154 break; 14155 default: 14156 if (ret > 0) { 14157 verbose(env, "visit_insn internal bug\n"); 14158 ret = -EFAULT; 14159 } 14160 goto err_free; 14161 } 14162 } 14163 14164 if (env->cfg.cur_stack < 0) { 14165 verbose(env, "pop stack internal bug\n"); 14166 ret = -EFAULT; 14167 goto err_free; 14168 } 14169 14170 for (i = 0; i < insn_cnt; i++) { 14171 if (insn_state[i] != EXPLORED) { 14172 verbose(env, "unreachable insn %d\n", i); 14173 ret = -EINVAL; 14174 goto err_free; 14175 } 14176 } 14177 ret = 0; /* cfg looks good */ 14178 14179 err_free: 14180 kvfree(insn_state); 14181 kvfree(insn_stack); 14182 env->cfg.insn_state = env->cfg.insn_stack = NULL; 14183 return ret; 14184 } 14185 14186 static int check_abnormal_return(struct bpf_verifier_env *env) 14187 { 14188 int i; 14189 14190 for (i = 1; i < env->subprog_cnt; i++) { 14191 if (env->subprog_info[i].has_ld_abs) { 14192 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 14193 return -EINVAL; 14194 } 14195 if (env->subprog_info[i].has_tail_call) { 14196 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 14197 return -EINVAL; 14198 } 14199 } 14200 return 0; 14201 } 14202 14203 /* The minimum supported BTF func info size */ 14204 #define MIN_BPF_FUNCINFO_SIZE 8 14205 #define MAX_FUNCINFO_REC_SIZE 252 14206 14207 static int check_btf_func(struct bpf_verifier_env *env, 14208 const union bpf_attr *attr, 14209 bpfptr_t uattr) 14210 { 14211 const struct btf_type *type, *func_proto, *ret_type; 14212 u32 i, nfuncs, urec_size, min_size; 14213 u32 krec_size = sizeof(struct bpf_func_info); 14214 struct bpf_func_info *krecord; 14215 struct bpf_func_info_aux *info_aux = NULL; 14216 struct bpf_prog *prog; 14217 const struct btf *btf; 14218 bpfptr_t urecord; 14219 u32 prev_offset = 0; 14220 bool scalar_return; 14221 int ret = -ENOMEM; 14222 14223 nfuncs = attr->func_info_cnt; 14224 if (!nfuncs) { 14225 if (check_abnormal_return(env)) 14226 return -EINVAL; 14227 return 0; 14228 } 14229 14230 if (nfuncs != env->subprog_cnt) { 14231 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 14232 return -EINVAL; 14233 } 14234 14235 urec_size = attr->func_info_rec_size; 14236 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 14237 urec_size > MAX_FUNCINFO_REC_SIZE || 14238 urec_size % sizeof(u32)) { 14239 verbose(env, "invalid func info rec size %u\n", urec_size); 14240 return -EINVAL; 14241 } 14242 14243 prog = env->prog; 14244 btf = prog->aux->btf; 14245 14246 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 14247 min_size = min_t(u32, krec_size, urec_size); 14248 14249 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 14250 if (!krecord) 14251 return -ENOMEM; 14252 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 14253 if (!info_aux) 14254 goto err_free; 14255 14256 for (i = 0; i < nfuncs; i++) { 14257 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 14258 if (ret) { 14259 if (ret == -E2BIG) { 14260 verbose(env, "nonzero tailing record in func info"); 14261 /* set the size kernel expects so loader can zero 14262 * out the rest of the record. 14263 */ 14264 if (copy_to_bpfptr_offset(uattr, 14265 offsetof(union bpf_attr, func_info_rec_size), 14266 &min_size, sizeof(min_size))) 14267 ret = -EFAULT; 14268 } 14269 goto err_free; 14270 } 14271 14272 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 14273 ret = -EFAULT; 14274 goto err_free; 14275 } 14276 14277 /* check insn_off */ 14278 ret = -EINVAL; 14279 if (i == 0) { 14280 if (krecord[i].insn_off) { 14281 verbose(env, 14282 "nonzero insn_off %u for the first func info record", 14283 krecord[i].insn_off); 14284 goto err_free; 14285 } 14286 } else if (krecord[i].insn_off <= prev_offset) { 14287 verbose(env, 14288 "same or smaller insn offset (%u) than previous func info record (%u)", 14289 krecord[i].insn_off, prev_offset); 14290 goto err_free; 14291 } 14292 14293 if (env->subprog_info[i].start != krecord[i].insn_off) { 14294 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 14295 goto err_free; 14296 } 14297 14298 /* check type_id */ 14299 type = btf_type_by_id(btf, krecord[i].type_id); 14300 if (!type || !btf_type_is_func(type)) { 14301 verbose(env, "invalid type id %d in func info", 14302 krecord[i].type_id); 14303 goto err_free; 14304 } 14305 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 14306 14307 func_proto = btf_type_by_id(btf, type->type); 14308 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 14309 /* btf_func_check() already verified it during BTF load */ 14310 goto err_free; 14311 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 14312 scalar_return = 14313 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 14314 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 14315 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 14316 goto err_free; 14317 } 14318 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 14319 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 14320 goto err_free; 14321 } 14322 14323 prev_offset = krecord[i].insn_off; 14324 bpfptr_add(&urecord, urec_size); 14325 } 14326 14327 prog->aux->func_info = krecord; 14328 prog->aux->func_info_cnt = nfuncs; 14329 prog->aux->func_info_aux = info_aux; 14330 return 0; 14331 14332 err_free: 14333 kvfree(krecord); 14334 kfree(info_aux); 14335 return ret; 14336 } 14337 14338 static void adjust_btf_func(struct bpf_verifier_env *env) 14339 { 14340 struct bpf_prog_aux *aux = env->prog->aux; 14341 int i; 14342 14343 if (!aux->func_info) 14344 return; 14345 14346 for (i = 0; i < env->subprog_cnt; i++) 14347 aux->func_info[i].insn_off = env->subprog_info[i].start; 14348 } 14349 14350 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 14351 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 14352 14353 static int check_btf_line(struct bpf_verifier_env *env, 14354 const union bpf_attr *attr, 14355 bpfptr_t uattr) 14356 { 14357 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 14358 struct bpf_subprog_info *sub; 14359 struct bpf_line_info *linfo; 14360 struct bpf_prog *prog; 14361 const struct btf *btf; 14362 bpfptr_t ulinfo; 14363 int err; 14364 14365 nr_linfo = attr->line_info_cnt; 14366 if (!nr_linfo) 14367 return 0; 14368 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 14369 return -EINVAL; 14370 14371 rec_size = attr->line_info_rec_size; 14372 if (rec_size < MIN_BPF_LINEINFO_SIZE || 14373 rec_size > MAX_LINEINFO_REC_SIZE || 14374 rec_size & (sizeof(u32) - 1)) 14375 return -EINVAL; 14376 14377 /* Need to zero it in case the userspace may 14378 * pass in a smaller bpf_line_info object. 14379 */ 14380 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 14381 GFP_KERNEL | __GFP_NOWARN); 14382 if (!linfo) 14383 return -ENOMEM; 14384 14385 prog = env->prog; 14386 btf = prog->aux->btf; 14387 14388 s = 0; 14389 sub = env->subprog_info; 14390 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 14391 expected_size = sizeof(struct bpf_line_info); 14392 ncopy = min_t(u32, expected_size, rec_size); 14393 for (i = 0; i < nr_linfo; i++) { 14394 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 14395 if (err) { 14396 if (err == -E2BIG) { 14397 verbose(env, "nonzero tailing record in line_info"); 14398 if (copy_to_bpfptr_offset(uattr, 14399 offsetof(union bpf_attr, line_info_rec_size), 14400 &expected_size, sizeof(expected_size))) 14401 err = -EFAULT; 14402 } 14403 goto err_free; 14404 } 14405 14406 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 14407 err = -EFAULT; 14408 goto err_free; 14409 } 14410 14411 /* 14412 * Check insn_off to ensure 14413 * 1) strictly increasing AND 14414 * 2) bounded by prog->len 14415 * 14416 * The linfo[0].insn_off == 0 check logically falls into 14417 * the later "missing bpf_line_info for func..." case 14418 * because the first linfo[0].insn_off must be the 14419 * first sub also and the first sub must have 14420 * subprog_info[0].start == 0. 14421 */ 14422 if ((i && linfo[i].insn_off <= prev_offset) || 14423 linfo[i].insn_off >= prog->len) { 14424 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 14425 i, linfo[i].insn_off, prev_offset, 14426 prog->len); 14427 err = -EINVAL; 14428 goto err_free; 14429 } 14430 14431 if (!prog->insnsi[linfo[i].insn_off].code) { 14432 verbose(env, 14433 "Invalid insn code at line_info[%u].insn_off\n", 14434 i); 14435 err = -EINVAL; 14436 goto err_free; 14437 } 14438 14439 if (!btf_name_by_offset(btf, linfo[i].line_off) || 14440 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 14441 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 14442 err = -EINVAL; 14443 goto err_free; 14444 } 14445 14446 if (s != env->subprog_cnt) { 14447 if (linfo[i].insn_off == sub[s].start) { 14448 sub[s].linfo_idx = i; 14449 s++; 14450 } else if (sub[s].start < linfo[i].insn_off) { 14451 verbose(env, "missing bpf_line_info for func#%u\n", s); 14452 err = -EINVAL; 14453 goto err_free; 14454 } 14455 } 14456 14457 prev_offset = linfo[i].insn_off; 14458 bpfptr_add(&ulinfo, rec_size); 14459 } 14460 14461 if (s != env->subprog_cnt) { 14462 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 14463 env->subprog_cnt - s, s); 14464 err = -EINVAL; 14465 goto err_free; 14466 } 14467 14468 prog->aux->linfo = linfo; 14469 prog->aux->nr_linfo = nr_linfo; 14470 14471 return 0; 14472 14473 err_free: 14474 kvfree(linfo); 14475 return err; 14476 } 14477 14478 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 14479 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 14480 14481 static int check_core_relo(struct bpf_verifier_env *env, 14482 const union bpf_attr *attr, 14483 bpfptr_t uattr) 14484 { 14485 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 14486 struct bpf_core_relo core_relo = {}; 14487 struct bpf_prog *prog = env->prog; 14488 const struct btf *btf = prog->aux->btf; 14489 struct bpf_core_ctx ctx = { 14490 .log = &env->log, 14491 .btf = btf, 14492 }; 14493 bpfptr_t u_core_relo; 14494 int err; 14495 14496 nr_core_relo = attr->core_relo_cnt; 14497 if (!nr_core_relo) 14498 return 0; 14499 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 14500 return -EINVAL; 14501 14502 rec_size = attr->core_relo_rec_size; 14503 if (rec_size < MIN_CORE_RELO_SIZE || 14504 rec_size > MAX_CORE_RELO_SIZE || 14505 rec_size % sizeof(u32)) 14506 return -EINVAL; 14507 14508 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 14509 expected_size = sizeof(struct bpf_core_relo); 14510 ncopy = min_t(u32, expected_size, rec_size); 14511 14512 /* Unlike func_info and line_info, copy and apply each CO-RE 14513 * relocation record one at a time. 14514 */ 14515 for (i = 0; i < nr_core_relo; i++) { 14516 /* future proofing when sizeof(bpf_core_relo) changes */ 14517 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 14518 if (err) { 14519 if (err == -E2BIG) { 14520 verbose(env, "nonzero tailing record in core_relo"); 14521 if (copy_to_bpfptr_offset(uattr, 14522 offsetof(union bpf_attr, core_relo_rec_size), 14523 &expected_size, sizeof(expected_size))) 14524 err = -EFAULT; 14525 } 14526 break; 14527 } 14528 14529 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 14530 err = -EFAULT; 14531 break; 14532 } 14533 14534 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 14535 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 14536 i, core_relo.insn_off, prog->len); 14537 err = -EINVAL; 14538 break; 14539 } 14540 14541 err = bpf_core_apply(&ctx, &core_relo, i, 14542 &prog->insnsi[core_relo.insn_off / 8]); 14543 if (err) 14544 break; 14545 bpfptr_add(&u_core_relo, rec_size); 14546 } 14547 return err; 14548 } 14549 14550 static int check_btf_info(struct bpf_verifier_env *env, 14551 const union bpf_attr *attr, 14552 bpfptr_t uattr) 14553 { 14554 struct btf *btf; 14555 int err; 14556 14557 if (!attr->func_info_cnt && !attr->line_info_cnt) { 14558 if (check_abnormal_return(env)) 14559 return -EINVAL; 14560 return 0; 14561 } 14562 14563 btf = btf_get_by_fd(attr->prog_btf_fd); 14564 if (IS_ERR(btf)) 14565 return PTR_ERR(btf); 14566 if (btf_is_kernel(btf)) { 14567 btf_put(btf); 14568 return -EACCES; 14569 } 14570 env->prog->aux->btf = btf; 14571 14572 err = check_btf_func(env, attr, uattr); 14573 if (err) 14574 return err; 14575 14576 err = check_btf_line(env, attr, uattr); 14577 if (err) 14578 return err; 14579 14580 err = check_core_relo(env, attr, uattr); 14581 if (err) 14582 return err; 14583 14584 return 0; 14585 } 14586 14587 /* check %cur's range satisfies %old's */ 14588 static bool range_within(struct bpf_reg_state *old, 14589 struct bpf_reg_state *cur) 14590 { 14591 return old->umin_value <= cur->umin_value && 14592 old->umax_value >= cur->umax_value && 14593 old->smin_value <= cur->smin_value && 14594 old->smax_value >= cur->smax_value && 14595 old->u32_min_value <= cur->u32_min_value && 14596 old->u32_max_value >= cur->u32_max_value && 14597 old->s32_min_value <= cur->s32_min_value && 14598 old->s32_max_value >= cur->s32_max_value; 14599 } 14600 14601 /* If in the old state two registers had the same id, then they need to have 14602 * the same id in the new state as well. But that id could be different from 14603 * the old state, so we need to track the mapping from old to new ids. 14604 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 14605 * regs with old id 5 must also have new id 9 for the new state to be safe. But 14606 * regs with a different old id could still have new id 9, we don't care about 14607 * that. 14608 * So we look through our idmap to see if this old id has been seen before. If 14609 * so, we require the new id to match; otherwise, we add the id pair to the map. 14610 */ 14611 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap) 14612 { 14613 unsigned int i; 14614 14615 /* either both IDs should be set or both should be zero */ 14616 if (!!old_id != !!cur_id) 14617 return false; 14618 14619 if (old_id == 0) /* cur_id == 0 as well */ 14620 return true; 14621 14622 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 14623 if (!idmap[i].old) { 14624 /* Reached an empty slot; haven't seen this id before */ 14625 idmap[i].old = old_id; 14626 idmap[i].cur = cur_id; 14627 return true; 14628 } 14629 if (idmap[i].old == old_id) 14630 return idmap[i].cur == cur_id; 14631 } 14632 /* We ran out of idmap slots, which should be impossible */ 14633 WARN_ON_ONCE(1); 14634 return false; 14635 } 14636 14637 static void clean_func_state(struct bpf_verifier_env *env, 14638 struct bpf_func_state *st) 14639 { 14640 enum bpf_reg_liveness live; 14641 int i, j; 14642 14643 for (i = 0; i < BPF_REG_FP; i++) { 14644 live = st->regs[i].live; 14645 /* liveness must not touch this register anymore */ 14646 st->regs[i].live |= REG_LIVE_DONE; 14647 if (!(live & REG_LIVE_READ)) 14648 /* since the register is unused, clear its state 14649 * to make further comparison simpler 14650 */ 14651 __mark_reg_not_init(env, &st->regs[i]); 14652 } 14653 14654 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 14655 live = st->stack[i].spilled_ptr.live; 14656 /* liveness must not touch this stack slot anymore */ 14657 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 14658 if (!(live & REG_LIVE_READ)) { 14659 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 14660 for (j = 0; j < BPF_REG_SIZE; j++) 14661 st->stack[i].slot_type[j] = STACK_INVALID; 14662 } 14663 } 14664 } 14665 14666 static void clean_verifier_state(struct bpf_verifier_env *env, 14667 struct bpf_verifier_state *st) 14668 { 14669 int i; 14670 14671 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 14672 /* all regs in this state in all frames were already marked */ 14673 return; 14674 14675 for (i = 0; i <= st->curframe; i++) 14676 clean_func_state(env, st->frame[i]); 14677 } 14678 14679 /* the parentage chains form a tree. 14680 * the verifier states are added to state lists at given insn and 14681 * pushed into state stack for future exploration. 14682 * when the verifier reaches bpf_exit insn some of the verifer states 14683 * stored in the state lists have their final liveness state already, 14684 * but a lot of states will get revised from liveness point of view when 14685 * the verifier explores other branches. 14686 * Example: 14687 * 1: r0 = 1 14688 * 2: if r1 == 100 goto pc+1 14689 * 3: r0 = 2 14690 * 4: exit 14691 * when the verifier reaches exit insn the register r0 in the state list of 14692 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 14693 * of insn 2 and goes exploring further. At the insn 4 it will walk the 14694 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 14695 * 14696 * Since the verifier pushes the branch states as it sees them while exploring 14697 * the program the condition of walking the branch instruction for the second 14698 * time means that all states below this branch were already explored and 14699 * their final liveness marks are already propagated. 14700 * Hence when the verifier completes the search of state list in is_state_visited() 14701 * we can call this clean_live_states() function to mark all liveness states 14702 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 14703 * will not be used. 14704 * This function also clears the registers and stack for states that !READ 14705 * to simplify state merging. 14706 * 14707 * Important note here that walking the same branch instruction in the callee 14708 * doesn't meant that the states are DONE. The verifier has to compare 14709 * the callsites 14710 */ 14711 static void clean_live_states(struct bpf_verifier_env *env, int insn, 14712 struct bpf_verifier_state *cur) 14713 { 14714 struct bpf_verifier_state_list *sl; 14715 int i; 14716 14717 sl = *explored_state(env, insn); 14718 while (sl) { 14719 if (sl->state.branches) 14720 goto next; 14721 if (sl->state.insn_idx != insn || 14722 sl->state.curframe != cur->curframe) 14723 goto next; 14724 for (i = 0; i <= cur->curframe; i++) 14725 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 14726 goto next; 14727 clean_verifier_state(env, &sl->state); 14728 next: 14729 sl = sl->next; 14730 } 14731 } 14732 14733 static bool regs_exact(const struct bpf_reg_state *rold, 14734 const struct bpf_reg_state *rcur, 14735 struct bpf_id_pair *idmap) 14736 { 14737 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 14738 check_ids(rold->id, rcur->id, idmap) && 14739 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 14740 } 14741 14742 /* Returns true if (rold safe implies rcur safe) */ 14743 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 14744 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap) 14745 { 14746 if (!(rold->live & REG_LIVE_READ)) 14747 /* explored state didn't use this */ 14748 return true; 14749 if (rold->type == NOT_INIT) 14750 /* explored state can't have used this */ 14751 return true; 14752 if (rcur->type == NOT_INIT) 14753 return false; 14754 14755 /* Enforce that register types have to match exactly, including their 14756 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 14757 * rule. 14758 * 14759 * One can make a point that using a pointer register as unbounded 14760 * SCALAR would be technically acceptable, but this could lead to 14761 * pointer leaks because scalars are allowed to leak while pointers 14762 * are not. We could make this safe in special cases if root is 14763 * calling us, but it's probably not worth the hassle. 14764 * 14765 * Also, register types that are *not* MAYBE_NULL could technically be 14766 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 14767 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 14768 * to the same map). 14769 * However, if the old MAYBE_NULL register then got NULL checked, 14770 * doing so could have affected others with the same id, and we can't 14771 * check for that because we lost the id when we converted to 14772 * a non-MAYBE_NULL variant. 14773 * So, as a general rule we don't allow mixing MAYBE_NULL and 14774 * non-MAYBE_NULL registers as well. 14775 */ 14776 if (rold->type != rcur->type) 14777 return false; 14778 14779 switch (base_type(rold->type)) { 14780 case SCALAR_VALUE: 14781 if (regs_exact(rold, rcur, idmap)) 14782 return true; 14783 if (env->explore_alu_limits) 14784 return false; 14785 if (!rold->precise) 14786 return true; 14787 /* new val must satisfy old val knowledge */ 14788 return range_within(rold, rcur) && 14789 tnum_in(rold->var_off, rcur->var_off); 14790 case PTR_TO_MAP_KEY: 14791 case PTR_TO_MAP_VALUE: 14792 case PTR_TO_MEM: 14793 case PTR_TO_BUF: 14794 case PTR_TO_TP_BUFFER: 14795 /* If the new min/max/var_off satisfy the old ones and 14796 * everything else matches, we are OK. 14797 */ 14798 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 14799 range_within(rold, rcur) && 14800 tnum_in(rold->var_off, rcur->var_off) && 14801 check_ids(rold->id, rcur->id, idmap) && 14802 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 14803 case PTR_TO_PACKET_META: 14804 case PTR_TO_PACKET: 14805 /* We must have at least as much range as the old ptr 14806 * did, so that any accesses which were safe before are 14807 * still safe. This is true even if old range < old off, 14808 * since someone could have accessed through (ptr - k), or 14809 * even done ptr -= k in a register, to get a safe access. 14810 */ 14811 if (rold->range > rcur->range) 14812 return false; 14813 /* If the offsets don't match, we can't trust our alignment; 14814 * nor can we be sure that we won't fall out of range. 14815 */ 14816 if (rold->off != rcur->off) 14817 return false; 14818 /* id relations must be preserved */ 14819 if (!check_ids(rold->id, rcur->id, idmap)) 14820 return false; 14821 /* new val must satisfy old val knowledge */ 14822 return range_within(rold, rcur) && 14823 tnum_in(rold->var_off, rcur->var_off); 14824 case PTR_TO_STACK: 14825 /* two stack pointers are equal only if they're pointing to 14826 * the same stack frame, since fp-8 in foo != fp-8 in bar 14827 */ 14828 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 14829 default: 14830 return regs_exact(rold, rcur, idmap); 14831 } 14832 } 14833 14834 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 14835 struct bpf_func_state *cur, struct bpf_id_pair *idmap) 14836 { 14837 int i, spi; 14838 14839 /* walk slots of the explored stack and ignore any additional 14840 * slots in the current stack, since explored(safe) state 14841 * didn't use them 14842 */ 14843 for (i = 0; i < old->allocated_stack; i++) { 14844 struct bpf_reg_state *old_reg, *cur_reg; 14845 14846 spi = i / BPF_REG_SIZE; 14847 14848 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 14849 i += BPF_REG_SIZE - 1; 14850 /* explored state didn't use this */ 14851 continue; 14852 } 14853 14854 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 14855 continue; 14856 14857 if (env->allow_uninit_stack && 14858 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 14859 continue; 14860 14861 /* explored stack has more populated slots than current stack 14862 * and these slots were used 14863 */ 14864 if (i >= cur->allocated_stack) 14865 return false; 14866 14867 /* if old state was safe with misc data in the stack 14868 * it will be safe with zero-initialized stack. 14869 * The opposite is not true 14870 */ 14871 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 14872 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 14873 continue; 14874 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 14875 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 14876 /* Ex: old explored (safe) state has STACK_SPILL in 14877 * this stack slot, but current has STACK_MISC -> 14878 * this verifier states are not equivalent, 14879 * return false to continue verification of this path 14880 */ 14881 return false; 14882 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 14883 continue; 14884 /* Both old and cur are having same slot_type */ 14885 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 14886 case STACK_SPILL: 14887 /* when explored and current stack slot are both storing 14888 * spilled registers, check that stored pointers types 14889 * are the same as well. 14890 * Ex: explored safe path could have stored 14891 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 14892 * but current path has stored: 14893 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 14894 * such verifier states are not equivalent. 14895 * return false to continue verification of this path 14896 */ 14897 if (!regsafe(env, &old->stack[spi].spilled_ptr, 14898 &cur->stack[spi].spilled_ptr, idmap)) 14899 return false; 14900 break; 14901 case STACK_DYNPTR: 14902 old_reg = &old->stack[spi].spilled_ptr; 14903 cur_reg = &cur->stack[spi].spilled_ptr; 14904 if (old_reg->dynptr.type != cur_reg->dynptr.type || 14905 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 14906 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 14907 return false; 14908 break; 14909 case STACK_ITER: 14910 old_reg = &old->stack[spi].spilled_ptr; 14911 cur_reg = &cur->stack[spi].spilled_ptr; 14912 /* iter.depth is not compared between states as it 14913 * doesn't matter for correctness and would otherwise 14914 * prevent convergence; we maintain it only to prevent 14915 * infinite loop check triggering, see 14916 * iter_active_depths_differ() 14917 */ 14918 if (old_reg->iter.btf != cur_reg->iter.btf || 14919 old_reg->iter.btf_id != cur_reg->iter.btf_id || 14920 old_reg->iter.state != cur_reg->iter.state || 14921 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 14922 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 14923 return false; 14924 break; 14925 case STACK_MISC: 14926 case STACK_ZERO: 14927 case STACK_INVALID: 14928 continue; 14929 /* Ensure that new unhandled slot types return false by default */ 14930 default: 14931 return false; 14932 } 14933 } 14934 return true; 14935 } 14936 14937 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 14938 struct bpf_id_pair *idmap) 14939 { 14940 int i; 14941 14942 if (old->acquired_refs != cur->acquired_refs) 14943 return false; 14944 14945 for (i = 0; i < old->acquired_refs; i++) { 14946 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 14947 return false; 14948 } 14949 14950 return true; 14951 } 14952 14953 /* compare two verifier states 14954 * 14955 * all states stored in state_list are known to be valid, since 14956 * verifier reached 'bpf_exit' instruction through them 14957 * 14958 * this function is called when verifier exploring different branches of 14959 * execution popped from the state stack. If it sees an old state that has 14960 * more strict register state and more strict stack state then this execution 14961 * branch doesn't need to be explored further, since verifier already 14962 * concluded that more strict state leads to valid finish. 14963 * 14964 * Therefore two states are equivalent if register state is more conservative 14965 * and explored stack state is more conservative than the current one. 14966 * Example: 14967 * explored current 14968 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 14969 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 14970 * 14971 * In other words if current stack state (one being explored) has more 14972 * valid slots than old one that already passed validation, it means 14973 * the verifier can stop exploring and conclude that current state is valid too 14974 * 14975 * Similarly with registers. If explored state has register type as invalid 14976 * whereas register type in current state is meaningful, it means that 14977 * the current state will reach 'bpf_exit' instruction safely 14978 */ 14979 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 14980 struct bpf_func_state *cur) 14981 { 14982 int i; 14983 14984 for (i = 0; i < MAX_BPF_REG; i++) 14985 if (!regsafe(env, &old->regs[i], &cur->regs[i], 14986 env->idmap_scratch)) 14987 return false; 14988 14989 if (!stacksafe(env, old, cur, env->idmap_scratch)) 14990 return false; 14991 14992 if (!refsafe(old, cur, env->idmap_scratch)) 14993 return false; 14994 14995 return true; 14996 } 14997 14998 static bool states_equal(struct bpf_verifier_env *env, 14999 struct bpf_verifier_state *old, 15000 struct bpf_verifier_state *cur) 15001 { 15002 int i; 15003 15004 if (old->curframe != cur->curframe) 15005 return false; 15006 15007 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch)); 15008 15009 /* Verification state from speculative execution simulation 15010 * must never prune a non-speculative execution one. 15011 */ 15012 if (old->speculative && !cur->speculative) 15013 return false; 15014 15015 if (old->active_lock.ptr != cur->active_lock.ptr) 15016 return false; 15017 15018 /* Old and cur active_lock's have to be either both present 15019 * or both absent. 15020 */ 15021 if (!!old->active_lock.id != !!cur->active_lock.id) 15022 return false; 15023 15024 if (old->active_lock.id && 15025 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch)) 15026 return false; 15027 15028 if (old->active_rcu_lock != cur->active_rcu_lock) 15029 return false; 15030 15031 /* for states to be equal callsites have to be the same 15032 * and all frame states need to be equivalent 15033 */ 15034 for (i = 0; i <= old->curframe; i++) { 15035 if (old->frame[i]->callsite != cur->frame[i]->callsite) 15036 return false; 15037 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 15038 return false; 15039 } 15040 return true; 15041 } 15042 15043 /* Return 0 if no propagation happened. Return negative error code if error 15044 * happened. Otherwise, return the propagated bit. 15045 */ 15046 static int propagate_liveness_reg(struct bpf_verifier_env *env, 15047 struct bpf_reg_state *reg, 15048 struct bpf_reg_state *parent_reg) 15049 { 15050 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 15051 u8 flag = reg->live & REG_LIVE_READ; 15052 int err; 15053 15054 /* When comes here, read flags of PARENT_REG or REG could be any of 15055 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 15056 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 15057 */ 15058 if (parent_flag == REG_LIVE_READ64 || 15059 /* Or if there is no read flag from REG. */ 15060 !flag || 15061 /* Or if the read flag from REG is the same as PARENT_REG. */ 15062 parent_flag == flag) 15063 return 0; 15064 15065 err = mark_reg_read(env, reg, parent_reg, flag); 15066 if (err) 15067 return err; 15068 15069 return flag; 15070 } 15071 15072 /* A write screens off any subsequent reads; but write marks come from the 15073 * straight-line code between a state and its parent. When we arrive at an 15074 * equivalent state (jump target or such) we didn't arrive by the straight-line 15075 * code, so read marks in the state must propagate to the parent regardless 15076 * of the state's write marks. That's what 'parent == state->parent' comparison 15077 * in mark_reg_read() is for. 15078 */ 15079 static int propagate_liveness(struct bpf_verifier_env *env, 15080 const struct bpf_verifier_state *vstate, 15081 struct bpf_verifier_state *vparent) 15082 { 15083 struct bpf_reg_state *state_reg, *parent_reg; 15084 struct bpf_func_state *state, *parent; 15085 int i, frame, err = 0; 15086 15087 if (vparent->curframe != vstate->curframe) { 15088 WARN(1, "propagate_live: parent frame %d current frame %d\n", 15089 vparent->curframe, vstate->curframe); 15090 return -EFAULT; 15091 } 15092 /* Propagate read liveness of registers... */ 15093 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 15094 for (frame = 0; frame <= vstate->curframe; frame++) { 15095 parent = vparent->frame[frame]; 15096 state = vstate->frame[frame]; 15097 parent_reg = parent->regs; 15098 state_reg = state->regs; 15099 /* We don't need to worry about FP liveness, it's read-only */ 15100 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 15101 err = propagate_liveness_reg(env, &state_reg[i], 15102 &parent_reg[i]); 15103 if (err < 0) 15104 return err; 15105 if (err == REG_LIVE_READ64) 15106 mark_insn_zext(env, &parent_reg[i]); 15107 } 15108 15109 /* Propagate stack slots. */ 15110 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 15111 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 15112 parent_reg = &parent->stack[i].spilled_ptr; 15113 state_reg = &state->stack[i].spilled_ptr; 15114 err = propagate_liveness_reg(env, state_reg, 15115 parent_reg); 15116 if (err < 0) 15117 return err; 15118 } 15119 } 15120 return 0; 15121 } 15122 15123 /* find precise scalars in the previous equivalent state and 15124 * propagate them into the current state 15125 */ 15126 static int propagate_precision(struct bpf_verifier_env *env, 15127 const struct bpf_verifier_state *old) 15128 { 15129 struct bpf_reg_state *state_reg; 15130 struct bpf_func_state *state; 15131 int i, err = 0, fr; 15132 15133 for (fr = old->curframe; fr >= 0; fr--) { 15134 state = old->frame[fr]; 15135 state_reg = state->regs; 15136 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 15137 if (state_reg->type != SCALAR_VALUE || 15138 !state_reg->precise || 15139 !(state_reg->live & REG_LIVE_READ)) 15140 continue; 15141 if (env->log.level & BPF_LOG_LEVEL2) 15142 verbose(env, "frame %d: propagating r%d\n", fr, i); 15143 err = mark_chain_precision_frame(env, fr, i); 15144 if (err < 0) 15145 return err; 15146 } 15147 15148 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 15149 if (!is_spilled_reg(&state->stack[i])) 15150 continue; 15151 state_reg = &state->stack[i].spilled_ptr; 15152 if (state_reg->type != SCALAR_VALUE || 15153 !state_reg->precise || 15154 !(state_reg->live & REG_LIVE_READ)) 15155 continue; 15156 if (env->log.level & BPF_LOG_LEVEL2) 15157 verbose(env, "frame %d: propagating fp%d\n", 15158 fr, (-i - 1) * BPF_REG_SIZE); 15159 err = mark_chain_precision_stack_frame(env, fr, i); 15160 if (err < 0) 15161 return err; 15162 } 15163 } 15164 return 0; 15165 } 15166 15167 static bool states_maybe_looping(struct bpf_verifier_state *old, 15168 struct bpf_verifier_state *cur) 15169 { 15170 struct bpf_func_state *fold, *fcur; 15171 int i, fr = cur->curframe; 15172 15173 if (old->curframe != fr) 15174 return false; 15175 15176 fold = old->frame[fr]; 15177 fcur = cur->frame[fr]; 15178 for (i = 0; i < MAX_BPF_REG; i++) 15179 if (memcmp(&fold->regs[i], &fcur->regs[i], 15180 offsetof(struct bpf_reg_state, parent))) 15181 return false; 15182 return true; 15183 } 15184 15185 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 15186 { 15187 return env->insn_aux_data[insn_idx].is_iter_next; 15188 } 15189 15190 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 15191 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 15192 * states to match, which otherwise would look like an infinite loop. So while 15193 * iter_next() calls are taken care of, we still need to be careful and 15194 * prevent erroneous and too eager declaration of "ininite loop", when 15195 * iterators are involved. 15196 * 15197 * Here's a situation in pseudo-BPF assembly form: 15198 * 15199 * 0: again: ; set up iter_next() call args 15200 * 1: r1 = &it ; <CHECKPOINT HERE> 15201 * 2: call bpf_iter_num_next ; this is iter_next() call 15202 * 3: if r0 == 0 goto done 15203 * 4: ... something useful here ... 15204 * 5: goto again ; another iteration 15205 * 6: done: 15206 * 7: r1 = &it 15207 * 8: call bpf_iter_num_destroy ; clean up iter state 15208 * 9: exit 15209 * 15210 * This is a typical loop. Let's assume that we have a prune point at 1:, 15211 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 15212 * again`, assuming other heuristics don't get in a way). 15213 * 15214 * When we first time come to 1:, let's say we have some state X. We proceed 15215 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 15216 * Now we come back to validate that forked ACTIVE state. We proceed through 15217 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 15218 * are converging. But the problem is that we don't know that yet, as this 15219 * convergence has to happen at iter_next() call site only. So if nothing is 15220 * done, at 1: verifier will use bounded loop logic and declare infinite 15221 * looping (and would be *technically* correct, if not for iterator's 15222 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 15223 * don't want that. So what we do in process_iter_next_call() when we go on 15224 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 15225 * a different iteration. So when we suspect an infinite loop, we additionally 15226 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 15227 * pretend we are not looping and wait for next iter_next() call. 15228 * 15229 * This only applies to ACTIVE state. In DRAINED state we don't expect to 15230 * loop, because that would actually mean infinite loop, as DRAINED state is 15231 * "sticky", and so we'll keep returning into the same instruction with the 15232 * same state (at least in one of possible code paths). 15233 * 15234 * This approach allows to keep infinite loop heuristic even in the face of 15235 * active iterator. E.g., C snippet below is and will be detected as 15236 * inifintely looping: 15237 * 15238 * struct bpf_iter_num it; 15239 * int *p, x; 15240 * 15241 * bpf_iter_num_new(&it, 0, 10); 15242 * while ((p = bpf_iter_num_next(&t))) { 15243 * x = p; 15244 * while (x--) {} // <<-- infinite loop here 15245 * } 15246 * 15247 */ 15248 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 15249 { 15250 struct bpf_reg_state *slot, *cur_slot; 15251 struct bpf_func_state *state; 15252 int i, fr; 15253 15254 for (fr = old->curframe; fr >= 0; fr--) { 15255 state = old->frame[fr]; 15256 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 15257 if (state->stack[i].slot_type[0] != STACK_ITER) 15258 continue; 15259 15260 slot = &state->stack[i].spilled_ptr; 15261 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 15262 continue; 15263 15264 cur_slot = &cur->frame[fr]->stack[i].spilled_ptr; 15265 if (cur_slot->iter.depth != slot->iter.depth) 15266 return true; 15267 } 15268 } 15269 return false; 15270 } 15271 15272 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 15273 { 15274 struct bpf_verifier_state_list *new_sl; 15275 struct bpf_verifier_state_list *sl, **pprev; 15276 struct bpf_verifier_state *cur = env->cur_state, *new; 15277 int i, j, err, states_cnt = 0; 15278 bool force_new_state = env->test_state_freq || is_force_checkpoint(env, insn_idx); 15279 bool add_new_state = force_new_state; 15280 15281 /* bpf progs typically have pruning point every 4 instructions 15282 * http://vger.kernel.org/bpfconf2019.html#session-1 15283 * Do not add new state for future pruning if the verifier hasn't seen 15284 * at least 2 jumps and at least 8 instructions. 15285 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 15286 * In tests that amounts to up to 50% reduction into total verifier 15287 * memory consumption and 20% verifier time speedup. 15288 */ 15289 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 15290 env->insn_processed - env->prev_insn_processed >= 8) 15291 add_new_state = true; 15292 15293 pprev = explored_state(env, insn_idx); 15294 sl = *pprev; 15295 15296 clean_live_states(env, insn_idx, cur); 15297 15298 while (sl) { 15299 states_cnt++; 15300 if (sl->state.insn_idx != insn_idx) 15301 goto next; 15302 15303 if (sl->state.branches) { 15304 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 15305 15306 if (frame->in_async_callback_fn && 15307 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 15308 /* Different async_entry_cnt means that the verifier is 15309 * processing another entry into async callback. 15310 * Seeing the same state is not an indication of infinite 15311 * loop or infinite recursion. 15312 * But finding the same state doesn't mean that it's safe 15313 * to stop processing the current state. The previous state 15314 * hasn't yet reached bpf_exit, since state.branches > 0. 15315 * Checking in_async_callback_fn alone is not enough either. 15316 * Since the verifier still needs to catch infinite loops 15317 * inside async callbacks. 15318 */ 15319 goto skip_inf_loop_check; 15320 } 15321 /* BPF open-coded iterators loop detection is special. 15322 * states_maybe_looping() logic is too simplistic in detecting 15323 * states that *might* be equivalent, because it doesn't know 15324 * about ID remapping, so don't even perform it. 15325 * See process_iter_next_call() and iter_active_depths_differ() 15326 * for overview of the logic. When current and one of parent 15327 * states are detected as equivalent, it's a good thing: we prove 15328 * convergence and can stop simulating further iterations. 15329 * It's safe to assume that iterator loop will finish, taking into 15330 * account iter_next() contract of eventually returning 15331 * sticky NULL result. 15332 */ 15333 if (is_iter_next_insn(env, insn_idx)) { 15334 if (states_equal(env, &sl->state, cur)) { 15335 struct bpf_func_state *cur_frame; 15336 struct bpf_reg_state *iter_state, *iter_reg; 15337 int spi; 15338 15339 cur_frame = cur->frame[cur->curframe]; 15340 /* btf_check_iter_kfuncs() enforces that 15341 * iter state pointer is always the first arg 15342 */ 15343 iter_reg = &cur_frame->regs[BPF_REG_1]; 15344 /* current state is valid due to states_equal(), 15345 * so we can assume valid iter and reg state, 15346 * no need for extra (re-)validations 15347 */ 15348 spi = __get_spi(iter_reg->off + iter_reg->var_off.value); 15349 iter_state = &func(env, iter_reg)->stack[spi].spilled_ptr; 15350 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE) 15351 goto hit; 15352 } 15353 goto skip_inf_loop_check; 15354 } 15355 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 15356 if (states_maybe_looping(&sl->state, cur) && 15357 states_equal(env, &sl->state, cur) && 15358 !iter_active_depths_differ(&sl->state, cur)) { 15359 verbose_linfo(env, insn_idx, "; "); 15360 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 15361 return -EINVAL; 15362 } 15363 /* if the verifier is processing a loop, avoid adding new state 15364 * too often, since different loop iterations have distinct 15365 * states and may not help future pruning. 15366 * This threshold shouldn't be too low to make sure that 15367 * a loop with large bound will be rejected quickly. 15368 * The most abusive loop will be: 15369 * r1 += 1 15370 * if r1 < 1000000 goto pc-2 15371 * 1M insn_procssed limit / 100 == 10k peak states. 15372 * This threshold shouldn't be too high either, since states 15373 * at the end of the loop are likely to be useful in pruning. 15374 */ 15375 skip_inf_loop_check: 15376 if (!force_new_state && 15377 env->jmps_processed - env->prev_jmps_processed < 20 && 15378 env->insn_processed - env->prev_insn_processed < 100) 15379 add_new_state = false; 15380 goto miss; 15381 } 15382 if (states_equal(env, &sl->state, cur)) { 15383 hit: 15384 sl->hit_cnt++; 15385 /* reached equivalent register/stack state, 15386 * prune the search. 15387 * Registers read by the continuation are read by us. 15388 * If we have any write marks in env->cur_state, they 15389 * will prevent corresponding reads in the continuation 15390 * from reaching our parent (an explored_state). Our 15391 * own state will get the read marks recorded, but 15392 * they'll be immediately forgotten as we're pruning 15393 * this state and will pop a new one. 15394 */ 15395 err = propagate_liveness(env, &sl->state, cur); 15396 15397 /* if previous state reached the exit with precision and 15398 * current state is equivalent to it (except precsion marks) 15399 * the precision needs to be propagated back in 15400 * the current state. 15401 */ 15402 err = err ? : push_jmp_history(env, cur); 15403 err = err ? : propagate_precision(env, &sl->state); 15404 if (err) 15405 return err; 15406 return 1; 15407 } 15408 miss: 15409 /* when new state is not going to be added do not increase miss count. 15410 * Otherwise several loop iterations will remove the state 15411 * recorded earlier. The goal of these heuristics is to have 15412 * states from some iterations of the loop (some in the beginning 15413 * and some at the end) to help pruning. 15414 */ 15415 if (add_new_state) 15416 sl->miss_cnt++; 15417 /* heuristic to determine whether this state is beneficial 15418 * to keep checking from state equivalence point of view. 15419 * Higher numbers increase max_states_per_insn and verification time, 15420 * but do not meaningfully decrease insn_processed. 15421 */ 15422 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 15423 /* the state is unlikely to be useful. Remove it to 15424 * speed up verification 15425 */ 15426 *pprev = sl->next; 15427 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 15428 u32 br = sl->state.branches; 15429 15430 WARN_ONCE(br, 15431 "BUG live_done but branches_to_explore %d\n", 15432 br); 15433 free_verifier_state(&sl->state, false); 15434 kfree(sl); 15435 env->peak_states--; 15436 } else { 15437 /* cannot free this state, since parentage chain may 15438 * walk it later. Add it for free_list instead to 15439 * be freed at the end of verification 15440 */ 15441 sl->next = env->free_list; 15442 env->free_list = sl; 15443 } 15444 sl = *pprev; 15445 continue; 15446 } 15447 next: 15448 pprev = &sl->next; 15449 sl = *pprev; 15450 } 15451 15452 if (env->max_states_per_insn < states_cnt) 15453 env->max_states_per_insn = states_cnt; 15454 15455 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 15456 return 0; 15457 15458 if (!add_new_state) 15459 return 0; 15460 15461 /* There were no equivalent states, remember the current one. 15462 * Technically the current state is not proven to be safe yet, 15463 * but it will either reach outer most bpf_exit (which means it's safe) 15464 * or it will be rejected. When there are no loops the verifier won't be 15465 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 15466 * again on the way to bpf_exit. 15467 * When looping the sl->state.branches will be > 0 and this state 15468 * will not be considered for equivalence until branches == 0. 15469 */ 15470 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 15471 if (!new_sl) 15472 return -ENOMEM; 15473 env->total_states++; 15474 env->peak_states++; 15475 env->prev_jmps_processed = env->jmps_processed; 15476 env->prev_insn_processed = env->insn_processed; 15477 15478 /* forget precise markings we inherited, see __mark_chain_precision */ 15479 if (env->bpf_capable) 15480 mark_all_scalars_imprecise(env, cur); 15481 15482 /* add new state to the head of linked list */ 15483 new = &new_sl->state; 15484 err = copy_verifier_state(new, cur); 15485 if (err) { 15486 free_verifier_state(new, false); 15487 kfree(new_sl); 15488 return err; 15489 } 15490 new->insn_idx = insn_idx; 15491 WARN_ONCE(new->branches != 1, 15492 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 15493 15494 cur->parent = new; 15495 cur->first_insn_idx = insn_idx; 15496 clear_jmp_history(cur); 15497 new_sl->next = *explored_state(env, insn_idx); 15498 *explored_state(env, insn_idx) = new_sl; 15499 /* connect new state to parentage chain. Current frame needs all 15500 * registers connected. Only r6 - r9 of the callers are alive (pushed 15501 * to the stack implicitly by JITs) so in callers' frames connect just 15502 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 15503 * the state of the call instruction (with WRITTEN set), and r0 comes 15504 * from callee with its full parentage chain, anyway. 15505 */ 15506 /* clear write marks in current state: the writes we did are not writes 15507 * our child did, so they don't screen off its reads from us. 15508 * (There are no read marks in current state, because reads always mark 15509 * their parent and current state never has children yet. Only 15510 * explored_states can get read marks.) 15511 */ 15512 for (j = 0; j <= cur->curframe; j++) { 15513 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 15514 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 15515 for (i = 0; i < BPF_REG_FP; i++) 15516 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 15517 } 15518 15519 /* all stack frames are accessible from callee, clear them all */ 15520 for (j = 0; j <= cur->curframe; j++) { 15521 struct bpf_func_state *frame = cur->frame[j]; 15522 struct bpf_func_state *newframe = new->frame[j]; 15523 15524 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 15525 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 15526 frame->stack[i].spilled_ptr.parent = 15527 &newframe->stack[i].spilled_ptr; 15528 } 15529 } 15530 return 0; 15531 } 15532 15533 /* Return true if it's OK to have the same insn return a different type. */ 15534 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 15535 { 15536 switch (base_type(type)) { 15537 case PTR_TO_CTX: 15538 case PTR_TO_SOCKET: 15539 case PTR_TO_SOCK_COMMON: 15540 case PTR_TO_TCP_SOCK: 15541 case PTR_TO_XDP_SOCK: 15542 case PTR_TO_BTF_ID: 15543 return false; 15544 default: 15545 return true; 15546 } 15547 } 15548 15549 /* If an instruction was previously used with particular pointer types, then we 15550 * need to be careful to avoid cases such as the below, where it may be ok 15551 * for one branch accessing the pointer, but not ok for the other branch: 15552 * 15553 * R1 = sock_ptr 15554 * goto X; 15555 * ... 15556 * R1 = some_other_valid_ptr; 15557 * goto X; 15558 * ... 15559 * R2 = *(u32 *)(R1 + 0); 15560 */ 15561 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 15562 { 15563 return src != prev && (!reg_type_mismatch_ok(src) || 15564 !reg_type_mismatch_ok(prev)); 15565 } 15566 15567 static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type type, 15568 bool allow_trust_missmatch) 15569 { 15570 enum bpf_reg_type *prev_type = &env->insn_aux_data[env->insn_idx].ptr_type; 15571 15572 if (*prev_type == NOT_INIT) { 15573 /* Saw a valid insn 15574 * dst_reg = *(u32 *)(src_reg + off) 15575 * save type to validate intersecting paths 15576 */ 15577 *prev_type = type; 15578 } else if (reg_type_mismatch(type, *prev_type)) { 15579 /* Abuser program is trying to use the same insn 15580 * dst_reg = *(u32*) (src_reg + off) 15581 * with different pointer types: 15582 * src_reg == ctx in one branch and 15583 * src_reg == stack|map in some other branch. 15584 * Reject it. 15585 */ 15586 if (allow_trust_missmatch && 15587 base_type(type) == PTR_TO_BTF_ID && 15588 base_type(*prev_type) == PTR_TO_BTF_ID) { 15589 /* 15590 * Have to support a use case when one path through 15591 * the program yields TRUSTED pointer while another 15592 * is UNTRUSTED. Fallback to UNTRUSTED to generate 15593 * BPF_PROBE_MEM. 15594 */ 15595 *prev_type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 15596 } else { 15597 verbose(env, "same insn cannot be used with different pointers\n"); 15598 return -EINVAL; 15599 } 15600 } 15601 15602 return 0; 15603 } 15604 15605 static int do_check(struct bpf_verifier_env *env) 15606 { 15607 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 15608 struct bpf_verifier_state *state = env->cur_state; 15609 struct bpf_insn *insns = env->prog->insnsi; 15610 struct bpf_reg_state *regs; 15611 int insn_cnt = env->prog->len; 15612 bool do_print_state = false; 15613 int prev_insn_idx = -1; 15614 15615 for (;;) { 15616 struct bpf_insn *insn; 15617 u8 class; 15618 int err; 15619 15620 env->prev_insn_idx = prev_insn_idx; 15621 if (env->insn_idx >= insn_cnt) { 15622 verbose(env, "invalid insn idx %d insn_cnt %d\n", 15623 env->insn_idx, insn_cnt); 15624 return -EFAULT; 15625 } 15626 15627 insn = &insns[env->insn_idx]; 15628 class = BPF_CLASS(insn->code); 15629 15630 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 15631 verbose(env, 15632 "BPF program is too large. Processed %d insn\n", 15633 env->insn_processed); 15634 return -E2BIG; 15635 } 15636 15637 state->last_insn_idx = env->prev_insn_idx; 15638 15639 if (is_prune_point(env, env->insn_idx)) { 15640 err = is_state_visited(env, env->insn_idx); 15641 if (err < 0) 15642 return err; 15643 if (err == 1) { 15644 /* found equivalent state, can prune the search */ 15645 if (env->log.level & BPF_LOG_LEVEL) { 15646 if (do_print_state) 15647 verbose(env, "\nfrom %d to %d%s: safe\n", 15648 env->prev_insn_idx, env->insn_idx, 15649 env->cur_state->speculative ? 15650 " (speculative execution)" : ""); 15651 else 15652 verbose(env, "%d: safe\n", env->insn_idx); 15653 } 15654 goto process_bpf_exit; 15655 } 15656 } 15657 15658 if (is_jmp_point(env, env->insn_idx)) { 15659 err = push_jmp_history(env, state); 15660 if (err) 15661 return err; 15662 } 15663 15664 if (signal_pending(current)) 15665 return -EAGAIN; 15666 15667 if (need_resched()) 15668 cond_resched(); 15669 15670 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 15671 verbose(env, "\nfrom %d to %d%s:", 15672 env->prev_insn_idx, env->insn_idx, 15673 env->cur_state->speculative ? 15674 " (speculative execution)" : ""); 15675 print_verifier_state(env, state->frame[state->curframe], true); 15676 do_print_state = false; 15677 } 15678 15679 if (env->log.level & BPF_LOG_LEVEL) { 15680 const struct bpf_insn_cbs cbs = { 15681 .cb_call = disasm_kfunc_name, 15682 .cb_print = verbose, 15683 .private_data = env, 15684 }; 15685 15686 if (verifier_state_scratched(env)) 15687 print_insn_state(env, state->frame[state->curframe]); 15688 15689 verbose_linfo(env, env->insn_idx, "; "); 15690 env->prev_log_len = env->log.len_used; 15691 verbose(env, "%d: ", env->insn_idx); 15692 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 15693 env->prev_insn_print_len = env->log.len_used - env->prev_log_len; 15694 env->prev_log_len = env->log.len_used; 15695 } 15696 15697 if (bpf_prog_is_offloaded(env->prog->aux)) { 15698 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 15699 env->prev_insn_idx); 15700 if (err) 15701 return err; 15702 } 15703 15704 regs = cur_regs(env); 15705 sanitize_mark_insn_seen(env); 15706 prev_insn_idx = env->insn_idx; 15707 15708 if (class == BPF_ALU || class == BPF_ALU64) { 15709 err = check_alu_op(env, insn); 15710 if (err) 15711 return err; 15712 15713 } else if (class == BPF_LDX) { 15714 enum bpf_reg_type src_reg_type; 15715 15716 /* check for reserved fields is already done */ 15717 15718 /* check src operand */ 15719 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15720 if (err) 15721 return err; 15722 15723 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 15724 if (err) 15725 return err; 15726 15727 src_reg_type = regs[insn->src_reg].type; 15728 15729 /* check that memory (src_reg + off) is readable, 15730 * the state of dst_reg will be updated by this func 15731 */ 15732 err = check_mem_access(env, env->insn_idx, insn->src_reg, 15733 insn->off, BPF_SIZE(insn->code), 15734 BPF_READ, insn->dst_reg, false); 15735 if (err) 15736 return err; 15737 15738 err = save_aux_ptr_type(env, src_reg_type, true); 15739 if (err) 15740 return err; 15741 } else if (class == BPF_STX) { 15742 enum bpf_reg_type dst_reg_type; 15743 15744 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 15745 err = check_atomic(env, env->insn_idx, insn); 15746 if (err) 15747 return err; 15748 env->insn_idx++; 15749 continue; 15750 } 15751 15752 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 15753 verbose(env, "BPF_STX uses reserved fields\n"); 15754 return -EINVAL; 15755 } 15756 15757 /* check src1 operand */ 15758 err = check_reg_arg(env, insn->src_reg, SRC_OP); 15759 if (err) 15760 return err; 15761 /* check src2 operand */ 15762 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15763 if (err) 15764 return err; 15765 15766 dst_reg_type = regs[insn->dst_reg].type; 15767 15768 /* check that memory (dst_reg + off) is writeable */ 15769 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 15770 insn->off, BPF_SIZE(insn->code), 15771 BPF_WRITE, insn->src_reg, false); 15772 if (err) 15773 return err; 15774 15775 err = save_aux_ptr_type(env, dst_reg_type, false); 15776 if (err) 15777 return err; 15778 } else if (class == BPF_ST) { 15779 enum bpf_reg_type dst_reg_type; 15780 15781 if (BPF_MODE(insn->code) != BPF_MEM || 15782 insn->src_reg != BPF_REG_0) { 15783 verbose(env, "BPF_ST uses reserved fields\n"); 15784 return -EINVAL; 15785 } 15786 /* check src operand */ 15787 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 15788 if (err) 15789 return err; 15790 15791 dst_reg_type = regs[insn->dst_reg].type; 15792 15793 /* check that memory (dst_reg + off) is writeable */ 15794 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 15795 insn->off, BPF_SIZE(insn->code), 15796 BPF_WRITE, -1, false); 15797 if (err) 15798 return err; 15799 15800 err = save_aux_ptr_type(env, dst_reg_type, false); 15801 if (err) 15802 return err; 15803 } else if (class == BPF_JMP || class == BPF_JMP32) { 15804 u8 opcode = BPF_OP(insn->code); 15805 15806 env->jmps_processed++; 15807 if (opcode == BPF_CALL) { 15808 if (BPF_SRC(insn->code) != BPF_K || 15809 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 15810 && insn->off != 0) || 15811 (insn->src_reg != BPF_REG_0 && 15812 insn->src_reg != BPF_PSEUDO_CALL && 15813 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 15814 insn->dst_reg != BPF_REG_0 || 15815 class == BPF_JMP32) { 15816 verbose(env, "BPF_CALL uses reserved fields\n"); 15817 return -EINVAL; 15818 } 15819 15820 if (env->cur_state->active_lock.ptr) { 15821 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 15822 (insn->src_reg == BPF_PSEUDO_CALL) || 15823 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 15824 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 15825 verbose(env, "function calls are not allowed while holding a lock\n"); 15826 return -EINVAL; 15827 } 15828 } 15829 if (insn->src_reg == BPF_PSEUDO_CALL) 15830 err = check_func_call(env, insn, &env->insn_idx); 15831 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 15832 err = check_kfunc_call(env, insn, &env->insn_idx); 15833 else 15834 err = check_helper_call(env, insn, &env->insn_idx); 15835 if (err) 15836 return err; 15837 15838 mark_reg_scratched(env, BPF_REG_0); 15839 } else if (opcode == BPF_JA) { 15840 if (BPF_SRC(insn->code) != BPF_K || 15841 insn->imm != 0 || 15842 insn->src_reg != BPF_REG_0 || 15843 insn->dst_reg != BPF_REG_0 || 15844 class == BPF_JMP32) { 15845 verbose(env, "BPF_JA uses reserved fields\n"); 15846 return -EINVAL; 15847 } 15848 15849 env->insn_idx += insn->off + 1; 15850 continue; 15851 15852 } else if (opcode == BPF_EXIT) { 15853 if (BPF_SRC(insn->code) != BPF_K || 15854 insn->imm != 0 || 15855 insn->src_reg != BPF_REG_0 || 15856 insn->dst_reg != BPF_REG_0 || 15857 class == BPF_JMP32) { 15858 verbose(env, "BPF_EXIT uses reserved fields\n"); 15859 return -EINVAL; 15860 } 15861 15862 if (env->cur_state->active_lock.ptr && 15863 !in_rbtree_lock_required_cb(env)) { 15864 verbose(env, "bpf_spin_unlock is missing\n"); 15865 return -EINVAL; 15866 } 15867 15868 if (env->cur_state->active_rcu_lock) { 15869 verbose(env, "bpf_rcu_read_unlock is missing\n"); 15870 return -EINVAL; 15871 } 15872 15873 /* We must do check_reference_leak here before 15874 * prepare_func_exit to handle the case when 15875 * state->curframe > 0, it may be a callback 15876 * function, for which reference_state must 15877 * match caller reference state when it exits. 15878 */ 15879 err = check_reference_leak(env); 15880 if (err) 15881 return err; 15882 15883 if (state->curframe) { 15884 /* exit from nested function */ 15885 err = prepare_func_exit(env, &env->insn_idx); 15886 if (err) 15887 return err; 15888 do_print_state = true; 15889 continue; 15890 } 15891 15892 err = check_return_code(env); 15893 if (err) 15894 return err; 15895 process_bpf_exit: 15896 mark_verifier_state_scratched(env); 15897 update_branch_counts(env, env->cur_state); 15898 err = pop_stack(env, &prev_insn_idx, 15899 &env->insn_idx, pop_log); 15900 if (err < 0) { 15901 if (err != -ENOENT) 15902 return err; 15903 break; 15904 } else { 15905 do_print_state = true; 15906 continue; 15907 } 15908 } else { 15909 err = check_cond_jmp_op(env, insn, &env->insn_idx); 15910 if (err) 15911 return err; 15912 } 15913 } else if (class == BPF_LD) { 15914 u8 mode = BPF_MODE(insn->code); 15915 15916 if (mode == BPF_ABS || mode == BPF_IND) { 15917 err = check_ld_abs(env, insn); 15918 if (err) 15919 return err; 15920 15921 } else if (mode == BPF_IMM) { 15922 err = check_ld_imm(env, insn); 15923 if (err) 15924 return err; 15925 15926 env->insn_idx++; 15927 sanitize_mark_insn_seen(env); 15928 } else { 15929 verbose(env, "invalid BPF_LD mode\n"); 15930 return -EINVAL; 15931 } 15932 } else { 15933 verbose(env, "unknown insn class %d\n", class); 15934 return -EINVAL; 15935 } 15936 15937 env->insn_idx++; 15938 } 15939 15940 return 0; 15941 } 15942 15943 static int find_btf_percpu_datasec(struct btf *btf) 15944 { 15945 const struct btf_type *t; 15946 const char *tname; 15947 int i, n; 15948 15949 /* 15950 * Both vmlinux and module each have their own ".data..percpu" 15951 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 15952 * types to look at only module's own BTF types. 15953 */ 15954 n = btf_nr_types(btf); 15955 if (btf_is_module(btf)) 15956 i = btf_nr_types(btf_vmlinux); 15957 else 15958 i = 1; 15959 15960 for(; i < n; i++) { 15961 t = btf_type_by_id(btf, i); 15962 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 15963 continue; 15964 15965 tname = btf_name_by_offset(btf, t->name_off); 15966 if (!strcmp(tname, ".data..percpu")) 15967 return i; 15968 } 15969 15970 return -ENOENT; 15971 } 15972 15973 /* replace pseudo btf_id with kernel symbol address */ 15974 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 15975 struct bpf_insn *insn, 15976 struct bpf_insn_aux_data *aux) 15977 { 15978 const struct btf_var_secinfo *vsi; 15979 const struct btf_type *datasec; 15980 struct btf_mod_pair *btf_mod; 15981 const struct btf_type *t; 15982 const char *sym_name; 15983 bool percpu = false; 15984 u32 type, id = insn->imm; 15985 struct btf *btf; 15986 s32 datasec_id; 15987 u64 addr; 15988 int i, btf_fd, err; 15989 15990 btf_fd = insn[1].imm; 15991 if (btf_fd) { 15992 btf = btf_get_by_fd(btf_fd); 15993 if (IS_ERR(btf)) { 15994 verbose(env, "invalid module BTF object FD specified.\n"); 15995 return -EINVAL; 15996 } 15997 } else { 15998 if (!btf_vmlinux) { 15999 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 16000 return -EINVAL; 16001 } 16002 btf = btf_vmlinux; 16003 btf_get(btf); 16004 } 16005 16006 t = btf_type_by_id(btf, id); 16007 if (!t) { 16008 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 16009 err = -ENOENT; 16010 goto err_put; 16011 } 16012 16013 if (!btf_type_is_var(t) && !btf_type_is_func(t)) { 16014 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR or KIND_FUNC\n", id); 16015 err = -EINVAL; 16016 goto err_put; 16017 } 16018 16019 sym_name = btf_name_by_offset(btf, t->name_off); 16020 addr = kallsyms_lookup_name(sym_name); 16021 if (!addr) { 16022 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 16023 sym_name); 16024 err = -ENOENT; 16025 goto err_put; 16026 } 16027 insn[0].imm = (u32)addr; 16028 insn[1].imm = addr >> 32; 16029 16030 if (btf_type_is_func(t)) { 16031 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 16032 aux->btf_var.mem_size = 0; 16033 goto check_btf; 16034 } 16035 16036 datasec_id = find_btf_percpu_datasec(btf); 16037 if (datasec_id > 0) { 16038 datasec = btf_type_by_id(btf, datasec_id); 16039 for_each_vsi(i, datasec, vsi) { 16040 if (vsi->type == id) { 16041 percpu = true; 16042 break; 16043 } 16044 } 16045 } 16046 16047 type = t->type; 16048 t = btf_type_skip_modifiers(btf, type, NULL); 16049 if (percpu) { 16050 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 16051 aux->btf_var.btf = btf; 16052 aux->btf_var.btf_id = type; 16053 } else if (!btf_type_is_struct(t)) { 16054 const struct btf_type *ret; 16055 const char *tname; 16056 u32 tsize; 16057 16058 /* resolve the type size of ksym. */ 16059 ret = btf_resolve_size(btf, t, &tsize); 16060 if (IS_ERR(ret)) { 16061 tname = btf_name_by_offset(btf, t->name_off); 16062 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 16063 tname, PTR_ERR(ret)); 16064 err = -EINVAL; 16065 goto err_put; 16066 } 16067 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 16068 aux->btf_var.mem_size = tsize; 16069 } else { 16070 aux->btf_var.reg_type = PTR_TO_BTF_ID; 16071 aux->btf_var.btf = btf; 16072 aux->btf_var.btf_id = type; 16073 } 16074 check_btf: 16075 /* check whether we recorded this BTF (and maybe module) already */ 16076 for (i = 0; i < env->used_btf_cnt; i++) { 16077 if (env->used_btfs[i].btf == btf) { 16078 btf_put(btf); 16079 return 0; 16080 } 16081 } 16082 16083 if (env->used_btf_cnt >= MAX_USED_BTFS) { 16084 err = -E2BIG; 16085 goto err_put; 16086 } 16087 16088 btf_mod = &env->used_btfs[env->used_btf_cnt]; 16089 btf_mod->btf = btf; 16090 btf_mod->module = NULL; 16091 16092 /* if we reference variables from kernel module, bump its refcount */ 16093 if (btf_is_module(btf)) { 16094 btf_mod->module = btf_try_get_module(btf); 16095 if (!btf_mod->module) { 16096 err = -ENXIO; 16097 goto err_put; 16098 } 16099 } 16100 16101 env->used_btf_cnt++; 16102 16103 return 0; 16104 err_put: 16105 btf_put(btf); 16106 return err; 16107 } 16108 16109 static bool is_tracing_prog_type(enum bpf_prog_type type) 16110 { 16111 switch (type) { 16112 case BPF_PROG_TYPE_KPROBE: 16113 case BPF_PROG_TYPE_TRACEPOINT: 16114 case BPF_PROG_TYPE_PERF_EVENT: 16115 case BPF_PROG_TYPE_RAW_TRACEPOINT: 16116 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 16117 return true; 16118 default: 16119 return false; 16120 } 16121 } 16122 16123 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 16124 struct bpf_map *map, 16125 struct bpf_prog *prog) 16126 16127 { 16128 enum bpf_prog_type prog_type = resolve_prog_type(prog); 16129 16130 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 16131 btf_record_has_field(map->record, BPF_RB_ROOT)) { 16132 if (is_tracing_prog_type(prog_type)) { 16133 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 16134 return -EINVAL; 16135 } 16136 } 16137 16138 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 16139 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 16140 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 16141 return -EINVAL; 16142 } 16143 16144 if (is_tracing_prog_type(prog_type)) { 16145 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 16146 return -EINVAL; 16147 } 16148 16149 if (prog->aux->sleepable) { 16150 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 16151 return -EINVAL; 16152 } 16153 } 16154 16155 if (btf_record_has_field(map->record, BPF_TIMER)) { 16156 if (is_tracing_prog_type(prog_type)) { 16157 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 16158 return -EINVAL; 16159 } 16160 } 16161 16162 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 16163 !bpf_offload_prog_map_match(prog, map)) { 16164 verbose(env, "offload device mismatch between prog and map\n"); 16165 return -EINVAL; 16166 } 16167 16168 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 16169 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 16170 return -EINVAL; 16171 } 16172 16173 if (prog->aux->sleepable) 16174 switch (map->map_type) { 16175 case BPF_MAP_TYPE_HASH: 16176 case BPF_MAP_TYPE_LRU_HASH: 16177 case BPF_MAP_TYPE_ARRAY: 16178 case BPF_MAP_TYPE_PERCPU_HASH: 16179 case BPF_MAP_TYPE_PERCPU_ARRAY: 16180 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 16181 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 16182 case BPF_MAP_TYPE_HASH_OF_MAPS: 16183 case BPF_MAP_TYPE_RINGBUF: 16184 case BPF_MAP_TYPE_USER_RINGBUF: 16185 case BPF_MAP_TYPE_INODE_STORAGE: 16186 case BPF_MAP_TYPE_SK_STORAGE: 16187 case BPF_MAP_TYPE_TASK_STORAGE: 16188 case BPF_MAP_TYPE_CGRP_STORAGE: 16189 break; 16190 default: 16191 verbose(env, 16192 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 16193 return -EINVAL; 16194 } 16195 16196 return 0; 16197 } 16198 16199 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 16200 { 16201 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 16202 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 16203 } 16204 16205 /* find and rewrite pseudo imm in ld_imm64 instructions: 16206 * 16207 * 1. if it accesses map FD, replace it with actual map pointer. 16208 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 16209 * 16210 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 16211 */ 16212 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 16213 { 16214 struct bpf_insn *insn = env->prog->insnsi; 16215 int insn_cnt = env->prog->len; 16216 int i, j, err; 16217 16218 err = bpf_prog_calc_tag(env->prog); 16219 if (err) 16220 return err; 16221 16222 for (i = 0; i < insn_cnt; i++, insn++) { 16223 if (BPF_CLASS(insn->code) == BPF_LDX && 16224 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 16225 verbose(env, "BPF_LDX uses reserved fields\n"); 16226 return -EINVAL; 16227 } 16228 16229 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 16230 struct bpf_insn_aux_data *aux; 16231 struct bpf_map *map; 16232 struct fd f; 16233 u64 addr; 16234 u32 fd; 16235 16236 if (i == insn_cnt - 1 || insn[1].code != 0 || 16237 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 16238 insn[1].off != 0) { 16239 verbose(env, "invalid bpf_ld_imm64 insn\n"); 16240 return -EINVAL; 16241 } 16242 16243 if (insn[0].src_reg == 0) 16244 /* valid generic load 64-bit imm */ 16245 goto next_insn; 16246 16247 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 16248 aux = &env->insn_aux_data[i]; 16249 err = check_pseudo_btf_id(env, insn, aux); 16250 if (err) 16251 return err; 16252 goto next_insn; 16253 } 16254 16255 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 16256 aux = &env->insn_aux_data[i]; 16257 aux->ptr_type = PTR_TO_FUNC; 16258 goto next_insn; 16259 } 16260 16261 /* In final convert_pseudo_ld_imm64() step, this is 16262 * converted into regular 64-bit imm load insn. 16263 */ 16264 switch (insn[0].src_reg) { 16265 case BPF_PSEUDO_MAP_VALUE: 16266 case BPF_PSEUDO_MAP_IDX_VALUE: 16267 break; 16268 case BPF_PSEUDO_MAP_FD: 16269 case BPF_PSEUDO_MAP_IDX: 16270 if (insn[1].imm == 0) 16271 break; 16272 fallthrough; 16273 default: 16274 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 16275 return -EINVAL; 16276 } 16277 16278 switch (insn[0].src_reg) { 16279 case BPF_PSEUDO_MAP_IDX_VALUE: 16280 case BPF_PSEUDO_MAP_IDX: 16281 if (bpfptr_is_null(env->fd_array)) { 16282 verbose(env, "fd_idx without fd_array is invalid\n"); 16283 return -EPROTO; 16284 } 16285 if (copy_from_bpfptr_offset(&fd, env->fd_array, 16286 insn[0].imm * sizeof(fd), 16287 sizeof(fd))) 16288 return -EFAULT; 16289 break; 16290 default: 16291 fd = insn[0].imm; 16292 break; 16293 } 16294 16295 f = fdget(fd); 16296 map = __bpf_map_get(f); 16297 if (IS_ERR(map)) { 16298 verbose(env, "fd %d is not pointing to valid bpf_map\n", 16299 insn[0].imm); 16300 return PTR_ERR(map); 16301 } 16302 16303 err = check_map_prog_compatibility(env, map, env->prog); 16304 if (err) { 16305 fdput(f); 16306 return err; 16307 } 16308 16309 aux = &env->insn_aux_data[i]; 16310 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 16311 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 16312 addr = (unsigned long)map; 16313 } else { 16314 u32 off = insn[1].imm; 16315 16316 if (off >= BPF_MAX_VAR_OFF) { 16317 verbose(env, "direct value offset of %u is not allowed\n", off); 16318 fdput(f); 16319 return -EINVAL; 16320 } 16321 16322 if (!map->ops->map_direct_value_addr) { 16323 verbose(env, "no direct value access support for this map type\n"); 16324 fdput(f); 16325 return -EINVAL; 16326 } 16327 16328 err = map->ops->map_direct_value_addr(map, &addr, off); 16329 if (err) { 16330 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 16331 map->value_size, off); 16332 fdput(f); 16333 return err; 16334 } 16335 16336 aux->map_off = off; 16337 addr += off; 16338 } 16339 16340 insn[0].imm = (u32)addr; 16341 insn[1].imm = addr >> 32; 16342 16343 /* check whether we recorded this map already */ 16344 for (j = 0; j < env->used_map_cnt; j++) { 16345 if (env->used_maps[j] == map) { 16346 aux->map_index = j; 16347 fdput(f); 16348 goto next_insn; 16349 } 16350 } 16351 16352 if (env->used_map_cnt >= MAX_USED_MAPS) { 16353 fdput(f); 16354 return -E2BIG; 16355 } 16356 16357 /* hold the map. If the program is rejected by verifier, 16358 * the map will be released by release_maps() or it 16359 * will be used by the valid program until it's unloaded 16360 * and all maps are released in free_used_maps() 16361 */ 16362 bpf_map_inc(map); 16363 16364 aux->map_index = env->used_map_cnt; 16365 env->used_maps[env->used_map_cnt++] = map; 16366 16367 if (bpf_map_is_cgroup_storage(map) && 16368 bpf_cgroup_storage_assign(env->prog->aux, map)) { 16369 verbose(env, "only one cgroup storage of each type is allowed\n"); 16370 fdput(f); 16371 return -EBUSY; 16372 } 16373 16374 fdput(f); 16375 next_insn: 16376 insn++; 16377 i++; 16378 continue; 16379 } 16380 16381 /* Basic sanity check before we invest more work here. */ 16382 if (!bpf_opcode_in_insntable(insn->code)) { 16383 verbose(env, "unknown opcode %02x\n", insn->code); 16384 return -EINVAL; 16385 } 16386 } 16387 16388 /* now all pseudo BPF_LD_IMM64 instructions load valid 16389 * 'struct bpf_map *' into a register instead of user map_fd. 16390 * These pointers will be used later by verifier to validate map access. 16391 */ 16392 return 0; 16393 } 16394 16395 /* drop refcnt of maps used by the rejected program */ 16396 static void release_maps(struct bpf_verifier_env *env) 16397 { 16398 __bpf_free_used_maps(env->prog->aux, env->used_maps, 16399 env->used_map_cnt); 16400 } 16401 16402 /* drop refcnt of maps used by the rejected program */ 16403 static void release_btfs(struct bpf_verifier_env *env) 16404 { 16405 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 16406 env->used_btf_cnt); 16407 } 16408 16409 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 16410 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 16411 { 16412 struct bpf_insn *insn = env->prog->insnsi; 16413 int insn_cnt = env->prog->len; 16414 int i; 16415 16416 for (i = 0; i < insn_cnt; i++, insn++) { 16417 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 16418 continue; 16419 if (insn->src_reg == BPF_PSEUDO_FUNC) 16420 continue; 16421 insn->src_reg = 0; 16422 } 16423 } 16424 16425 /* single env->prog->insni[off] instruction was replaced with the range 16426 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 16427 * [0, off) and [off, end) to new locations, so the patched range stays zero 16428 */ 16429 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 16430 struct bpf_insn_aux_data *new_data, 16431 struct bpf_prog *new_prog, u32 off, u32 cnt) 16432 { 16433 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 16434 struct bpf_insn *insn = new_prog->insnsi; 16435 u32 old_seen = old_data[off].seen; 16436 u32 prog_len; 16437 int i; 16438 16439 /* aux info at OFF always needs adjustment, no matter fast path 16440 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 16441 * original insn at old prog. 16442 */ 16443 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 16444 16445 if (cnt == 1) 16446 return; 16447 prog_len = new_prog->len; 16448 16449 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 16450 memcpy(new_data + off + cnt - 1, old_data + off, 16451 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 16452 for (i = off; i < off + cnt - 1; i++) { 16453 /* Expand insni[off]'s seen count to the patched range. */ 16454 new_data[i].seen = old_seen; 16455 new_data[i].zext_dst = insn_has_def32(env, insn + i); 16456 } 16457 env->insn_aux_data = new_data; 16458 vfree(old_data); 16459 } 16460 16461 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 16462 { 16463 int i; 16464 16465 if (len == 1) 16466 return; 16467 /* NOTE: fake 'exit' subprog should be updated as well. */ 16468 for (i = 0; i <= env->subprog_cnt; i++) { 16469 if (env->subprog_info[i].start <= off) 16470 continue; 16471 env->subprog_info[i].start += len - 1; 16472 } 16473 } 16474 16475 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 16476 { 16477 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 16478 int i, sz = prog->aux->size_poke_tab; 16479 struct bpf_jit_poke_descriptor *desc; 16480 16481 for (i = 0; i < sz; i++) { 16482 desc = &tab[i]; 16483 if (desc->insn_idx <= off) 16484 continue; 16485 desc->insn_idx += len - 1; 16486 } 16487 } 16488 16489 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 16490 const struct bpf_insn *patch, u32 len) 16491 { 16492 struct bpf_prog *new_prog; 16493 struct bpf_insn_aux_data *new_data = NULL; 16494 16495 if (len > 1) { 16496 new_data = vzalloc(array_size(env->prog->len + len - 1, 16497 sizeof(struct bpf_insn_aux_data))); 16498 if (!new_data) 16499 return NULL; 16500 } 16501 16502 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 16503 if (IS_ERR(new_prog)) { 16504 if (PTR_ERR(new_prog) == -ERANGE) 16505 verbose(env, 16506 "insn %d cannot be patched due to 16-bit range\n", 16507 env->insn_aux_data[off].orig_idx); 16508 vfree(new_data); 16509 return NULL; 16510 } 16511 adjust_insn_aux_data(env, new_data, new_prog, off, len); 16512 adjust_subprog_starts(env, off, len); 16513 adjust_poke_descs(new_prog, off, len); 16514 return new_prog; 16515 } 16516 16517 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 16518 u32 off, u32 cnt) 16519 { 16520 int i, j; 16521 16522 /* find first prog starting at or after off (first to remove) */ 16523 for (i = 0; i < env->subprog_cnt; i++) 16524 if (env->subprog_info[i].start >= off) 16525 break; 16526 /* find first prog starting at or after off + cnt (first to stay) */ 16527 for (j = i; j < env->subprog_cnt; j++) 16528 if (env->subprog_info[j].start >= off + cnt) 16529 break; 16530 /* if j doesn't start exactly at off + cnt, we are just removing 16531 * the front of previous prog 16532 */ 16533 if (env->subprog_info[j].start != off + cnt) 16534 j--; 16535 16536 if (j > i) { 16537 struct bpf_prog_aux *aux = env->prog->aux; 16538 int move; 16539 16540 /* move fake 'exit' subprog as well */ 16541 move = env->subprog_cnt + 1 - j; 16542 16543 memmove(env->subprog_info + i, 16544 env->subprog_info + j, 16545 sizeof(*env->subprog_info) * move); 16546 env->subprog_cnt -= j - i; 16547 16548 /* remove func_info */ 16549 if (aux->func_info) { 16550 move = aux->func_info_cnt - j; 16551 16552 memmove(aux->func_info + i, 16553 aux->func_info + j, 16554 sizeof(*aux->func_info) * move); 16555 aux->func_info_cnt -= j - i; 16556 /* func_info->insn_off is set after all code rewrites, 16557 * in adjust_btf_func() - no need to adjust 16558 */ 16559 } 16560 } else { 16561 /* convert i from "first prog to remove" to "first to adjust" */ 16562 if (env->subprog_info[i].start == off) 16563 i++; 16564 } 16565 16566 /* update fake 'exit' subprog as well */ 16567 for (; i <= env->subprog_cnt; i++) 16568 env->subprog_info[i].start -= cnt; 16569 16570 return 0; 16571 } 16572 16573 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 16574 u32 cnt) 16575 { 16576 struct bpf_prog *prog = env->prog; 16577 u32 i, l_off, l_cnt, nr_linfo; 16578 struct bpf_line_info *linfo; 16579 16580 nr_linfo = prog->aux->nr_linfo; 16581 if (!nr_linfo) 16582 return 0; 16583 16584 linfo = prog->aux->linfo; 16585 16586 /* find first line info to remove, count lines to be removed */ 16587 for (i = 0; i < nr_linfo; i++) 16588 if (linfo[i].insn_off >= off) 16589 break; 16590 16591 l_off = i; 16592 l_cnt = 0; 16593 for (; i < nr_linfo; i++) 16594 if (linfo[i].insn_off < off + cnt) 16595 l_cnt++; 16596 else 16597 break; 16598 16599 /* First live insn doesn't match first live linfo, it needs to "inherit" 16600 * last removed linfo. prog is already modified, so prog->len == off 16601 * means no live instructions after (tail of the program was removed). 16602 */ 16603 if (prog->len != off && l_cnt && 16604 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 16605 l_cnt--; 16606 linfo[--i].insn_off = off + cnt; 16607 } 16608 16609 /* remove the line info which refer to the removed instructions */ 16610 if (l_cnt) { 16611 memmove(linfo + l_off, linfo + i, 16612 sizeof(*linfo) * (nr_linfo - i)); 16613 16614 prog->aux->nr_linfo -= l_cnt; 16615 nr_linfo = prog->aux->nr_linfo; 16616 } 16617 16618 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 16619 for (i = l_off; i < nr_linfo; i++) 16620 linfo[i].insn_off -= cnt; 16621 16622 /* fix up all subprogs (incl. 'exit') which start >= off */ 16623 for (i = 0; i <= env->subprog_cnt; i++) 16624 if (env->subprog_info[i].linfo_idx > l_off) { 16625 /* program may have started in the removed region but 16626 * may not be fully removed 16627 */ 16628 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 16629 env->subprog_info[i].linfo_idx -= l_cnt; 16630 else 16631 env->subprog_info[i].linfo_idx = l_off; 16632 } 16633 16634 return 0; 16635 } 16636 16637 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 16638 { 16639 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 16640 unsigned int orig_prog_len = env->prog->len; 16641 int err; 16642 16643 if (bpf_prog_is_offloaded(env->prog->aux)) 16644 bpf_prog_offload_remove_insns(env, off, cnt); 16645 16646 err = bpf_remove_insns(env->prog, off, cnt); 16647 if (err) 16648 return err; 16649 16650 err = adjust_subprog_starts_after_remove(env, off, cnt); 16651 if (err) 16652 return err; 16653 16654 err = bpf_adj_linfo_after_remove(env, off, cnt); 16655 if (err) 16656 return err; 16657 16658 memmove(aux_data + off, aux_data + off + cnt, 16659 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 16660 16661 return 0; 16662 } 16663 16664 /* The verifier does more data flow analysis than llvm and will not 16665 * explore branches that are dead at run time. Malicious programs can 16666 * have dead code too. Therefore replace all dead at-run-time code 16667 * with 'ja -1'. 16668 * 16669 * Just nops are not optimal, e.g. if they would sit at the end of the 16670 * program and through another bug we would manage to jump there, then 16671 * we'd execute beyond program memory otherwise. Returning exception 16672 * code also wouldn't work since we can have subprogs where the dead 16673 * code could be located. 16674 */ 16675 static void sanitize_dead_code(struct bpf_verifier_env *env) 16676 { 16677 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 16678 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 16679 struct bpf_insn *insn = env->prog->insnsi; 16680 const int insn_cnt = env->prog->len; 16681 int i; 16682 16683 for (i = 0; i < insn_cnt; i++) { 16684 if (aux_data[i].seen) 16685 continue; 16686 memcpy(insn + i, &trap, sizeof(trap)); 16687 aux_data[i].zext_dst = false; 16688 } 16689 } 16690 16691 static bool insn_is_cond_jump(u8 code) 16692 { 16693 u8 op; 16694 16695 if (BPF_CLASS(code) == BPF_JMP32) 16696 return true; 16697 16698 if (BPF_CLASS(code) != BPF_JMP) 16699 return false; 16700 16701 op = BPF_OP(code); 16702 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 16703 } 16704 16705 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 16706 { 16707 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 16708 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 16709 struct bpf_insn *insn = env->prog->insnsi; 16710 const int insn_cnt = env->prog->len; 16711 int i; 16712 16713 for (i = 0; i < insn_cnt; i++, insn++) { 16714 if (!insn_is_cond_jump(insn->code)) 16715 continue; 16716 16717 if (!aux_data[i + 1].seen) 16718 ja.off = insn->off; 16719 else if (!aux_data[i + 1 + insn->off].seen) 16720 ja.off = 0; 16721 else 16722 continue; 16723 16724 if (bpf_prog_is_offloaded(env->prog->aux)) 16725 bpf_prog_offload_replace_insn(env, i, &ja); 16726 16727 memcpy(insn, &ja, sizeof(ja)); 16728 } 16729 } 16730 16731 static int opt_remove_dead_code(struct bpf_verifier_env *env) 16732 { 16733 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 16734 int insn_cnt = env->prog->len; 16735 int i, err; 16736 16737 for (i = 0; i < insn_cnt; i++) { 16738 int j; 16739 16740 j = 0; 16741 while (i + j < insn_cnt && !aux_data[i + j].seen) 16742 j++; 16743 if (!j) 16744 continue; 16745 16746 err = verifier_remove_insns(env, i, j); 16747 if (err) 16748 return err; 16749 insn_cnt = env->prog->len; 16750 } 16751 16752 return 0; 16753 } 16754 16755 static int opt_remove_nops(struct bpf_verifier_env *env) 16756 { 16757 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 16758 struct bpf_insn *insn = env->prog->insnsi; 16759 int insn_cnt = env->prog->len; 16760 int i, err; 16761 16762 for (i = 0; i < insn_cnt; i++) { 16763 if (memcmp(&insn[i], &ja, sizeof(ja))) 16764 continue; 16765 16766 err = verifier_remove_insns(env, i, 1); 16767 if (err) 16768 return err; 16769 insn_cnt--; 16770 i--; 16771 } 16772 16773 return 0; 16774 } 16775 16776 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 16777 const union bpf_attr *attr) 16778 { 16779 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 16780 struct bpf_insn_aux_data *aux = env->insn_aux_data; 16781 int i, patch_len, delta = 0, len = env->prog->len; 16782 struct bpf_insn *insns = env->prog->insnsi; 16783 struct bpf_prog *new_prog; 16784 bool rnd_hi32; 16785 16786 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 16787 zext_patch[1] = BPF_ZEXT_REG(0); 16788 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 16789 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 16790 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 16791 for (i = 0; i < len; i++) { 16792 int adj_idx = i + delta; 16793 struct bpf_insn insn; 16794 int load_reg; 16795 16796 insn = insns[adj_idx]; 16797 load_reg = insn_def_regno(&insn); 16798 if (!aux[adj_idx].zext_dst) { 16799 u8 code, class; 16800 u32 imm_rnd; 16801 16802 if (!rnd_hi32) 16803 continue; 16804 16805 code = insn.code; 16806 class = BPF_CLASS(code); 16807 if (load_reg == -1) 16808 continue; 16809 16810 /* NOTE: arg "reg" (the fourth one) is only used for 16811 * BPF_STX + SRC_OP, so it is safe to pass NULL 16812 * here. 16813 */ 16814 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 16815 if (class == BPF_LD && 16816 BPF_MODE(code) == BPF_IMM) 16817 i++; 16818 continue; 16819 } 16820 16821 /* ctx load could be transformed into wider load. */ 16822 if (class == BPF_LDX && 16823 aux[adj_idx].ptr_type == PTR_TO_CTX) 16824 continue; 16825 16826 imm_rnd = get_random_u32(); 16827 rnd_hi32_patch[0] = insn; 16828 rnd_hi32_patch[1].imm = imm_rnd; 16829 rnd_hi32_patch[3].dst_reg = load_reg; 16830 patch = rnd_hi32_patch; 16831 patch_len = 4; 16832 goto apply_patch_buffer; 16833 } 16834 16835 /* Add in an zero-extend instruction if a) the JIT has requested 16836 * it or b) it's a CMPXCHG. 16837 * 16838 * The latter is because: BPF_CMPXCHG always loads a value into 16839 * R0, therefore always zero-extends. However some archs' 16840 * equivalent instruction only does this load when the 16841 * comparison is successful. This detail of CMPXCHG is 16842 * orthogonal to the general zero-extension behaviour of the 16843 * CPU, so it's treated independently of bpf_jit_needs_zext. 16844 */ 16845 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 16846 continue; 16847 16848 /* Zero-extension is done by the caller. */ 16849 if (bpf_pseudo_kfunc_call(&insn)) 16850 continue; 16851 16852 if (WARN_ON(load_reg == -1)) { 16853 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 16854 return -EFAULT; 16855 } 16856 16857 zext_patch[0] = insn; 16858 zext_patch[1].dst_reg = load_reg; 16859 zext_patch[1].src_reg = load_reg; 16860 patch = zext_patch; 16861 patch_len = 2; 16862 apply_patch_buffer: 16863 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 16864 if (!new_prog) 16865 return -ENOMEM; 16866 env->prog = new_prog; 16867 insns = new_prog->insnsi; 16868 aux = env->insn_aux_data; 16869 delta += patch_len - 1; 16870 } 16871 16872 return 0; 16873 } 16874 16875 /* convert load instructions that access fields of a context type into a 16876 * sequence of instructions that access fields of the underlying structure: 16877 * struct __sk_buff -> struct sk_buff 16878 * struct bpf_sock_ops -> struct sock 16879 */ 16880 static int convert_ctx_accesses(struct bpf_verifier_env *env) 16881 { 16882 const struct bpf_verifier_ops *ops = env->ops; 16883 int i, cnt, size, ctx_field_size, delta = 0; 16884 const int insn_cnt = env->prog->len; 16885 struct bpf_insn insn_buf[16], *insn; 16886 u32 target_size, size_default, off; 16887 struct bpf_prog *new_prog; 16888 enum bpf_access_type type; 16889 bool is_narrower_load; 16890 16891 if (ops->gen_prologue || env->seen_direct_write) { 16892 if (!ops->gen_prologue) { 16893 verbose(env, "bpf verifier is misconfigured\n"); 16894 return -EINVAL; 16895 } 16896 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 16897 env->prog); 16898 if (cnt >= ARRAY_SIZE(insn_buf)) { 16899 verbose(env, "bpf verifier is misconfigured\n"); 16900 return -EINVAL; 16901 } else if (cnt) { 16902 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 16903 if (!new_prog) 16904 return -ENOMEM; 16905 16906 env->prog = new_prog; 16907 delta += cnt - 1; 16908 } 16909 } 16910 16911 if (bpf_prog_is_offloaded(env->prog->aux)) 16912 return 0; 16913 16914 insn = env->prog->insnsi + delta; 16915 16916 for (i = 0; i < insn_cnt; i++, insn++) { 16917 bpf_convert_ctx_access_t convert_ctx_access; 16918 16919 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 16920 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 16921 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 16922 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) { 16923 type = BPF_READ; 16924 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 16925 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 16926 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 16927 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 16928 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 16929 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 16930 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 16931 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 16932 type = BPF_WRITE; 16933 } else { 16934 continue; 16935 } 16936 16937 if (type == BPF_WRITE && 16938 env->insn_aux_data[i + delta].sanitize_stack_spill) { 16939 struct bpf_insn patch[] = { 16940 *insn, 16941 BPF_ST_NOSPEC(), 16942 }; 16943 16944 cnt = ARRAY_SIZE(patch); 16945 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 16946 if (!new_prog) 16947 return -ENOMEM; 16948 16949 delta += cnt - 1; 16950 env->prog = new_prog; 16951 insn = new_prog->insnsi + i + delta; 16952 continue; 16953 } 16954 16955 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 16956 case PTR_TO_CTX: 16957 if (!ops->convert_ctx_access) 16958 continue; 16959 convert_ctx_access = ops->convert_ctx_access; 16960 break; 16961 case PTR_TO_SOCKET: 16962 case PTR_TO_SOCK_COMMON: 16963 convert_ctx_access = bpf_sock_convert_ctx_access; 16964 break; 16965 case PTR_TO_TCP_SOCK: 16966 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 16967 break; 16968 case PTR_TO_XDP_SOCK: 16969 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 16970 break; 16971 case PTR_TO_BTF_ID: 16972 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 16973 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 16974 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 16975 * be said once it is marked PTR_UNTRUSTED, hence we must handle 16976 * any faults for loads into such types. BPF_WRITE is disallowed 16977 * for this case. 16978 */ 16979 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 16980 if (type == BPF_READ) { 16981 insn->code = BPF_LDX | BPF_PROBE_MEM | 16982 BPF_SIZE((insn)->code); 16983 env->prog->aux->num_exentries++; 16984 } 16985 continue; 16986 default: 16987 continue; 16988 } 16989 16990 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 16991 size = BPF_LDST_BYTES(insn); 16992 16993 /* If the read access is a narrower load of the field, 16994 * convert to a 4/8-byte load, to minimum program type specific 16995 * convert_ctx_access changes. If conversion is successful, 16996 * we will apply proper mask to the result. 16997 */ 16998 is_narrower_load = size < ctx_field_size; 16999 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 17000 off = insn->off; 17001 if (is_narrower_load) { 17002 u8 size_code; 17003 17004 if (type == BPF_WRITE) { 17005 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 17006 return -EINVAL; 17007 } 17008 17009 size_code = BPF_H; 17010 if (ctx_field_size == 4) 17011 size_code = BPF_W; 17012 else if (ctx_field_size == 8) 17013 size_code = BPF_DW; 17014 17015 insn->off = off & ~(size_default - 1); 17016 insn->code = BPF_LDX | BPF_MEM | size_code; 17017 } 17018 17019 target_size = 0; 17020 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 17021 &target_size); 17022 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 17023 (ctx_field_size && !target_size)) { 17024 verbose(env, "bpf verifier is misconfigured\n"); 17025 return -EINVAL; 17026 } 17027 17028 if (is_narrower_load && size < target_size) { 17029 u8 shift = bpf_ctx_narrow_access_offset( 17030 off, size, size_default) * 8; 17031 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 17032 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 17033 return -EINVAL; 17034 } 17035 if (ctx_field_size <= 4) { 17036 if (shift) 17037 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 17038 insn->dst_reg, 17039 shift); 17040 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 17041 (1 << size * 8) - 1); 17042 } else { 17043 if (shift) 17044 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 17045 insn->dst_reg, 17046 shift); 17047 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 17048 (1ULL << size * 8) - 1); 17049 } 17050 } 17051 17052 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17053 if (!new_prog) 17054 return -ENOMEM; 17055 17056 delta += cnt - 1; 17057 17058 /* keep walking new program and skip insns we just inserted */ 17059 env->prog = new_prog; 17060 insn = new_prog->insnsi + i + delta; 17061 } 17062 17063 return 0; 17064 } 17065 17066 static int jit_subprogs(struct bpf_verifier_env *env) 17067 { 17068 struct bpf_prog *prog = env->prog, **func, *tmp; 17069 int i, j, subprog_start, subprog_end = 0, len, subprog; 17070 struct bpf_map *map_ptr; 17071 struct bpf_insn *insn; 17072 void *old_bpf_func; 17073 int err, num_exentries; 17074 17075 if (env->subprog_cnt <= 1) 17076 return 0; 17077 17078 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 17079 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 17080 continue; 17081 17082 /* Upon error here we cannot fall back to interpreter but 17083 * need a hard reject of the program. Thus -EFAULT is 17084 * propagated in any case. 17085 */ 17086 subprog = find_subprog(env, i + insn->imm + 1); 17087 if (subprog < 0) { 17088 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 17089 i + insn->imm + 1); 17090 return -EFAULT; 17091 } 17092 /* temporarily remember subprog id inside insn instead of 17093 * aux_data, since next loop will split up all insns into funcs 17094 */ 17095 insn->off = subprog; 17096 /* remember original imm in case JIT fails and fallback 17097 * to interpreter will be needed 17098 */ 17099 env->insn_aux_data[i].call_imm = insn->imm; 17100 /* point imm to __bpf_call_base+1 from JITs point of view */ 17101 insn->imm = 1; 17102 if (bpf_pseudo_func(insn)) 17103 /* jit (e.g. x86_64) may emit fewer instructions 17104 * if it learns a u32 imm is the same as a u64 imm. 17105 * Force a non zero here. 17106 */ 17107 insn[1].imm = 1; 17108 } 17109 17110 err = bpf_prog_alloc_jited_linfo(prog); 17111 if (err) 17112 goto out_undo_insn; 17113 17114 err = -ENOMEM; 17115 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 17116 if (!func) 17117 goto out_undo_insn; 17118 17119 for (i = 0; i < env->subprog_cnt; i++) { 17120 subprog_start = subprog_end; 17121 subprog_end = env->subprog_info[i + 1].start; 17122 17123 len = subprog_end - subprog_start; 17124 /* bpf_prog_run() doesn't call subprogs directly, 17125 * hence main prog stats include the runtime of subprogs. 17126 * subprogs don't have IDs and not reachable via prog_get_next_id 17127 * func[i]->stats will never be accessed and stays NULL 17128 */ 17129 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 17130 if (!func[i]) 17131 goto out_free; 17132 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 17133 len * sizeof(struct bpf_insn)); 17134 func[i]->type = prog->type; 17135 func[i]->len = len; 17136 if (bpf_prog_calc_tag(func[i])) 17137 goto out_free; 17138 func[i]->is_func = 1; 17139 func[i]->aux->func_idx = i; 17140 /* Below members will be freed only at prog->aux */ 17141 func[i]->aux->btf = prog->aux->btf; 17142 func[i]->aux->func_info = prog->aux->func_info; 17143 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 17144 func[i]->aux->poke_tab = prog->aux->poke_tab; 17145 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 17146 17147 for (j = 0; j < prog->aux->size_poke_tab; j++) { 17148 struct bpf_jit_poke_descriptor *poke; 17149 17150 poke = &prog->aux->poke_tab[j]; 17151 if (poke->insn_idx < subprog_end && 17152 poke->insn_idx >= subprog_start) 17153 poke->aux = func[i]->aux; 17154 } 17155 17156 func[i]->aux->name[0] = 'F'; 17157 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 17158 func[i]->jit_requested = 1; 17159 func[i]->blinding_requested = prog->blinding_requested; 17160 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 17161 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 17162 func[i]->aux->linfo = prog->aux->linfo; 17163 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 17164 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 17165 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 17166 num_exentries = 0; 17167 insn = func[i]->insnsi; 17168 for (j = 0; j < func[i]->len; j++, insn++) { 17169 if (BPF_CLASS(insn->code) == BPF_LDX && 17170 BPF_MODE(insn->code) == BPF_PROBE_MEM) 17171 num_exentries++; 17172 } 17173 func[i]->aux->num_exentries = num_exentries; 17174 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 17175 func[i] = bpf_int_jit_compile(func[i]); 17176 if (!func[i]->jited) { 17177 err = -ENOTSUPP; 17178 goto out_free; 17179 } 17180 cond_resched(); 17181 } 17182 17183 /* at this point all bpf functions were successfully JITed 17184 * now populate all bpf_calls with correct addresses and 17185 * run last pass of JIT 17186 */ 17187 for (i = 0; i < env->subprog_cnt; i++) { 17188 insn = func[i]->insnsi; 17189 for (j = 0; j < func[i]->len; j++, insn++) { 17190 if (bpf_pseudo_func(insn)) { 17191 subprog = insn->off; 17192 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 17193 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 17194 continue; 17195 } 17196 if (!bpf_pseudo_call(insn)) 17197 continue; 17198 subprog = insn->off; 17199 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 17200 } 17201 17202 /* we use the aux data to keep a list of the start addresses 17203 * of the JITed images for each function in the program 17204 * 17205 * for some architectures, such as powerpc64, the imm field 17206 * might not be large enough to hold the offset of the start 17207 * address of the callee's JITed image from __bpf_call_base 17208 * 17209 * in such cases, we can lookup the start address of a callee 17210 * by using its subprog id, available from the off field of 17211 * the call instruction, as an index for this list 17212 */ 17213 func[i]->aux->func = func; 17214 func[i]->aux->func_cnt = env->subprog_cnt; 17215 } 17216 for (i = 0; i < env->subprog_cnt; i++) { 17217 old_bpf_func = func[i]->bpf_func; 17218 tmp = bpf_int_jit_compile(func[i]); 17219 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 17220 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 17221 err = -ENOTSUPP; 17222 goto out_free; 17223 } 17224 cond_resched(); 17225 } 17226 17227 /* finally lock prog and jit images for all functions and 17228 * populate kallsysm 17229 */ 17230 for (i = 0; i < env->subprog_cnt; i++) { 17231 bpf_prog_lock_ro(func[i]); 17232 bpf_prog_kallsyms_add(func[i]); 17233 } 17234 17235 /* Last step: make now unused interpreter insns from main 17236 * prog consistent for later dump requests, so they can 17237 * later look the same as if they were interpreted only. 17238 */ 17239 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 17240 if (bpf_pseudo_func(insn)) { 17241 insn[0].imm = env->insn_aux_data[i].call_imm; 17242 insn[1].imm = insn->off; 17243 insn->off = 0; 17244 continue; 17245 } 17246 if (!bpf_pseudo_call(insn)) 17247 continue; 17248 insn->off = env->insn_aux_data[i].call_imm; 17249 subprog = find_subprog(env, i + insn->off + 1); 17250 insn->imm = subprog; 17251 } 17252 17253 prog->jited = 1; 17254 prog->bpf_func = func[0]->bpf_func; 17255 prog->jited_len = func[0]->jited_len; 17256 prog->aux->func = func; 17257 prog->aux->func_cnt = env->subprog_cnt; 17258 bpf_prog_jit_attempt_done(prog); 17259 return 0; 17260 out_free: 17261 /* We failed JIT'ing, so at this point we need to unregister poke 17262 * descriptors from subprogs, so that kernel is not attempting to 17263 * patch it anymore as we're freeing the subprog JIT memory. 17264 */ 17265 for (i = 0; i < prog->aux->size_poke_tab; i++) { 17266 map_ptr = prog->aux->poke_tab[i].tail_call.map; 17267 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 17268 } 17269 /* At this point we're guaranteed that poke descriptors are not 17270 * live anymore. We can just unlink its descriptor table as it's 17271 * released with the main prog. 17272 */ 17273 for (i = 0; i < env->subprog_cnt; i++) { 17274 if (!func[i]) 17275 continue; 17276 func[i]->aux->poke_tab = NULL; 17277 bpf_jit_free(func[i]); 17278 } 17279 kfree(func); 17280 out_undo_insn: 17281 /* cleanup main prog to be interpreted */ 17282 prog->jit_requested = 0; 17283 prog->blinding_requested = 0; 17284 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 17285 if (!bpf_pseudo_call(insn)) 17286 continue; 17287 insn->off = 0; 17288 insn->imm = env->insn_aux_data[i].call_imm; 17289 } 17290 bpf_prog_jit_attempt_done(prog); 17291 return err; 17292 } 17293 17294 static int fixup_call_args(struct bpf_verifier_env *env) 17295 { 17296 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 17297 struct bpf_prog *prog = env->prog; 17298 struct bpf_insn *insn = prog->insnsi; 17299 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 17300 int i, depth; 17301 #endif 17302 int err = 0; 17303 17304 if (env->prog->jit_requested && 17305 !bpf_prog_is_offloaded(env->prog->aux)) { 17306 err = jit_subprogs(env); 17307 if (err == 0) 17308 return 0; 17309 if (err == -EFAULT) 17310 return err; 17311 } 17312 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 17313 if (has_kfunc_call) { 17314 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 17315 return -EINVAL; 17316 } 17317 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 17318 /* When JIT fails the progs with bpf2bpf calls and tail_calls 17319 * have to be rejected, since interpreter doesn't support them yet. 17320 */ 17321 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 17322 return -EINVAL; 17323 } 17324 for (i = 0; i < prog->len; i++, insn++) { 17325 if (bpf_pseudo_func(insn)) { 17326 /* When JIT fails the progs with callback calls 17327 * have to be rejected, since interpreter doesn't support them yet. 17328 */ 17329 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 17330 return -EINVAL; 17331 } 17332 17333 if (!bpf_pseudo_call(insn)) 17334 continue; 17335 depth = get_callee_stack_depth(env, insn, i); 17336 if (depth < 0) 17337 return depth; 17338 bpf_patch_call_args(insn, depth); 17339 } 17340 err = 0; 17341 #endif 17342 return err; 17343 } 17344 17345 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 17346 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 17347 { 17348 const struct bpf_kfunc_desc *desc; 17349 void *xdp_kfunc; 17350 17351 if (!insn->imm) { 17352 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 17353 return -EINVAL; 17354 } 17355 17356 *cnt = 0; 17357 17358 if (bpf_dev_bound_kfunc_id(insn->imm)) { 17359 xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm); 17360 if (xdp_kfunc) { 17361 insn->imm = BPF_CALL_IMM(xdp_kfunc); 17362 return 0; 17363 } 17364 17365 /* fallback to default kfunc when not supported by netdev */ 17366 } 17367 17368 /* insn->imm has the btf func_id. Replace it with 17369 * an address (relative to __bpf_call_base). 17370 */ 17371 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 17372 if (!desc) { 17373 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 17374 insn->imm); 17375 return -EFAULT; 17376 } 17377 17378 insn->imm = desc->imm; 17379 if (insn->off) 17380 return 0; 17381 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 17382 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 17383 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 17384 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 17385 17386 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 17387 insn_buf[1] = addr[0]; 17388 insn_buf[2] = addr[1]; 17389 insn_buf[3] = *insn; 17390 *cnt = 4; 17391 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 17392 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 17393 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 17394 17395 insn_buf[0] = addr[0]; 17396 insn_buf[1] = addr[1]; 17397 insn_buf[2] = *insn; 17398 *cnt = 3; 17399 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 17400 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 17401 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 17402 *cnt = 1; 17403 } else if (desc->func_id == special_kfunc_list[KF_bpf_dynptr_from_skb]) { 17404 bool seen_direct_write = env->seen_direct_write; 17405 bool is_rdonly = !may_access_direct_pkt_data(env, NULL, BPF_WRITE); 17406 17407 if (is_rdonly) 17408 insn->imm = BPF_CALL_IMM(bpf_dynptr_from_skb_rdonly); 17409 17410 /* restore env->seen_direct_write to its original value, since 17411 * may_access_direct_pkt_data mutates it 17412 */ 17413 env->seen_direct_write = seen_direct_write; 17414 } 17415 return 0; 17416 } 17417 17418 /* Do various post-verification rewrites in a single program pass. 17419 * These rewrites simplify JIT and interpreter implementations. 17420 */ 17421 static int do_misc_fixups(struct bpf_verifier_env *env) 17422 { 17423 struct bpf_prog *prog = env->prog; 17424 enum bpf_attach_type eatype = prog->expected_attach_type; 17425 enum bpf_prog_type prog_type = resolve_prog_type(prog); 17426 struct bpf_insn *insn = prog->insnsi; 17427 const struct bpf_func_proto *fn; 17428 const int insn_cnt = prog->len; 17429 const struct bpf_map_ops *ops; 17430 struct bpf_insn_aux_data *aux; 17431 struct bpf_insn insn_buf[16]; 17432 struct bpf_prog *new_prog; 17433 struct bpf_map *map_ptr; 17434 int i, ret, cnt, delta = 0; 17435 17436 for (i = 0; i < insn_cnt; i++, insn++) { 17437 /* Make divide-by-zero exceptions impossible. */ 17438 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 17439 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 17440 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 17441 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 17442 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 17443 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 17444 struct bpf_insn *patchlet; 17445 struct bpf_insn chk_and_div[] = { 17446 /* [R,W]x div 0 -> 0 */ 17447 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 17448 BPF_JNE | BPF_K, insn->src_reg, 17449 0, 2, 0), 17450 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 17451 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 17452 *insn, 17453 }; 17454 struct bpf_insn chk_and_mod[] = { 17455 /* [R,W]x mod 0 -> [R,W]x */ 17456 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 17457 BPF_JEQ | BPF_K, insn->src_reg, 17458 0, 1 + (is64 ? 0 : 1), 0), 17459 *insn, 17460 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 17461 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 17462 }; 17463 17464 patchlet = isdiv ? chk_and_div : chk_and_mod; 17465 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 17466 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 17467 17468 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 17469 if (!new_prog) 17470 return -ENOMEM; 17471 17472 delta += cnt - 1; 17473 env->prog = prog = new_prog; 17474 insn = new_prog->insnsi + i + delta; 17475 continue; 17476 } 17477 17478 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 17479 if (BPF_CLASS(insn->code) == BPF_LD && 17480 (BPF_MODE(insn->code) == BPF_ABS || 17481 BPF_MODE(insn->code) == BPF_IND)) { 17482 cnt = env->ops->gen_ld_abs(insn, insn_buf); 17483 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 17484 verbose(env, "bpf verifier is misconfigured\n"); 17485 return -EINVAL; 17486 } 17487 17488 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17489 if (!new_prog) 17490 return -ENOMEM; 17491 17492 delta += cnt - 1; 17493 env->prog = prog = new_prog; 17494 insn = new_prog->insnsi + i + delta; 17495 continue; 17496 } 17497 17498 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 17499 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 17500 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 17501 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 17502 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 17503 struct bpf_insn *patch = &insn_buf[0]; 17504 bool issrc, isneg, isimm; 17505 u32 off_reg; 17506 17507 aux = &env->insn_aux_data[i + delta]; 17508 if (!aux->alu_state || 17509 aux->alu_state == BPF_ALU_NON_POINTER) 17510 continue; 17511 17512 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 17513 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 17514 BPF_ALU_SANITIZE_SRC; 17515 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 17516 17517 off_reg = issrc ? insn->src_reg : insn->dst_reg; 17518 if (isimm) { 17519 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 17520 } else { 17521 if (isneg) 17522 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 17523 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 17524 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 17525 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 17526 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 17527 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 17528 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 17529 } 17530 if (!issrc) 17531 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 17532 insn->src_reg = BPF_REG_AX; 17533 if (isneg) 17534 insn->code = insn->code == code_add ? 17535 code_sub : code_add; 17536 *patch++ = *insn; 17537 if (issrc && isneg && !isimm) 17538 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 17539 cnt = patch - insn_buf; 17540 17541 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17542 if (!new_prog) 17543 return -ENOMEM; 17544 17545 delta += cnt - 1; 17546 env->prog = prog = new_prog; 17547 insn = new_prog->insnsi + i + delta; 17548 continue; 17549 } 17550 17551 if (insn->code != (BPF_JMP | BPF_CALL)) 17552 continue; 17553 if (insn->src_reg == BPF_PSEUDO_CALL) 17554 continue; 17555 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 17556 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 17557 if (ret) 17558 return ret; 17559 if (cnt == 0) 17560 continue; 17561 17562 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17563 if (!new_prog) 17564 return -ENOMEM; 17565 17566 delta += cnt - 1; 17567 env->prog = prog = new_prog; 17568 insn = new_prog->insnsi + i + delta; 17569 continue; 17570 } 17571 17572 if (insn->imm == BPF_FUNC_get_route_realm) 17573 prog->dst_needed = 1; 17574 if (insn->imm == BPF_FUNC_get_prandom_u32) 17575 bpf_user_rnd_init_once(); 17576 if (insn->imm == BPF_FUNC_override_return) 17577 prog->kprobe_override = 1; 17578 if (insn->imm == BPF_FUNC_tail_call) { 17579 /* If we tail call into other programs, we 17580 * cannot make any assumptions since they can 17581 * be replaced dynamically during runtime in 17582 * the program array. 17583 */ 17584 prog->cb_access = 1; 17585 if (!allow_tail_call_in_subprogs(env)) 17586 prog->aux->stack_depth = MAX_BPF_STACK; 17587 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 17588 17589 /* mark bpf_tail_call as different opcode to avoid 17590 * conditional branch in the interpreter for every normal 17591 * call and to prevent accidental JITing by JIT compiler 17592 * that doesn't support bpf_tail_call yet 17593 */ 17594 insn->imm = 0; 17595 insn->code = BPF_JMP | BPF_TAIL_CALL; 17596 17597 aux = &env->insn_aux_data[i + delta]; 17598 if (env->bpf_capable && !prog->blinding_requested && 17599 prog->jit_requested && 17600 !bpf_map_key_poisoned(aux) && 17601 !bpf_map_ptr_poisoned(aux) && 17602 !bpf_map_ptr_unpriv(aux)) { 17603 struct bpf_jit_poke_descriptor desc = { 17604 .reason = BPF_POKE_REASON_TAIL_CALL, 17605 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 17606 .tail_call.key = bpf_map_key_immediate(aux), 17607 .insn_idx = i + delta, 17608 }; 17609 17610 ret = bpf_jit_add_poke_descriptor(prog, &desc); 17611 if (ret < 0) { 17612 verbose(env, "adding tail call poke descriptor failed\n"); 17613 return ret; 17614 } 17615 17616 insn->imm = ret + 1; 17617 continue; 17618 } 17619 17620 if (!bpf_map_ptr_unpriv(aux)) 17621 continue; 17622 17623 /* instead of changing every JIT dealing with tail_call 17624 * emit two extra insns: 17625 * if (index >= max_entries) goto out; 17626 * index &= array->index_mask; 17627 * to avoid out-of-bounds cpu speculation 17628 */ 17629 if (bpf_map_ptr_poisoned(aux)) { 17630 verbose(env, "tail_call abusing map_ptr\n"); 17631 return -EINVAL; 17632 } 17633 17634 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 17635 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 17636 map_ptr->max_entries, 2); 17637 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 17638 container_of(map_ptr, 17639 struct bpf_array, 17640 map)->index_mask); 17641 insn_buf[2] = *insn; 17642 cnt = 3; 17643 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17644 if (!new_prog) 17645 return -ENOMEM; 17646 17647 delta += cnt - 1; 17648 env->prog = prog = new_prog; 17649 insn = new_prog->insnsi + i + delta; 17650 continue; 17651 } 17652 17653 if (insn->imm == BPF_FUNC_timer_set_callback) { 17654 /* The verifier will process callback_fn as many times as necessary 17655 * with different maps and the register states prepared by 17656 * set_timer_callback_state will be accurate. 17657 * 17658 * The following use case is valid: 17659 * map1 is shared by prog1, prog2, prog3. 17660 * prog1 calls bpf_timer_init for some map1 elements 17661 * prog2 calls bpf_timer_set_callback for some map1 elements. 17662 * Those that were not bpf_timer_init-ed will return -EINVAL. 17663 * prog3 calls bpf_timer_start for some map1 elements. 17664 * Those that were not both bpf_timer_init-ed and 17665 * bpf_timer_set_callback-ed will return -EINVAL. 17666 */ 17667 struct bpf_insn ld_addrs[2] = { 17668 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 17669 }; 17670 17671 insn_buf[0] = ld_addrs[0]; 17672 insn_buf[1] = ld_addrs[1]; 17673 insn_buf[2] = *insn; 17674 cnt = 3; 17675 17676 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17677 if (!new_prog) 17678 return -ENOMEM; 17679 17680 delta += cnt - 1; 17681 env->prog = prog = new_prog; 17682 insn = new_prog->insnsi + i + delta; 17683 goto patch_call_imm; 17684 } 17685 17686 if (is_storage_get_function(insn->imm)) { 17687 if (!env->prog->aux->sleepable || 17688 env->insn_aux_data[i + delta].storage_get_func_atomic) 17689 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 17690 else 17691 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 17692 insn_buf[1] = *insn; 17693 cnt = 2; 17694 17695 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17696 if (!new_prog) 17697 return -ENOMEM; 17698 17699 delta += cnt - 1; 17700 env->prog = prog = new_prog; 17701 insn = new_prog->insnsi + i + delta; 17702 goto patch_call_imm; 17703 } 17704 17705 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 17706 * and other inlining handlers are currently limited to 64 bit 17707 * only. 17708 */ 17709 if (prog->jit_requested && BITS_PER_LONG == 64 && 17710 (insn->imm == BPF_FUNC_map_lookup_elem || 17711 insn->imm == BPF_FUNC_map_update_elem || 17712 insn->imm == BPF_FUNC_map_delete_elem || 17713 insn->imm == BPF_FUNC_map_push_elem || 17714 insn->imm == BPF_FUNC_map_pop_elem || 17715 insn->imm == BPF_FUNC_map_peek_elem || 17716 insn->imm == BPF_FUNC_redirect_map || 17717 insn->imm == BPF_FUNC_for_each_map_elem || 17718 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 17719 aux = &env->insn_aux_data[i + delta]; 17720 if (bpf_map_ptr_poisoned(aux)) 17721 goto patch_call_imm; 17722 17723 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 17724 ops = map_ptr->ops; 17725 if (insn->imm == BPF_FUNC_map_lookup_elem && 17726 ops->map_gen_lookup) { 17727 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 17728 if (cnt == -EOPNOTSUPP) 17729 goto patch_map_ops_generic; 17730 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 17731 verbose(env, "bpf verifier is misconfigured\n"); 17732 return -EINVAL; 17733 } 17734 17735 new_prog = bpf_patch_insn_data(env, i + delta, 17736 insn_buf, cnt); 17737 if (!new_prog) 17738 return -ENOMEM; 17739 17740 delta += cnt - 1; 17741 env->prog = prog = new_prog; 17742 insn = new_prog->insnsi + i + delta; 17743 continue; 17744 } 17745 17746 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 17747 (void *(*)(struct bpf_map *map, void *key))NULL)); 17748 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 17749 (long (*)(struct bpf_map *map, void *key))NULL)); 17750 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 17751 (long (*)(struct bpf_map *map, void *key, void *value, 17752 u64 flags))NULL)); 17753 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 17754 (long (*)(struct bpf_map *map, void *value, 17755 u64 flags))NULL)); 17756 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 17757 (long (*)(struct bpf_map *map, void *value))NULL)); 17758 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 17759 (long (*)(struct bpf_map *map, void *value))NULL)); 17760 BUILD_BUG_ON(!__same_type(ops->map_redirect, 17761 (long (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 17762 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 17763 (long (*)(struct bpf_map *map, 17764 bpf_callback_t callback_fn, 17765 void *callback_ctx, 17766 u64 flags))NULL)); 17767 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 17768 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 17769 17770 patch_map_ops_generic: 17771 switch (insn->imm) { 17772 case BPF_FUNC_map_lookup_elem: 17773 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 17774 continue; 17775 case BPF_FUNC_map_update_elem: 17776 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 17777 continue; 17778 case BPF_FUNC_map_delete_elem: 17779 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 17780 continue; 17781 case BPF_FUNC_map_push_elem: 17782 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 17783 continue; 17784 case BPF_FUNC_map_pop_elem: 17785 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 17786 continue; 17787 case BPF_FUNC_map_peek_elem: 17788 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 17789 continue; 17790 case BPF_FUNC_redirect_map: 17791 insn->imm = BPF_CALL_IMM(ops->map_redirect); 17792 continue; 17793 case BPF_FUNC_for_each_map_elem: 17794 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 17795 continue; 17796 case BPF_FUNC_map_lookup_percpu_elem: 17797 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 17798 continue; 17799 } 17800 17801 goto patch_call_imm; 17802 } 17803 17804 /* Implement bpf_jiffies64 inline. */ 17805 if (prog->jit_requested && BITS_PER_LONG == 64 && 17806 insn->imm == BPF_FUNC_jiffies64) { 17807 struct bpf_insn ld_jiffies_addr[2] = { 17808 BPF_LD_IMM64(BPF_REG_0, 17809 (unsigned long)&jiffies), 17810 }; 17811 17812 insn_buf[0] = ld_jiffies_addr[0]; 17813 insn_buf[1] = ld_jiffies_addr[1]; 17814 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 17815 BPF_REG_0, 0); 17816 cnt = 3; 17817 17818 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 17819 cnt); 17820 if (!new_prog) 17821 return -ENOMEM; 17822 17823 delta += cnt - 1; 17824 env->prog = prog = new_prog; 17825 insn = new_prog->insnsi + i + delta; 17826 continue; 17827 } 17828 17829 /* Implement bpf_get_func_arg inline. */ 17830 if (prog_type == BPF_PROG_TYPE_TRACING && 17831 insn->imm == BPF_FUNC_get_func_arg) { 17832 /* Load nr_args from ctx - 8 */ 17833 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 17834 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 17835 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 17836 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 17837 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 17838 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 17839 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 17840 insn_buf[7] = BPF_JMP_A(1); 17841 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 17842 cnt = 9; 17843 17844 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17845 if (!new_prog) 17846 return -ENOMEM; 17847 17848 delta += cnt - 1; 17849 env->prog = prog = new_prog; 17850 insn = new_prog->insnsi + i + delta; 17851 continue; 17852 } 17853 17854 /* Implement bpf_get_func_ret inline. */ 17855 if (prog_type == BPF_PROG_TYPE_TRACING && 17856 insn->imm == BPF_FUNC_get_func_ret) { 17857 if (eatype == BPF_TRACE_FEXIT || 17858 eatype == BPF_MODIFY_RETURN) { 17859 /* Load nr_args from ctx - 8 */ 17860 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 17861 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 17862 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 17863 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 17864 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 17865 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 17866 cnt = 6; 17867 } else { 17868 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 17869 cnt = 1; 17870 } 17871 17872 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 17873 if (!new_prog) 17874 return -ENOMEM; 17875 17876 delta += cnt - 1; 17877 env->prog = prog = new_prog; 17878 insn = new_prog->insnsi + i + delta; 17879 continue; 17880 } 17881 17882 /* Implement get_func_arg_cnt inline. */ 17883 if (prog_type == BPF_PROG_TYPE_TRACING && 17884 insn->imm == BPF_FUNC_get_func_arg_cnt) { 17885 /* Load nr_args from ctx - 8 */ 17886 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 17887 17888 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 17889 if (!new_prog) 17890 return -ENOMEM; 17891 17892 env->prog = prog = new_prog; 17893 insn = new_prog->insnsi + i + delta; 17894 continue; 17895 } 17896 17897 /* Implement bpf_get_func_ip inline. */ 17898 if (prog_type == BPF_PROG_TYPE_TRACING && 17899 insn->imm == BPF_FUNC_get_func_ip) { 17900 /* Load IP address from ctx - 16 */ 17901 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 17902 17903 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 17904 if (!new_prog) 17905 return -ENOMEM; 17906 17907 env->prog = prog = new_prog; 17908 insn = new_prog->insnsi + i + delta; 17909 continue; 17910 } 17911 17912 patch_call_imm: 17913 fn = env->ops->get_func_proto(insn->imm, env->prog); 17914 /* all functions that have prototype and verifier allowed 17915 * programs to call them, must be real in-kernel functions 17916 */ 17917 if (!fn->func) { 17918 verbose(env, 17919 "kernel subsystem misconfigured func %s#%d\n", 17920 func_id_name(insn->imm), insn->imm); 17921 return -EFAULT; 17922 } 17923 insn->imm = fn->func - __bpf_call_base; 17924 } 17925 17926 /* Since poke tab is now finalized, publish aux to tracker. */ 17927 for (i = 0; i < prog->aux->size_poke_tab; i++) { 17928 map_ptr = prog->aux->poke_tab[i].tail_call.map; 17929 if (!map_ptr->ops->map_poke_track || 17930 !map_ptr->ops->map_poke_untrack || 17931 !map_ptr->ops->map_poke_run) { 17932 verbose(env, "bpf verifier is misconfigured\n"); 17933 return -EINVAL; 17934 } 17935 17936 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 17937 if (ret < 0) { 17938 verbose(env, "tracking tail call prog failed\n"); 17939 return ret; 17940 } 17941 } 17942 17943 sort_kfunc_descs_by_imm(env->prog); 17944 17945 return 0; 17946 } 17947 17948 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 17949 int position, 17950 s32 stack_base, 17951 u32 callback_subprogno, 17952 u32 *cnt) 17953 { 17954 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 17955 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 17956 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 17957 int reg_loop_max = BPF_REG_6; 17958 int reg_loop_cnt = BPF_REG_7; 17959 int reg_loop_ctx = BPF_REG_8; 17960 17961 struct bpf_prog *new_prog; 17962 u32 callback_start; 17963 u32 call_insn_offset; 17964 s32 callback_offset; 17965 17966 /* This represents an inlined version of bpf_iter.c:bpf_loop, 17967 * be careful to modify this code in sync. 17968 */ 17969 struct bpf_insn insn_buf[] = { 17970 /* Return error and jump to the end of the patch if 17971 * expected number of iterations is too big. 17972 */ 17973 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 17974 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 17975 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 17976 /* spill R6, R7, R8 to use these as loop vars */ 17977 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 17978 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 17979 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 17980 /* initialize loop vars */ 17981 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 17982 BPF_MOV32_IMM(reg_loop_cnt, 0), 17983 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 17984 /* loop header, 17985 * if reg_loop_cnt >= reg_loop_max skip the loop body 17986 */ 17987 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 17988 /* callback call, 17989 * correct callback offset would be set after patching 17990 */ 17991 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 17992 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 17993 BPF_CALL_REL(0), 17994 /* increment loop counter */ 17995 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 17996 /* jump to loop header if callback returned 0 */ 17997 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 17998 /* return value of bpf_loop, 17999 * set R0 to the number of iterations 18000 */ 18001 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 18002 /* restore original values of R6, R7, R8 */ 18003 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 18004 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 18005 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 18006 }; 18007 18008 *cnt = ARRAY_SIZE(insn_buf); 18009 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 18010 if (!new_prog) 18011 return new_prog; 18012 18013 /* callback start is known only after patching */ 18014 callback_start = env->subprog_info[callback_subprogno].start; 18015 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 18016 call_insn_offset = position + 12; 18017 callback_offset = callback_start - call_insn_offset - 1; 18018 new_prog->insnsi[call_insn_offset].imm = callback_offset; 18019 18020 return new_prog; 18021 } 18022 18023 static bool is_bpf_loop_call(struct bpf_insn *insn) 18024 { 18025 return insn->code == (BPF_JMP | BPF_CALL) && 18026 insn->src_reg == 0 && 18027 insn->imm == BPF_FUNC_loop; 18028 } 18029 18030 /* For all sub-programs in the program (including main) check 18031 * insn_aux_data to see if there are bpf_loop calls that require 18032 * inlining. If such calls are found the calls are replaced with a 18033 * sequence of instructions produced by `inline_bpf_loop` function and 18034 * subprog stack_depth is increased by the size of 3 registers. 18035 * This stack space is used to spill values of the R6, R7, R8. These 18036 * registers are used to store the loop bound, counter and context 18037 * variables. 18038 */ 18039 static int optimize_bpf_loop(struct bpf_verifier_env *env) 18040 { 18041 struct bpf_subprog_info *subprogs = env->subprog_info; 18042 int i, cur_subprog = 0, cnt, delta = 0; 18043 struct bpf_insn *insn = env->prog->insnsi; 18044 int insn_cnt = env->prog->len; 18045 u16 stack_depth = subprogs[cur_subprog].stack_depth; 18046 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 18047 u16 stack_depth_extra = 0; 18048 18049 for (i = 0; i < insn_cnt; i++, insn++) { 18050 struct bpf_loop_inline_state *inline_state = 18051 &env->insn_aux_data[i + delta].loop_inline_state; 18052 18053 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 18054 struct bpf_prog *new_prog; 18055 18056 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 18057 new_prog = inline_bpf_loop(env, 18058 i + delta, 18059 -(stack_depth + stack_depth_extra), 18060 inline_state->callback_subprogno, 18061 &cnt); 18062 if (!new_prog) 18063 return -ENOMEM; 18064 18065 delta += cnt - 1; 18066 env->prog = new_prog; 18067 insn = new_prog->insnsi + i + delta; 18068 } 18069 18070 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 18071 subprogs[cur_subprog].stack_depth += stack_depth_extra; 18072 cur_subprog++; 18073 stack_depth = subprogs[cur_subprog].stack_depth; 18074 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 18075 stack_depth_extra = 0; 18076 } 18077 } 18078 18079 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18080 18081 return 0; 18082 } 18083 18084 static void free_states(struct bpf_verifier_env *env) 18085 { 18086 struct bpf_verifier_state_list *sl, *sln; 18087 int i; 18088 18089 sl = env->free_list; 18090 while (sl) { 18091 sln = sl->next; 18092 free_verifier_state(&sl->state, false); 18093 kfree(sl); 18094 sl = sln; 18095 } 18096 env->free_list = NULL; 18097 18098 if (!env->explored_states) 18099 return; 18100 18101 for (i = 0; i < state_htab_size(env); i++) { 18102 sl = env->explored_states[i]; 18103 18104 while (sl) { 18105 sln = sl->next; 18106 free_verifier_state(&sl->state, false); 18107 kfree(sl); 18108 sl = sln; 18109 } 18110 env->explored_states[i] = NULL; 18111 } 18112 } 18113 18114 static int do_check_common(struct bpf_verifier_env *env, int subprog) 18115 { 18116 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 18117 struct bpf_verifier_state *state; 18118 struct bpf_reg_state *regs; 18119 int ret, i; 18120 18121 env->prev_linfo = NULL; 18122 env->pass_cnt++; 18123 18124 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 18125 if (!state) 18126 return -ENOMEM; 18127 state->curframe = 0; 18128 state->speculative = false; 18129 state->branches = 1; 18130 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 18131 if (!state->frame[0]) { 18132 kfree(state); 18133 return -ENOMEM; 18134 } 18135 env->cur_state = state; 18136 init_func_state(env, state->frame[0], 18137 BPF_MAIN_FUNC /* callsite */, 18138 0 /* frameno */, 18139 subprog); 18140 state->first_insn_idx = env->subprog_info[subprog].start; 18141 state->last_insn_idx = -1; 18142 18143 regs = state->frame[state->curframe]->regs; 18144 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 18145 ret = btf_prepare_func_args(env, subprog, regs); 18146 if (ret) 18147 goto out; 18148 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 18149 if (regs[i].type == PTR_TO_CTX) 18150 mark_reg_known_zero(env, regs, i); 18151 else if (regs[i].type == SCALAR_VALUE) 18152 mark_reg_unknown(env, regs, i); 18153 else if (base_type(regs[i].type) == PTR_TO_MEM) { 18154 const u32 mem_size = regs[i].mem_size; 18155 18156 mark_reg_known_zero(env, regs, i); 18157 regs[i].mem_size = mem_size; 18158 regs[i].id = ++env->id_gen; 18159 } 18160 } 18161 } else { 18162 /* 1st arg to a function */ 18163 regs[BPF_REG_1].type = PTR_TO_CTX; 18164 mark_reg_known_zero(env, regs, BPF_REG_1); 18165 ret = btf_check_subprog_arg_match(env, subprog, regs); 18166 if (ret == -EFAULT) 18167 /* unlikely verifier bug. abort. 18168 * ret == 0 and ret < 0 are sadly acceptable for 18169 * main() function due to backward compatibility. 18170 * Like socket filter program may be written as: 18171 * int bpf_prog(struct pt_regs *ctx) 18172 * and never dereference that ctx in the program. 18173 * 'struct pt_regs' is a type mismatch for socket 18174 * filter that should be using 'struct __sk_buff'. 18175 */ 18176 goto out; 18177 } 18178 18179 ret = do_check(env); 18180 out: 18181 /* check for NULL is necessary, since cur_state can be freed inside 18182 * do_check() under memory pressure. 18183 */ 18184 if (env->cur_state) { 18185 free_verifier_state(env->cur_state, true); 18186 env->cur_state = NULL; 18187 } 18188 while (!pop_stack(env, NULL, NULL, false)); 18189 if (!ret && pop_log) 18190 bpf_vlog_reset(&env->log, 0); 18191 free_states(env); 18192 return ret; 18193 } 18194 18195 /* Verify all global functions in a BPF program one by one based on their BTF. 18196 * All global functions must pass verification. Otherwise the whole program is rejected. 18197 * Consider: 18198 * int bar(int); 18199 * int foo(int f) 18200 * { 18201 * return bar(f); 18202 * } 18203 * int bar(int b) 18204 * { 18205 * ... 18206 * } 18207 * foo() will be verified first for R1=any_scalar_value. During verification it 18208 * will be assumed that bar() already verified successfully and call to bar() 18209 * from foo() will be checked for type match only. Later bar() will be verified 18210 * independently to check that it's safe for R1=any_scalar_value. 18211 */ 18212 static int do_check_subprogs(struct bpf_verifier_env *env) 18213 { 18214 struct bpf_prog_aux *aux = env->prog->aux; 18215 int i, ret; 18216 18217 if (!aux->func_info) 18218 return 0; 18219 18220 for (i = 1; i < env->subprog_cnt; i++) { 18221 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 18222 continue; 18223 env->insn_idx = env->subprog_info[i].start; 18224 WARN_ON_ONCE(env->insn_idx == 0); 18225 ret = do_check_common(env, i); 18226 if (ret) { 18227 return ret; 18228 } else if (env->log.level & BPF_LOG_LEVEL) { 18229 verbose(env, 18230 "Func#%d is safe for any args that match its prototype\n", 18231 i); 18232 } 18233 } 18234 return 0; 18235 } 18236 18237 static int do_check_main(struct bpf_verifier_env *env) 18238 { 18239 int ret; 18240 18241 env->insn_idx = 0; 18242 ret = do_check_common(env, 0); 18243 if (!ret) 18244 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 18245 return ret; 18246 } 18247 18248 18249 static void print_verification_stats(struct bpf_verifier_env *env) 18250 { 18251 int i; 18252 18253 if (env->log.level & BPF_LOG_STATS) { 18254 verbose(env, "verification time %lld usec\n", 18255 div_u64(env->verification_time, 1000)); 18256 verbose(env, "stack depth "); 18257 for (i = 0; i < env->subprog_cnt; i++) { 18258 u32 depth = env->subprog_info[i].stack_depth; 18259 18260 verbose(env, "%d", depth); 18261 if (i + 1 < env->subprog_cnt) 18262 verbose(env, "+"); 18263 } 18264 verbose(env, "\n"); 18265 } 18266 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 18267 "total_states %d peak_states %d mark_read %d\n", 18268 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 18269 env->max_states_per_insn, env->total_states, 18270 env->peak_states, env->longest_mark_read_walk); 18271 } 18272 18273 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 18274 { 18275 const struct btf_type *t, *func_proto; 18276 const struct bpf_struct_ops *st_ops; 18277 const struct btf_member *member; 18278 struct bpf_prog *prog = env->prog; 18279 u32 btf_id, member_idx; 18280 const char *mname; 18281 18282 if (!prog->gpl_compatible) { 18283 verbose(env, "struct ops programs must have a GPL compatible license\n"); 18284 return -EINVAL; 18285 } 18286 18287 btf_id = prog->aux->attach_btf_id; 18288 st_ops = bpf_struct_ops_find(btf_id); 18289 if (!st_ops) { 18290 verbose(env, "attach_btf_id %u is not a supported struct\n", 18291 btf_id); 18292 return -ENOTSUPP; 18293 } 18294 18295 t = st_ops->type; 18296 member_idx = prog->expected_attach_type; 18297 if (member_idx >= btf_type_vlen(t)) { 18298 verbose(env, "attach to invalid member idx %u of struct %s\n", 18299 member_idx, st_ops->name); 18300 return -EINVAL; 18301 } 18302 18303 member = &btf_type_member(t)[member_idx]; 18304 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 18305 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 18306 NULL); 18307 if (!func_proto) { 18308 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 18309 mname, member_idx, st_ops->name); 18310 return -EINVAL; 18311 } 18312 18313 if (st_ops->check_member) { 18314 int err = st_ops->check_member(t, member, prog); 18315 18316 if (err) { 18317 verbose(env, "attach to unsupported member %s of struct %s\n", 18318 mname, st_ops->name); 18319 return err; 18320 } 18321 } 18322 18323 prog->aux->attach_func_proto = func_proto; 18324 prog->aux->attach_func_name = mname; 18325 env->ops = st_ops->verifier_ops; 18326 18327 return 0; 18328 } 18329 #define SECURITY_PREFIX "security_" 18330 18331 static int check_attach_modify_return(unsigned long addr, const char *func_name) 18332 { 18333 if (within_error_injection_list(addr) || 18334 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 18335 return 0; 18336 18337 return -EINVAL; 18338 } 18339 18340 /* list of non-sleepable functions that are otherwise on 18341 * ALLOW_ERROR_INJECTION list 18342 */ 18343 BTF_SET_START(btf_non_sleepable_error_inject) 18344 /* Three functions below can be called from sleepable and non-sleepable context. 18345 * Assume non-sleepable from bpf safety point of view. 18346 */ 18347 BTF_ID(func, __filemap_add_folio) 18348 BTF_ID(func, should_fail_alloc_page) 18349 BTF_ID(func, should_failslab) 18350 BTF_SET_END(btf_non_sleepable_error_inject) 18351 18352 static int check_non_sleepable_error_inject(u32 btf_id) 18353 { 18354 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 18355 } 18356 18357 int bpf_check_attach_target(struct bpf_verifier_log *log, 18358 const struct bpf_prog *prog, 18359 const struct bpf_prog *tgt_prog, 18360 u32 btf_id, 18361 struct bpf_attach_target_info *tgt_info) 18362 { 18363 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 18364 const char prefix[] = "btf_trace_"; 18365 int ret = 0, subprog = -1, i; 18366 const struct btf_type *t; 18367 bool conservative = true; 18368 const char *tname; 18369 struct btf *btf; 18370 long addr = 0; 18371 struct module *mod = NULL; 18372 18373 if (!btf_id) { 18374 bpf_log(log, "Tracing programs must provide btf_id\n"); 18375 return -EINVAL; 18376 } 18377 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 18378 if (!btf) { 18379 bpf_log(log, 18380 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 18381 return -EINVAL; 18382 } 18383 t = btf_type_by_id(btf, btf_id); 18384 if (!t) { 18385 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 18386 return -EINVAL; 18387 } 18388 tname = btf_name_by_offset(btf, t->name_off); 18389 if (!tname) { 18390 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 18391 return -EINVAL; 18392 } 18393 if (tgt_prog) { 18394 struct bpf_prog_aux *aux = tgt_prog->aux; 18395 18396 if (bpf_prog_is_dev_bound(prog->aux) && 18397 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 18398 bpf_log(log, "Target program bound device mismatch"); 18399 return -EINVAL; 18400 } 18401 18402 for (i = 0; i < aux->func_info_cnt; i++) 18403 if (aux->func_info[i].type_id == btf_id) { 18404 subprog = i; 18405 break; 18406 } 18407 if (subprog == -1) { 18408 bpf_log(log, "Subprog %s doesn't exist\n", tname); 18409 return -EINVAL; 18410 } 18411 conservative = aux->func_info_aux[subprog].unreliable; 18412 if (prog_extension) { 18413 if (conservative) { 18414 bpf_log(log, 18415 "Cannot replace static functions\n"); 18416 return -EINVAL; 18417 } 18418 if (!prog->jit_requested) { 18419 bpf_log(log, 18420 "Extension programs should be JITed\n"); 18421 return -EINVAL; 18422 } 18423 } 18424 if (!tgt_prog->jited) { 18425 bpf_log(log, "Can attach to only JITed progs\n"); 18426 return -EINVAL; 18427 } 18428 if (tgt_prog->type == prog->type) { 18429 /* Cannot fentry/fexit another fentry/fexit program. 18430 * Cannot attach program extension to another extension. 18431 * It's ok to attach fentry/fexit to extension program. 18432 */ 18433 bpf_log(log, "Cannot recursively attach\n"); 18434 return -EINVAL; 18435 } 18436 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 18437 prog_extension && 18438 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 18439 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 18440 /* Program extensions can extend all program types 18441 * except fentry/fexit. The reason is the following. 18442 * The fentry/fexit programs are used for performance 18443 * analysis, stats and can be attached to any program 18444 * type except themselves. When extension program is 18445 * replacing XDP function it is necessary to allow 18446 * performance analysis of all functions. Both original 18447 * XDP program and its program extension. Hence 18448 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 18449 * allowed. If extending of fentry/fexit was allowed it 18450 * would be possible to create long call chain 18451 * fentry->extension->fentry->extension beyond 18452 * reasonable stack size. Hence extending fentry is not 18453 * allowed. 18454 */ 18455 bpf_log(log, "Cannot extend fentry/fexit\n"); 18456 return -EINVAL; 18457 } 18458 } else { 18459 if (prog_extension) { 18460 bpf_log(log, "Cannot replace kernel functions\n"); 18461 return -EINVAL; 18462 } 18463 } 18464 18465 switch (prog->expected_attach_type) { 18466 case BPF_TRACE_RAW_TP: 18467 if (tgt_prog) { 18468 bpf_log(log, 18469 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 18470 return -EINVAL; 18471 } 18472 if (!btf_type_is_typedef(t)) { 18473 bpf_log(log, "attach_btf_id %u is not a typedef\n", 18474 btf_id); 18475 return -EINVAL; 18476 } 18477 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 18478 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 18479 btf_id, tname); 18480 return -EINVAL; 18481 } 18482 tname += sizeof(prefix) - 1; 18483 t = btf_type_by_id(btf, t->type); 18484 if (!btf_type_is_ptr(t)) 18485 /* should never happen in valid vmlinux build */ 18486 return -EINVAL; 18487 t = btf_type_by_id(btf, t->type); 18488 if (!btf_type_is_func_proto(t)) 18489 /* should never happen in valid vmlinux build */ 18490 return -EINVAL; 18491 18492 break; 18493 case BPF_TRACE_ITER: 18494 if (!btf_type_is_func(t)) { 18495 bpf_log(log, "attach_btf_id %u is not a function\n", 18496 btf_id); 18497 return -EINVAL; 18498 } 18499 t = btf_type_by_id(btf, t->type); 18500 if (!btf_type_is_func_proto(t)) 18501 return -EINVAL; 18502 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 18503 if (ret) 18504 return ret; 18505 break; 18506 default: 18507 if (!prog_extension) 18508 return -EINVAL; 18509 fallthrough; 18510 case BPF_MODIFY_RETURN: 18511 case BPF_LSM_MAC: 18512 case BPF_LSM_CGROUP: 18513 case BPF_TRACE_FENTRY: 18514 case BPF_TRACE_FEXIT: 18515 if (!btf_type_is_func(t)) { 18516 bpf_log(log, "attach_btf_id %u is not a function\n", 18517 btf_id); 18518 return -EINVAL; 18519 } 18520 if (prog_extension && 18521 btf_check_type_match(log, prog, btf, t)) 18522 return -EINVAL; 18523 t = btf_type_by_id(btf, t->type); 18524 if (!btf_type_is_func_proto(t)) 18525 return -EINVAL; 18526 18527 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 18528 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 18529 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 18530 return -EINVAL; 18531 18532 if (tgt_prog && conservative) 18533 t = NULL; 18534 18535 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 18536 if (ret < 0) 18537 return ret; 18538 18539 if (tgt_prog) { 18540 if (subprog == 0) 18541 addr = (long) tgt_prog->bpf_func; 18542 else 18543 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 18544 } else { 18545 if (btf_is_module(btf)) { 18546 mod = btf_try_get_module(btf); 18547 if (mod) 18548 addr = find_kallsyms_symbol_value(mod, tname); 18549 else 18550 addr = 0; 18551 } else { 18552 addr = kallsyms_lookup_name(tname); 18553 } 18554 if (!addr) { 18555 module_put(mod); 18556 bpf_log(log, 18557 "The address of function %s cannot be found\n", 18558 tname); 18559 return -ENOENT; 18560 } 18561 } 18562 18563 if (prog->aux->sleepable) { 18564 ret = -EINVAL; 18565 switch (prog->type) { 18566 case BPF_PROG_TYPE_TRACING: 18567 18568 /* fentry/fexit/fmod_ret progs can be sleepable if they are 18569 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 18570 */ 18571 if (!check_non_sleepable_error_inject(btf_id) && 18572 within_error_injection_list(addr)) 18573 ret = 0; 18574 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 18575 * in the fmodret id set with the KF_SLEEPABLE flag. 18576 */ 18577 else { 18578 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id); 18579 18580 if (flags && (*flags & KF_SLEEPABLE)) 18581 ret = 0; 18582 } 18583 break; 18584 case BPF_PROG_TYPE_LSM: 18585 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 18586 * Only some of them are sleepable. 18587 */ 18588 if (bpf_lsm_is_sleepable_hook(btf_id)) 18589 ret = 0; 18590 break; 18591 default: 18592 break; 18593 } 18594 if (ret) { 18595 module_put(mod); 18596 bpf_log(log, "%s is not sleepable\n", tname); 18597 return ret; 18598 } 18599 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 18600 if (tgt_prog) { 18601 module_put(mod); 18602 bpf_log(log, "can't modify return codes of BPF programs\n"); 18603 return -EINVAL; 18604 } 18605 ret = -EINVAL; 18606 if (btf_kfunc_is_modify_return(btf, btf_id) || 18607 !check_attach_modify_return(addr, tname)) 18608 ret = 0; 18609 if (ret) { 18610 module_put(mod); 18611 bpf_log(log, "%s() is not modifiable\n", tname); 18612 return ret; 18613 } 18614 } 18615 18616 break; 18617 } 18618 tgt_info->tgt_addr = addr; 18619 tgt_info->tgt_name = tname; 18620 tgt_info->tgt_type = t; 18621 tgt_info->tgt_mod = mod; 18622 return 0; 18623 } 18624 18625 BTF_SET_START(btf_id_deny) 18626 BTF_ID_UNUSED 18627 #ifdef CONFIG_SMP 18628 BTF_ID(func, migrate_disable) 18629 BTF_ID(func, migrate_enable) 18630 #endif 18631 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 18632 BTF_ID(func, rcu_read_unlock_strict) 18633 #endif 18634 BTF_SET_END(btf_id_deny) 18635 18636 static bool can_be_sleepable(struct bpf_prog *prog) 18637 { 18638 if (prog->type == BPF_PROG_TYPE_TRACING) { 18639 switch (prog->expected_attach_type) { 18640 case BPF_TRACE_FENTRY: 18641 case BPF_TRACE_FEXIT: 18642 case BPF_MODIFY_RETURN: 18643 case BPF_TRACE_ITER: 18644 return true; 18645 default: 18646 return false; 18647 } 18648 } 18649 return prog->type == BPF_PROG_TYPE_LSM || 18650 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 18651 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 18652 } 18653 18654 static int check_attach_btf_id(struct bpf_verifier_env *env) 18655 { 18656 struct bpf_prog *prog = env->prog; 18657 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 18658 struct bpf_attach_target_info tgt_info = {}; 18659 u32 btf_id = prog->aux->attach_btf_id; 18660 struct bpf_trampoline *tr; 18661 int ret; 18662 u64 key; 18663 18664 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 18665 if (prog->aux->sleepable) 18666 /* attach_btf_id checked to be zero already */ 18667 return 0; 18668 verbose(env, "Syscall programs can only be sleepable\n"); 18669 return -EINVAL; 18670 } 18671 18672 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 18673 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 18674 return -EINVAL; 18675 } 18676 18677 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 18678 return check_struct_ops_btf_id(env); 18679 18680 if (prog->type != BPF_PROG_TYPE_TRACING && 18681 prog->type != BPF_PROG_TYPE_LSM && 18682 prog->type != BPF_PROG_TYPE_EXT) 18683 return 0; 18684 18685 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 18686 if (ret) 18687 return ret; 18688 18689 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 18690 /* to make freplace equivalent to their targets, they need to 18691 * inherit env->ops and expected_attach_type for the rest of the 18692 * verification 18693 */ 18694 env->ops = bpf_verifier_ops[tgt_prog->type]; 18695 prog->expected_attach_type = tgt_prog->expected_attach_type; 18696 } 18697 18698 /* store info about the attachment target that will be used later */ 18699 prog->aux->attach_func_proto = tgt_info.tgt_type; 18700 prog->aux->attach_func_name = tgt_info.tgt_name; 18701 prog->aux->mod = tgt_info.tgt_mod; 18702 18703 if (tgt_prog) { 18704 prog->aux->saved_dst_prog_type = tgt_prog->type; 18705 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 18706 } 18707 18708 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 18709 prog->aux->attach_btf_trace = true; 18710 return 0; 18711 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 18712 if (!bpf_iter_prog_supported(prog)) 18713 return -EINVAL; 18714 return 0; 18715 } 18716 18717 if (prog->type == BPF_PROG_TYPE_LSM) { 18718 ret = bpf_lsm_verify_prog(&env->log, prog); 18719 if (ret < 0) 18720 return ret; 18721 } else if (prog->type == BPF_PROG_TYPE_TRACING && 18722 btf_id_set_contains(&btf_id_deny, btf_id)) { 18723 return -EINVAL; 18724 } 18725 18726 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 18727 tr = bpf_trampoline_get(key, &tgt_info); 18728 if (!tr) 18729 return -ENOMEM; 18730 18731 prog->aux->dst_trampoline = tr; 18732 return 0; 18733 } 18734 18735 struct btf *bpf_get_btf_vmlinux(void) 18736 { 18737 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 18738 mutex_lock(&bpf_verifier_lock); 18739 if (!btf_vmlinux) 18740 btf_vmlinux = btf_parse_vmlinux(); 18741 mutex_unlock(&bpf_verifier_lock); 18742 } 18743 return btf_vmlinux; 18744 } 18745 18746 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr) 18747 { 18748 u64 start_time = ktime_get_ns(); 18749 struct bpf_verifier_env *env; 18750 struct bpf_verifier_log *log; 18751 int i, len, ret = -EINVAL; 18752 bool is_priv; 18753 18754 /* no program is valid */ 18755 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 18756 return -EINVAL; 18757 18758 /* 'struct bpf_verifier_env' can be global, but since it's not small, 18759 * allocate/free it every time bpf_check() is called 18760 */ 18761 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 18762 if (!env) 18763 return -ENOMEM; 18764 log = &env->log; 18765 18766 len = (*prog)->len; 18767 env->insn_aux_data = 18768 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 18769 ret = -ENOMEM; 18770 if (!env->insn_aux_data) 18771 goto err_free_env; 18772 for (i = 0; i < len; i++) 18773 env->insn_aux_data[i].orig_idx = i; 18774 env->prog = *prog; 18775 env->ops = bpf_verifier_ops[env->prog->type]; 18776 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 18777 is_priv = bpf_capable(); 18778 18779 bpf_get_btf_vmlinux(); 18780 18781 /* grab the mutex to protect few globals used by verifier */ 18782 if (!is_priv) 18783 mutex_lock(&bpf_verifier_lock); 18784 18785 if (attr->log_level || attr->log_buf || attr->log_size) { 18786 /* user requested verbose verifier output 18787 * and supplied buffer to store the verification trace 18788 */ 18789 log->level = attr->log_level; 18790 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 18791 log->len_total = attr->log_size; 18792 18793 /* log attributes have to be sane */ 18794 if (!bpf_verifier_log_attr_valid(log)) { 18795 ret = -EINVAL; 18796 goto err_unlock; 18797 } 18798 } 18799 18800 mark_verifier_state_clean(env); 18801 18802 if (IS_ERR(btf_vmlinux)) { 18803 /* Either gcc or pahole or kernel are broken. */ 18804 verbose(env, "in-kernel BTF is malformed\n"); 18805 ret = PTR_ERR(btf_vmlinux); 18806 goto skip_full_check; 18807 } 18808 18809 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 18810 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 18811 env->strict_alignment = true; 18812 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 18813 env->strict_alignment = false; 18814 18815 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 18816 env->allow_uninit_stack = bpf_allow_uninit_stack(); 18817 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 18818 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 18819 env->bpf_capable = bpf_capable(); 18820 18821 if (is_priv) 18822 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 18823 18824 env->explored_states = kvcalloc(state_htab_size(env), 18825 sizeof(struct bpf_verifier_state_list *), 18826 GFP_USER); 18827 ret = -ENOMEM; 18828 if (!env->explored_states) 18829 goto skip_full_check; 18830 18831 ret = add_subprog_and_kfunc(env); 18832 if (ret < 0) 18833 goto skip_full_check; 18834 18835 ret = check_subprogs(env); 18836 if (ret < 0) 18837 goto skip_full_check; 18838 18839 ret = check_btf_info(env, attr, uattr); 18840 if (ret < 0) 18841 goto skip_full_check; 18842 18843 ret = check_attach_btf_id(env); 18844 if (ret) 18845 goto skip_full_check; 18846 18847 ret = resolve_pseudo_ldimm64(env); 18848 if (ret < 0) 18849 goto skip_full_check; 18850 18851 if (bpf_prog_is_offloaded(env->prog->aux)) { 18852 ret = bpf_prog_offload_verifier_prep(env->prog); 18853 if (ret) 18854 goto skip_full_check; 18855 } 18856 18857 ret = check_cfg(env); 18858 if (ret < 0) 18859 goto skip_full_check; 18860 18861 ret = do_check_subprogs(env); 18862 ret = ret ?: do_check_main(env); 18863 18864 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 18865 ret = bpf_prog_offload_finalize(env); 18866 18867 skip_full_check: 18868 kvfree(env->explored_states); 18869 18870 if (ret == 0) 18871 ret = check_max_stack_depth(env); 18872 18873 /* instruction rewrites happen after this point */ 18874 if (ret == 0) 18875 ret = optimize_bpf_loop(env); 18876 18877 if (is_priv) { 18878 if (ret == 0) 18879 opt_hard_wire_dead_code_branches(env); 18880 if (ret == 0) 18881 ret = opt_remove_dead_code(env); 18882 if (ret == 0) 18883 ret = opt_remove_nops(env); 18884 } else { 18885 if (ret == 0) 18886 sanitize_dead_code(env); 18887 } 18888 18889 if (ret == 0) 18890 /* program is valid, convert *(u32*)(ctx + off) accesses */ 18891 ret = convert_ctx_accesses(env); 18892 18893 if (ret == 0) 18894 ret = do_misc_fixups(env); 18895 18896 /* do 32-bit optimization after insn patching has done so those patched 18897 * insns could be handled correctly. 18898 */ 18899 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 18900 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 18901 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 18902 : false; 18903 } 18904 18905 if (ret == 0) 18906 ret = fixup_call_args(env); 18907 18908 env->verification_time = ktime_get_ns() - start_time; 18909 print_verification_stats(env); 18910 env->prog->aux->verified_insns = env->insn_processed; 18911 18912 if (log->level && bpf_verifier_log_full(log)) 18913 ret = -ENOSPC; 18914 if (log->level && !log->ubuf) { 18915 ret = -EFAULT; 18916 goto err_release_maps; 18917 } 18918 18919 if (ret) 18920 goto err_release_maps; 18921 18922 if (env->used_map_cnt) { 18923 /* if program passed verifier, update used_maps in bpf_prog_info */ 18924 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 18925 sizeof(env->used_maps[0]), 18926 GFP_KERNEL); 18927 18928 if (!env->prog->aux->used_maps) { 18929 ret = -ENOMEM; 18930 goto err_release_maps; 18931 } 18932 18933 memcpy(env->prog->aux->used_maps, env->used_maps, 18934 sizeof(env->used_maps[0]) * env->used_map_cnt); 18935 env->prog->aux->used_map_cnt = env->used_map_cnt; 18936 } 18937 if (env->used_btf_cnt) { 18938 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 18939 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 18940 sizeof(env->used_btfs[0]), 18941 GFP_KERNEL); 18942 if (!env->prog->aux->used_btfs) { 18943 ret = -ENOMEM; 18944 goto err_release_maps; 18945 } 18946 18947 memcpy(env->prog->aux->used_btfs, env->used_btfs, 18948 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 18949 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 18950 } 18951 if (env->used_map_cnt || env->used_btf_cnt) { 18952 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 18953 * bpf_ld_imm64 instructions 18954 */ 18955 convert_pseudo_ld_imm64(env); 18956 } 18957 18958 adjust_btf_func(env); 18959 18960 err_release_maps: 18961 if (!env->prog->aux->used_maps) 18962 /* if we didn't copy map pointers into bpf_prog_info, release 18963 * them now. Otherwise free_used_maps() will release them. 18964 */ 18965 release_maps(env); 18966 if (!env->prog->aux->used_btfs) 18967 release_btfs(env); 18968 18969 /* extension progs temporarily inherit the attach_type of their targets 18970 for verification purposes, so set it back to zero before returning 18971 */ 18972 if (env->prog->type == BPF_PROG_TYPE_EXT) 18973 env->prog->expected_attach_type = 0; 18974 18975 *prog = env->prog; 18976 err_unlock: 18977 if (!is_priv) 18978 mutex_unlock(&bpf_verifier_lock); 18979 vfree(env->insn_aux_data); 18980 err_free_env: 18981 kfree(env); 18982 return ret; 18983 } 18984