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 28 #include "disasm.h" 29 30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 31 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 32 [_id] = & _name ## _verifier_ops, 33 #define BPF_MAP_TYPE(_id, _ops) 34 #define BPF_LINK_TYPE(_id, _name) 35 #include <linux/bpf_types.h> 36 #undef BPF_PROG_TYPE 37 #undef BPF_MAP_TYPE 38 #undef BPF_LINK_TYPE 39 }; 40 41 /* bpf_check() is a static code analyzer that walks eBPF program 42 * instruction by instruction and updates register/stack state. 43 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 44 * 45 * The first pass is depth-first-search to check that the program is a DAG. 46 * It rejects the following programs: 47 * - larger than BPF_MAXINSNS insns 48 * - if loop is present (detected via back-edge) 49 * - unreachable insns exist (shouldn't be a forest. program = one function) 50 * - out of bounds or malformed jumps 51 * The second pass is all possible path descent from the 1st insn. 52 * Since it's analyzing all paths through the program, the length of the 53 * analysis is limited to 64k insn, which may be hit even if total number of 54 * insn is less then 4K, but there are too many branches that change stack/regs. 55 * Number of 'branches to be analyzed' is limited to 1k 56 * 57 * On entry to each instruction, each register has a type, and the instruction 58 * changes the types of the registers depending on instruction semantics. 59 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 60 * copied to R1. 61 * 62 * All registers are 64-bit. 63 * R0 - return register 64 * R1-R5 argument passing registers 65 * R6-R9 callee saved registers 66 * R10 - frame pointer read-only 67 * 68 * At the start of BPF program the register R1 contains a pointer to bpf_context 69 * and has type PTR_TO_CTX. 70 * 71 * Verifier tracks arithmetic operations on pointers in case: 72 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 73 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 74 * 1st insn copies R10 (which has FRAME_PTR) type into R1 75 * and 2nd arithmetic instruction is pattern matched to recognize 76 * that it wants to construct a pointer to some element within stack. 77 * So after 2nd insn, the register R1 has type PTR_TO_STACK 78 * (and -20 constant is saved for further stack bounds checking). 79 * Meaning that this reg is a pointer to stack plus known immediate constant. 80 * 81 * Most of the time the registers have SCALAR_VALUE type, which 82 * means the register has some value, but it's not a valid pointer. 83 * (like pointer plus pointer becomes SCALAR_VALUE type) 84 * 85 * When verifier sees load or store instructions the type of base register 86 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 87 * four pointer types recognized by check_mem_access() function. 88 * 89 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 90 * and the range of [ptr, ptr + map's value_size) is accessible. 91 * 92 * registers used to pass values to function calls are checked against 93 * function argument constraints. 94 * 95 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 96 * It means that the register type passed to this function must be 97 * PTR_TO_STACK and it will be used inside the function as 98 * 'pointer to map element key' 99 * 100 * For example the argument constraints for bpf_map_lookup_elem(): 101 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 102 * .arg1_type = ARG_CONST_MAP_PTR, 103 * .arg2_type = ARG_PTR_TO_MAP_KEY, 104 * 105 * ret_type says that this function returns 'pointer to map elem value or null' 106 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 107 * 2nd argument should be a pointer to stack, which will be used inside 108 * the helper function as a pointer to map element key. 109 * 110 * On the kernel side the helper function looks like: 111 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 112 * { 113 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 114 * void *key = (void *) (unsigned long) r2; 115 * void *value; 116 * 117 * here kernel can access 'key' and 'map' pointers safely, knowing that 118 * [key, key + map->key_size) bytes are valid and were initialized on 119 * the stack of eBPF program. 120 * } 121 * 122 * Corresponding eBPF program may look like: 123 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 124 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 125 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 126 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 127 * here verifier looks at prototype of map_lookup_elem() and sees: 128 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 129 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 130 * 131 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 132 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 133 * and were initialized prior to this call. 134 * If it's ok, then verifier allows this BPF_CALL insn and looks at 135 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 136 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 137 * returns either pointer to map value or NULL. 138 * 139 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 140 * insn, the register holding that pointer in the true branch changes state to 141 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 142 * branch. See check_cond_jmp_op(). 143 * 144 * After the call R0 is set to return type of the function and registers R1-R5 145 * are set to NOT_INIT to indicate that they are no longer readable. 146 * 147 * The following reference types represent a potential reference to a kernel 148 * resource which, after first being allocated, must be checked and freed by 149 * the BPF program: 150 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 151 * 152 * When the verifier sees a helper call return a reference type, it allocates a 153 * pointer id for the reference and stores it in the current function state. 154 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 155 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 156 * passes through a NULL-check conditional. For the branch wherein the state is 157 * changed to CONST_IMM, the verifier releases the reference. 158 * 159 * For each helper function that allocates a reference, such as 160 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 161 * bpf_sk_release(). When a reference type passes into the release function, 162 * the verifier also releases the reference. If any unchecked or unreleased 163 * reference remains at the end of the program, the verifier rejects it. 164 */ 165 166 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 167 struct bpf_verifier_stack_elem { 168 /* verifer state is 'st' 169 * before processing instruction 'insn_idx' 170 * and after processing instruction 'prev_insn_idx' 171 */ 172 struct bpf_verifier_state st; 173 int insn_idx; 174 int prev_insn_idx; 175 struct bpf_verifier_stack_elem *next; 176 /* length of verifier log at the time this state was pushed on stack */ 177 u32 log_pos; 178 }; 179 180 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 181 #define BPF_COMPLEXITY_LIMIT_STATES 64 182 183 #define BPF_MAP_KEY_POISON (1ULL << 63) 184 #define BPF_MAP_KEY_SEEN (1ULL << 62) 185 186 #define BPF_MAP_PTR_UNPRIV 1UL 187 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 188 POISON_POINTER_DELTA)) 189 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 190 191 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx); 192 static int release_reference(struct bpf_verifier_env *env, int ref_obj_id); 193 static void invalidate_non_owning_refs(struct bpf_verifier_env *env); 194 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env); 195 static int ref_set_non_owning(struct bpf_verifier_env *env, 196 struct bpf_reg_state *reg); 197 198 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 199 { 200 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 201 } 202 203 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 204 { 205 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 206 } 207 208 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 209 const struct bpf_map *map, bool unpriv) 210 { 211 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 212 unpriv |= bpf_map_ptr_unpriv(aux); 213 aux->map_ptr_state = (unsigned long)map | 214 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 215 } 216 217 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 218 { 219 return aux->map_key_state & BPF_MAP_KEY_POISON; 220 } 221 222 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 223 { 224 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 225 } 226 227 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 228 { 229 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 230 } 231 232 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 233 { 234 bool poisoned = bpf_map_key_poisoned(aux); 235 236 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 237 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 238 } 239 240 static bool bpf_pseudo_call(const struct bpf_insn *insn) 241 { 242 return insn->code == (BPF_JMP | BPF_CALL) && 243 insn->src_reg == BPF_PSEUDO_CALL; 244 } 245 246 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 247 { 248 return insn->code == (BPF_JMP | BPF_CALL) && 249 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 250 } 251 252 struct bpf_call_arg_meta { 253 struct bpf_map *map_ptr; 254 bool raw_mode; 255 bool pkt_access; 256 u8 release_regno; 257 int regno; 258 int access_size; 259 int mem_size; 260 u64 msize_max_value; 261 int ref_obj_id; 262 int dynptr_id; 263 int map_uid; 264 int func_id; 265 struct btf *btf; 266 u32 btf_id; 267 struct btf *ret_btf; 268 u32 ret_btf_id; 269 u32 subprogno; 270 struct btf_field *kptr_field; 271 u8 uninit_dynptr_regno; 272 }; 273 274 struct btf *btf_vmlinux; 275 276 static DEFINE_MUTEX(bpf_verifier_lock); 277 278 static const struct bpf_line_info * 279 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 280 { 281 const struct bpf_line_info *linfo; 282 const struct bpf_prog *prog; 283 u32 i, nr_linfo; 284 285 prog = env->prog; 286 nr_linfo = prog->aux->nr_linfo; 287 288 if (!nr_linfo || insn_off >= prog->len) 289 return NULL; 290 291 linfo = prog->aux->linfo; 292 for (i = 1; i < nr_linfo; i++) 293 if (insn_off < linfo[i].insn_off) 294 break; 295 296 return &linfo[i - 1]; 297 } 298 299 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, 300 va_list args) 301 { 302 unsigned int n; 303 304 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); 305 306 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, 307 "verifier log line truncated - local buffer too short\n"); 308 309 if (log->level == BPF_LOG_KERNEL) { 310 bool newline = n > 0 && log->kbuf[n - 1] == '\n'; 311 312 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n"); 313 return; 314 } 315 316 n = min(log->len_total - log->len_used - 1, n); 317 log->kbuf[n] = '\0'; 318 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) 319 log->len_used += n; 320 else 321 log->ubuf = NULL; 322 } 323 324 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos) 325 { 326 char zero = 0; 327 328 if (!bpf_verifier_log_needed(log)) 329 return; 330 331 log->len_used = new_pos; 332 if (put_user(zero, log->ubuf + new_pos)) 333 log->ubuf = NULL; 334 } 335 336 /* log_level controls verbosity level of eBPF verifier. 337 * bpf_verifier_log_write() is used to dump the verification trace to the log, 338 * so the user can figure out what's wrong with the program 339 */ 340 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 341 const char *fmt, ...) 342 { 343 va_list args; 344 345 if (!bpf_verifier_log_needed(&env->log)) 346 return; 347 348 va_start(args, fmt); 349 bpf_verifier_vlog(&env->log, fmt, args); 350 va_end(args); 351 } 352 EXPORT_SYMBOL_GPL(bpf_verifier_log_write); 353 354 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 355 { 356 struct bpf_verifier_env *env = private_data; 357 va_list args; 358 359 if (!bpf_verifier_log_needed(&env->log)) 360 return; 361 362 va_start(args, fmt); 363 bpf_verifier_vlog(&env->log, fmt, args); 364 va_end(args); 365 } 366 367 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log, 368 const char *fmt, ...) 369 { 370 va_list args; 371 372 if (!bpf_verifier_log_needed(log)) 373 return; 374 375 va_start(args, fmt); 376 bpf_verifier_vlog(log, fmt, args); 377 va_end(args); 378 } 379 EXPORT_SYMBOL_GPL(bpf_log); 380 381 static const char *ltrim(const char *s) 382 { 383 while (isspace(*s)) 384 s++; 385 386 return s; 387 } 388 389 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 390 u32 insn_off, 391 const char *prefix_fmt, ...) 392 { 393 const struct bpf_line_info *linfo; 394 395 if (!bpf_verifier_log_needed(&env->log)) 396 return; 397 398 linfo = find_linfo(env, insn_off); 399 if (!linfo || linfo == env->prev_linfo) 400 return; 401 402 if (prefix_fmt) { 403 va_list args; 404 405 va_start(args, prefix_fmt); 406 bpf_verifier_vlog(&env->log, prefix_fmt, args); 407 va_end(args); 408 } 409 410 verbose(env, "%s\n", 411 ltrim(btf_name_by_offset(env->prog->aux->btf, 412 linfo->line_off))); 413 414 env->prev_linfo = linfo; 415 } 416 417 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 418 struct bpf_reg_state *reg, 419 struct tnum *range, const char *ctx, 420 const char *reg_name) 421 { 422 char tn_buf[48]; 423 424 verbose(env, "At %s the register %s ", ctx, reg_name); 425 if (!tnum_is_unknown(reg->var_off)) { 426 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 427 verbose(env, "has value %s", tn_buf); 428 } else { 429 verbose(env, "has unknown scalar value"); 430 } 431 tnum_strn(tn_buf, sizeof(tn_buf), *range); 432 verbose(env, " should have been in %s\n", tn_buf); 433 } 434 435 static bool type_is_pkt_pointer(enum bpf_reg_type type) 436 { 437 type = base_type(type); 438 return type == PTR_TO_PACKET || 439 type == PTR_TO_PACKET_META; 440 } 441 442 static bool type_is_sk_pointer(enum bpf_reg_type type) 443 { 444 return type == PTR_TO_SOCKET || 445 type == PTR_TO_SOCK_COMMON || 446 type == PTR_TO_TCP_SOCK || 447 type == PTR_TO_XDP_SOCK; 448 } 449 450 static bool reg_type_not_null(enum bpf_reg_type type) 451 { 452 return type == PTR_TO_SOCKET || 453 type == PTR_TO_TCP_SOCK || 454 type == PTR_TO_MAP_VALUE || 455 type == PTR_TO_MAP_KEY || 456 type == PTR_TO_SOCK_COMMON; 457 } 458 459 static bool type_is_ptr_alloc_obj(u32 type) 460 { 461 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 462 } 463 464 static bool type_is_non_owning_ref(u32 type) 465 { 466 return type_is_ptr_alloc_obj(type) && type_flag(type) & NON_OWN_REF; 467 } 468 469 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 470 { 471 struct btf_record *rec = NULL; 472 struct btf_struct_meta *meta; 473 474 if (reg->type == PTR_TO_MAP_VALUE) { 475 rec = reg->map_ptr->record; 476 } else if (type_is_ptr_alloc_obj(reg->type)) { 477 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 478 if (meta) 479 rec = meta->record; 480 } 481 return rec; 482 } 483 484 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 485 { 486 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 487 } 488 489 static bool type_is_rdonly_mem(u32 type) 490 { 491 return type & MEM_RDONLY; 492 } 493 494 static bool type_may_be_null(u32 type) 495 { 496 return type & PTR_MAYBE_NULL; 497 } 498 499 static bool is_acquire_function(enum bpf_func_id func_id, 500 const struct bpf_map *map) 501 { 502 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 503 504 if (func_id == BPF_FUNC_sk_lookup_tcp || 505 func_id == BPF_FUNC_sk_lookup_udp || 506 func_id == BPF_FUNC_skc_lookup_tcp || 507 func_id == BPF_FUNC_ringbuf_reserve || 508 func_id == BPF_FUNC_kptr_xchg) 509 return true; 510 511 if (func_id == BPF_FUNC_map_lookup_elem && 512 (map_type == BPF_MAP_TYPE_SOCKMAP || 513 map_type == BPF_MAP_TYPE_SOCKHASH)) 514 return true; 515 516 return false; 517 } 518 519 static bool is_ptr_cast_function(enum bpf_func_id func_id) 520 { 521 return func_id == BPF_FUNC_tcp_sock || 522 func_id == BPF_FUNC_sk_fullsock || 523 func_id == BPF_FUNC_skc_to_tcp_sock || 524 func_id == BPF_FUNC_skc_to_tcp6_sock || 525 func_id == BPF_FUNC_skc_to_udp6_sock || 526 func_id == BPF_FUNC_skc_to_mptcp_sock || 527 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 528 func_id == BPF_FUNC_skc_to_tcp_request_sock; 529 } 530 531 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 532 { 533 return func_id == BPF_FUNC_dynptr_data; 534 } 535 536 static bool is_callback_calling_function(enum bpf_func_id func_id) 537 { 538 return func_id == BPF_FUNC_for_each_map_elem || 539 func_id == BPF_FUNC_timer_set_callback || 540 func_id == BPF_FUNC_find_vma || 541 func_id == BPF_FUNC_loop || 542 func_id == BPF_FUNC_user_ringbuf_drain; 543 } 544 545 static bool is_storage_get_function(enum bpf_func_id func_id) 546 { 547 return func_id == BPF_FUNC_sk_storage_get || 548 func_id == BPF_FUNC_inode_storage_get || 549 func_id == BPF_FUNC_task_storage_get || 550 func_id == BPF_FUNC_cgrp_storage_get; 551 } 552 553 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 554 const struct bpf_map *map) 555 { 556 int ref_obj_uses = 0; 557 558 if (is_ptr_cast_function(func_id)) 559 ref_obj_uses++; 560 if (is_acquire_function(func_id, map)) 561 ref_obj_uses++; 562 if (is_dynptr_ref_function(func_id)) 563 ref_obj_uses++; 564 565 return ref_obj_uses > 1; 566 } 567 568 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 569 { 570 return BPF_CLASS(insn->code) == BPF_STX && 571 BPF_MODE(insn->code) == BPF_ATOMIC && 572 insn->imm == BPF_CMPXCHG; 573 } 574 575 /* string representation of 'enum bpf_reg_type' 576 * 577 * Note that reg_type_str() can not appear more than once in a single verbose() 578 * statement. 579 */ 580 static const char *reg_type_str(struct bpf_verifier_env *env, 581 enum bpf_reg_type type) 582 { 583 char postfix[16] = {0}, prefix[64] = {0}; 584 static const char * const str[] = { 585 [NOT_INIT] = "?", 586 [SCALAR_VALUE] = "scalar", 587 [PTR_TO_CTX] = "ctx", 588 [CONST_PTR_TO_MAP] = "map_ptr", 589 [PTR_TO_MAP_VALUE] = "map_value", 590 [PTR_TO_STACK] = "fp", 591 [PTR_TO_PACKET] = "pkt", 592 [PTR_TO_PACKET_META] = "pkt_meta", 593 [PTR_TO_PACKET_END] = "pkt_end", 594 [PTR_TO_FLOW_KEYS] = "flow_keys", 595 [PTR_TO_SOCKET] = "sock", 596 [PTR_TO_SOCK_COMMON] = "sock_common", 597 [PTR_TO_TCP_SOCK] = "tcp_sock", 598 [PTR_TO_TP_BUFFER] = "tp_buffer", 599 [PTR_TO_XDP_SOCK] = "xdp_sock", 600 [PTR_TO_BTF_ID] = "ptr_", 601 [PTR_TO_MEM] = "mem", 602 [PTR_TO_BUF] = "buf", 603 [PTR_TO_FUNC] = "func", 604 [PTR_TO_MAP_KEY] = "map_key", 605 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 606 }; 607 608 if (type & PTR_MAYBE_NULL) { 609 if (base_type(type) == PTR_TO_BTF_ID) 610 strncpy(postfix, "or_null_", 16); 611 else 612 strncpy(postfix, "_or_null", 16); 613 } 614 615 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 616 type & MEM_RDONLY ? "rdonly_" : "", 617 type & MEM_RINGBUF ? "ringbuf_" : "", 618 type & MEM_USER ? "user_" : "", 619 type & MEM_PERCPU ? "percpu_" : "", 620 type & MEM_RCU ? "rcu_" : "", 621 type & PTR_UNTRUSTED ? "untrusted_" : "", 622 type & PTR_TRUSTED ? "trusted_" : "" 623 ); 624 625 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s", 626 prefix, str[base_type(type)], postfix); 627 return env->type_str_buf; 628 } 629 630 static char slot_type_char[] = { 631 [STACK_INVALID] = '?', 632 [STACK_SPILL] = 'r', 633 [STACK_MISC] = 'm', 634 [STACK_ZERO] = '0', 635 [STACK_DYNPTR] = 'd', 636 }; 637 638 static void print_liveness(struct bpf_verifier_env *env, 639 enum bpf_reg_liveness live) 640 { 641 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 642 verbose(env, "_"); 643 if (live & REG_LIVE_READ) 644 verbose(env, "r"); 645 if (live & REG_LIVE_WRITTEN) 646 verbose(env, "w"); 647 if (live & REG_LIVE_DONE) 648 verbose(env, "D"); 649 } 650 651 static int __get_spi(s32 off) 652 { 653 return (-off - 1) / BPF_REG_SIZE; 654 } 655 656 static struct bpf_func_state *func(struct bpf_verifier_env *env, 657 const struct bpf_reg_state *reg) 658 { 659 struct bpf_verifier_state *cur = env->cur_state; 660 661 return cur->frame[reg->frameno]; 662 } 663 664 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 665 { 666 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 667 668 /* We need to check that slots between [spi - nr_slots + 1, spi] are 669 * within [0, allocated_stack). 670 * 671 * Please note that the spi grows downwards. For example, a dynptr 672 * takes the size of two stack slots; the first slot will be at 673 * spi and the second slot will be at spi - 1. 674 */ 675 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 676 } 677 678 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 679 { 680 int off, spi; 681 682 if (!tnum_is_const(reg->var_off)) { 683 verbose(env, "dynptr has to be at a constant offset\n"); 684 return -EINVAL; 685 } 686 687 off = reg->off + reg->var_off.value; 688 if (off % BPF_REG_SIZE) { 689 verbose(env, "cannot pass in dynptr at an offset=%d\n", off); 690 return -EINVAL; 691 } 692 693 spi = __get_spi(off); 694 if (spi < 1) { 695 verbose(env, "cannot pass in dynptr at an offset=%d\n", off); 696 return -EINVAL; 697 } 698 699 if (!is_spi_bounds_valid(func(env, reg), spi, BPF_DYNPTR_NR_SLOTS)) 700 return -ERANGE; 701 return spi; 702 } 703 704 static const char *kernel_type_name(const struct btf* btf, u32 id) 705 { 706 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 707 } 708 709 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 710 { 711 env->scratched_regs |= 1U << regno; 712 } 713 714 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 715 { 716 env->scratched_stack_slots |= 1ULL << spi; 717 } 718 719 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 720 { 721 return (env->scratched_regs >> regno) & 1; 722 } 723 724 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 725 { 726 return (env->scratched_stack_slots >> regno) & 1; 727 } 728 729 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 730 { 731 return env->scratched_regs || env->scratched_stack_slots; 732 } 733 734 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 735 { 736 env->scratched_regs = 0U; 737 env->scratched_stack_slots = 0ULL; 738 } 739 740 /* Used for printing the entire verifier state. */ 741 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 742 { 743 env->scratched_regs = ~0U; 744 env->scratched_stack_slots = ~0ULL; 745 } 746 747 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 748 { 749 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 750 case DYNPTR_TYPE_LOCAL: 751 return BPF_DYNPTR_TYPE_LOCAL; 752 case DYNPTR_TYPE_RINGBUF: 753 return BPF_DYNPTR_TYPE_RINGBUF; 754 default: 755 return BPF_DYNPTR_TYPE_INVALID; 756 } 757 } 758 759 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 760 { 761 return type == BPF_DYNPTR_TYPE_RINGBUF; 762 } 763 764 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 765 enum bpf_dynptr_type type, 766 bool first_slot, int dynptr_id); 767 768 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 769 struct bpf_reg_state *reg); 770 771 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 772 struct bpf_reg_state *sreg1, 773 struct bpf_reg_state *sreg2, 774 enum bpf_dynptr_type type) 775 { 776 int id = ++env->id_gen; 777 778 __mark_dynptr_reg(sreg1, type, true, id); 779 __mark_dynptr_reg(sreg2, type, false, id); 780 } 781 782 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 783 struct bpf_reg_state *reg, 784 enum bpf_dynptr_type type) 785 { 786 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 787 } 788 789 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 790 struct bpf_func_state *state, int spi); 791 792 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 793 enum bpf_arg_type arg_type, int insn_idx) 794 { 795 struct bpf_func_state *state = func(env, reg); 796 enum bpf_dynptr_type type; 797 int spi, i, id, err; 798 799 spi = dynptr_get_spi(env, reg); 800 if (spi < 0) 801 return spi; 802 803 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 804 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 805 * to ensure that for the following example: 806 * [d1][d1][d2][d2] 807 * spi 3 2 1 0 808 * So marking spi = 2 should lead to destruction of both d1 and d2. In 809 * case they do belong to same dynptr, second call won't see slot_type 810 * as STACK_DYNPTR and will simply skip destruction. 811 */ 812 err = destroy_if_dynptr_stack_slot(env, state, spi); 813 if (err) 814 return err; 815 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 816 if (err) 817 return err; 818 819 for (i = 0; i < BPF_REG_SIZE; i++) { 820 state->stack[spi].slot_type[i] = STACK_DYNPTR; 821 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 822 } 823 824 type = arg_to_dynptr_type(arg_type); 825 if (type == BPF_DYNPTR_TYPE_INVALID) 826 return -EINVAL; 827 828 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 829 &state->stack[spi - 1].spilled_ptr, type); 830 831 if (dynptr_type_refcounted(type)) { 832 /* The id is used to track proper releasing */ 833 id = acquire_reference_state(env, insn_idx); 834 if (id < 0) 835 return id; 836 837 state->stack[spi].spilled_ptr.ref_obj_id = id; 838 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 839 } 840 841 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 842 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 843 844 return 0; 845 } 846 847 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 848 { 849 struct bpf_func_state *state = func(env, reg); 850 int spi, i; 851 852 spi = dynptr_get_spi(env, reg); 853 if (spi < 0) 854 return spi; 855 856 for (i = 0; i < BPF_REG_SIZE; i++) { 857 state->stack[spi].slot_type[i] = STACK_INVALID; 858 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 859 } 860 861 /* Invalidate any slices associated with this dynptr */ 862 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) 863 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id)); 864 865 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 866 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 867 868 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 869 * 870 * While we don't allow reading STACK_INVALID, it is still possible to 871 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 872 * helpers or insns can do partial read of that part without failing, 873 * but check_stack_range_initialized, check_stack_read_var_off, and 874 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 875 * the slot conservatively. Hence we need to prevent those liveness 876 * marking walks. 877 * 878 * This was not a problem before because STACK_INVALID is only set by 879 * default (where the default reg state has its reg->parent as NULL), or 880 * in clean_live_states after REG_LIVE_DONE (at which point 881 * mark_reg_read won't walk reg->parent chain), but not randomly during 882 * verifier state exploration (like we did above). Hence, for our case 883 * parentage chain will still be live (i.e. reg->parent may be 884 * non-NULL), while earlier reg->parent was NULL, so we need 885 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 886 * done later on reads or by mark_dynptr_read as well to unnecessary 887 * mark registers in verifier state. 888 */ 889 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 890 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 891 892 return 0; 893 } 894 895 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 896 struct bpf_reg_state *reg); 897 898 static void mark_reg_invalid(const struct bpf_verifier_env *env, struct bpf_reg_state *reg) 899 { 900 if (!env->allow_ptr_leaks) 901 __mark_reg_not_init(env, reg); 902 else 903 __mark_reg_unknown(env, reg); 904 } 905 906 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 907 struct bpf_func_state *state, int spi) 908 { 909 struct bpf_func_state *fstate; 910 struct bpf_reg_state *dreg; 911 int i, dynptr_id; 912 913 /* We always ensure that STACK_DYNPTR is never set partially, 914 * hence just checking for slot_type[0] is enough. This is 915 * different for STACK_SPILL, where it may be only set for 916 * 1 byte, so code has to use is_spilled_reg. 917 */ 918 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 919 return 0; 920 921 /* Reposition spi to first slot */ 922 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 923 spi = spi + 1; 924 925 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 926 verbose(env, "cannot overwrite referenced dynptr\n"); 927 return -EINVAL; 928 } 929 930 mark_stack_slot_scratched(env, spi); 931 mark_stack_slot_scratched(env, spi - 1); 932 933 /* Writing partially to one dynptr stack slot destroys both. */ 934 for (i = 0; i < BPF_REG_SIZE; i++) { 935 state->stack[spi].slot_type[i] = STACK_INVALID; 936 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 937 } 938 939 dynptr_id = state->stack[spi].spilled_ptr.id; 940 /* Invalidate any slices associated with this dynptr */ 941 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 942 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 943 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 944 continue; 945 if (dreg->dynptr_id == dynptr_id) 946 mark_reg_invalid(env, dreg); 947 })); 948 949 /* Do not release reference state, we are destroying dynptr on stack, 950 * not using some helper to release it. Just reset register. 951 */ 952 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 953 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 954 955 /* Same reason as unmark_stack_slots_dynptr above */ 956 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 957 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 958 959 return 0; 960 } 961 962 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 963 int spi) 964 { 965 if (reg->type == CONST_PTR_TO_DYNPTR) 966 return false; 967 968 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 969 * will do check_mem_access to check and update stack bounds later, so 970 * return true for that case. 971 */ 972 if (spi < 0) 973 return spi == -ERANGE; 974 /* We allow overwriting existing unreferenced STACK_DYNPTR slots, see 975 * mark_stack_slots_dynptr which calls destroy_if_dynptr_stack_slot to 976 * ensure dynptr objects at the slots we are touching are completely 977 * destructed before we reinitialize them for a new one. For referenced 978 * ones, destroy_if_dynptr_stack_slot returns an error early instead of 979 * delaying it until the end where the user will get "Unreleased 980 * reference" error. 981 */ 982 return true; 983 } 984 985 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 986 int spi) 987 { 988 struct bpf_func_state *state = func(env, reg); 989 int i; 990 991 /* This already represents first slot of initialized bpf_dynptr */ 992 if (reg->type == CONST_PTR_TO_DYNPTR) 993 return true; 994 995 if (spi < 0) 996 return false; 997 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 998 return false; 999 1000 for (i = 0; i < BPF_REG_SIZE; i++) { 1001 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 1002 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 1003 return false; 1004 } 1005 1006 return true; 1007 } 1008 1009 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 1010 enum bpf_arg_type arg_type) 1011 { 1012 struct bpf_func_state *state = func(env, reg); 1013 enum bpf_dynptr_type dynptr_type; 1014 int spi; 1015 1016 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1017 if (arg_type == ARG_PTR_TO_DYNPTR) 1018 return true; 1019 1020 dynptr_type = arg_to_dynptr_type(arg_type); 1021 if (reg->type == CONST_PTR_TO_DYNPTR) { 1022 return reg->dynptr.type == dynptr_type; 1023 } else { 1024 spi = dynptr_get_spi(env, reg); 1025 if (spi < 0) 1026 return false; 1027 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1028 } 1029 } 1030 1031 /* The reg state of a pointer or a bounded scalar was saved when 1032 * it was spilled to the stack. 1033 */ 1034 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1035 { 1036 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1037 } 1038 1039 static void scrub_spilled_slot(u8 *stype) 1040 { 1041 if (*stype != STACK_INVALID) 1042 *stype = STACK_MISC; 1043 } 1044 1045 static void print_verifier_state(struct bpf_verifier_env *env, 1046 const struct bpf_func_state *state, 1047 bool print_all) 1048 { 1049 const struct bpf_reg_state *reg; 1050 enum bpf_reg_type t; 1051 int i; 1052 1053 if (state->frameno) 1054 verbose(env, " frame%d:", state->frameno); 1055 for (i = 0; i < MAX_BPF_REG; i++) { 1056 reg = &state->regs[i]; 1057 t = reg->type; 1058 if (t == NOT_INIT) 1059 continue; 1060 if (!print_all && !reg_scratched(env, i)) 1061 continue; 1062 verbose(env, " R%d", i); 1063 print_liveness(env, reg->live); 1064 verbose(env, "="); 1065 if (t == SCALAR_VALUE && reg->precise) 1066 verbose(env, "P"); 1067 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1068 tnum_is_const(reg->var_off)) { 1069 /* reg->off should be 0 for SCALAR_VALUE */ 1070 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1071 verbose(env, "%lld", reg->var_off.value + reg->off); 1072 } else { 1073 const char *sep = ""; 1074 1075 verbose(env, "%s", reg_type_str(env, t)); 1076 if (base_type(t) == PTR_TO_BTF_ID) 1077 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id)); 1078 verbose(env, "("); 1079 /* 1080 * _a stands for append, was shortened to avoid multiline statements below. 1081 * This macro is used to output a comma separated list of attributes. 1082 */ 1083 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1084 1085 if (reg->id) 1086 verbose_a("id=%d", reg->id); 1087 if (reg->ref_obj_id) 1088 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1089 if (type_is_non_owning_ref(reg->type)) 1090 verbose_a("%s", "non_own_ref"); 1091 if (t != SCALAR_VALUE) 1092 verbose_a("off=%d", reg->off); 1093 if (type_is_pkt_pointer(t)) 1094 verbose_a("r=%d", reg->range); 1095 else if (base_type(t) == CONST_PTR_TO_MAP || 1096 base_type(t) == PTR_TO_MAP_KEY || 1097 base_type(t) == PTR_TO_MAP_VALUE) 1098 verbose_a("ks=%d,vs=%d", 1099 reg->map_ptr->key_size, 1100 reg->map_ptr->value_size); 1101 if (tnum_is_const(reg->var_off)) { 1102 /* Typically an immediate SCALAR_VALUE, but 1103 * could be a pointer whose offset is too big 1104 * for reg->off 1105 */ 1106 verbose_a("imm=%llx", reg->var_off.value); 1107 } else { 1108 if (reg->smin_value != reg->umin_value && 1109 reg->smin_value != S64_MIN) 1110 verbose_a("smin=%lld", (long long)reg->smin_value); 1111 if (reg->smax_value != reg->umax_value && 1112 reg->smax_value != S64_MAX) 1113 verbose_a("smax=%lld", (long long)reg->smax_value); 1114 if (reg->umin_value != 0) 1115 verbose_a("umin=%llu", (unsigned long long)reg->umin_value); 1116 if (reg->umax_value != U64_MAX) 1117 verbose_a("umax=%llu", (unsigned long long)reg->umax_value); 1118 if (!tnum_is_unknown(reg->var_off)) { 1119 char tn_buf[48]; 1120 1121 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1122 verbose_a("var_off=%s", tn_buf); 1123 } 1124 if (reg->s32_min_value != reg->smin_value && 1125 reg->s32_min_value != S32_MIN) 1126 verbose_a("s32_min=%d", (int)(reg->s32_min_value)); 1127 if (reg->s32_max_value != reg->smax_value && 1128 reg->s32_max_value != S32_MAX) 1129 verbose_a("s32_max=%d", (int)(reg->s32_max_value)); 1130 if (reg->u32_min_value != reg->umin_value && 1131 reg->u32_min_value != U32_MIN) 1132 verbose_a("u32_min=%d", (int)(reg->u32_min_value)); 1133 if (reg->u32_max_value != reg->umax_value && 1134 reg->u32_max_value != U32_MAX) 1135 verbose_a("u32_max=%d", (int)(reg->u32_max_value)); 1136 } 1137 #undef verbose_a 1138 1139 verbose(env, ")"); 1140 } 1141 } 1142 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1143 char types_buf[BPF_REG_SIZE + 1]; 1144 bool valid = false; 1145 int j; 1146 1147 for (j = 0; j < BPF_REG_SIZE; j++) { 1148 if (state->stack[i].slot_type[j] != STACK_INVALID) 1149 valid = true; 1150 types_buf[j] = slot_type_char[ 1151 state->stack[i].slot_type[j]]; 1152 } 1153 types_buf[BPF_REG_SIZE] = 0; 1154 if (!valid) 1155 continue; 1156 if (!print_all && !stack_slot_scratched(env, i)) 1157 continue; 1158 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1159 print_liveness(env, state->stack[i].spilled_ptr.live); 1160 if (is_spilled_reg(&state->stack[i])) { 1161 reg = &state->stack[i].spilled_ptr; 1162 t = reg->type; 1163 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1164 if (t == SCALAR_VALUE && reg->precise) 1165 verbose(env, "P"); 1166 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1167 verbose(env, "%lld", reg->var_off.value + reg->off); 1168 } else { 1169 verbose(env, "=%s", types_buf); 1170 } 1171 } 1172 if (state->acquired_refs && state->refs[0].id) { 1173 verbose(env, " refs=%d", state->refs[0].id); 1174 for (i = 1; i < state->acquired_refs; i++) 1175 if (state->refs[i].id) 1176 verbose(env, ",%d", state->refs[i].id); 1177 } 1178 if (state->in_callback_fn) 1179 verbose(env, " cb"); 1180 if (state->in_async_callback_fn) 1181 verbose(env, " async_cb"); 1182 verbose(env, "\n"); 1183 mark_verifier_state_clean(env); 1184 } 1185 1186 static inline u32 vlog_alignment(u32 pos) 1187 { 1188 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1189 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1190 } 1191 1192 static void print_insn_state(struct bpf_verifier_env *env, 1193 const struct bpf_func_state *state) 1194 { 1195 if (env->prev_log_len && env->prev_log_len == env->log.len_used) { 1196 /* remove new line character */ 1197 bpf_vlog_reset(&env->log, env->prev_log_len - 1); 1198 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' '); 1199 } else { 1200 verbose(env, "%d:", env->insn_idx); 1201 } 1202 print_verifier_state(env, state, false); 1203 } 1204 1205 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1206 * small to hold src. This is different from krealloc since we don't want to preserve 1207 * the contents of dst. 1208 * 1209 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1210 * not be allocated. 1211 */ 1212 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1213 { 1214 size_t alloc_bytes; 1215 void *orig = dst; 1216 size_t bytes; 1217 1218 if (ZERO_OR_NULL_PTR(src)) 1219 goto out; 1220 1221 if (unlikely(check_mul_overflow(n, size, &bytes))) 1222 return NULL; 1223 1224 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1225 dst = krealloc(orig, alloc_bytes, flags); 1226 if (!dst) { 1227 kfree(orig); 1228 return NULL; 1229 } 1230 1231 memcpy(dst, src, bytes); 1232 out: 1233 return dst ? dst : ZERO_SIZE_PTR; 1234 } 1235 1236 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1237 * small to hold new_n items. new items are zeroed out if the array grows. 1238 * 1239 * Contrary to krealloc_array, does not free arr if new_n is zero. 1240 */ 1241 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1242 { 1243 size_t alloc_size; 1244 void *new_arr; 1245 1246 if (!new_n || old_n == new_n) 1247 goto out; 1248 1249 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1250 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1251 if (!new_arr) { 1252 kfree(arr); 1253 return NULL; 1254 } 1255 arr = new_arr; 1256 1257 if (new_n > old_n) 1258 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1259 1260 out: 1261 return arr ? arr : ZERO_SIZE_PTR; 1262 } 1263 1264 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1265 { 1266 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1267 sizeof(struct bpf_reference_state), GFP_KERNEL); 1268 if (!dst->refs) 1269 return -ENOMEM; 1270 1271 dst->acquired_refs = src->acquired_refs; 1272 return 0; 1273 } 1274 1275 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1276 { 1277 size_t n = src->allocated_stack / BPF_REG_SIZE; 1278 1279 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1280 GFP_KERNEL); 1281 if (!dst->stack) 1282 return -ENOMEM; 1283 1284 dst->allocated_stack = src->allocated_stack; 1285 return 0; 1286 } 1287 1288 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1289 { 1290 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1291 sizeof(struct bpf_reference_state)); 1292 if (!state->refs) 1293 return -ENOMEM; 1294 1295 state->acquired_refs = n; 1296 return 0; 1297 } 1298 1299 static int grow_stack_state(struct bpf_func_state *state, int size) 1300 { 1301 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1302 1303 if (old_n >= n) 1304 return 0; 1305 1306 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1307 if (!state->stack) 1308 return -ENOMEM; 1309 1310 state->allocated_stack = size; 1311 return 0; 1312 } 1313 1314 /* Acquire a pointer id from the env and update the state->refs to include 1315 * this new pointer reference. 1316 * On success, returns a valid pointer id to associate with the register 1317 * On failure, returns a negative errno. 1318 */ 1319 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1320 { 1321 struct bpf_func_state *state = cur_func(env); 1322 int new_ofs = state->acquired_refs; 1323 int id, err; 1324 1325 err = resize_reference_state(state, state->acquired_refs + 1); 1326 if (err) 1327 return err; 1328 id = ++env->id_gen; 1329 state->refs[new_ofs].id = id; 1330 state->refs[new_ofs].insn_idx = insn_idx; 1331 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1332 1333 return id; 1334 } 1335 1336 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1337 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1338 { 1339 int i, last_idx; 1340 1341 last_idx = state->acquired_refs - 1; 1342 for (i = 0; i < state->acquired_refs; i++) { 1343 if (state->refs[i].id == ptr_id) { 1344 /* Cannot release caller references in callbacks */ 1345 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1346 return -EINVAL; 1347 if (last_idx && i != last_idx) 1348 memcpy(&state->refs[i], &state->refs[last_idx], 1349 sizeof(*state->refs)); 1350 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1351 state->acquired_refs--; 1352 return 0; 1353 } 1354 } 1355 return -EINVAL; 1356 } 1357 1358 static void free_func_state(struct bpf_func_state *state) 1359 { 1360 if (!state) 1361 return; 1362 kfree(state->refs); 1363 kfree(state->stack); 1364 kfree(state); 1365 } 1366 1367 static void clear_jmp_history(struct bpf_verifier_state *state) 1368 { 1369 kfree(state->jmp_history); 1370 state->jmp_history = NULL; 1371 state->jmp_history_cnt = 0; 1372 } 1373 1374 static void free_verifier_state(struct bpf_verifier_state *state, 1375 bool free_self) 1376 { 1377 int i; 1378 1379 for (i = 0; i <= state->curframe; i++) { 1380 free_func_state(state->frame[i]); 1381 state->frame[i] = NULL; 1382 } 1383 clear_jmp_history(state); 1384 if (free_self) 1385 kfree(state); 1386 } 1387 1388 /* copy verifier state from src to dst growing dst stack space 1389 * when necessary to accommodate larger src stack 1390 */ 1391 static int copy_func_state(struct bpf_func_state *dst, 1392 const struct bpf_func_state *src) 1393 { 1394 int err; 1395 1396 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1397 err = copy_reference_state(dst, src); 1398 if (err) 1399 return err; 1400 return copy_stack_state(dst, src); 1401 } 1402 1403 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1404 const struct bpf_verifier_state *src) 1405 { 1406 struct bpf_func_state *dst; 1407 int i, err; 1408 1409 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1410 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1411 GFP_USER); 1412 if (!dst_state->jmp_history) 1413 return -ENOMEM; 1414 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1415 1416 /* if dst has more stack frames then src frame, free them */ 1417 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1418 free_func_state(dst_state->frame[i]); 1419 dst_state->frame[i] = NULL; 1420 } 1421 dst_state->speculative = src->speculative; 1422 dst_state->active_rcu_lock = src->active_rcu_lock; 1423 dst_state->curframe = src->curframe; 1424 dst_state->active_lock.ptr = src->active_lock.ptr; 1425 dst_state->active_lock.id = src->active_lock.id; 1426 dst_state->branches = src->branches; 1427 dst_state->parent = src->parent; 1428 dst_state->first_insn_idx = src->first_insn_idx; 1429 dst_state->last_insn_idx = src->last_insn_idx; 1430 for (i = 0; i <= src->curframe; i++) { 1431 dst = dst_state->frame[i]; 1432 if (!dst) { 1433 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1434 if (!dst) 1435 return -ENOMEM; 1436 dst_state->frame[i] = dst; 1437 } 1438 err = copy_func_state(dst, src->frame[i]); 1439 if (err) 1440 return err; 1441 } 1442 return 0; 1443 } 1444 1445 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1446 { 1447 while (st) { 1448 u32 br = --st->branches; 1449 1450 /* WARN_ON(br > 1) technically makes sense here, 1451 * but see comment in push_stack(), hence: 1452 */ 1453 WARN_ONCE((int)br < 0, 1454 "BUG update_branch_counts:branches_to_explore=%d\n", 1455 br); 1456 if (br) 1457 break; 1458 st = st->parent; 1459 } 1460 } 1461 1462 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1463 int *insn_idx, bool pop_log) 1464 { 1465 struct bpf_verifier_state *cur = env->cur_state; 1466 struct bpf_verifier_stack_elem *elem, *head = env->head; 1467 int err; 1468 1469 if (env->head == NULL) 1470 return -ENOENT; 1471 1472 if (cur) { 1473 err = copy_verifier_state(cur, &head->st); 1474 if (err) 1475 return err; 1476 } 1477 if (pop_log) 1478 bpf_vlog_reset(&env->log, head->log_pos); 1479 if (insn_idx) 1480 *insn_idx = head->insn_idx; 1481 if (prev_insn_idx) 1482 *prev_insn_idx = head->prev_insn_idx; 1483 elem = head->next; 1484 free_verifier_state(&head->st, false); 1485 kfree(head); 1486 env->head = elem; 1487 env->stack_size--; 1488 return 0; 1489 } 1490 1491 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1492 int insn_idx, int prev_insn_idx, 1493 bool speculative) 1494 { 1495 struct bpf_verifier_state *cur = env->cur_state; 1496 struct bpf_verifier_stack_elem *elem; 1497 int err; 1498 1499 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1500 if (!elem) 1501 goto err; 1502 1503 elem->insn_idx = insn_idx; 1504 elem->prev_insn_idx = prev_insn_idx; 1505 elem->next = env->head; 1506 elem->log_pos = env->log.len_used; 1507 env->head = elem; 1508 env->stack_size++; 1509 err = copy_verifier_state(&elem->st, cur); 1510 if (err) 1511 goto err; 1512 elem->st.speculative |= speculative; 1513 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1514 verbose(env, "The sequence of %d jumps is too complex.\n", 1515 env->stack_size); 1516 goto err; 1517 } 1518 if (elem->st.parent) { 1519 ++elem->st.parent->branches; 1520 /* WARN_ON(branches > 2) technically makes sense here, 1521 * but 1522 * 1. speculative states will bump 'branches' for non-branch 1523 * instructions 1524 * 2. is_state_visited() heuristics may decide not to create 1525 * a new state for a sequence of branches and all such current 1526 * and cloned states will be pointing to a single parent state 1527 * which might have large 'branches' count. 1528 */ 1529 } 1530 return &elem->st; 1531 err: 1532 free_verifier_state(env->cur_state, true); 1533 env->cur_state = NULL; 1534 /* pop all elements and return */ 1535 while (!pop_stack(env, NULL, NULL, false)); 1536 return NULL; 1537 } 1538 1539 #define CALLER_SAVED_REGS 6 1540 static const int caller_saved[CALLER_SAVED_REGS] = { 1541 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1542 }; 1543 1544 /* This helper doesn't clear reg->id */ 1545 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1546 { 1547 reg->var_off = tnum_const(imm); 1548 reg->smin_value = (s64)imm; 1549 reg->smax_value = (s64)imm; 1550 reg->umin_value = imm; 1551 reg->umax_value = imm; 1552 1553 reg->s32_min_value = (s32)imm; 1554 reg->s32_max_value = (s32)imm; 1555 reg->u32_min_value = (u32)imm; 1556 reg->u32_max_value = (u32)imm; 1557 } 1558 1559 /* Mark the unknown part of a register (variable offset or scalar value) as 1560 * known to have the value @imm. 1561 */ 1562 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1563 { 1564 /* Clear off and union(map_ptr, range) */ 1565 memset(((u8 *)reg) + sizeof(reg->type), 0, 1566 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1567 reg->id = 0; 1568 reg->ref_obj_id = 0; 1569 ___mark_reg_known(reg, imm); 1570 } 1571 1572 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1573 { 1574 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1575 reg->s32_min_value = (s32)imm; 1576 reg->s32_max_value = (s32)imm; 1577 reg->u32_min_value = (u32)imm; 1578 reg->u32_max_value = (u32)imm; 1579 } 1580 1581 /* Mark the 'variable offset' part of a register as zero. This should be 1582 * used only on registers holding a pointer type. 1583 */ 1584 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1585 { 1586 __mark_reg_known(reg, 0); 1587 } 1588 1589 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1590 { 1591 __mark_reg_known(reg, 0); 1592 reg->type = SCALAR_VALUE; 1593 } 1594 1595 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1596 struct bpf_reg_state *regs, u32 regno) 1597 { 1598 if (WARN_ON(regno >= MAX_BPF_REG)) { 1599 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1600 /* Something bad happened, let's kill all regs */ 1601 for (regno = 0; regno < MAX_BPF_REG; regno++) 1602 __mark_reg_not_init(env, regs + regno); 1603 return; 1604 } 1605 __mark_reg_known_zero(regs + regno); 1606 } 1607 1608 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1609 bool first_slot, int dynptr_id) 1610 { 1611 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1612 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1613 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1614 */ 1615 __mark_reg_known_zero(reg); 1616 reg->type = CONST_PTR_TO_DYNPTR; 1617 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1618 reg->id = dynptr_id; 1619 reg->dynptr.type = type; 1620 reg->dynptr.first_slot = first_slot; 1621 } 1622 1623 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1624 { 1625 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1626 const struct bpf_map *map = reg->map_ptr; 1627 1628 if (map->inner_map_meta) { 1629 reg->type = CONST_PTR_TO_MAP; 1630 reg->map_ptr = map->inner_map_meta; 1631 /* transfer reg's id which is unique for every map_lookup_elem 1632 * as UID of the inner map. 1633 */ 1634 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1635 reg->map_uid = reg->id; 1636 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1637 reg->type = PTR_TO_XDP_SOCK; 1638 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1639 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1640 reg->type = PTR_TO_SOCKET; 1641 } else { 1642 reg->type = PTR_TO_MAP_VALUE; 1643 } 1644 return; 1645 } 1646 1647 reg->type &= ~PTR_MAYBE_NULL; 1648 } 1649 1650 static void mark_reg_graph_node(struct bpf_reg_state *regs, u32 regno, 1651 struct btf_field_graph_root *ds_head) 1652 { 1653 __mark_reg_known_zero(®s[regno]); 1654 regs[regno].type = PTR_TO_BTF_ID | MEM_ALLOC; 1655 regs[regno].btf = ds_head->btf; 1656 regs[regno].btf_id = ds_head->value_btf_id; 1657 regs[regno].off = ds_head->node_offset; 1658 } 1659 1660 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1661 { 1662 return type_is_pkt_pointer(reg->type); 1663 } 1664 1665 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1666 { 1667 return reg_is_pkt_pointer(reg) || 1668 reg->type == PTR_TO_PACKET_END; 1669 } 1670 1671 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1672 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1673 enum bpf_reg_type which) 1674 { 1675 /* The register can already have a range from prior markings. 1676 * This is fine as long as it hasn't been advanced from its 1677 * origin. 1678 */ 1679 return reg->type == which && 1680 reg->id == 0 && 1681 reg->off == 0 && 1682 tnum_equals_const(reg->var_off, 0); 1683 } 1684 1685 /* Reset the min/max bounds of a register */ 1686 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1687 { 1688 reg->smin_value = S64_MIN; 1689 reg->smax_value = S64_MAX; 1690 reg->umin_value = 0; 1691 reg->umax_value = U64_MAX; 1692 1693 reg->s32_min_value = S32_MIN; 1694 reg->s32_max_value = S32_MAX; 1695 reg->u32_min_value = 0; 1696 reg->u32_max_value = U32_MAX; 1697 } 1698 1699 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1700 { 1701 reg->smin_value = S64_MIN; 1702 reg->smax_value = S64_MAX; 1703 reg->umin_value = 0; 1704 reg->umax_value = U64_MAX; 1705 } 1706 1707 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1708 { 1709 reg->s32_min_value = S32_MIN; 1710 reg->s32_max_value = S32_MAX; 1711 reg->u32_min_value = 0; 1712 reg->u32_max_value = U32_MAX; 1713 } 1714 1715 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1716 { 1717 struct tnum var32_off = tnum_subreg(reg->var_off); 1718 1719 /* min signed is max(sign bit) | min(other bits) */ 1720 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1721 var32_off.value | (var32_off.mask & S32_MIN)); 1722 /* max signed is min(sign bit) | max(other bits) */ 1723 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1724 var32_off.value | (var32_off.mask & S32_MAX)); 1725 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1726 reg->u32_max_value = min(reg->u32_max_value, 1727 (u32)(var32_off.value | var32_off.mask)); 1728 } 1729 1730 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1731 { 1732 /* min signed is max(sign bit) | min(other bits) */ 1733 reg->smin_value = max_t(s64, reg->smin_value, 1734 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1735 /* max signed is min(sign bit) | max(other bits) */ 1736 reg->smax_value = min_t(s64, reg->smax_value, 1737 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1738 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1739 reg->umax_value = min(reg->umax_value, 1740 reg->var_off.value | reg->var_off.mask); 1741 } 1742 1743 static void __update_reg_bounds(struct bpf_reg_state *reg) 1744 { 1745 __update_reg32_bounds(reg); 1746 __update_reg64_bounds(reg); 1747 } 1748 1749 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1750 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1751 { 1752 /* Learn sign from signed bounds. 1753 * If we cannot cross the sign boundary, then signed and unsigned bounds 1754 * are the same, so combine. This works even in the negative case, e.g. 1755 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1756 */ 1757 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 1758 reg->s32_min_value = reg->u32_min_value = 1759 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1760 reg->s32_max_value = reg->u32_max_value = 1761 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1762 return; 1763 } 1764 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1765 * boundary, so we must be careful. 1766 */ 1767 if ((s32)reg->u32_max_value >= 0) { 1768 /* Positive. We can't learn anything from the smin, but smax 1769 * is positive, hence safe. 1770 */ 1771 reg->s32_min_value = reg->u32_min_value; 1772 reg->s32_max_value = reg->u32_max_value = 1773 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1774 } else if ((s32)reg->u32_min_value < 0) { 1775 /* Negative. We can't learn anything from the smax, but smin 1776 * is negative, hence safe. 1777 */ 1778 reg->s32_min_value = reg->u32_min_value = 1779 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1780 reg->s32_max_value = reg->u32_max_value; 1781 } 1782 } 1783 1784 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 1785 { 1786 /* Learn sign from signed bounds. 1787 * If we cannot cross the sign boundary, then signed and unsigned bounds 1788 * are the same, so combine. This works even in the negative case, e.g. 1789 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1790 */ 1791 if (reg->smin_value >= 0 || reg->smax_value < 0) { 1792 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1793 reg->umin_value); 1794 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1795 reg->umax_value); 1796 return; 1797 } 1798 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1799 * boundary, so we must be careful. 1800 */ 1801 if ((s64)reg->umax_value >= 0) { 1802 /* Positive. We can't learn anything from the smin, but smax 1803 * is positive, hence safe. 1804 */ 1805 reg->smin_value = reg->umin_value; 1806 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1807 reg->umax_value); 1808 } else if ((s64)reg->umin_value < 0) { 1809 /* Negative. We can't learn anything from the smax, but smin 1810 * is negative, hence safe. 1811 */ 1812 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1813 reg->umin_value); 1814 reg->smax_value = reg->umax_value; 1815 } 1816 } 1817 1818 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 1819 { 1820 __reg32_deduce_bounds(reg); 1821 __reg64_deduce_bounds(reg); 1822 } 1823 1824 /* Attempts to improve var_off based on unsigned min/max information */ 1825 static void __reg_bound_offset(struct bpf_reg_state *reg) 1826 { 1827 struct tnum var64_off = tnum_intersect(reg->var_off, 1828 tnum_range(reg->umin_value, 1829 reg->umax_value)); 1830 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off), 1831 tnum_range(reg->u32_min_value, 1832 reg->u32_max_value)); 1833 1834 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 1835 } 1836 1837 static void reg_bounds_sync(struct bpf_reg_state *reg) 1838 { 1839 /* We might have learned new bounds from the var_off. */ 1840 __update_reg_bounds(reg); 1841 /* We might have learned something about the sign bit. */ 1842 __reg_deduce_bounds(reg); 1843 /* We might have learned some bits from the bounds. */ 1844 __reg_bound_offset(reg); 1845 /* Intersecting with the old var_off might have improved our bounds 1846 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1847 * then new var_off is (0; 0x7f...fc) which improves our umax. 1848 */ 1849 __update_reg_bounds(reg); 1850 } 1851 1852 static bool __reg32_bound_s64(s32 a) 1853 { 1854 return a >= 0 && a <= S32_MAX; 1855 } 1856 1857 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 1858 { 1859 reg->umin_value = reg->u32_min_value; 1860 reg->umax_value = reg->u32_max_value; 1861 1862 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 1863 * be positive otherwise set to worse case bounds and refine later 1864 * from tnum. 1865 */ 1866 if (__reg32_bound_s64(reg->s32_min_value) && 1867 __reg32_bound_s64(reg->s32_max_value)) { 1868 reg->smin_value = reg->s32_min_value; 1869 reg->smax_value = reg->s32_max_value; 1870 } else { 1871 reg->smin_value = 0; 1872 reg->smax_value = U32_MAX; 1873 } 1874 } 1875 1876 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 1877 { 1878 /* special case when 64-bit register has upper 32-bit register 1879 * zeroed. Typically happens after zext or <<32, >>32 sequence 1880 * allowing us to use 32-bit bounds directly, 1881 */ 1882 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 1883 __reg_assign_32_into_64(reg); 1884 } else { 1885 /* Otherwise the best we can do is push lower 32bit known and 1886 * unknown bits into register (var_off set from jmp logic) 1887 * then learn as much as possible from the 64-bit tnum 1888 * known and unknown bits. The previous smin/smax bounds are 1889 * invalid here because of jmp32 compare so mark them unknown 1890 * so they do not impact tnum bounds calculation. 1891 */ 1892 __mark_reg64_unbounded(reg); 1893 } 1894 reg_bounds_sync(reg); 1895 } 1896 1897 static bool __reg64_bound_s32(s64 a) 1898 { 1899 return a >= S32_MIN && a <= S32_MAX; 1900 } 1901 1902 static bool __reg64_bound_u32(u64 a) 1903 { 1904 return a >= U32_MIN && a <= U32_MAX; 1905 } 1906 1907 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 1908 { 1909 __mark_reg32_unbounded(reg); 1910 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 1911 reg->s32_min_value = (s32)reg->smin_value; 1912 reg->s32_max_value = (s32)reg->smax_value; 1913 } 1914 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 1915 reg->u32_min_value = (u32)reg->umin_value; 1916 reg->u32_max_value = (u32)reg->umax_value; 1917 } 1918 reg_bounds_sync(reg); 1919 } 1920 1921 /* Mark a register as having a completely unknown (scalar) value. */ 1922 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1923 struct bpf_reg_state *reg) 1924 { 1925 /* 1926 * Clear type, off, and union(map_ptr, range) and 1927 * padding between 'type' and union 1928 */ 1929 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 1930 reg->type = SCALAR_VALUE; 1931 reg->id = 0; 1932 reg->ref_obj_id = 0; 1933 reg->var_off = tnum_unknown; 1934 reg->frameno = 0; 1935 reg->precise = !env->bpf_capable; 1936 __mark_reg_unbounded(reg); 1937 } 1938 1939 static void mark_reg_unknown(struct bpf_verifier_env *env, 1940 struct bpf_reg_state *regs, u32 regno) 1941 { 1942 if (WARN_ON(regno >= MAX_BPF_REG)) { 1943 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 1944 /* Something bad happened, let's kill all regs except FP */ 1945 for (regno = 0; regno < BPF_REG_FP; regno++) 1946 __mark_reg_not_init(env, regs + regno); 1947 return; 1948 } 1949 __mark_reg_unknown(env, regs + regno); 1950 } 1951 1952 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1953 struct bpf_reg_state *reg) 1954 { 1955 __mark_reg_unknown(env, reg); 1956 reg->type = NOT_INIT; 1957 } 1958 1959 static void mark_reg_not_init(struct bpf_verifier_env *env, 1960 struct bpf_reg_state *regs, u32 regno) 1961 { 1962 if (WARN_ON(regno >= MAX_BPF_REG)) { 1963 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 1964 /* Something bad happened, let's kill all regs except FP */ 1965 for (regno = 0; regno < BPF_REG_FP; regno++) 1966 __mark_reg_not_init(env, regs + regno); 1967 return; 1968 } 1969 __mark_reg_not_init(env, regs + regno); 1970 } 1971 1972 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 1973 struct bpf_reg_state *regs, u32 regno, 1974 enum bpf_reg_type reg_type, 1975 struct btf *btf, u32 btf_id, 1976 enum bpf_type_flag flag) 1977 { 1978 if (reg_type == SCALAR_VALUE) { 1979 mark_reg_unknown(env, regs, regno); 1980 return; 1981 } 1982 mark_reg_known_zero(env, regs, regno); 1983 regs[regno].type = PTR_TO_BTF_ID | flag; 1984 regs[regno].btf = btf; 1985 regs[regno].btf_id = btf_id; 1986 } 1987 1988 #define DEF_NOT_SUBREG (0) 1989 static void init_reg_state(struct bpf_verifier_env *env, 1990 struct bpf_func_state *state) 1991 { 1992 struct bpf_reg_state *regs = state->regs; 1993 int i; 1994 1995 for (i = 0; i < MAX_BPF_REG; i++) { 1996 mark_reg_not_init(env, regs, i); 1997 regs[i].live = REG_LIVE_NONE; 1998 regs[i].parent = NULL; 1999 regs[i].subreg_def = DEF_NOT_SUBREG; 2000 } 2001 2002 /* frame pointer */ 2003 regs[BPF_REG_FP].type = PTR_TO_STACK; 2004 mark_reg_known_zero(env, regs, BPF_REG_FP); 2005 regs[BPF_REG_FP].frameno = state->frameno; 2006 } 2007 2008 #define BPF_MAIN_FUNC (-1) 2009 static void init_func_state(struct bpf_verifier_env *env, 2010 struct bpf_func_state *state, 2011 int callsite, int frameno, int subprogno) 2012 { 2013 state->callsite = callsite; 2014 state->frameno = frameno; 2015 state->subprogno = subprogno; 2016 state->callback_ret_range = tnum_range(0, 0); 2017 init_reg_state(env, state); 2018 mark_verifier_state_scratched(env); 2019 } 2020 2021 /* Similar to push_stack(), but for async callbacks */ 2022 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 2023 int insn_idx, int prev_insn_idx, 2024 int subprog) 2025 { 2026 struct bpf_verifier_stack_elem *elem; 2027 struct bpf_func_state *frame; 2028 2029 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2030 if (!elem) 2031 goto err; 2032 2033 elem->insn_idx = insn_idx; 2034 elem->prev_insn_idx = prev_insn_idx; 2035 elem->next = env->head; 2036 elem->log_pos = env->log.len_used; 2037 env->head = elem; 2038 env->stack_size++; 2039 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2040 verbose(env, 2041 "The sequence of %d jumps is too complex for async cb.\n", 2042 env->stack_size); 2043 goto err; 2044 } 2045 /* Unlike push_stack() do not copy_verifier_state(). 2046 * The caller state doesn't matter. 2047 * This is async callback. It starts in a fresh stack. 2048 * Initialize it similar to do_check_common(). 2049 */ 2050 elem->st.branches = 1; 2051 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2052 if (!frame) 2053 goto err; 2054 init_func_state(env, frame, 2055 BPF_MAIN_FUNC /* callsite */, 2056 0 /* frameno within this callchain */, 2057 subprog /* subprog number within this prog */); 2058 elem->st.frame[0] = frame; 2059 return &elem->st; 2060 err: 2061 free_verifier_state(env->cur_state, true); 2062 env->cur_state = NULL; 2063 /* pop all elements and return */ 2064 while (!pop_stack(env, NULL, NULL, false)); 2065 return NULL; 2066 } 2067 2068 2069 enum reg_arg_type { 2070 SRC_OP, /* register is used as source operand */ 2071 DST_OP, /* register is used as destination operand */ 2072 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2073 }; 2074 2075 static int cmp_subprogs(const void *a, const void *b) 2076 { 2077 return ((struct bpf_subprog_info *)a)->start - 2078 ((struct bpf_subprog_info *)b)->start; 2079 } 2080 2081 static int find_subprog(struct bpf_verifier_env *env, int off) 2082 { 2083 struct bpf_subprog_info *p; 2084 2085 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2086 sizeof(env->subprog_info[0]), cmp_subprogs); 2087 if (!p) 2088 return -ENOENT; 2089 return p - env->subprog_info; 2090 2091 } 2092 2093 static int add_subprog(struct bpf_verifier_env *env, int off) 2094 { 2095 int insn_cnt = env->prog->len; 2096 int ret; 2097 2098 if (off >= insn_cnt || off < 0) { 2099 verbose(env, "call to invalid destination\n"); 2100 return -EINVAL; 2101 } 2102 ret = find_subprog(env, off); 2103 if (ret >= 0) 2104 return ret; 2105 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2106 verbose(env, "too many subprograms\n"); 2107 return -E2BIG; 2108 } 2109 /* determine subprog starts. The end is one before the next starts */ 2110 env->subprog_info[env->subprog_cnt++].start = off; 2111 sort(env->subprog_info, env->subprog_cnt, 2112 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2113 return env->subprog_cnt - 1; 2114 } 2115 2116 #define MAX_KFUNC_DESCS 256 2117 #define MAX_KFUNC_BTFS 256 2118 2119 struct bpf_kfunc_desc { 2120 struct btf_func_model func_model; 2121 u32 func_id; 2122 s32 imm; 2123 u16 offset; 2124 }; 2125 2126 struct bpf_kfunc_btf { 2127 struct btf *btf; 2128 struct module *module; 2129 u16 offset; 2130 }; 2131 2132 struct bpf_kfunc_desc_tab { 2133 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2134 u32 nr_descs; 2135 }; 2136 2137 struct bpf_kfunc_btf_tab { 2138 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2139 u32 nr_descs; 2140 }; 2141 2142 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2143 { 2144 const struct bpf_kfunc_desc *d0 = a; 2145 const struct bpf_kfunc_desc *d1 = b; 2146 2147 /* func_id is not greater than BTF_MAX_TYPE */ 2148 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2149 } 2150 2151 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2152 { 2153 const struct bpf_kfunc_btf *d0 = a; 2154 const struct bpf_kfunc_btf *d1 = b; 2155 2156 return d0->offset - d1->offset; 2157 } 2158 2159 static const struct bpf_kfunc_desc * 2160 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2161 { 2162 struct bpf_kfunc_desc desc = { 2163 .func_id = func_id, 2164 .offset = offset, 2165 }; 2166 struct bpf_kfunc_desc_tab *tab; 2167 2168 tab = prog->aux->kfunc_tab; 2169 return bsearch(&desc, tab->descs, tab->nr_descs, 2170 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2171 } 2172 2173 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2174 s16 offset) 2175 { 2176 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2177 struct bpf_kfunc_btf_tab *tab; 2178 struct bpf_kfunc_btf *b; 2179 struct module *mod; 2180 struct btf *btf; 2181 int btf_fd; 2182 2183 tab = env->prog->aux->kfunc_btf_tab; 2184 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2185 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2186 if (!b) { 2187 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2188 verbose(env, "too many different module BTFs\n"); 2189 return ERR_PTR(-E2BIG); 2190 } 2191 2192 if (bpfptr_is_null(env->fd_array)) { 2193 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2194 return ERR_PTR(-EPROTO); 2195 } 2196 2197 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2198 offset * sizeof(btf_fd), 2199 sizeof(btf_fd))) 2200 return ERR_PTR(-EFAULT); 2201 2202 btf = btf_get_by_fd(btf_fd); 2203 if (IS_ERR(btf)) { 2204 verbose(env, "invalid module BTF fd specified\n"); 2205 return btf; 2206 } 2207 2208 if (!btf_is_module(btf)) { 2209 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2210 btf_put(btf); 2211 return ERR_PTR(-EINVAL); 2212 } 2213 2214 mod = btf_try_get_module(btf); 2215 if (!mod) { 2216 btf_put(btf); 2217 return ERR_PTR(-ENXIO); 2218 } 2219 2220 b = &tab->descs[tab->nr_descs++]; 2221 b->btf = btf; 2222 b->module = mod; 2223 b->offset = offset; 2224 2225 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2226 kfunc_btf_cmp_by_off, NULL); 2227 } 2228 return b->btf; 2229 } 2230 2231 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2232 { 2233 if (!tab) 2234 return; 2235 2236 while (tab->nr_descs--) { 2237 module_put(tab->descs[tab->nr_descs].module); 2238 btf_put(tab->descs[tab->nr_descs].btf); 2239 } 2240 kfree(tab); 2241 } 2242 2243 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2244 { 2245 if (offset) { 2246 if (offset < 0) { 2247 /* In the future, this can be allowed to increase limit 2248 * of fd index into fd_array, interpreted as u16. 2249 */ 2250 verbose(env, "negative offset disallowed for kernel module function call\n"); 2251 return ERR_PTR(-EINVAL); 2252 } 2253 2254 return __find_kfunc_desc_btf(env, offset); 2255 } 2256 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2257 } 2258 2259 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2260 { 2261 const struct btf_type *func, *func_proto; 2262 struct bpf_kfunc_btf_tab *btf_tab; 2263 struct bpf_kfunc_desc_tab *tab; 2264 struct bpf_prog_aux *prog_aux; 2265 struct bpf_kfunc_desc *desc; 2266 const char *func_name; 2267 struct btf *desc_btf; 2268 unsigned long call_imm; 2269 unsigned long addr; 2270 int err; 2271 2272 prog_aux = env->prog->aux; 2273 tab = prog_aux->kfunc_tab; 2274 btf_tab = prog_aux->kfunc_btf_tab; 2275 if (!tab) { 2276 if (!btf_vmlinux) { 2277 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2278 return -ENOTSUPP; 2279 } 2280 2281 if (!env->prog->jit_requested) { 2282 verbose(env, "JIT is required for calling kernel function\n"); 2283 return -ENOTSUPP; 2284 } 2285 2286 if (!bpf_jit_supports_kfunc_call()) { 2287 verbose(env, "JIT does not support calling kernel function\n"); 2288 return -ENOTSUPP; 2289 } 2290 2291 if (!env->prog->gpl_compatible) { 2292 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2293 return -EINVAL; 2294 } 2295 2296 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2297 if (!tab) 2298 return -ENOMEM; 2299 prog_aux->kfunc_tab = tab; 2300 } 2301 2302 /* func_id == 0 is always invalid, but instead of returning an error, be 2303 * conservative and wait until the code elimination pass before returning 2304 * error, so that invalid calls that get pruned out can be in BPF programs 2305 * loaded from userspace. It is also required that offset be untouched 2306 * for such calls. 2307 */ 2308 if (!func_id && !offset) 2309 return 0; 2310 2311 if (!btf_tab && offset) { 2312 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2313 if (!btf_tab) 2314 return -ENOMEM; 2315 prog_aux->kfunc_btf_tab = btf_tab; 2316 } 2317 2318 desc_btf = find_kfunc_desc_btf(env, offset); 2319 if (IS_ERR(desc_btf)) { 2320 verbose(env, "failed to find BTF for kernel function\n"); 2321 return PTR_ERR(desc_btf); 2322 } 2323 2324 if (find_kfunc_desc(env->prog, func_id, offset)) 2325 return 0; 2326 2327 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2328 verbose(env, "too many different kernel function calls\n"); 2329 return -E2BIG; 2330 } 2331 2332 func = btf_type_by_id(desc_btf, func_id); 2333 if (!func || !btf_type_is_func(func)) { 2334 verbose(env, "kernel btf_id %u is not a function\n", 2335 func_id); 2336 return -EINVAL; 2337 } 2338 func_proto = btf_type_by_id(desc_btf, func->type); 2339 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2340 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2341 func_id); 2342 return -EINVAL; 2343 } 2344 2345 func_name = btf_name_by_offset(desc_btf, func->name_off); 2346 addr = kallsyms_lookup_name(func_name); 2347 if (!addr) { 2348 verbose(env, "cannot find address for kernel function %s\n", 2349 func_name); 2350 return -EINVAL; 2351 } 2352 2353 call_imm = BPF_CALL_IMM(addr); 2354 /* Check whether or not the relative offset overflows desc->imm */ 2355 if ((unsigned long)(s32)call_imm != call_imm) { 2356 verbose(env, "address of kernel function %s is out of range\n", 2357 func_name); 2358 return -EINVAL; 2359 } 2360 2361 if (bpf_dev_bound_kfunc_id(func_id)) { 2362 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2363 if (err) 2364 return err; 2365 } 2366 2367 desc = &tab->descs[tab->nr_descs++]; 2368 desc->func_id = func_id; 2369 desc->imm = call_imm; 2370 desc->offset = offset; 2371 err = btf_distill_func_proto(&env->log, desc_btf, 2372 func_proto, func_name, 2373 &desc->func_model); 2374 if (!err) 2375 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2376 kfunc_desc_cmp_by_id_off, NULL); 2377 return err; 2378 } 2379 2380 static int kfunc_desc_cmp_by_imm(const void *a, const void *b) 2381 { 2382 const struct bpf_kfunc_desc *d0 = a; 2383 const struct bpf_kfunc_desc *d1 = b; 2384 2385 if (d0->imm > d1->imm) 2386 return 1; 2387 else if (d0->imm < d1->imm) 2388 return -1; 2389 return 0; 2390 } 2391 2392 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog) 2393 { 2394 struct bpf_kfunc_desc_tab *tab; 2395 2396 tab = prog->aux->kfunc_tab; 2397 if (!tab) 2398 return; 2399 2400 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2401 kfunc_desc_cmp_by_imm, NULL); 2402 } 2403 2404 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2405 { 2406 return !!prog->aux->kfunc_tab; 2407 } 2408 2409 const struct btf_func_model * 2410 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2411 const struct bpf_insn *insn) 2412 { 2413 const struct bpf_kfunc_desc desc = { 2414 .imm = insn->imm, 2415 }; 2416 const struct bpf_kfunc_desc *res; 2417 struct bpf_kfunc_desc_tab *tab; 2418 2419 tab = prog->aux->kfunc_tab; 2420 res = bsearch(&desc, tab->descs, tab->nr_descs, 2421 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm); 2422 2423 return res ? &res->func_model : NULL; 2424 } 2425 2426 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2427 { 2428 struct bpf_subprog_info *subprog = env->subprog_info; 2429 struct bpf_insn *insn = env->prog->insnsi; 2430 int i, ret, insn_cnt = env->prog->len; 2431 2432 /* Add entry function. */ 2433 ret = add_subprog(env, 0); 2434 if (ret) 2435 return ret; 2436 2437 for (i = 0; i < insn_cnt; i++, insn++) { 2438 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2439 !bpf_pseudo_kfunc_call(insn)) 2440 continue; 2441 2442 if (!env->bpf_capable) { 2443 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2444 return -EPERM; 2445 } 2446 2447 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2448 ret = add_subprog(env, i + insn->imm + 1); 2449 else 2450 ret = add_kfunc_call(env, insn->imm, insn->off); 2451 2452 if (ret < 0) 2453 return ret; 2454 } 2455 2456 /* Add a fake 'exit' subprog which could simplify subprog iteration 2457 * logic. 'subprog_cnt' should not be increased. 2458 */ 2459 subprog[env->subprog_cnt].start = insn_cnt; 2460 2461 if (env->log.level & BPF_LOG_LEVEL2) 2462 for (i = 0; i < env->subprog_cnt; i++) 2463 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2464 2465 return 0; 2466 } 2467 2468 static int check_subprogs(struct bpf_verifier_env *env) 2469 { 2470 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2471 struct bpf_subprog_info *subprog = env->subprog_info; 2472 struct bpf_insn *insn = env->prog->insnsi; 2473 int insn_cnt = env->prog->len; 2474 2475 /* now check that all jumps are within the same subprog */ 2476 subprog_start = subprog[cur_subprog].start; 2477 subprog_end = subprog[cur_subprog + 1].start; 2478 for (i = 0; i < insn_cnt; i++) { 2479 u8 code = insn[i].code; 2480 2481 if (code == (BPF_JMP | BPF_CALL) && 2482 insn[i].imm == BPF_FUNC_tail_call && 2483 insn[i].src_reg != BPF_PSEUDO_CALL) 2484 subprog[cur_subprog].has_tail_call = true; 2485 if (BPF_CLASS(code) == BPF_LD && 2486 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2487 subprog[cur_subprog].has_ld_abs = true; 2488 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2489 goto next; 2490 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2491 goto next; 2492 off = i + insn[i].off + 1; 2493 if (off < subprog_start || off >= subprog_end) { 2494 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2495 return -EINVAL; 2496 } 2497 next: 2498 if (i == subprog_end - 1) { 2499 /* to avoid fall-through from one subprog into another 2500 * the last insn of the subprog should be either exit 2501 * or unconditional jump back 2502 */ 2503 if (code != (BPF_JMP | BPF_EXIT) && 2504 code != (BPF_JMP | BPF_JA)) { 2505 verbose(env, "last insn is not an exit or jmp\n"); 2506 return -EINVAL; 2507 } 2508 subprog_start = subprog_end; 2509 cur_subprog++; 2510 if (cur_subprog < env->subprog_cnt) 2511 subprog_end = subprog[cur_subprog + 1].start; 2512 } 2513 } 2514 return 0; 2515 } 2516 2517 /* Parentage chain of this register (or stack slot) should take care of all 2518 * issues like callee-saved registers, stack slot allocation time, etc. 2519 */ 2520 static int mark_reg_read(struct bpf_verifier_env *env, 2521 const struct bpf_reg_state *state, 2522 struct bpf_reg_state *parent, u8 flag) 2523 { 2524 bool writes = parent == state->parent; /* Observe write marks */ 2525 int cnt = 0; 2526 2527 while (parent) { 2528 /* if read wasn't screened by an earlier write ... */ 2529 if (writes && state->live & REG_LIVE_WRITTEN) 2530 break; 2531 if (parent->live & REG_LIVE_DONE) { 2532 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2533 reg_type_str(env, parent->type), 2534 parent->var_off.value, parent->off); 2535 return -EFAULT; 2536 } 2537 /* The first condition is more likely to be true than the 2538 * second, checked it first. 2539 */ 2540 if ((parent->live & REG_LIVE_READ) == flag || 2541 parent->live & REG_LIVE_READ64) 2542 /* The parentage chain never changes and 2543 * this parent was already marked as LIVE_READ. 2544 * There is no need to keep walking the chain again and 2545 * keep re-marking all parents as LIVE_READ. 2546 * This case happens when the same register is read 2547 * multiple times without writes into it in-between. 2548 * Also, if parent has the stronger REG_LIVE_READ64 set, 2549 * then no need to set the weak REG_LIVE_READ32. 2550 */ 2551 break; 2552 /* ... then we depend on parent's value */ 2553 parent->live |= flag; 2554 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 2555 if (flag == REG_LIVE_READ64) 2556 parent->live &= ~REG_LIVE_READ32; 2557 state = parent; 2558 parent = state->parent; 2559 writes = true; 2560 cnt++; 2561 } 2562 2563 if (env->longest_mark_read_walk < cnt) 2564 env->longest_mark_read_walk = cnt; 2565 return 0; 2566 } 2567 2568 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 2569 { 2570 struct bpf_func_state *state = func(env, reg); 2571 int spi, ret; 2572 2573 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 2574 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 2575 * check_kfunc_call. 2576 */ 2577 if (reg->type == CONST_PTR_TO_DYNPTR) 2578 return 0; 2579 spi = dynptr_get_spi(env, reg); 2580 if (spi < 0) 2581 return spi; 2582 /* Caller ensures dynptr is valid and initialized, which means spi is in 2583 * bounds and spi is the first dynptr slot. Simply mark stack slot as 2584 * read. 2585 */ 2586 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 2587 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 2588 if (ret) 2589 return ret; 2590 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 2591 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 2592 } 2593 2594 /* This function is supposed to be used by the following 32-bit optimization 2595 * code only. It returns TRUE if the source or destination register operates 2596 * on 64-bit, otherwise return FALSE. 2597 */ 2598 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 2599 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 2600 { 2601 u8 code, class, op; 2602 2603 code = insn->code; 2604 class = BPF_CLASS(code); 2605 op = BPF_OP(code); 2606 if (class == BPF_JMP) { 2607 /* BPF_EXIT for "main" will reach here. Return TRUE 2608 * conservatively. 2609 */ 2610 if (op == BPF_EXIT) 2611 return true; 2612 if (op == BPF_CALL) { 2613 /* BPF to BPF call will reach here because of marking 2614 * caller saved clobber with DST_OP_NO_MARK for which we 2615 * don't care the register def because they are anyway 2616 * marked as NOT_INIT already. 2617 */ 2618 if (insn->src_reg == BPF_PSEUDO_CALL) 2619 return false; 2620 /* Helper call will reach here because of arg type 2621 * check, conservatively return TRUE. 2622 */ 2623 if (t == SRC_OP) 2624 return true; 2625 2626 return false; 2627 } 2628 } 2629 2630 if (class == BPF_ALU64 || class == BPF_JMP || 2631 /* BPF_END always use BPF_ALU class. */ 2632 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 2633 return true; 2634 2635 if (class == BPF_ALU || class == BPF_JMP32) 2636 return false; 2637 2638 if (class == BPF_LDX) { 2639 if (t != SRC_OP) 2640 return BPF_SIZE(code) == BPF_DW; 2641 /* LDX source must be ptr. */ 2642 return true; 2643 } 2644 2645 if (class == BPF_STX) { 2646 /* BPF_STX (including atomic variants) has multiple source 2647 * operands, one of which is a ptr. Check whether the caller is 2648 * asking about it. 2649 */ 2650 if (t == SRC_OP && reg->type != SCALAR_VALUE) 2651 return true; 2652 return BPF_SIZE(code) == BPF_DW; 2653 } 2654 2655 if (class == BPF_LD) { 2656 u8 mode = BPF_MODE(code); 2657 2658 /* LD_IMM64 */ 2659 if (mode == BPF_IMM) 2660 return true; 2661 2662 /* Both LD_IND and LD_ABS return 32-bit data. */ 2663 if (t != SRC_OP) 2664 return false; 2665 2666 /* Implicit ctx ptr. */ 2667 if (regno == BPF_REG_6) 2668 return true; 2669 2670 /* Explicit source could be any width. */ 2671 return true; 2672 } 2673 2674 if (class == BPF_ST) 2675 /* The only source register for BPF_ST is a ptr. */ 2676 return true; 2677 2678 /* Conservatively return true at default. */ 2679 return true; 2680 } 2681 2682 /* Return the regno defined by the insn, or -1. */ 2683 static int insn_def_regno(const struct bpf_insn *insn) 2684 { 2685 switch (BPF_CLASS(insn->code)) { 2686 case BPF_JMP: 2687 case BPF_JMP32: 2688 case BPF_ST: 2689 return -1; 2690 case BPF_STX: 2691 if (BPF_MODE(insn->code) == BPF_ATOMIC && 2692 (insn->imm & BPF_FETCH)) { 2693 if (insn->imm == BPF_CMPXCHG) 2694 return BPF_REG_0; 2695 else 2696 return insn->src_reg; 2697 } else { 2698 return -1; 2699 } 2700 default: 2701 return insn->dst_reg; 2702 } 2703 } 2704 2705 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 2706 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 2707 { 2708 int dst_reg = insn_def_regno(insn); 2709 2710 if (dst_reg == -1) 2711 return false; 2712 2713 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 2714 } 2715 2716 static void mark_insn_zext(struct bpf_verifier_env *env, 2717 struct bpf_reg_state *reg) 2718 { 2719 s32 def_idx = reg->subreg_def; 2720 2721 if (def_idx == DEF_NOT_SUBREG) 2722 return; 2723 2724 env->insn_aux_data[def_idx - 1].zext_dst = true; 2725 /* The dst will be zero extended, so won't be sub-register anymore. */ 2726 reg->subreg_def = DEF_NOT_SUBREG; 2727 } 2728 2729 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 2730 enum reg_arg_type t) 2731 { 2732 struct bpf_verifier_state *vstate = env->cur_state; 2733 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2734 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 2735 struct bpf_reg_state *reg, *regs = state->regs; 2736 bool rw64; 2737 2738 if (regno >= MAX_BPF_REG) { 2739 verbose(env, "R%d is invalid\n", regno); 2740 return -EINVAL; 2741 } 2742 2743 mark_reg_scratched(env, regno); 2744 2745 reg = ®s[regno]; 2746 rw64 = is_reg64(env, insn, regno, reg, t); 2747 if (t == SRC_OP) { 2748 /* check whether register used as source operand can be read */ 2749 if (reg->type == NOT_INIT) { 2750 verbose(env, "R%d !read_ok\n", regno); 2751 return -EACCES; 2752 } 2753 /* We don't need to worry about FP liveness because it's read-only */ 2754 if (regno == BPF_REG_FP) 2755 return 0; 2756 2757 if (rw64) 2758 mark_insn_zext(env, reg); 2759 2760 return mark_reg_read(env, reg, reg->parent, 2761 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 2762 } else { 2763 /* check whether register used as dest operand can be written to */ 2764 if (regno == BPF_REG_FP) { 2765 verbose(env, "frame pointer is read only\n"); 2766 return -EACCES; 2767 } 2768 reg->live |= REG_LIVE_WRITTEN; 2769 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 2770 if (t == DST_OP) 2771 mark_reg_unknown(env, regs, regno); 2772 } 2773 return 0; 2774 } 2775 2776 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 2777 { 2778 env->insn_aux_data[idx].jmp_point = true; 2779 } 2780 2781 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 2782 { 2783 return env->insn_aux_data[insn_idx].jmp_point; 2784 } 2785 2786 /* for any branch, call, exit record the history of jmps in the given state */ 2787 static int push_jmp_history(struct bpf_verifier_env *env, 2788 struct bpf_verifier_state *cur) 2789 { 2790 u32 cnt = cur->jmp_history_cnt; 2791 struct bpf_idx_pair *p; 2792 size_t alloc_size; 2793 2794 if (!is_jmp_point(env, env->insn_idx)) 2795 return 0; 2796 2797 cnt++; 2798 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 2799 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 2800 if (!p) 2801 return -ENOMEM; 2802 p[cnt - 1].idx = env->insn_idx; 2803 p[cnt - 1].prev_idx = env->prev_insn_idx; 2804 cur->jmp_history = p; 2805 cur->jmp_history_cnt = cnt; 2806 return 0; 2807 } 2808 2809 /* Backtrack one insn at a time. If idx is not at the top of recorded 2810 * history then previous instruction came from straight line execution. 2811 */ 2812 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 2813 u32 *history) 2814 { 2815 u32 cnt = *history; 2816 2817 if (cnt && st->jmp_history[cnt - 1].idx == i) { 2818 i = st->jmp_history[cnt - 1].prev_idx; 2819 (*history)--; 2820 } else { 2821 i--; 2822 } 2823 return i; 2824 } 2825 2826 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 2827 { 2828 const struct btf_type *func; 2829 struct btf *desc_btf; 2830 2831 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 2832 return NULL; 2833 2834 desc_btf = find_kfunc_desc_btf(data, insn->off); 2835 if (IS_ERR(desc_btf)) 2836 return "<error>"; 2837 2838 func = btf_type_by_id(desc_btf, insn->imm); 2839 return btf_name_by_offset(desc_btf, func->name_off); 2840 } 2841 2842 /* For given verifier state backtrack_insn() is called from the last insn to 2843 * the first insn. Its purpose is to compute a bitmask of registers and 2844 * stack slots that needs precision in the parent verifier state. 2845 */ 2846 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 2847 u32 *reg_mask, u64 *stack_mask) 2848 { 2849 const struct bpf_insn_cbs cbs = { 2850 .cb_call = disasm_kfunc_name, 2851 .cb_print = verbose, 2852 .private_data = env, 2853 }; 2854 struct bpf_insn *insn = env->prog->insnsi + idx; 2855 u8 class = BPF_CLASS(insn->code); 2856 u8 opcode = BPF_OP(insn->code); 2857 u8 mode = BPF_MODE(insn->code); 2858 u32 dreg = 1u << insn->dst_reg; 2859 u32 sreg = 1u << insn->src_reg; 2860 u32 spi; 2861 2862 if (insn->code == 0) 2863 return 0; 2864 if (env->log.level & BPF_LOG_LEVEL2) { 2865 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask); 2866 verbose(env, "%d: ", idx); 2867 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 2868 } 2869 2870 if (class == BPF_ALU || class == BPF_ALU64) { 2871 if (!(*reg_mask & dreg)) 2872 return 0; 2873 if (opcode == BPF_MOV) { 2874 if (BPF_SRC(insn->code) == BPF_X) { 2875 /* dreg = sreg 2876 * dreg needs precision after this insn 2877 * sreg needs precision before this insn 2878 */ 2879 *reg_mask &= ~dreg; 2880 *reg_mask |= sreg; 2881 } else { 2882 /* dreg = K 2883 * dreg needs precision after this insn. 2884 * Corresponding register is already marked 2885 * as precise=true in this verifier state. 2886 * No further markings in parent are necessary 2887 */ 2888 *reg_mask &= ~dreg; 2889 } 2890 } else { 2891 if (BPF_SRC(insn->code) == BPF_X) { 2892 /* dreg += sreg 2893 * both dreg and sreg need precision 2894 * before this insn 2895 */ 2896 *reg_mask |= sreg; 2897 } /* else dreg += K 2898 * dreg still needs precision before this insn 2899 */ 2900 } 2901 } else if (class == BPF_LDX) { 2902 if (!(*reg_mask & dreg)) 2903 return 0; 2904 *reg_mask &= ~dreg; 2905 2906 /* scalars can only be spilled into stack w/o losing precision. 2907 * Load from any other memory can be zero extended. 2908 * The desire to keep that precision is already indicated 2909 * by 'precise' mark in corresponding register of this state. 2910 * No further tracking necessary. 2911 */ 2912 if (insn->src_reg != BPF_REG_FP) 2913 return 0; 2914 2915 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 2916 * that [fp - off] slot contains scalar that needs to be 2917 * tracked with precision 2918 */ 2919 spi = (-insn->off - 1) / BPF_REG_SIZE; 2920 if (spi >= 64) { 2921 verbose(env, "BUG spi %d\n", spi); 2922 WARN_ONCE(1, "verifier backtracking bug"); 2923 return -EFAULT; 2924 } 2925 *stack_mask |= 1ull << spi; 2926 } else if (class == BPF_STX || class == BPF_ST) { 2927 if (*reg_mask & dreg) 2928 /* stx & st shouldn't be using _scalar_ dst_reg 2929 * to access memory. It means backtracking 2930 * encountered a case of pointer subtraction. 2931 */ 2932 return -ENOTSUPP; 2933 /* scalars can only be spilled into stack */ 2934 if (insn->dst_reg != BPF_REG_FP) 2935 return 0; 2936 spi = (-insn->off - 1) / BPF_REG_SIZE; 2937 if (spi >= 64) { 2938 verbose(env, "BUG spi %d\n", spi); 2939 WARN_ONCE(1, "verifier backtracking bug"); 2940 return -EFAULT; 2941 } 2942 if (!(*stack_mask & (1ull << spi))) 2943 return 0; 2944 *stack_mask &= ~(1ull << spi); 2945 if (class == BPF_STX) 2946 *reg_mask |= sreg; 2947 } else if (class == BPF_JMP || class == BPF_JMP32) { 2948 if (opcode == BPF_CALL) { 2949 if (insn->src_reg == BPF_PSEUDO_CALL) 2950 return -ENOTSUPP; 2951 /* BPF helpers that invoke callback subprogs are 2952 * equivalent to BPF_PSEUDO_CALL above 2953 */ 2954 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm)) 2955 return -ENOTSUPP; 2956 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 2957 * catch this error later. Make backtracking conservative 2958 * with ENOTSUPP. 2959 */ 2960 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 2961 return -ENOTSUPP; 2962 /* regular helper call sets R0 */ 2963 *reg_mask &= ~1; 2964 if (*reg_mask & 0x3f) { 2965 /* if backtracing was looking for registers R1-R5 2966 * they should have been found already. 2967 */ 2968 verbose(env, "BUG regs %x\n", *reg_mask); 2969 WARN_ONCE(1, "verifier backtracking bug"); 2970 return -EFAULT; 2971 } 2972 } else if (opcode == BPF_EXIT) { 2973 return -ENOTSUPP; 2974 } 2975 } else if (class == BPF_LD) { 2976 if (!(*reg_mask & dreg)) 2977 return 0; 2978 *reg_mask &= ~dreg; 2979 /* It's ld_imm64 or ld_abs or ld_ind. 2980 * For ld_imm64 no further tracking of precision 2981 * into parent is necessary 2982 */ 2983 if (mode == BPF_IND || mode == BPF_ABS) 2984 /* to be analyzed */ 2985 return -ENOTSUPP; 2986 } 2987 return 0; 2988 } 2989 2990 /* the scalar precision tracking algorithm: 2991 * . at the start all registers have precise=false. 2992 * . scalar ranges are tracked as normal through alu and jmp insns. 2993 * . once precise value of the scalar register is used in: 2994 * . ptr + scalar alu 2995 * . if (scalar cond K|scalar) 2996 * . helper_call(.., scalar, ...) where ARG_CONST is expected 2997 * backtrack through the verifier states and mark all registers and 2998 * stack slots with spilled constants that these scalar regisers 2999 * should be precise. 3000 * . during state pruning two registers (or spilled stack slots) 3001 * are equivalent if both are not precise. 3002 * 3003 * Note the verifier cannot simply walk register parentage chain, 3004 * since many different registers and stack slots could have been 3005 * used to compute single precise scalar. 3006 * 3007 * The approach of starting with precise=true for all registers and then 3008 * backtrack to mark a register as not precise when the verifier detects 3009 * that program doesn't care about specific value (e.g., when helper 3010 * takes register as ARG_ANYTHING parameter) is not safe. 3011 * 3012 * It's ok to walk single parentage chain of the verifier states. 3013 * It's possible that this backtracking will go all the way till 1st insn. 3014 * All other branches will be explored for needing precision later. 3015 * 3016 * The backtracking needs to deal with cases like: 3017 * 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) 3018 * r9 -= r8 3019 * r5 = r9 3020 * if r5 > 0x79f goto pc+7 3021 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 3022 * r5 += 1 3023 * ... 3024 * call bpf_perf_event_output#25 3025 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 3026 * 3027 * and this case: 3028 * r6 = 1 3029 * call foo // uses callee's r6 inside to compute r0 3030 * r0 += r6 3031 * if r0 == 0 goto 3032 * 3033 * to track above reg_mask/stack_mask needs to be independent for each frame. 3034 * 3035 * Also if parent's curframe > frame where backtracking started, 3036 * the verifier need to mark registers in both frames, otherwise callees 3037 * may incorrectly prune callers. This is similar to 3038 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3039 * 3040 * For now backtracking falls back into conservative marking. 3041 */ 3042 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3043 struct bpf_verifier_state *st) 3044 { 3045 struct bpf_func_state *func; 3046 struct bpf_reg_state *reg; 3047 int i, j; 3048 3049 /* big hammer: mark all scalars precise in this path. 3050 * pop_stack may still get !precise scalars. 3051 * We also skip current state and go straight to first parent state, 3052 * because precision markings in current non-checkpointed state are 3053 * not needed. See why in the comment in __mark_chain_precision below. 3054 */ 3055 for (st = st->parent; st; st = st->parent) { 3056 for (i = 0; i <= st->curframe; i++) { 3057 func = st->frame[i]; 3058 for (j = 0; j < BPF_REG_FP; j++) { 3059 reg = &func->regs[j]; 3060 if (reg->type != SCALAR_VALUE) 3061 continue; 3062 reg->precise = true; 3063 } 3064 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3065 if (!is_spilled_reg(&func->stack[j])) 3066 continue; 3067 reg = &func->stack[j].spilled_ptr; 3068 if (reg->type != SCALAR_VALUE) 3069 continue; 3070 reg->precise = true; 3071 } 3072 } 3073 } 3074 } 3075 3076 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3077 { 3078 struct bpf_func_state *func; 3079 struct bpf_reg_state *reg; 3080 int i, j; 3081 3082 for (i = 0; i <= st->curframe; i++) { 3083 func = st->frame[i]; 3084 for (j = 0; j < BPF_REG_FP; j++) { 3085 reg = &func->regs[j]; 3086 if (reg->type != SCALAR_VALUE) 3087 continue; 3088 reg->precise = false; 3089 } 3090 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3091 if (!is_spilled_reg(&func->stack[j])) 3092 continue; 3093 reg = &func->stack[j].spilled_ptr; 3094 if (reg->type != SCALAR_VALUE) 3095 continue; 3096 reg->precise = false; 3097 } 3098 } 3099 } 3100 3101 /* 3102 * __mark_chain_precision() backtracks BPF program instruction sequence and 3103 * chain of verifier states making sure that register *regno* (if regno >= 0) 3104 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 3105 * SCALARS, as well as any other registers and slots that contribute to 3106 * a tracked state of given registers/stack slots, depending on specific BPF 3107 * assembly instructions (see backtrack_insns() for exact instruction handling 3108 * logic). This backtracking relies on recorded jmp_history and is able to 3109 * traverse entire chain of parent states. This process ends only when all the 3110 * necessary registers/slots and their transitive dependencies are marked as 3111 * precise. 3112 * 3113 * One important and subtle aspect is that precise marks *do not matter* in 3114 * the currently verified state (current state). It is important to understand 3115 * why this is the case. 3116 * 3117 * First, note that current state is the state that is not yet "checkpointed", 3118 * i.e., it is not yet put into env->explored_states, and it has no children 3119 * states as well. It's ephemeral, and can end up either a) being discarded if 3120 * compatible explored state is found at some point or BPF_EXIT instruction is 3121 * reached or b) checkpointed and put into env->explored_states, branching out 3122 * into one or more children states. 3123 * 3124 * In the former case, precise markings in current state are completely 3125 * ignored by state comparison code (see regsafe() for details). Only 3126 * checkpointed ("old") state precise markings are important, and if old 3127 * state's register/slot is precise, regsafe() assumes current state's 3128 * register/slot as precise and checks value ranges exactly and precisely. If 3129 * states turn out to be compatible, current state's necessary precise 3130 * markings and any required parent states' precise markings are enforced 3131 * after the fact with propagate_precision() logic, after the fact. But it's 3132 * important to realize that in this case, even after marking current state 3133 * registers/slots as precise, we immediately discard current state. So what 3134 * actually matters is any of the precise markings propagated into current 3135 * state's parent states, which are always checkpointed (due to b) case above). 3136 * As such, for scenario a) it doesn't matter if current state has precise 3137 * markings set or not. 3138 * 3139 * Now, for the scenario b), checkpointing and forking into child(ren) 3140 * state(s). Note that before current state gets to checkpointing step, any 3141 * processed instruction always assumes precise SCALAR register/slot 3142 * knowledge: if precise value or range is useful to prune jump branch, BPF 3143 * verifier takes this opportunity enthusiastically. Similarly, when 3144 * register's value is used to calculate offset or memory address, exact 3145 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 3146 * what we mentioned above about state comparison ignoring precise markings 3147 * during state comparison, BPF verifier ignores and also assumes precise 3148 * markings *at will* during instruction verification process. But as verifier 3149 * assumes precision, it also propagates any precision dependencies across 3150 * parent states, which are not yet finalized, so can be further restricted 3151 * based on new knowledge gained from restrictions enforced by their children 3152 * states. This is so that once those parent states are finalized, i.e., when 3153 * they have no more active children state, state comparison logic in 3154 * is_state_visited() would enforce strict and precise SCALAR ranges, if 3155 * required for correctness. 3156 * 3157 * To build a bit more intuition, note also that once a state is checkpointed, 3158 * the path we took to get to that state is not important. This is crucial 3159 * property for state pruning. When state is checkpointed and finalized at 3160 * some instruction index, it can be correctly and safely used to "short 3161 * circuit" any *compatible* state that reaches exactly the same instruction 3162 * index. I.e., if we jumped to that instruction from a completely different 3163 * code path than original finalized state was derived from, it doesn't 3164 * matter, current state can be discarded because from that instruction 3165 * forward having a compatible state will ensure we will safely reach the 3166 * exit. States describe preconditions for further exploration, but completely 3167 * forget the history of how we got here. 3168 * 3169 * This also means that even if we needed precise SCALAR range to get to 3170 * finalized state, but from that point forward *that same* SCALAR register is 3171 * never used in a precise context (i.e., it's precise value is not needed for 3172 * correctness), it's correct and safe to mark such register as "imprecise" 3173 * (i.e., precise marking set to false). This is what we rely on when we do 3174 * not set precise marking in current state. If no child state requires 3175 * precision for any given SCALAR register, it's safe to dictate that it can 3176 * be imprecise. If any child state does require this register to be precise, 3177 * we'll mark it precise later retroactively during precise markings 3178 * propagation from child state to parent states. 3179 * 3180 * Skipping precise marking setting in current state is a mild version of 3181 * relying on the above observation. But we can utilize this property even 3182 * more aggressively by proactively forgetting any precise marking in the 3183 * current state (which we inherited from the parent state), right before we 3184 * checkpoint it and branch off into new child state. This is done by 3185 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 3186 * finalized states which help in short circuiting more future states. 3187 */ 3188 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno, 3189 int spi) 3190 { 3191 struct bpf_verifier_state *st = env->cur_state; 3192 int first_idx = st->first_insn_idx; 3193 int last_idx = env->insn_idx; 3194 struct bpf_func_state *func; 3195 struct bpf_reg_state *reg; 3196 u32 reg_mask = regno >= 0 ? 1u << regno : 0; 3197 u64 stack_mask = spi >= 0 ? 1ull << spi : 0; 3198 bool skip_first = true; 3199 bool new_marks = false; 3200 int i, err; 3201 3202 if (!env->bpf_capable) 3203 return 0; 3204 3205 /* Do sanity checks against current state of register and/or stack 3206 * slot, but don't set precise flag in current state, as precision 3207 * tracking in the current state is unnecessary. 3208 */ 3209 func = st->frame[frame]; 3210 if (regno >= 0) { 3211 reg = &func->regs[regno]; 3212 if (reg->type != SCALAR_VALUE) { 3213 WARN_ONCE(1, "backtracing misuse"); 3214 return -EFAULT; 3215 } 3216 new_marks = true; 3217 } 3218 3219 while (spi >= 0) { 3220 if (!is_spilled_reg(&func->stack[spi])) { 3221 stack_mask = 0; 3222 break; 3223 } 3224 reg = &func->stack[spi].spilled_ptr; 3225 if (reg->type != SCALAR_VALUE) { 3226 stack_mask = 0; 3227 break; 3228 } 3229 new_marks = true; 3230 break; 3231 } 3232 3233 if (!new_marks) 3234 return 0; 3235 if (!reg_mask && !stack_mask) 3236 return 0; 3237 3238 for (;;) { 3239 DECLARE_BITMAP(mask, 64); 3240 u32 history = st->jmp_history_cnt; 3241 3242 if (env->log.level & BPF_LOG_LEVEL2) 3243 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx); 3244 3245 if (last_idx < 0) { 3246 /* we are at the entry into subprog, which 3247 * is expected for global funcs, but only if 3248 * requested precise registers are R1-R5 3249 * (which are global func's input arguments) 3250 */ 3251 if (st->curframe == 0 && 3252 st->frame[0]->subprogno > 0 && 3253 st->frame[0]->callsite == BPF_MAIN_FUNC && 3254 stack_mask == 0 && (reg_mask & ~0x3e) == 0) { 3255 bitmap_from_u64(mask, reg_mask); 3256 for_each_set_bit(i, mask, 32) { 3257 reg = &st->frame[0]->regs[i]; 3258 if (reg->type != SCALAR_VALUE) { 3259 reg_mask &= ~(1u << i); 3260 continue; 3261 } 3262 reg->precise = true; 3263 } 3264 return 0; 3265 } 3266 3267 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n", 3268 st->frame[0]->subprogno, reg_mask, stack_mask); 3269 WARN_ONCE(1, "verifier backtracking bug"); 3270 return -EFAULT; 3271 } 3272 3273 for (i = last_idx;;) { 3274 if (skip_first) { 3275 err = 0; 3276 skip_first = false; 3277 } else { 3278 err = backtrack_insn(env, i, ®_mask, &stack_mask); 3279 } 3280 if (err == -ENOTSUPP) { 3281 mark_all_scalars_precise(env, st); 3282 return 0; 3283 } else if (err) { 3284 return err; 3285 } 3286 if (!reg_mask && !stack_mask) 3287 /* Found assignment(s) into tracked register in this state. 3288 * Since this state is already marked, just return. 3289 * Nothing to be tracked further in the parent state. 3290 */ 3291 return 0; 3292 if (i == first_idx) 3293 break; 3294 i = get_prev_insn_idx(st, i, &history); 3295 if (i >= env->prog->len) { 3296 /* This can happen if backtracking reached insn 0 3297 * and there are still reg_mask or stack_mask 3298 * to backtrack. 3299 * It means the backtracking missed the spot where 3300 * particular register was initialized with a constant. 3301 */ 3302 verbose(env, "BUG backtracking idx %d\n", i); 3303 WARN_ONCE(1, "verifier backtracking bug"); 3304 return -EFAULT; 3305 } 3306 } 3307 st = st->parent; 3308 if (!st) 3309 break; 3310 3311 new_marks = false; 3312 func = st->frame[frame]; 3313 bitmap_from_u64(mask, reg_mask); 3314 for_each_set_bit(i, mask, 32) { 3315 reg = &func->regs[i]; 3316 if (reg->type != SCALAR_VALUE) { 3317 reg_mask &= ~(1u << i); 3318 continue; 3319 } 3320 if (!reg->precise) 3321 new_marks = true; 3322 reg->precise = true; 3323 } 3324 3325 bitmap_from_u64(mask, stack_mask); 3326 for_each_set_bit(i, mask, 64) { 3327 if (i >= func->allocated_stack / BPF_REG_SIZE) { 3328 /* the sequence of instructions: 3329 * 2: (bf) r3 = r10 3330 * 3: (7b) *(u64 *)(r3 -8) = r0 3331 * 4: (79) r4 = *(u64 *)(r10 -8) 3332 * doesn't contain jmps. It's backtracked 3333 * as a single block. 3334 * During backtracking insn 3 is not recognized as 3335 * stack access, so at the end of backtracking 3336 * stack slot fp-8 is still marked in stack_mask. 3337 * However the parent state may not have accessed 3338 * fp-8 and it's "unallocated" stack space. 3339 * In such case fallback to conservative. 3340 */ 3341 mark_all_scalars_precise(env, st); 3342 return 0; 3343 } 3344 3345 if (!is_spilled_reg(&func->stack[i])) { 3346 stack_mask &= ~(1ull << i); 3347 continue; 3348 } 3349 reg = &func->stack[i].spilled_ptr; 3350 if (reg->type != SCALAR_VALUE) { 3351 stack_mask &= ~(1ull << i); 3352 continue; 3353 } 3354 if (!reg->precise) 3355 new_marks = true; 3356 reg->precise = true; 3357 } 3358 if (env->log.level & BPF_LOG_LEVEL2) { 3359 verbose(env, "parent %s regs=%x stack=%llx marks:", 3360 new_marks ? "didn't have" : "already had", 3361 reg_mask, stack_mask); 3362 print_verifier_state(env, func, true); 3363 } 3364 3365 if (!reg_mask && !stack_mask) 3366 break; 3367 if (!new_marks) 3368 break; 3369 3370 last_idx = st->last_insn_idx; 3371 first_idx = st->first_insn_idx; 3372 } 3373 return 0; 3374 } 3375 3376 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3377 { 3378 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1); 3379 } 3380 3381 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno) 3382 { 3383 return __mark_chain_precision(env, frame, regno, -1); 3384 } 3385 3386 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi) 3387 { 3388 return __mark_chain_precision(env, frame, -1, spi); 3389 } 3390 3391 static bool is_spillable_regtype(enum bpf_reg_type type) 3392 { 3393 switch (base_type(type)) { 3394 case PTR_TO_MAP_VALUE: 3395 case PTR_TO_STACK: 3396 case PTR_TO_CTX: 3397 case PTR_TO_PACKET: 3398 case PTR_TO_PACKET_META: 3399 case PTR_TO_PACKET_END: 3400 case PTR_TO_FLOW_KEYS: 3401 case CONST_PTR_TO_MAP: 3402 case PTR_TO_SOCKET: 3403 case PTR_TO_SOCK_COMMON: 3404 case PTR_TO_TCP_SOCK: 3405 case PTR_TO_XDP_SOCK: 3406 case PTR_TO_BTF_ID: 3407 case PTR_TO_BUF: 3408 case PTR_TO_MEM: 3409 case PTR_TO_FUNC: 3410 case PTR_TO_MAP_KEY: 3411 return true; 3412 default: 3413 return false; 3414 } 3415 } 3416 3417 /* Does this register contain a constant zero? */ 3418 static bool register_is_null(struct bpf_reg_state *reg) 3419 { 3420 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 3421 } 3422 3423 static bool register_is_const(struct bpf_reg_state *reg) 3424 { 3425 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 3426 } 3427 3428 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 3429 { 3430 return tnum_is_unknown(reg->var_off) && 3431 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 3432 reg->umin_value == 0 && reg->umax_value == U64_MAX && 3433 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 3434 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 3435 } 3436 3437 static bool register_is_bounded(struct bpf_reg_state *reg) 3438 { 3439 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 3440 } 3441 3442 static bool __is_pointer_value(bool allow_ptr_leaks, 3443 const struct bpf_reg_state *reg) 3444 { 3445 if (allow_ptr_leaks) 3446 return false; 3447 3448 return reg->type != SCALAR_VALUE; 3449 } 3450 3451 /* Copy src state preserving dst->parent and dst->live fields */ 3452 static void copy_register_state(struct bpf_reg_state *dst, const struct bpf_reg_state *src) 3453 { 3454 struct bpf_reg_state *parent = dst->parent; 3455 enum bpf_reg_liveness live = dst->live; 3456 3457 *dst = *src; 3458 dst->parent = parent; 3459 dst->live = live; 3460 } 3461 3462 static void save_register_state(struct bpf_func_state *state, 3463 int spi, struct bpf_reg_state *reg, 3464 int size) 3465 { 3466 int i; 3467 3468 copy_register_state(&state->stack[spi].spilled_ptr, reg); 3469 if (size == BPF_REG_SIZE) 3470 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 3471 3472 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3473 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3474 3475 /* size < 8 bytes spill */ 3476 for (; i; i--) 3477 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 3478 } 3479 3480 static bool is_bpf_st_mem(struct bpf_insn *insn) 3481 { 3482 return BPF_CLASS(insn->code) == BPF_ST && BPF_MODE(insn->code) == BPF_MEM; 3483 } 3484 3485 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3486 * stack boundary and alignment are checked in check_mem_access() 3487 */ 3488 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3489 /* stack frame we're writing to */ 3490 struct bpf_func_state *state, 3491 int off, int size, int value_regno, 3492 int insn_idx) 3493 { 3494 struct bpf_func_state *cur; /* state of the current function */ 3495 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3496 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3497 struct bpf_reg_state *reg = NULL; 3498 u32 dst_reg = insn->dst_reg; 3499 3500 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 3501 if (err) 3502 return err; 3503 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3504 * so it's aligned access and [off, off + size) are within stack limits 3505 */ 3506 if (!env->allow_ptr_leaks && 3507 state->stack[spi].slot_type[0] == STACK_SPILL && 3508 size != BPF_REG_SIZE) { 3509 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3510 return -EACCES; 3511 } 3512 3513 cur = env->cur_state->frame[env->cur_state->curframe]; 3514 if (value_regno >= 0) 3515 reg = &cur->regs[value_regno]; 3516 if (!env->bypass_spec_v4) { 3517 bool sanitize = reg && is_spillable_regtype(reg->type); 3518 3519 for (i = 0; i < size; i++) { 3520 u8 type = state->stack[spi].slot_type[i]; 3521 3522 if (type != STACK_MISC && type != STACK_ZERO) { 3523 sanitize = true; 3524 break; 3525 } 3526 } 3527 3528 if (sanitize) 3529 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 3530 } 3531 3532 err = destroy_if_dynptr_stack_slot(env, state, spi); 3533 if (err) 3534 return err; 3535 3536 mark_stack_slot_scratched(env, spi); 3537 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 3538 !register_is_null(reg) && env->bpf_capable) { 3539 if (dst_reg != BPF_REG_FP) { 3540 /* The backtracking logic can only recognize explicit 3541 * stack slot address like [fp - 8]. Other spill of 3542 * scalar via different register has to be conservative. 3543 * Backtrack from here and mark all registers as precise 3544 * that contributed into 'reg' being a constant. 3545 */ 3546 err = mark_chain_precision(env, value_regno); 3547 if (err) 3548 return err; 3549 } 3550 save_register_state(state, spi, reg, size); 3551 } else if (!reg && !(off % BPF_REG_SIZE) && is_bpf_st_mem(insn) && 3552 insn->imm != 0 && env->bpf_capable) { 3553 struct bpf_reg_state fake_reg = {}; 3554 3555 __mark_reg_known(&fake_reg, (u32)insn->imm); 3556 fake_reg.type = SCALAR_VALUE; 3557 save_register_state(state, spi, &fake_reg, size); 3558 } else if (reg && is_spillable_regtype(reg->type)) { 3559 /* register containing pointer is being spilled into stack */ 3560 if (size != BPF_REG_SIZE) { 3561 verbose_linfo(env, insn_idx, "; "); 3562 verbose(env, "invalid size of register spill\n"); 3563 return -EACCES; 3564 } 3565 if (state != cur && reg->type == PTR_TO_STACK) { 3566 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3567 return -EINVAL; 3568 } 3569 save_register_state(state, spi, reg, size); 3570 } else { 3571 u8 type = STACK_MISC; 3572 3573 /* regular write of data into stack destroys any spilled ptr */ 3574 state->stack[spi].spilled_ptr.type = NOT_INIT; 3575 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */ 3576 if (is_spilled_reg(&state->stack[spi])) 3577 for (i = 0; i < BPF_REG_SIZE; i++) 3578 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3579 3580 /* only mark the slot as written if all 8 bytes were written 3581 * otherwise read propagation may incorrectly stop too soon 3582 * when stack slots are partially written. 3583 * This heuristic means that read propagation will be 3584 * conservative, since it will add reg_live_read marks 3585 * to stack slots all the way to first state when programs 3586 * writes+reads less than 8 bytes 3587 */ 3588 if (size == BPF_REG_SIZE) 3589 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 3590 3591 /* when we zero initialize stack slots mark them as such */ 3592 if ((reg && register_is_null(reg)) || 3593 (!reg && is_bpf_st_mem(insn) && insn->imm == 0)) { 3594 /* backtracking doesn't work for STACK_ZERO yet. */ 3595 err = mark_chain_precision(env, value_regno); 3596 if (err) 3597 return err; 3598 type = STACK_ZERO; 3599 } 3600 3601 /* Mark slots affected by this stack write. */ 3602 for (i = 0; i < size; i++) 3603 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 3604 type; 3605 } 3606 return 0; 3607 } 3608 3609 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 3610 * known to contain a variable offset. 3611 * This function checks whether the write is permitted and conservatively 3612 * tracks the effects of the write, considering that each stack slot in the 3613 * dynamic range is potentially written to. 3614 * 3615 * 'off' includes 'regno->off'. 3616 * 'value_regno' can be -1, meaning that an unknown value is being written to 3617 * the stack. 3618 * 3619 * Spilled pointers in range are not marked as written because we don't know 3620 * what's going to be actually written. This means that read propagation for 3621 * future reads cannot be terminated by this write. 3622 * 3623 * For privileged programs, uninitialized stack slots are considered 3624 * initialized by this write (even though we don't know exactly what offsets 3625 * are going to be written to). The idea is that we don't want the verifier to 3626 * reject future reads that access slots written to through variable offsets. 3627 */ 3628 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3629 /* func where register points to */ 3630 struct bpf_func_state *state, 3631 int ptr_regno, int off, int size, 3632 int value_regno, int insn_idx) 3633 { 3634 struct bpf_func_state *cur; /* state of the current function */ 3635 int min_off, max_off; 3636 int i, err; 3637 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 3638 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 3639 bool writing_zero = false; 3640 /* set if the fact that we're writing a zero is used to let any 3641 * stack slots remain STACK_ZERO 3642 */ 3643 bool zero_used = false; 3644 3645 cur = env->cur_state->frame[env->cur_state->curframe]; 3646 ptr_reg = &cur->regs[ptr_regno]; 3647 min_off = ptr_reg->smin_value + off; 3648 max_off = ptr_reg->smax_value + off + size; 3649 if (value_regno >= 0) 3650 value_reg = &cur->regs[value_regno]; 3651 if ((value_reg && register_is_null(value_reg)) || 3652 (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0)) 3653 writing_zero = true; 3654 3655 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 3656 if (err) 3657 return err; 3658 3659 for (i = min_off; i < max_off; i++) { 3660 int spi; 3661 3662 spi = __get_spi(i); 3663 err = destroy_if_dynptr_stack_slot(env, state, spi); 3664 if (err) 3665 return err; 3666 } 3667 3668 /* Variable offset writes destroy any spilled pointers in range. */ 3669 for (i = min_off; i < max_off; i++) { 3670 u8 new_type, *stype; 3671 int slot, spi; 3672 3673 slot = -i - 1; 3674 spi = slot / BPF_REG_SIZE; 3675 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3676 mark_stack_slot_scratched(env, spi); 3677 3678 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 3679 /* Reject the write if range we may write to has not 3680 * been initialized beforehand. If we didn't reject 3681 * here, the ptr status would be erased below (even 3682 * though not all slots are actually overwritten), 3683 * possibly opening the door to leaks. 3684 * 3685 * We do however catch STACK_INVALID case below, and 3686 * only allow reading possibly uninitialized memory 3687 * later for CAP_PERFMON, as the write may not happen to 3688 * that slot. 3689 */ 3690 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3691 insn_idx, i); 3692 return -EINVAL; 3693 } 3694 3695 /* Erase all spilled pointers. */ 3696 state->stack[spi].spilled_ptr.type = NOT_INIT; 3697 3698 /* Update the slot type. */ 3699 new_type = STACK_MISC; 3700 if (writing_zero && *stype == STACK_ZERO) { 3701 new_type = STACK_ZERO; 3702 zero_used = true; 3703 } 3704 /* If the slot is STACK_INVALID, we check whether it's OK to 3705 * pretend that it will be initialized by this write. The slot 3706 * might not actually be written to, and so if we mark it as 3707 * initialized future reads might leak uninitialized memory. 3708 * For privileged programs, we will accept such reads to slots 3709 * that may or may not be written because, if we're reject 3710 * them, the error would be too confusing. 3711 */ 3712 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 3713 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3714 insn_idx, i); 3715 return -EINVAL; 3716 } 3717 *stype = new_type; 3718 } 3719 if (zero_used) { 3720 /* backtracking doesn't work for STACK_ZERO yet. */ 3721 err = mark_chain_precision(env, value_regno); 3722 if (err) 3723 return err; 3724 } 3725 return 0; 3726 } 3727 3728 /* When register 'dst_regno' is assigned some values from stack[min_off, 3729 * max_off), we set the register's type according to the types of the 3730 * respective stack slots. If all the stack values are known to be zeros, then 3731 * so is the destination reg. Otherwise, the register is considered to be 3732 * SCALAR. This function does not deal with register filling; the caller must 3733 * ensure that all spilled registers in the stack range have been marked as 3734 * read. 3735 */ 3736 static void mark_reg_stack_read(struct bpf_verifier_env *env, 3737 /* func where src register points to */ 3738 struct bpf_func_state *ptr_state, 3739 int min_off, int max_off, int dst_regno) 3740 { 3741 struct bpf_verifier_state *vstate = env->cur_state; 3742 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3743 int i, slot, spi; 3744 u8 *stype; 3745 int zeros = 0; 3746 3747 for (i = min_off; i < max_off; i++) { 3748 slot = -i - 1; 3749 spi = slot / BPF_REG_SIZE; 3750 stype = ptr_state->stack[spi].slot_type; 3751 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 3752 break; 3753 zeros++; 3754 } 3755 if (zeros == max_off - min_off) { 3756 /* any access_size read into register is zero extended, 3757 * so the whole register == const_zero 3758 */ 3759 __mark_reg_const_zero(&state->regs[dst_regno]); 3760 /* backtracking doesn't support STACK_ZERO yet, 3761 * so mark it precise here, so that later 3762 * backtracking can stop here. 3763 * Backtracking may not need this if this register 3764 * doesn't participate in pointer adjustment. 3765 * Forward propagation of precise flag is not 3766 * necessary either. This mark is only to stop 3767 * backtracking. Any register that contributed 3768 * to const 0 was marked precise before spill. 3769 */ 3770 state->regs[dst_regno].precise = true; 3771 } else { 3772 /* have read misc data from the stack */ 3773 mark_reg_unknown(env, state->regs, dst_regno); 3774 } 3775 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3776 } 3777 3778 /* Read the stack at 'off' and put the results into the register indicated by 3779 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3780 * spilled reg. 3781 * 3782 * 'dst_regno' can be -1, meaning that the read value is not going to a 3783 * register. 3784 * 3785 * The access is assumed to be within the current stack bounds. 3786 */ 3787 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3788 /* func where src register points to */ 3789 struct bpf_func_state *reg_state, 3790 int off, int size, int dst_regno) 3791 { 3792 struct bpf_verifier_state *vstate = env->cur_state; 3793 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3794 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3795 struct bpf_reg_state *reg; 3796 u8 *stype, type; 3797 3798 stype = reg_state->stack[spi].slot_type; 3799 reg = ®_state->stack[spi].spilled_ptr; 3800 3801 if (is_spilled_reg(®_state->stack[spi])) { 3802 u8 spill_size = 1; 3803 3804 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3805 spill_size++; 3806 3807 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3808 if (reg->type != SCALAR_VALUE) { 3809 verbose_linfo(env, env->insn_idx, "; "); 3810 verbose(env, "invalid size of register fill\n"); 3811 return -EACCES; 3812 } 3813 3814 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3815 if (dst_regno < 0) 3816 return 0; 3817 3818 if (!(off % BPF_REG_SIZE) && size == spill_size) { 3819 /* The earlier check_reg_arg() has decided the 3820 * subreg_def for this insn. Save it first. 3821 */ 3822 s32 subreg_def = state->regs[dst_regno].subreg_def; 3823 3824 copy_register_state(&state->regs[dst_regno], reg); 3825 state->regs[dst_regno].subreg_def = subreg_def; 3826 } else { 3827 for (i = 0; i < size; i++) { 3828 type = stype[(slot - i) % BPF_REG_SIZE]; 3829 if (type == STACK_SPILL) 3830 continue; 3831 if (type == STACK_MISC) 3832 continue; 3833 if (type == STACK_INVALID && env->allow_uninit_stack) 3834 continue; 3835 verbose(env, "invalid read from stack off %d+%d size %d\n", 3836 off, i, size); 3837 return -EACCES; 3838 } 3839 mark_reg_unknown(env, state->regs, dst_regno); 3840 } 3841 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3842 return 0; 3843 } 3844 3845 if (dst_regno >= 0) { 3846 /* restore register state from stack */ 3847 copy_register_state(&state->regs[dst_regno], reg); 3848 /* mark reg as written since spilled pointer state likely 3849 * has its liveness marks cleared by is_state_visited() 3850 * which resets stack/reg liveness for state transitions 3851 */ 3852 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3853 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3854 /* If dst_regno==-1, the caller is asking us whether 3855 * it is acceptable to use this value as a SCALAR_VALUE 3856 * (e.g. for XADD). 3857 * We must not allow unprivileged callers to do that 3858 * with spilled pointers. 3859 */ 3860 verbose(env, "leaking pointer from stack off %d\n", 3861 off); 3862 return -EACCES; 3863 } 3864 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3865 } else { 3866 for (i = 0; i < size; i++) { 3867 type = stype[(slot - i) % BPF_REG_SIZE]; 3868 if (type == STACK_MISC) 3869 continue; 3870 if (type == STACK_ZERO) 3871 continue; 3872 if (type == STACK_INVALID && env->allow_uninit_stack) 3873 continue; 3874 verbose(env, "invalid read from stack off %d+%d size %d\n", 3875 off, i, size); 3876 return -EACCES; 3877 } 3878 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3879 if (dst_regno >= 0) 3880 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3881 } 3882 return 0; 3883 } 3884 3885 enum bpf_access_src { 3886 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3887 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3888 }; 3889 3890 static int check_stack_range_initialized(struct bpf_verifier_env *env, 3891 int regno, int off, int access_size, 3892 bool zero_size_allowed, 3893 enum bpf_access_src type, 3894 struct bpf_call_arg_meta *meta); 3895 3896 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3897 { 3898 return cur_regs(env) + regno; 3899 } 3900 3901 /* Read the stack at 'ptr_regno + off' and put the result into the register 3902 * 'dst_regno'. 3903 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 3904 * but not its variable offset. 3905 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3906 * 3907 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3908 * filling registers (i.e. reads of spilled register cannot be detected when 3909 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3910 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 3911 * offset; for a fixed offset check_stack_read_fixed_off should be used 3912 * instead. 3913 */ 3914 static int check_stack_read_var_off(struct bpf_verifier_env *env, 3915 int ptr_regno, int off, int size, int dst_regno) 3916 { 3917 /* The state of the source register. */ 3918 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3919 struct bpf_func_state *ptr_state = func(env, reg); 3920 int err; 3921 int min_off, max_off; 3922 3923 /* Note that we pass a NULL meta, so raw access will not be permitted. 3924 */ 3925 err = check_stack_range_initialized(env, ptr_regno, off, size, 3926 false, ACCESS_DIRECT, NULL); 3927 if (err) 3928 return err; 3929 3930 min_off = reg->smin_value + off; 3931 max_off = reg->smax_value + off; 3932 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 3933 return 0; 3934 } 3935 3936 /* check_stack_read dispatches to check_stack_read_fixed_off or 3937 * check_stack_read_var_off. 3938 * 3939 * The caller must ensure that the offset falls within the allocated stack 3940 * bounds. 3941 * 3942 * 'dst_regno' is a register which will receive the value from the stack. It 3943 * can be -1, meaning that the read value is not going to a register. 3944 */ 3945 static int check_stack_read(struct bpf_verifier_env *env, 3946 int ptr_regno, int off, int size, 3947 int dst_regno) 3948 { 3949 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3950 struct bpf_func_state *state = func(env, reg); 3951 int err; 3952 /* Some accesses are only permitted with a static offset. */ 3953 bool var_off = !tnum_is_const(reg->var_off); 3954 3955 /* The offset is required to be static when reads don't go to a 3956 * register, in order to not leak pointers (see 3957 * check_stack_read_fixed_off). 3958 */ 3959 if (dst_regno < 0 && var_off) { 3960 char tn_buf[48]; 3961 3962 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3963 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 3964 tn_buf, off, size); 3965 return -EACCES; 3966 } 3967 /* Variable offset is prohibited for unprivileged mode for simplicity 3968 * since it requires corresponding support in Spectre masking for stack 3969 * ALU. See also retrieve_ptr_limit(). 3970 */ 3971 if (!env->bypass_spec_v1 && var_off) { 3972 char tn_buf[48]; 3973 3974 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3975 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 3976 ptr_regno, tn_buf); 3977 return -EACCES; 3978 } 3979 3980 if (!var_off) { 3981 off += reg->var_off.value; 3982 err = check_stack_read_fixed_off(env, state, off, size, 3983 dst_regno); 3984 } else { 3985 /* Variable offset stack reads need more conservative handling 3986 * than fixed offset ones. Note that dst_regno >= 0 on this 3987 * branch. 3988 */ 3989 err = check_stack_read_var_off(env, ptr_regno, off, size, 3990 dst_regno); 3991 } 3992 return err; 3993 } 3994 3995 3996 /* check_stack_write dispatches to check_stack_write_fixed_off or 3997 * check_stack_write_var_off. 3998 * 3999 * 'ptr_regno' is the register used as a pointer into the stack. 4000 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 4001 * 'value_regno' is the register whose value we're writing to the stack. It can 4002 * be -1, meaning that we're not writing from a register. 4003 * 4004 * The caller must ensure that the offset falls within the maximum stack size. 4005 */ 4006 static int check_stack_write(struct bpf_verifier_env *env, 4007 int ptr_regno, int off, int size, 4008 int value_regno, int insn_idx) 4009 { 4010 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 4011 struct bpf_func_state *state = func(env, reg); 4012 int err; 4013 4014 if (tnum_is_const(reg->var_off)) { 4015 off += reg->var_off.value; 4016 err = check_stack_write_fixed_off(env, state, off, size, 4017 value_regno, insn_idx); 4018 } else { 4019 /* Variable offset stack reads need more conservative handling 4020 * than fixed offset ones. 4021 */ 4022 err = check_stack_write_var_off(env, state, 4023 ptr_regno, off, size, 4024 value_regno, insn_idx); 4025 } 4026 return err; 4027 } 4028 4029 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 4030 int off, int size, enum bpf_access_type type) 4031 { 4032 struct bpf_reg_state *regs = cur_regs(env); 4033 struct bpf_map *map = regs[regno].map_ptr; 4034 u32 cap = bpf_map_flags_to_cap(map); 4035 4036 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 4037 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 4038 map->value_size, off, size); 4039 return -EACCES; 4040 } 4041 4042 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 4043 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 4044 map->value_size, off, size); 4045 return -EACCES; 4046 } 4047 4048 return 0; 4049 } 4050 4051 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 4052 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 4053 int off, int size, u32 mem_size, 4054 bool zero_size_allowed) 4055 { 4056 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 4057 struct bpf_reg_state *reg; 4058 4059 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 4060 return 0; 4061 4062 reg = &cur_regs(env)[regno]; 4063 switch (reg->type) { 4064 case PTR_TO_MAP_KEY: 4065 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4066 mem_size, off, size); 4067 break; 4068 case PTR_TO_MAP_VALUE: 4069 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4070 mem_size, off, size); 4071 break; 4072 case PTR_TO_PACKET: 4073 case PTR_TO_PACKET_META: 4074 case PTR_TO_PACKET_END: 4075 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 4076 off, size, regno, reg->id, off, mem_size); 4077 break; 4078 case PTR_TO_MEM: 4079 default: 4080 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4081 mem_size, off, size); 4082 } 4083 4084 return -EACCES; 4085 } 4086 4087 /* check read/write into a memory region with possible variable offset */ 4088 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 4089 int off, int size, u32 mem_size, 4090 bool zero_size_allowed) 4091 { 4092 struct bpf_verifier_state *vstate = env->cur_state; 4093 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4094 struct bpf_reg_state *reg = &state->regs[regno]; 4095 int err; 4096 4097 /* We may have adjusted the register pointing to memory region, so we 4098 * need to try adding each of min_value and max_value to off 4099 * to make sure our theoretical access will be safe. 4100 * 4101 * The minimum value is only important with signed 4102 * comparisons where we can't assume the floor of a 4103 * value is 0. If we are using signed variables for our 4104 * index'es we need to make sure that whatever we use 4105 * will have a set floor within our range. 4106 */ 4107 if (reg->smin_value < 0 && 4108 (reg->smin_value == S64_MIN || 4109 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 4110 reg->smin_value + off < 0)) { 4111 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4112 regno); 4113 return -EACCES; 4114 } 4115 err = __check_mem_access(env, regno, reg->smin_value + off, size, 4116 mem_size, zero_size_allowed); 4117 if (err) { 4118 verbose(env, "R%d min value is outside of the allowed memory range\n", 4119 regno); 4120 return err; 4121 } 4122 4123 /* If we haven't set a max value then we need to bail since we can't be 4124 * sure we won't do bad things. 4125 * If reg->umax_value + off could overflow, treat that as unbounded too. 4126 */ 4127 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 4128 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 4129 regno); 4130 return -EACCES; 4131 } 4132 err = __check_mem_access(env, regno, reg->umax_value + off, size, 4133 mem_size, zero_size_allowed); 4134 if (err) { 4135 verbose(env, "R%d max value is outside of the allowed memory range\n", 4136 regno); 4137 return err; 4138 } 4139 4140 return 0; 4141 } 4142 4143 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4144 const struct bpf_reg_state *reg, int regno, 4145 bool fixed_off_ok) 4146 { 4147 /* Access to this pointer-typed register or passing it to a helper 4148 * is only allowed in its original, unmodified form. 4149 */ 4150 4151 if (reg->off < 0) { 4152 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 4153 reg_type_str(env, reg->type), regno, reg->off); 4154 return -EACCES; 4155 } 4156 4157 if (!fixed_off_ok && reg->off) { 4158 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 4159 reg_type_str(env, reg->type), regno, reg->off); 4160 return -EACCES; 4161 } 4162 4163 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4164 char tn_buf[48]; 4165 4166 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4167 verbose(env, "variable %s access var_off=%s disallowed\n", 4168 reg_type_str(env, reg->type), tn_buf); 4169 return -EACCES; 4170 } 4171 4172 return 0; 4173 } 4174 4175 int check_ptr_off_reg(struct bpf_verifier_env *env, 4176 const struct bpf_reg_state *reg, int regno) 4177 { 4178 return __check_ptr_off_reg(env, reg, regno, false); 4179 } 4180 4181 static int map_kptr_match_type(struct bpf_verifier_env *env, 4182 struct btf_field *kptr_field, 4183 struct bpf_reg_state *reg, u32 regno) 4184 { 4185 const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4186 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED; 4187 const char *reg_name = ""; 4188 4189 /* Only unreferenced case accepts untrusted pointers */ 4190 if (kptr_field->type == BPF_KPTR_UNREF) 4191 perm_flags |= PTR_UNTRUSTED; 4192 4193 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 4194 goto bad_type; 4195 4196 if (!btf_is_kernel(reg->btf)) { 4197 verbose(env, "R%d must point to kernel BTF\n", regno); 4198 return -EINVAL; 4199 } 4200 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4201 reg_name = kernel_type_name(reg->btf, reg->btf_id); 4202 4203 /* For ref_ptr case, release function check should ensure we get one 4204 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4205 * normal store of unreferenced kptr, we must ensure var_off is zero. 4206 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 4207 * reg->off and reg->ref_obj_id are not needed here. 4208 */ 4209 if (__check_ptr_off_reg(env, reg, regno, true)) 4210 return -EACCES; 4211 4212 /* A full type match is needed, as BTF can be vmlinux or module BTF, and 4213 * we also need to take into account the reg->off. 4214 * 4215 * We want to support cases like: 4216 * 4217 * struct foo { 4218 * struct bar br; 4219 * struct baz bz; 4220 * }; 4221 * 4222 * struct foo *v; 4223 * v = func(); // PTR_TO_BTF_ID 4224 * val->foo = v; // reg->off is zero, btf and btf_id match type 4225 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 4226 * // first member type of struct after comparison fails 4227 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 4228 * // to match type 4229 * 4230 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 4231 * is zero. We must also ensure that btf_struct_ids_match does not walk 4232 * the struct to match type against first member of struct, i.e. reject 4233 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4234 * strict mode to true for type match. 4235 */ 4236 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 4237 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4238 kptr_field->type == BPF_KPTR_REF)) 4239 goto bad_type; 4240 return 0; 4241 bad_type: 4242 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4243 reg_type_str(env, reg->type), reg_name); 4244 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4245 if (kptr_field->type == BPF_KPTR_UNREF) 4246 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4247 targ_name); 4248 else 4249 verbose(env, "\n"); 4250 return -EINVAL; 4251 } 4252 4253 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 4254 int value_regno, int insn_idx, 4255 struct btf_field *kptr_field) 4256 { 4257 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4258 int class = BPF_CLASS(insn->code); 4259 struct bpf_reg_state *val_reg; 4260 4261 /* Things we already checked for in check_map_access and caller: 4262 * - Reject cases where variable offset may touch kptr 4263 * - size of access (must be BPF_DW) 4264 * - tnum_is_const(reg->var_off) 4265 * - kptr_field->offset == off + reg->var_off.value 4266 */ 4267 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4268 if (BPF_MODE(insn->code) != BPF_MEM) { 4269 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4270 return -EACCES; 4271 } 4272 4273 /* We only allow loading referenced kptr, since it will be marked as 4274 * untrusted, similar to unreferenced kptr. 4275 */ 4276 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) { 4277 verbose(env, "store to referenced kptr disallowed\n"); 4278 return -EACCES; 4279 } 4280 4281 if (class == BPF_LDX) { 4282 val_reg = reg_state(env, value_regno); 4283 /* We can simply mark the value_regno receiving the pointer 4284 * value from map as PTR_TO_BTF_ID, with the correct type. 4285 */ 4286 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 4287 kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED); 4288 /* For mark_ptr_or_null_reg */ 4289 val_reg->id = ++env->id_gen; 4290 } else if (class == BPF_STX) { 4291 val_reg = reg_state(env, value_regno); 4292 if (!register_is_null(val_reg) && 4293 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4294 return -EACCES; 4295 } else if (class == BPF_ST) { 4296 if (insn->imm) { 4297 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4298 kptr_field->offset); 4299 return -EACCES; 4300 } 4301 } else { 4302 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4303 return -EACCES; 4304 } 4305 return 0; 4306 } 4307 4308 /* check read/write into a map element with possible variable offset */ 4309 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 4310 int off, int size, bool zero_size_allowed, 4311 enum bpf_access_src src) 4312 { 4313 struct bpf_verifier_state *vstate = env->cur_state; 4314 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4315 struct bpf_reg_state *reg = &state->regs[regno]; 4316 struct bpf_map *map = reg->map_ptr; 4317 struct btf_record *rec; 4318 int err, i; 4319 4320 err = check_mem_region_access(env, regno, off, size, map->value_size, 4321 zero_size_allowed); 4322 if (err) 4323 return err; 4324 4325 if (IS_ERR_OR_NULL(map->record)) 4326 return 0; 4327 rec = map->record; 4328 for (i = 0; i < rec->cnt; i++) { 4329 struct btf_field *field = &rec->fields[i]; 4330 u32 p = field->offset; 4331 4332 /* If any part of a field can be touched by load/store, reject 4333 * this program. To check that [x1, x2) overlaps with [y1, y2), 4334 * it is sufficient to check x1 < y2 && y1 < x2. 4335 */ 4336 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 4337 p < reg->umax_value + off + size) { 4338 switch (field->type) { 4339 case BPF_KPTR_UNREF: 4340 case BPF_KPTR_REF: 4341 if (src != ACCESS_DIRECT) { 4342 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 4343 return -EACCES; 4344 } 4345 if (!tnum_is_const(reg->var_off)) { 4346 verbose(env, "kptr access cannot have variable offset\n"); 4347 return -EACCES; 4348 } 4349 if (p != off + reg->var_off.value) { 4350 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 4351 p, off + reg->var_off.value); 4352 return -EACCES; 4353 } 4354 if (size != bpf_size_to_bytes(BPF_DW)) { 4355 verbose(env, "kptr access size must be BPF_DW\n"); 4356 return -EACCES; 4357 } 4358 break; 4359 default: 4360 verbose(env, "%s cannot be accessed directly by load/store\n", 4361 btf_field_type_name(field->type)); 4362 return -EACCES; 4363 } 4364 } 4365 } 4366 return 0; 4367 } 4368 4369 #define MAX_PACKET_OFF 0xffff 4370 4371 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4372 const struct bpf_call_arg_meta *meta, 4373 enum bpf_access_type t) 4374 { 4375 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4376 4377 switch (prog_type) { 4378 /* Program types only with direct read access go here! */ 4379 case BPF_PROG_TYPE_LWT_IN: 4380 case BPF_PROG_TYPE_LWT_OUT: 4381 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4382 case BPF_PROG_TYPE_SK_REUSEPORT: 4383 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4384 case BPF_PROG_TYPE_CGROUP_SKB: 4385 if (t == BPF_WRITE) 4386 return false; 4387 fallthrough; 4388 4389 /* Program types with direct read + write access go here! */ 4390 case BPF_PROG_TYPE_SCHED_CLS: 4391 case BPF_PROG_TYPE_SCHED_ACT: 4392 case BPF_PROG_TYPE_XDP: 4393 case BPF_PROG_TYPE_LWT_XMIT: 4394 case BPF_PROG_TYPE_SK_SKB: 4395 case BPF_PROG_TYPE_SK_MSG: 4396 if (meta) 4397 return meta->pkt_access; 4398 4399 env->seen_direct_write = true; 4400 return true; 4401 4402 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4403 if (t == BPF_WRITE) 4404 env->seen_direct_write = true; 4405 4406 return true; 4407 4408 default: 4409 return false; 4410 } 4411 } 4412 4413 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 4414 int size, bool zero_size_allowed) 4415 { 4416 struct bpf_reg_state *regs = cur_regs(env); 4417 struct bpf_reg_state *reg = ®s[regno]; 4418 int err; 4419 4420 /* We may have added a variable offset to the packet pointer; but any 4421 * reg->range we have comes after that. We are only checking the fixed 4422 * offset. 4423 */ 4424 4425 /* We don't allow negative numbers, because we aren't tracking enough 4426 * detail to prove they're safe. 4427 */ 4428 if (reg->smin_value < 0) { 4429 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4430 regno); 4431 return -EACCES; 4432 } 4433 4434 err = reg->range < 0 ? -EINVAL : 4435 __check_mem_access(env, regno, off, size, reg->range, 4436 zero_size_allowed); 4437 if (err) { 4438 verbose(env, "R%d offset is outside of the packet\n", regno); 4439 return err; 4440 } 4441 4442 /* __check_mem_access has made sure "off + size - 1" is within u16. 4443 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 4444 * otherwise find_good_pkt_pointers would have refused to set range info 4445 * that __check_mem_access would have rejected this pkt access. 4446 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 4447 */ 4448 env->prog->aux->max_pkt_offset = 4449 max_t(u32, env->prog->aux->max_pkt_offset, 4450 off + reg->umax_value + size - 1); 4451 4452 return err; 4453 } 4454 4455 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4456 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4457 enum bpf_access_type t, enum bpf_reg_type *reg_type, 4458 struct btf **btf, u32 *btf_id) 4459 { 4460 struct bpf_insn_access_aux info = { 4461 .reg_type = *reg_type, 4462 .log = &env->log, 4463 }; 4464 4465 if (env->ops->is_valid_access && 4466 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 4467 /* A non zero info.ctx_field_size indicates that this field is a 4468 * candidate for later verifier transformation to load the whole 4469 * field and then apply a mask when accessed with a narrower 4470 * access than actual ctx access size. A zero info.ctx_field_size 4471 * will only allow for whole field access and rejects any other 4472 * type of narrower access. 4473 */ 4474 *reg_type = info.reg_type; 4475 4476 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 4477 *btf = info.btf; 4478 *btf_id = info.btf_id; 4479 } else { 4480 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 4481 } 4482 /* remember the offset of last byte accessed in ctx */ 4483 if (env->prog->aux->max_ctx_offset < off + size) 4484 env->prog->aux->max_ctx_offset = off + size; 4485 return 0; 4486 } 4487 4488 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4489 return -EACCES; 4490 } 4491 4492 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 4493 int size) 4494 { 4495 if (size < 0 || off < 0 || 4496 (u64)off + size > sizeof(struct bpf_flow_keys)) { 4497 verbose(env, "invalid access to flow keys off=%d size=%d\n", 4498 off, size); 4499 return -EACCES; 4500 } 4501 return 0; 4502 } 4503 4504 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 4505 u32 regno, int off, int size, 4506 enum bpf_access_type t) 4507 { 4508 struct bpf_reg_state *regs = cur_regs(env); 4509 struct bpf_reg_state *reg = ®s[regno]; 4510 struct bpf_insn_access_aux info = {}; 4511 bool valid; 4512 4513 if (reg->smin_value < 0) { 4514 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4515 regno); 4516 return -EACCES; 4517 } 4518 4519 switch (reg->type) { 4520 case PTR_TO_SOCK_COMMON: 4521 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 4522 break; 4523 case PTR_TO_SOCKET: 4524 valid = bpf_sock_is_valid_access(off, size, t, &info); 4525 break; 4526 case PTR_TO_TCP_SOCK: 4527 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 4528 break; 4529 case PTR_TO_XDP_SOCK: 4530 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 4531 break; 4532 default: 4533 valid = false; 4534 } 4535 4536 4537 if (valid) { 4538 env->insn_aux_data[insn_idx].ctx_field_size = 4539 info.ctx_field_size; 4540 return 0; 4541 } 4542 4543 verbose(env, "R%d invalid %s access off=%d size=%d\n", 4544 regno, reg_type_str(env, reg->type), off, size); 4545 4546 return -EACCES; 4547 } 4548 4549 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 4550 { 4551 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 4552 } 4553 4554 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 4555 { 4556 const struct bpf_reg_state *reg = reg_state(env, regno); 4557 4558 return reg->type == PTR_TO_CTX; 4559 } 4560 4561 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 4562 { 4563 const struct bpf_reg_state *reg = reg_state(env, regno); 4564 4565 return type_is_sk_pointer(reg->type); 4566 } 4567 4568 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 4569 { 4570 const struct bpf_reg_state *reg = reg_state(env, regno); 4571 4572 return type_is_pkt_pointer(reg->type); 4573 } 4574 4575 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 4576 { 4577 const struct bpf_reg_state *reg = reg_state(env, regno); 4578 4579 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 4580 return reg->type == PTR_TO_FLOW_KEYS; 4581 } 4582 4583 static bool is_trusted_reg(const struct bpf_reg_state *reg) 4584 { 4585 /* A referenced register is always trusted. */ 4586 if (reg->ref_obj_id) 4587 return true; 4588 4589 /* If a register is not referenced, it is trusted if it has the 4590 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 4591 * other type modifiers may be safe, but we elect to take an opt-in 4592 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 4593 * not. 4594 * 4595 * Eventually, we should make PTR_TRUSTED the single source of truth 4596 * for whether a register is trusted. 4597 */ 4598 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 4599 !bpf_type_has_unsafe_modifiers(reg->type); 4600 } 4601 4602 static bool is_rcu_reg(const struct bpf_reg_state *reg) 4603 { 4604 return reg->type & MEM_RCU; 4605 } 4606 4607 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 4608 const struct bpf_reg_state *reg, 4609 int off, int size, bool strict) 4610 { 4611 struct tnum reg_off; 4612 int ip_align; 4613 4614 /* Byte size accesses are always allowed. */ 4615 if (!strict || size == 1) 4616 return 0; 4617 4618 /* For platforms that do not have a Kconfig enabling 4619 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 4620 * NET_IP_ALIGN is universally set to '2'. And on platforms 4621 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 4622 * to this code only in strict mode where we want to emulate 4623 * the NET_IP_ALIGN==2 checking. Therefore use an 4624 * unconditional IP align value of '2'. 4625 */ 4626 ip_align = 2; 4627 4628 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 4629 if (!tnum_is_aligned(reg_off, size)) { 4630 char tn_buf[48]; 4631 4632 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4633 verbose(env, 4634 "misaligned packet access off %d+%s+%d+%d size %d\n", 4635 ip_align, tn_buf, reg->off, off, size); 4636 return -EACCES; 4637 } 4638 4639 return 0; 4640 } 4641 4642 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 4643 const struct bpf_reg_state *reg, 4644 const char *pointer_desc, 4645 int off, int size, bool strict) 4646 { 4647 struct tnum reg_off; 4648 4649 /* Byte size accesses are always allowed. */ 4650 if (!strict || size == 1) 4651 return 0; 4652 4653 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 4654 if (!tnum_is_aligned(reg_off, size)) { 4655 char tn_buf[48]; 4656 4657 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4658 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 4659 pointer_desc, tn_buf, reg->off, off, size); 4660 return -EACCES; 4661 } 4662 4663 return 0; 4664 } 4665 4666 static int check_ptr_alignment(struct bpf_verifier_env *env, 4667 const struct bpf_reg_state *reg, int off, 4668 int size, bool strict_alignment_once) 4669 { 4670 bool strict = env->strict_alignment || strict_alignment_once; 4671 const char *pointer_desc = ""; 4672 4673 switch (reg->type) { 4674 case PTR_TO_PACKET: 4675 case PTR_TO_PACKET_META: 4676 /* Special case, because of NET_IP_ALIGN. Given metadata sits 4677 * right in front, treat it the very same way. 4678 */ 4679 return check_pkt_ptr_alignment(env, reg, off, size, strict); 4680 case PTR_TO_FLOW_KEYS: 4681 pointer_desc = "flow keys "; 4682 break; 4683 case PTR_TO_MAP_KEY: 4684 pointer_desc = "key "; 4685 break; 4686 case PTR_TO_MAP_VALUE: 4687 pointer_desc = "value "; 4688 break; 4689 case PTR_TO_CTX: 4690 pointer_desc = "context "; 4691 break; 4692 case PTR_TO_STACK: 4693 pointer_desc = "stack "; 4694 /* The stack spill tracking logic in check_stack_write_fixed_off() 4695 * and check_stack_read_fixed_off() relies on stack accesses being 4696 * aligned. 4697 */ 4698 strict = true; 4699 break; 4700 case PTR_TO_SOCKET: 4701 pointer_desc = "sock "; 4702 break; 4703 case PTR_TO_SOCK_COMMON: 4704 pointer_desc = "sock_common "; 4705 break; 4706 case PTR_TO_TCP_SOCK: 4707 pointer_desc = "tcp_sock "; 4708 break; 4709 case PTR_TO_XDP_SOCK: 4710 pointer_desc = "xdp_sock "; 4711 break; 4712 default: 4713 break; 4714 } 4715 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 4716 strict); 4717 } 4718 4719 static int update_stack_depth(struct bpf_verifier_env *env, 4720 const struct bpf_func_state *func, 4721 int off) 4722 { 4723 u16 stack = env->subprog_info[func->subprogno].stack_depth; 4724 4725 if (stack >= -off) 4726 return 0; 4727 4728 /* update known max for given subprogram */ 4729 env->subprog_info[func->subprogno].stack_depth = -off; 4730 return 0; 4731 } 4732 4733 /* starting from main bpf function walk all instructions of the function 4734 * and recursively walk all callees that given function can call. 4735 * Ignore jump and exit insns. 4736 * Since recursion is prevented by check_cfg() this algorithm 4737 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 4738 */ 4739 static int check_max_stack_depth(struct bpf_verifier_env *env) 4740 { 4741 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 4742 struct bpf_subprog_info *subprog = env->subprog_info; 4743 struct bpf_insn *insn = env->prog->insnsi; 4744 bool tail_call_reachable = false; 4745 int ret_insn[MAX_CALL_FRAMES]; 4746 int ret_prog[MAX_CALL_FRAMES]; 4747 int j; 4748 4749 process_func: 4750 /* protect against potential stack overflow that might happen when 4751 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 4752 * depth for such case down to 256 so that the worst case scenario 4753 * would result in 8k stack size (32 which is tailcall limit * 256 = 4754 * 8k). 4755 * 4756 * To get the idea what might happen, see an example: 4757 * func1 -> sub rsp, 128 4758 * subfunc1 -> sub rsp, 256 4759 * tailcall1 -> add rsp, 256 4760 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 4761 * subfunc2 -> sub rsp, 64 4762 * subfunc22 -> sub rsp, 128 4763 * tailcall2 -> add rsp, 128 4764 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 4765 * 4766 * tailcall will unwind the current stack frame but it will not get rid 4767 * of caller's stack as shown on the example above. 4768 */ 4769 if (idx && subprog[idx].has_tail_call && depth >= 256) { 4770 verbose(env, 4771 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 4772 depth); 4773 return -EACCES; 4774 } 4775 /* round up to 32-bytes, since this is granularity 4776 * of interpreter stack size 4777 */ 4778 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 4779 if (depth > MAX_BPF_STACK) { 4780 verbose(env, "combined stack size of %d calls is %d. Too large\n", 4781 frame + 1, depth); 4782 return -EACCES; 4783 } 4784 continue_func: 4785 subprog_end = subprog[idx + 1].start; 4786 for (; i < subprog_end; i++) { 4787 int next_insn; 4788 4789 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 4790 continue; 4791 /* remember insn and function to return to */ 4792 ret_insn[frame] = i + 1; 4793 ret_prog[frame] = idx; 4794 4795 /* find the callee */ 4796 next_insn = i + insn[i].imm + 1; 4797 idx = find_subprog(env, next_insn); 4798 if (idx < 0) { 4799 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 4800 next_insn); 4801 return -EFAULT; 4802 } 4803 if (subprog[idx].is_async_cb) { 4804 if (subprog[idx].has_tail_call) { 4805 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 4806 return -EFAULT; 4807 } 4808 /* async callbacks don't increase bpf prog stack size */ 4809 continue; 4810 } 4811 i = next_insn; 4812 4813 if (subprog[idx].has_tail_call) 4814 tail_call_reachable = true; 4815 4816 frame++; 4817 if (frame >= MAX_CALL_FRAMES) { 4818 verbose(env, "the call stack of %d frames is too deep !\n", 4819 frame); 4820 return -E2BIG; 4821 } 4822 goto process_func; 4823 } 4824 /* if tail call got detected across bpf2bpf calls then mark each of the 4825 * currently present subprog frames as tail call reachable subprogs; 4826 * this info will be utilized by JIT so that we will be preserving the 4827 * tail call counter throughout bpf2bpf calls combined with tailcalls 4828 */ 4829 if (tail_call_reachable) 4830 for (j = 0; j < frame; j++) 4831 subprog[ret_prog[j]].tail_call_reachable = true; 4832 if (subprog[0].tail_call_reachable) 4833 env->prog->aux->tail_call_reachable = true; 4834 4835 /* end of for() loop means the last insn of the 'subprog' 4836 * was reached. Doesn't matter whether it was JA or EXIT 4837 */ 4838 if (frame == 0) 4839 return 0; 4840 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 4841 frame--; 4842 i = ret_insn[frame]; 4843 idx = ret_prog[frame]; 4844 goto continue_func; 4845 } 4846 4847 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 4848 static int get_callee_stack_depth(struct bpf_verifier_env *env, 4849 const struct bpf_insn *insn, int idx) 4850 { 4851 int start = idx + insn->imm + 1, subprog; 4852 4853 subprog = find_subprog(env, start); 4854 if (subprog < 0) { 4855 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 4856 start); 4857 return -EFAULT; 4858 } 4859 return env->subprog_info[subprog].stack_depth; 4860 } 4861 #endif 4862 4863 static int __check_buffer_access(struct bpf_verifier_env *env, 4864 const char *buf_info, 4865 const struct bpf_reg_state *reg, 4866 int regno, int off, int size) 4867 { 4868 if (off < 0) { 4869 verbose(env, 4870 "R%d invalid %s buffer access: off=%d, size=%d\n", 4871 regno, buf_info, off, size); 4872 return -EACCES; 4873 } 4874 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4875 char tn_buf[48]; 4876 4877 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4878 verbose(env, 4879 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 4880 regno, off, tn_buf); 4881 return -EACCES; 4882 } 4883 4884 return 0; 4885 } 4886 4887 static int check_tp_buffer_access(struct bpf_verifier_env *env, 4888 const struct bpf_reg_state *reg, 4889 int regno, int off, int size) 4890 { 4891 int err; 4892 4893 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 4894 if (err) 4895 return err; 4896 4897 if (off + size > env->prog->aux->max_tp_access) 4898 env->prog->aux->max_tp_access = off + size; 4899 4900 return 0; 4901 } 4902 4903 static int check_buffer_access(struct bpf_verifier_env *env, 4904 const struct bpf_reg_state *reg, 4905 int regno, int off, int size, 4906 bool zero_size_allowed, 4907 u32 *max_access) 4908 { 4909 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 4910 int err; 4911 4912 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 4913 if (err) 4914 return err; 4915 4916 if (off + size > *max_access) 4917 *max_access = off + size; 4918 4919 return 0; 4920 } 4921 4922 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 4923 static void zext_32_to_64(struct bpf_reg_state *reg) 4924 { 4925 reg->var_off = tnum_subreg(reg->var_off); 4926 __reg_assign_32_into_64(reg); 4927 } 4928 4929 /* truncate register to smaller size (in bytes) 4930 * must be called with size < BPF_REG_SIZE 4931 */ 4932 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 4933 { 4934 u64 mask; 4935 4936 /* clear high bits in bit representation */ 4937 reg->var_off = tnum_cast(reg->var_off, size); 4938 4939 /* fix arithmetic bounds */ 4940 mask = ((u64)1 << (size * 8)) - 1; 4941 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 4942 reg->umin_value &= mask; 4943 reg->umax_value &= mask; 4944 } else { 4945 reg->umin_value = 0; 4946 reg->umax_value = mask; 4947 } 4948 reg->smin_value = reg->umin_value; 4949 reg->smax_value = reg->umax_value; 4950 4951 /* If size is smaller than 32bit register the 32bit register 4952 * values are also truncated so we push 64-bit bounds into 4953 * 32-bit bounds. Above were truncated < 32-bits already. 4954 */ 4955 if (size >= 4) 4956 return; 4957 __reg_combine_64_into_32(reg); 4958 } 4959 4960 static bool bpf_map_is_rdonly(const struct bpf_map *map) 4961 { 4962 /* A map is considered read-only if the following condition are true: 4963 * 4964 * 1) BPF program side cannot change any of the map content. The 4965 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 4966 * and was set at map creation time. 4967 * 2) The map value(s) have been initialized from user space by a 4968 * loader and then "frozen", such that no new map update/delete 4969 * operations from syscall side are possible for the rest of 4970 * the map's lifetime from that point onwards. 4971 * 3) Any parallel/pending map update/delete operations from syscall 4972 * side have been completed. Only after that point, it's safe to 4973 * assume that map value(s) are immutable. 4974 */ 4975 return (map->map_flags & BPF_F_RDONLY_PROG) && 4976 READ_ONCE(map->frozen) && 4977 !bpf_map_write_active(map); 4978 } 4979 4980 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 4981 { 4982 void *ptr; 4983 u64 addr; 4984 int err; 4985 4986 err = map->ops->map_direct_value_addr(map, &addr, off); 4987 if (err) 4988 return err; 4989 ptr = (void *)(long)addr + off; 4990 4991 switch (size) { 4992 case sizeof(u8): 4993 *val = (u64)*(u8 *)ptr; 4994 break; 4995 case sizeof(u16): 4996 *val = (u64)*(u16 *)ptr; 4997 break; 4998 case sizeof(u32): 4999 *val = (u64)*(u32 *)ptr; 5000 break; 5001 case sizeof(u64): 5002 *val = *(u64 *)ptr; 5003 break; 5004 default: 5005 return -EINVAL; 5006 } 5007 return 0; 5008 } 5009 5010 #define BTF_TYPE_SAFE_NESTED(__type) __PASTE(__type, __safe_fields) 5011 5012 BTF_TYPE_SAFE_NESTED(struct task_struct) { 5013 const cpumask_t *cpus_ptr; 5014 }; 5015 5016 static bool nested_ptr_is_trusted(struct bpf_verifier_env *env, 5017 struct bpf_reg_state *reg, 5018 int off) 5019 { 5020 /* If its parent is not trusted, it can't regain its trusted status. */ 5021 if (!is_trusted_reg(reg)) 5022 return false; 5023 5024 BTF_TYPE_EMIT(BTF_TYPE_SAFE_NESTED(struct task_struct)); 5025 5026 return btf_nested_type_is_trusted(&env->log, reg, off); 5027 } 5028 5029 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 5030 struct bpf_reg_state *regs, 5031 int regno, int off, int size, 5032 enum bpf_access_type atype, 5033 int value_regno) 5034 { 5035 struct bpf_reg_state *reg = regs + regno; 5036 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 5037 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 5038 enum bpf_type_flag flag = 0; 5039 u32 btf_id; 5040 int ret; 5041 5042 if (!env->allow_ptr_leaks) { 5043 verbose(env, 5044 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5045 tname); 5046 return -EPERM; 5047 } 5048 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 5049 verbose(env, 5050 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 5051 tname); 5052 return -EINVAL; 5053 } 5054 if (off < 0) { 5055 verbose(env, 5056 "R%d is ptr_%s invalid negative access: off=%d\n", 5057 regno, tname, off); 5058 return -EACCES; 5059 } 5060 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5061 char tn_buf[48]; 5062 5063 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5064 verbose(env, 5065 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5066 regno, tname, off, tn_buf); 5067 return -EACCES; 5068 } 5069 5070 if (reg->type & MEM_USER) { 5071 verbose(env, 5072 "R%d is ptr_%s access user memory: off=%d\n", 5073 regno, tname, off); 5074 return -EACCES; 5075 } 5076 5077 if (reg->type & MEM_PERCPU) { 5078 verbose(env, 5079 "R%d is ptr_%s access percpu memory: off=%d\n", 5080 regno, tname, off); 5081 return -EACCES; 5082 } 5083 5084 if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) { 5085 if (!btf_is_kernel(reg->btf)) { 5086 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 5087 return -EFAULT; 5088 } 5089 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag); 5090 } else { 5091 /* Writes are permitted with default btf_struct_access for 5092 * program allocated objects (which always have ref_obj_id > 0), 5093 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 5094 */ 5095 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 5096 verbose(env, "only read is supported\n"); 5097 return -EACCES; 5098 } 5099 5100 if (type_is_alloc(reg->type) && !type_is_non_owning_ref(reg->type) && 5101 !reg->ref_obj_id) { 5102 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 5103 return -EFAULT; 5104 } 5105 5106 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag); 5107 } 5108 5109 if (ret < 0) 5110 return ret; 5111 5112 /* If this is an untrusted pointer, all pointers formed by walking it 5113 * also inherit the untrusted flag. 5114 */ 5115 if (type_flag(reg->type) & PTR_UNTRUSTED) 5116 flag |= PTR_UNTRUSTED; 5117 5118 /* By default any pointer obtained from walking a trusted pointer is no 5119 * longer trusted, unless the field being accessed has explicitly been 5120 * marked as inheriting its parent's state of trust. 5121 * 5122 * An RCU-protected pointer can also be deemed trusted if we are in an 5123 * RCU read region. This case is handled below. 5124 */ 5125 if (nested_ptr_is_trusted(env, reg, off)) 5126 flag |= PTR_TRUSTED; 5127 else 5128 flag &= ~PTR_TRUSTED; 5129 5130 if (flag & MEM_RCU) { 5131 /* Mark value register as MEM_RCU only if it is protected by 5132 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU 5133 * itself can already indicate trustedness inside the rcu 5134 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since 5135 * it could be null in some cases. 5136 */ 5137 if (!env->cur_state->active_rcu_lock || 5138 !(is_trusted_reg(reg) || is_rcu_reg(reg))) 5139 flag &= ~MEM_RCU; 5140 else 5141 flag |= PTR_MAYBE_NULL; 5142 } else if (reg->type & MEM_RCU) { 5143 /* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged 5144 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively. 5145 */ 5146 flag |= PTR_UNTRUSTED; 5147 } 5148 5149 if (atype == BPF_READ && value_regno >= 0) 5150 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5151 5152 return 0; 5153 } 5154 5155 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5156 struct bpf_reg_state *regs, 5157 int regno, int off, int size, 5158 enum bpf_access_type atype, 5159 int value_regno) 5160 { 5161 struct bpf_reg_state *reg = regs + regno; 5162 struct bpf_map *map = reg->map_ptr; 5163 struct bpf_reg_state map_reg; 5164 enum bpf_type_flag flag = 0; 5165 const struct btf_type *t; 5166 const char *tname; 5167 u32 btf_id; 5168 int ret; 5169 5170 if (!btf_vmlinux) { 5171 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5172 return -ENOTSUPP; 5173 } 5174 5175 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5176 verbose(env, "map_ptr access not supported for map type %d\n", 5177 map->map_type); 5178 return -ENOTSUPP; 5179 } 5180 5181 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5182 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5183 5184 if (!env->allow_ptr_leaks) { 5185 verbose(env, 5186 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5187 tname); 5188 return -EPERM; 5189 } 5190 5191 if (off < 0) { 5192 verbose(env, "R%d is %s invalid negative access: off=%d\n", 5193 regno, tname, off); 5194 return -EACCES; 5195 } 5196 5197 if (atype != BPF_READ) { 5198 verbose(env, "only read from %s is supported\n", tname); 5199 return -EACCES; 5200 } 5201 5202 /* Simulate access to a PTR_TO_BTF_ID */ 5203 memset(&map_reg, 0, sizeof(map_reg)); 5204 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 5205 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag); 5206 if (ret < 0) 5207 return ret; 5208 5209 if (value_regno >= 0) 5210 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 5211 5212 return 0; 5213 } 5214 5215 /* Check that the stack access at the given offset is within bounds. The 5216 * maximum valid offset is -1. 5217 * 5218 * The minimum valid offset is -MAX_BPF_STACK for writes, and 5219 * -state->allocated_stack for reads. 5220 */ 5221 static int check_stack_slot_within_bounds(int off, 5222 struct bpf_func_state *state, 5223 enum bpf_access_type t) 5224 { 5225 int min_valid_off; 5226 5227 if (t == BPF_WRITE) 5228 min_valid_off = -MAX_BPF_STACK; 5229 else 5230 min_valid_off = -state->allocated_stack; 5231 5232 if (off < min_valid_off || off > -1) 5233 return -EACCES; 5234 return 0; 5235 } 5236 5237 /* Check that the stack access at 'regno + off' falls within the maximum stack 5238 * bounds. 5239 * 5240 * 'off' includes `regno->offset`, but not its dynamic part (if any). 5241 */ 5242 static int check_stack_access_within_bounds( 5243 struct bpf_verifier_env *env, 5244 int regno, int off, int access_size, 5245 enum bpf_access_src src, enum bpf_access_type type) 5246 { 5247 struct bpf_reg_state *regs = cur_regs(env); 5248 struct bpf_reg_state *reg = regs + regno; 5249 struct bpf_func_state *state = func(env, reg); 5250 int min_off, max_off; 5251 int err; 5252 char *err_extra; 5253 5254 if (src == ACCESS_HELPER) 5255 /* We don't know if helpers are reading or writing (or both). */ 5256 err_extra = " indirect access to"; 5257 else if (type == BPF_READ) 5258 err_extra = " read from"; 5259 else 5260 err_extra = " write to"; 5261 5262 if (tnum_is_const(reg->var_off)) { 5263 min_off = reg->var_off.value + off; 5264 if (access_size > 0) 5265 max_off = min_off + access_size - 1; 5266 else 5267 max_off = min_off; 5268 } else { 5269 if (reg->smax_value >= BPF_MAX_VAR_OFF || 5270 reg->smin_value <= -BPF_MAX_VAR_OFF) { 5271 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 5272 err_extra, regno); 5273 return -EACCES; 5274 } 5275 min_off = reg->smin_value + off; 5276 if (access_size > 0) 5277 max_off = reg->smax_value + off + access_size - 1; 5278 else 5279 max_off = min_off; 5280 } 5281 5282 err = check_stack_slot_within_bounds(min_off, state, type); 5283 if (!err) 5284 err = check_stack_slot_within_bounds(max_off, state, type); 5285 5286 if (err) { 5287 if (tnum_is_const(reg->var_off)) { 5288 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 5289 err_extra, regno, off, access_size); 5290 } else { 5291 char tn_buf[48]; 5292 5293 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5294 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 5295 err_extra, regno, tn_buf, access_size); 5296 } 5297 } 5298 return err; 5299 } 5300 5301 /* check whether memory at (regno + off) is accessible for t = (read | write) 5302 * if t==write, value_regno is a register which value is stored into memory 5303 * if t==read, value_regno is a register which will receive the value from memory 5304 * if t==write && value_regno==-1, some unknown value is stored into memory 5305 * if t==read && value_regno==-1, don't care what we read from memory 5306 */ 5307 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 5308 int off, int bpf_size, enum bpf_access_type t, 5309 int value_regno, bool strict_alignment_once) 5310 { 5311 struct bpf_reg_state *regs = cur_regs(env); 5312 struct bpf_reg_state *reg = regs + regno; 5313 struct bpf_func_state *state; 5314 int size, err = 0; 5315 5316 size = bpf_size_to_bytes(bpf_size); 5317 if (size < 0) 5318 return size; 5319 5320 /* alignment checks will add in reg->off themselves */ 5321 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 5322 if (err) 5323 return err; 5324 5325 /* for access checks, reg->off is just part of off */ 5326 off += reg->off; 5327 5328 if (reg->type == PTR_TO_MAP_KEY) { 5329 if (t == BPF_WRITE) { 5330 verbose(env, "write to change key R%d not allowed\n", regno); 5331 return -EACCES; 5332 } 5333 5334 err = check_mem_region_access(env, regno, off, size, 5335 reg->map_ptr->key_size, false); 5336 if (err) 5337 return err; 5338 if (value_regno >= 0) 5339 mark_reg_unknown(env, regs, value_regno); 5340 } else if (reg->type == PTR_TO_MAP_VALUE) { 5341 struct btf_field *kptr_field = NULL; 5342 5343 if (t == BPF_WRITE && value_regno >= 0 && 5344 is_pointer_value(env, value_regno)) { 5345 verbose(env, "R%d leaks addr into map\n", value_regno); 5346 return -EACCES; 5347 } 5348 err = check_map_access_type(env, regno, off, size, t); 5349 if (err) 5350 return err; 5351 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 5352 if (err) 5353 return err; 5354 if (tnum_is_const(reg->var_off)) 5355 kptr_field = btf_record_find(reg->map_ptr->record, 5356 off + reg->var_off.value, BPF_KPTR); 5357 if (kptr_field) { 5358 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 5359 } else if (t == BPF_READ && value_regno >= 0) { 5360 struct bpf_map *map = reg->map_ptr; 5361 5362 /* if map is read-only, track its contents as scalars */ 5363 if (tnum_is_const(reg->var_off) && 5364 bpf_map_is_rdonly(map) && 5365 map->ops->map_direct_value_addr) { 5366 int map_off = off + reg->var_off.value; 5367 u64 val = 0; 5368 5369 err = bpf_map_direct_read(map, map_off, size, 5370 &val); 5371 if (err) 5372 return err; 5373 5374 regs[value_regno].type = SCALAR_VALUE; 5375 __mark_reg_known(®s[value_regno], val); 5376 } else { 5377 mark_reg_unknown(env, regs, value_regno); 5378 } 5379 } 5380 } else if (base_type(reg->type) == PTR_TO_MEM) { 5381 bool rdonly_mem = type_is_rdonly_mem(reg->type); 5382 5383 if (type_may_be_null(reg->type)) { 5384 verbose(env, "R%d invalid mem access '%s'\n", regno, 5385 reg_type_str(env, reg->type)); 5386 return -EACCES; 5387 } 5388 5389 if (t == BPF_WRITE && rdonly_mem) { 5390 verbose(env, "R%d cannot write into %s\n", 5391 regno, reg_type_str(env, reg->type)); 5392 return -EACCES; 5393 } 5394 5395 if (t == BPF_WRITE && value_regno >= 0 && 5396 is_pointer_value(env, value_regno)) { 5397 verbose(env, "R%d leaks addr into mem\n", value_regno); 5398 return -EACCES; 5399 } 5400 5401 err = check_mem_region_access(env, regno, off, size, 5402 reg->mem_size, false); 5403 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 5404 mark_reg_unknown(env, regs, value_regno); 5405 } else if (reg->type == PTR_TO_CTX) { 5406 enum bpf_reg_type reg_type = SCALAR_VALUE; 5407 struct btf *btf = NULL; 5408 u32 btf_id = 0; 5409 5410 if (t == BPF_WRITE && value_regno >= 0 && 5411 is_pointer_value(env, value_regno)) { 5412 verbose(env, "R%d leaks addr into ctx\n", value_regno); 5413 return -EACCES; 5414 } 5415 5416 err = check_ptr_off_reg(env, reg, regno); 5417 if (err < 0) 5418 return err; 5419 5420 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 5421 &btf_id); 5422 if (err) 5423 verbose_linfo(env, insn_idx, "; "); 5424 if (!err && t == BPF_READ && value_regno >= 0) { 5425 /* ctx access returns either a scalar, or a 5426 * PTR_TO_PACKET[_META,_END]. In the latter 5427 * case, we know the offset is zero. 5428 */ 5429 if (reg_type == SCALAR_VALUE) { 5430 mark_reg_unknown(env, regs, value_regno); 5431 } else { 5432 mark_reg_known_zero(env, regs, 5433 value_regno); 5434 if (type_may_be_null(reg_type)) 5435 regs[value_regno].id = ++env->id_gen; 5436 /* A load of ctx field could have different 5437 * actual load size with the one encoded in the 5438 * insn. When the dst is PTR, it is for sure not 5439 * a sub-register. 5440 */ 5441 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 5442 if (base_type(reg_type) == PTR_TO_BTF_ID) { 5443 regs[value_regno].btf = btf; 5444 regs[value_regno].btf_id = btf_id; 5445 } 5446 } 5447 regs[value_regno].type = reg_type; 5448 } 5449 5450 } else if (reg->type == PTR_TO_STACK) { 5451 /* Basic bounds checks. */ 5452 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 5453 if (err) 5454 return err; 5455 5456 state = func(env, reg); 5457 err = update_stack_depth(env, state, off); 5458 if (err) 5459 return err; 5460 5461 if (t == BPF_READ) 5462 err = check_stack_read(env, regno, off, size, 5463 value_regno); 5464 else 5465 err = check_stack_write(env, regno, off, size, 5466 value_regno, insn_idx); 5467 } else if (reg_is_pkt_pointer(reg)) { 5468 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 5469 verbose(env, "cannot write into packet\n"); 5470 return -EACCES; 5471 } 5472 if (t == BPF_WRITE && value_regno >= 0 && 5473 is_pointer_value(env, value_regno)) { 5474 verbose(env, "R%d leaks addr into packet\n", 5475 value_regno); 5476 return -EACCES; 5477 } 5478 err = check_packet_access(env, regno, off, size, false); 5479 if (!err && t == BPF_READ && value_regno >= 0) 5480 mark_reg_unknown(env, regs, value_regno); 5481 } else if (reg->type == PTR_TO_FLOW_KEYS) { 5482 if (t == BPF_WRITE && value_regno >= 0 && 5483 is_pointer_value(env, value_regno)) { 5484 verbose(env, "R%d leaks addr into flow keys\n", 5485 value_regno); 5486 return -EACCES; 5487 } 5488 5489 err = check_flow_keys_access(env, off, size); 5490 if (!err && t == BPF_READ && value_regno >= 0) 5491 mark_reg_unknown(env, regs, value_regno); 5492 } else if (type_is_sk_pointer(reg->type)) { 5493 if (t == BPF_WRITE) { 5494 verbose(env, "R%d cannot write into %s\n", 5495 regno, reg_type_str(env, reg->type)); 5496 return -EACCES; 5497 } 5498 err = check_sock_access(env, insn_idx, regno, off, size, t); 5499 if (!err && value_regno >= 0) 5500 mark_reg_unknown(env, regs, value_regno); 5501 } else if (reg->type == PTR_TO_TP_BUFFER) { 5502 err = check_tp_buffer_access(env, reg, regno, off, size); 5503 if (!err && t == BPF_READ && value_regno >= 0) 5504 mark_reg_unknown(env, regs, value_regno); 5505 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 5506 !type_may_be_null(reg->type)) { 5507 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 5508 value_regno); 5509 } else if (reg->type == CONST_PTR_TO_MAP) { 5510 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 5511 value_regno); 5512 } else if (base_type(reg->type) == PTR_TO_BUF) { 5513 bool rdonly_mem = type_is_rdonly_mem(reg->type); 5514 u32 *max_access; 5515 5516 if (rdonly_mem) { 5517 if (t == BPF_WRITE) { 5518 verbose(env, "R%d cannot write into %s\n", 5519 regno, reg_type_str(env, reg->type)); 5520 return -EACCES; 5521 } 5522 max_access = &env->prog->aux->max_rdonly_access; 5523 } else { 5524 max_access = &env->prog->aux->max_rdwr_access; 5525 } 5526 5527 err = check_buffer_access(env, reg, regno, off, size, false, 5528 max_access); 5529 5530 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 5531 mark_reg_unknown(env, regs, value_regno); 5532 } else { 5533 verbose(env, "R%d invalid mem access '%s'\n", regno, 5534 reg_type_str(env, reg->type)); 5535 return -EACCES; 5536 } 5537 5538 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 5539 regs[value_regno].type == SCALAR_VALUE) { 5540 /* b/h/w load zero-extends, mark upper bits as known 0 */ 5541 coerce_reg_to_size(®s[value_regno], size); 5542 } 5543 return err; 5544 } 5545 5546 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 5547 { 5548 int load_reg; 5549 int err; 5550 5551 switch (insn->imm) { 5552 case BPF_ADD: 5553 case BPF_ADD | BPF_FETCH: 5554 case BPF_AND: 5555 case BPF_AND | BPF_FETCH: 5556 case BPF_OR: 5557 case BPF_OR | BPF_FETCH: 5558 case BPF_XOR: 5559 case BPF_XOR | BPF_FETCH: 5560 case BPF_XCHG: 5561 case BPF_CMPXCHG: 5562 break; 5563 default: 5564 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 5565 return -EINVAL; 5566 } 5567 5568 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 5569 verbose(env, "invalid atomic operand size\n"); 5570 return -EINVAL; 5571 } 5572 5573 /* check src1 operand */ 5574 err = check_reg_arg(env, insn->src_reg, SRC_OP); 5575 if (err) 5576 return err; 5577 5578 /* check src2 operand */ 5579 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 5580 if (err) 5581 return err; 5582 5583 if (insn->imm == BPF_CMPXCHG) { 5584 /* Check comparison of R0 with memory location */ 5585 const u32 aux_reg = BPF_REG_0; 5586 5587 err = check_reg_arg(env, aux_reg, SRC_OP); 5588 if (err) 5589 return err; 5590 5591 if (is_pointer_value(env, aux_reg)) { 5592 verbose(env, "R%d leaks addr into mem\n", aux_reg); 5593 return -EACCES; 5594 } 5595 } 5596 5597 if (is_pointer_value(env, insn->src_reg)) { 5598 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 5599 return -EACCES; 5600 } 5601 5602 if (is_ctx_reg(env, insn->dst_reg) || 5603 is_pkt_reg(env, insn->dst_reg) || 5604 is_flow_key_reg(env, insn->dst_reg) || 5605 is_sk_reg(env, insn->dst_reg)) { 5606 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 5607 insn->dst_reg, 5608 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 5609 return -EACCES; 5610 } 5611 5612 if (insn->imm & BPF_FETCH) { 5613 if (insn->imm == BPF_CMPXCHG) 5614 load_reg = BPF_REG_0; 5615 else 5616 load_reg = insn->src_reg; 5617 5618 /* check and record load of old value */ 5619 err = check_reg_arg(env, load_reg, DST_OP); 5620 if (err) 5621 return err; 5622 } else { 5623 /* This instruction accesses a memory location but doesn't 5624 * actually load it into a register. 5625 */ 5626 load_reg = -1; 5627 } 5628 5629 /* Check whether we can read the memory, with second call for fetch 5630 * case to simulate the register fill. 5631 */ 5632 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5633 BPF_SIZE(insn->code), BPF_READ, -1, true); 5634 if (!err && load_reg >= 0) 5635 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5636 BPF_SIZE(insn->code), BPF_READ, load_reg, 5637 true); 5638 if (err) 5639 return err; 5640 5641 /* Check whether we can write into the same memory. */ 5642 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5643 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 5644 if (err) 5645 return err; 5646 5647 return 0; 5648 } 5649 5650 /* When register 'regno' is used to read the stack (either directly or through 5651 * a helper function) make sure that it's within stack boundary and, depending 5652 * on the access type, that all elements of the stack are initialized. 5653 * 5654 * 'off' includes 'regno->off', but not its dynamic part (if any). 5655 * 5656 * All registers that have been spilled on the stack in the slots within the 5657 * read offsets are marked as read. 5658 */ 5659 static int check_stack_range_initialized( 5660 struct bpf_verifier_env *env, int regno, int off, 5661 int access_size, bool zero_size_allowed, 5662 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 5663 { 5664 struct bpf_reg_state *reg = reg_state(env, regno); 5665 struct bpf_func_state *state = func(env, reg); 5666 int err, min_off, max_off, i, j, slot, spi; 5667 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 5668 enum bpf_access_type bounds_check_type; 5669 /* Some accesses can write anything into the stack, others are 5670 * read-only. 5671 */ 5672 bool clobber = false; 5673 5674 if (access_size == 0 && !zero_size_allowed) { 5675 verbose(env, "invalid zero-sized read\n"); 5676 return -EACCES; 5677 } 5678 5679 if (type == ACCESS_HELPER) { 5680 /* The bounds checks for writes are more permissive than for 5681 * reads. However, if raw_mode is not set, we'll do extra 5682 * checks below. 5683 */ 5684 bounds_check_type = BPF_WRITE; 5685 clobber = true; 5686 } else { 5687 bounds_check_type = BPF_READ; 5688 } 5689 err = check_stack_access_within_bounds(env, regno, off, access_size, 5690 type, bounds_check_type); 5691 if (err) 5692 return err; 5693 5694 5695 if (tnum_is_const(reg->var_off)) { 5696 min_off = max_off = reg->var_off.value + off; 5697 } else { 5698 /* Variable offset is prohibited for unprivileged mode for 5699 * simplicity since it requires corresponding support in 5700 * Spectre masking for stack ALU. 5701 * See also retrieve_ptr_limit(). 5702 */ 5703 if (!env->bypass_spec_v1) { 5704 char tn_buf[48]; 5705 5706 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5707 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 5708 regno, err_extra, tn_buf); 5709 return -EACCES; 5710 } 5711 /* Only initialized buffer on stack is allowed to be accessed 5712 * with variable offset. With uninitialized buffer it's hard to 5713 * guarantee that whole memory is marked as initialized on 5714 * helper return since specific bounds are unknown what may 5715 * cause uninitialized stack leaking. 5716 */ 5717 if (meta && meta->raw_mode) 5718 meta = NULL; 5719 5720 min_off = reg->smin_value + off; 5721 max_off = reg->smax_value + off; 5722 } 5723 5724 if (meta && meta->raw_mode) { 5725 /* Ensure we won't be overwriting dynptrs when simulating byte 5726 * by byte access in check_helper_call using meta.access_size. 5727 * This would be a problem if we have a helper in the future 5728 * which takes: 5729 * 5730 * helper(uninit_mem, len, dynptr) 5731 * 5732 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 5733 * may end up writing to dynptr itself when touching memory from 5734 * arg 1. This can be relaxed on a case by case basis for known 5735 * safe cases, but reject due to the possibilitiy of aliasing by 5736 * default. 5737 */ 5738 for (i = min_off; i < max_off + access_size; i++) { 5739 int stack_off = -i - 1; 5740 5741 spi = __get_spi(i); 5742 /* raw_mode may write past allocated_stack */ 5743 if (state->allocated_stack <= stack_off) 5744 continue; 5745 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 5746 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 5747 return -EACCES; 5748 } 5749 } 5750 meta->access_size = access_size; 5751 meta->regno = regno; 5752 return 0; 5753 } 5754 5755 for (i = min_off; i < max_off + access_size; i++) { 5756 u8 *stype; 5757 5758 slot = -i - 1; 5759 spi = slot / BPF_REG_SIZE; 5760 if (state->allocated_stack <= slot) 5761 goto err; 5762 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 5763 if (*stype == STACK_MISC) 5764 goto mark; 5765 if ((*stype == STACK_ZERO) || 5766 (*stype == STACK_INVALID && env->allow_uninit_stack)) { 5767 if (clobber) { 5768 /* helper can write anything into the stack */ 5769 *stype = STACK_MISC; 5770 } 5771 goto mark; 5772 } 5773 5774 if (is_spilled_reg(&state->stack[spi]) && 5775 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 5776 env->allow_ptr_leaks)) { 5777 if (clobber) { 5778 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 5779 for (j = 0; j < BPF_REG_SIZE; j++) 5780 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 5781 } 5782 goto mark; 5783 } 5784 5785 err: 5786 if (tnum_is_const(reg->var_off)) { 5787 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 5788 err_extra, regno, min_off, i - min_off, access_size); 5789 } else { 5790 char tn_buf[48]; 5791 5792 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5793 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 5794 err_extra, regno, tn_buf, i - min_off, access_size); 5795 } 5796 return -EACCES; 5797 mark: 5798 /* reading any byte out of 8-byte 'spill_slot' will cause 5799 * the whole slot to be marked as 'read' 5800 */ 5801 mark_reg_read(env, &state->stack[spi].spilled_ptr, 5802 state->stack[spi].spilled_ptr.parent, 5803 REG_LIVE_READ64); 5804 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 5805 * be sure that whether stack slot is written to or not. Hence, 5806 * we must still conservatively propagate reads upwards even if 5807 * helper may write to the entire memory range. 5808 */ 5809 } 5810 return update_stack_depth(env, state, min_off); 5811 } 5812 5813 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 5814 int access_size, bool zero_size_allowed, 5815 struct bpf_call_arg_meta *meta) 5816 { 5817 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5818 u32 *max_access; 5819 5820 switch (base_type(reg->type)) { 5821 case PTR_TO_PACKET: 5822 case PTR_TO_PACKET_META: 5823 return check_packet_access(env, regno, reg->off, access_size, 5824 zero_size_allowed); 5825 case PTR_TO_MAP_KEY: 5826 if (meta && meta->raw_mode) { 5827 verbose(env, "R%d cannot write into %s\n", regno, 5828 reg_type_str(env, reg->type)); 5829 return -EACCES; 5830 } 5831 return check_mem_region_access(env, regno, reg->off, access_size, 5832 reg->map_ptr->key_size, false); 5833 case PTR_TO_MAP_VALUE: 5834 if (check_map_access_type(env, regno, reg->off, access_size, 5835 meta && meta->raw_mode ? BPF_WRITE : 5836 BPF_READ)) 5837 return -EACCES; 5838 return check_map_access(env, regno, reg->off, access_size, 5839 zero_size_allowed, ACCESS_HELPER); 5840 case PTR_TO_MEM: 5841 if (type_is_rdonly_mem(reg->type)) { 5842 if (meta && meta->raw_mode) { 5843 verbose(env, "R%d cannot write into %s\n", regno, 5844 reg_type_str(env, reg->type)); 5845 return -EACCES; 5846 } 5847 } 5848 return check_mem_region_access(env, regno, reg->off, 5849 access_size, reg->mem_size, 5850 zero_size_allowed); 5851 case PTR_TO_BUF: 5852 if (type_is_rdonly_mem(reg->type)) { 5853 if (meta && meta->raw_mode) { 5854 verbose(env, "R%d cannot write into %s\n", regno, 5855 reg_type_str(env, reg->type)); 5856 return -EACCES; 5857 } 5858 5859 max_access = &env->prog->aux->max_rdonly_access; 5860 } else { 5861 max_access = &env->prog->aux->max_rdwr_access; 5862 } 5863 return check_buffer_access(env, reg, regno, reg->off, 5864 access_size, zero_size_allowed, 5865 max_access); 5866 case PTR_TO_STACK: 5867 return check_stack_range_initialized( 5868 env, 5869 regno, reg->off, access_size, 5870 zero_size_allowed, ACCESS_HELPER, meta); 5871 case PTR_TO_CTX: 5872 /* in case the function doesn't know how to access the context, 5873 * (because we are in a program of type SYSCALL for example), we 5874 * can not statically check its size. 5875 * Dynamically check it now. 5876 */ 5877 if (!env->ops->convert_ctx_access) { 5878 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 5879 int offset = access_size - 1; 5880 5881 /* Allow zero-byte read from PTR_TO_CTX */ 5882 if (access_size == 0) 5883 return zero_size_allowed ? 0 : -EACCES; 5884 5885 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 5886 atype, -1, false); 5887 } 5888 5889 fallthrough; 5890 default: /* scalar_value or invalid ptr */ 5891 /* Allow zero-byte read from NULL, regardless of pointer type */ 5892 if (zero_size_allowed && access_size == 0 && 5893 register_is_null(reg)) 5894 return 0; 5895 5896 verbose(env, "R%d type=%s ", regno, 5897 reg_type_str(env, reg->type)); 5898 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 5899 return -EACCES; 5900 } 5901 } 5902 5903 static int check_mem_size_reg(struct bpf_verifier_env *env, 5904 struct bpf_reg_state *reg, u32 regno, 5905 bool zero_size_allowed, 5906 struct bpf_call_arg_meta *meta) 5907 { 5908 int err; 5909 5910 /* This is used to refine r0 return value bounds for helpers 5911 * that enforce this value as an upper bound on return values. 5912 * See do_refine_retval_range() for helpers that can refine 5913 * the return value. C type of helper is u32 so we pull register 5914 * bound from umax_value however, if negative verifier errors 5915 * out. Only upper bounds can be learned because retval is an 5916 * int type and negative retvals are allowed. 5917 */ 5918 meta->msize_max_value = reg->umax_value; 5919 5920 /* The register is SCALAR_VALUE; the access check 5921 * happens using its boundaries. 5922 */ 5923 if (!tnum_is_const(reg->var_off)) 5924 /* For unprivileged variable accesses, disable raw 5925 * mode so that the program is required to 5926 * initialize all the memory that the helper could 5927 * just partially fill up. 5928 */ 5929 meta = NULL; 5930 5931 if (reg->smin_value < 0) { 5932 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 5933 regno); 5934 return -EACCES; 5935 } 5936 5937 if (reg->umin_value == 0) { 5938 err = check_helper_mem_access(env, regno - 1, 0, 5939 zero_size_allowed, 5940 meta); 5941 if (err) 5942 return err; 5943 } 5944 5945 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 5946 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 5947 regno); 5948 return -EACCES; 5949 } 5950 err = check_helper_mem_access(env, regno - 1, 5951 reg->umax_value, 5952 zero_size_allowed, meta); 5953 if (!err) 5954 err = mark_chain_precision(env, regno); 5955 return err; 5956 } 5957 5958 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5959 u32 regno, u32 mem_size) 5960 { 5961 bool may_be_null = type_may_be_null(reg->type); 5962 struct bpf_reg_state saved_reg; 5963 struct bpf_call_arg_meta meta; 5964 int err; 5965 5966 if (register_is_null(reg)) 5967 return 0; 5968 5969 memset(&meta, 0, sizeof(meta)); 5970 /* Assuming that the register contains a value check if the memory 5971 * access is safe. Temporarily save and restore the register's state as 5972 * the conversion shouldn't be visible to a caller. 5973 */ 5974 if (may_be_null) { 5975 saved_reg = *reg; 5976 mark_ptr_not_null_reg(reg); 5977 } 5978 5979 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 5980 /* Check access for BPF_WRITE */ 5981 meta.raw_mode = true; 5982 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 5983 5984 if (may_be_null) 5985 *reg = saved_reg; 5986 5987 return err; 5988 } 5989 5990 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5991 u32 regno) 5992 { 5993 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 5994 bool may_be_null = type_may_be_null(mem_reg->type); 5995 struct bpf_reg_state saved_reg; 5996 struct bpf_call_arg_meta meta; 5997 int err; 5998 5999 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 6000 6001 memset(&meta, 0, sizeof(meta)); 6002 6003 if (may_be_null) { 6004 saved_reg = *mem_reg; 6005 mark_ptr_not_null_reg(mem_reg); 6006 } 6007 6008 err = check_mem_size_reg(env, reg, regno, true, &meta); 6009 /* Check access for BPF_WRITE */ 6010 meta.raw_mode = true; 6011 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 6012 6013 if (may_be_null) 6014 *mem_reg = saved_reg; 6015 return err; 6016 } 6017 6018 /* Implementation details: 6019 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 6020 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 6021 * Two bpf_map_lookups (even with the same key) will have different reg->id. 6022 * Two separate bpf_obj_new will also have different reg->id. 6023 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 6024 * clears reg->id after value_or_null->value transition, since the verifier only 6025 * cares about the range of access to valid map value pointer and doesn't care 6026 * about actual address of the map element. 6027 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 6028 * reg->id > 0 after value_or_null->value transition. By doing so 6029 * two bpf_map_lookups will be considered two different pointers that 6030 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 6031 * returned from bpf_obj_new. 6032 * The verifier allows taking only one bpf_spin_lock at a time to avoid 6033 * dead-locks. 6034 * Since only one bpf_spin_lock is allowed the checks are simpler than 6035 * reg_is_refcounted() logic. The verifier needs to remember only 6036 * one spin_lock instead of array of acquired_refs. 6037 * cur_state->active_lock remembers which map value element or allocated 6038 * object got locked and clears it after bpf_spin_unlock. 6039 */ 6040 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 6041 bool is_lock) 6042 { 6043 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6044 struct bpf_verifier_state *cur = env->cur_state; 6045 bool is_const = tnum_is_const(reg->var_off); 6046 u64 val = reg->var_off.value; 6047 struct bpf_map *map = NULL; 6048 struct btf *btf = NULL; 6049 struct btf_record *rec; 6050 6051 if (!is_const) { 6052 verbose(env, 6053 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 6054 regno); 6055 return -EINVAL; 6056 } 6057 if (reg->type == PTR_TO_MAP_VALUE) { 6058 map = reg->map_ptr; 6059 if (!map->btf) { 6060 verbose(env, 6061 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 6062 map->name); 6063 return -EINVAL; 6064 } 6065 } else { 6066 btf = reg->btf; 6067 } 6068 6069 rec = reg_btf_record(reg); 6070 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 6071 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 6072 map ? map->name : "kptr"); 6073 return -EINVAL; 6074 } 6075 if (rec->spin_lock_off != val + reg->off) { 6076 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 6077 val + reg->off, rec->spin_lock_off); 6078 return -EINVAL; 6079 } 6080 if (is_lock) { 6081 if (cur->active_lock.ptr) { 6082 verbose(env, 6083 "Locking two bpf_spin_locks are not allowed\n"); 6084 return -EINVAL; 6085 } 6086 if (map) 6087 cur->active_lock.ptr = map; 6088 else 6089 cur->active_lock.ptr = btf; 6090 cur->active_lock.id = reg->id; 6091 } else { 6092 void *ptr; 6093 6094 if (map) 6095 ptr = map; 6096 else 6097 ptr = btf; 6098 6099 if (!cur->active_lock.ptr) { 6100 verbose(env, "bpf_spin_unlock without taking a lock\n"); 6101 return -EINVAL; 6102 } 6103 if (cur->active_lock.ptr != ptr || 6104 cur->active_lock.id != reg->id) { 6105 verbose(env, "bpf_spin_unlock of different lock\n"); 6106 return -EINVAL; 6107 } 6108 6109 invalidate_non_owning_refs(env); 6110 6111 cur->active_lock.ptr = NULL; 6112 cur->active_lock.id = 0; 6113 } 6114 return 0; 6115 } 6116 6117 static int process_timer_func(struct bpf_verifier_env *env, int regno, 6118 struct bpf_call_arg_meta *meta) 6119 { 6120 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6121 bool is_const = tnum_is_const(reg->var_off); 6122 struct bpf_map *map = reg->map_ptr; 6123 u64 val = reg->var_off.value; 6124 6125 if (!is_const) { 6126 verbose(env, 6127 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 6128 regno); 6129 return -EINVAL; 6130 } 6131 if (!map->btf) { 6132 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 6133 map->name); 6134 return -EINVAL; 6135 } 6136 if (!btf_record_has_field(map->record, BPF_TIMER)) { 6137 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 6138 return -EINVAL; 6139 } 6140 if (map->record->timer_off != val + reg->off) { 6141 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 6142 val + reg->off, map->record->timer_off); 6143 return -EINVAL; 6144 } 6145 if (meta->map_ptr) { 6146 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 6147 return -EFAULT; 6148 } 6149 meta->map_uid = reg->map_uid; 6150 meta->map_ptr = map; 6151 return 0; 6152 } 6153 6154 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 6155 struct bpf_call_arg_meta *meta) 6156 { 6157 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6158 struct bpf_map *map_ptr = reg->map_ptr; 6159 struct btf_field *kptr_field; 6160 u32 kptr_off; 6161 6162 if (!tnum_is_const(reg->var_off)) { 6163 verbose(env, 6164 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 6165 regno); 6166 return -EINVAL; 6167 } 6168 if (!map_ptr->btf) { 6169 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 6170 map_ptr->name); 6171 return -EINVAL; 6172 } 6173 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 6174 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 6175 return -EINVAL; 6176 } 6177 6178 meta->map_ptr = map_ptr; 6179 kptr_off = reg->off + reg->var_off.value; 6180 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 6181 if (!kptr_field) { 6182 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 6183 return -EACCES; 6184 } 6185 if (kptr_field->type != BPF_KPTR_REF) { 6186 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 6187 return -EACCES; 6188 } 6189 meta->kptr_field = kptr_field; 6190 return 0; 6191 } 6192 6193 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 6194 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 6195 * 6196 * In both cases we deal with the first 8 bytes, but need to mark the next 8 6197 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 6198 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 6199 * 6200 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 6201 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 6202 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 6203 * mutate the view of the dynptr and also possibly destroy it. In the latter 6204 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 6205 * memory that dynptr points to. 6206 * 6207 * The verifier will keep track both levels of mutation (bpf_dynptr's in 6208 * reg->type and the memory's in reg->dynptr.type), but there is no support for 6209 * readonly dynptr view yet, hence only the first case is tracked and checked. 6210 * 6211 * This is consistent with how C applies the const modifier to a struct object, 6212 * where the pointer itself inside bpf_dynptr becomes const but not what it 6213 * points to. 6214 * 6215 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 6216 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 6217 */ 6218 int process_dynptr_func(struct bpf_verifier_env *env, int regno, 6219 enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) 6220 { 6221 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6222 int spi = 0; 6223 6224 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 6225 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 6226 */ 6227 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 6228 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 6229 return -EFAULT; 6230 } 6231 /* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 6232 * check_func_arg_reg_off's logic. We only need to check offset 6233 * and its alignment for PTR_TO_STACK. 6234 */ 6235 if (reg->type == PTR_TO_STACK) { 6236 spi = dynptr_get_spi(env, reg); 6237 if (spi < 0 && spi != -ERANGE) 6238 return spi; 6239 } 6240 6241 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 6242 * constructing a mutable bpf_dynptr object. 6243 * 6244 * Currently, this is only possible with PTR_TO_STACK 6245 * pointing to a region of at least 16 bytes which doesn't 6246 * contain an existing bpf_dynptr. 6247 * 6248 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 6249 * mutated or destroyed. However, the memory it points to 6250 * may be mutated. 6251 * 6252 * None - Points to a initialized dynptr that can be mutated and 6253 * destroyed, including mutation of the memory it points 6254 * to. 6255 */ 6256 if (arg_type & MEM_UNINIT) { 6257 if (!is_dynptr_reg_valid_uninit(env, reg, spi)) { 6258 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 6259 return -EINVAL; 6260 } 6261 6262 /* We only support one dynptr being uninitialized at the moment, 6263 * which is sufficient for the helper functions we have right now. 6264 */ 6265 if (meta->uninit_dynptr_regno) { 6266 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n"); 6267 return -EFAULT; 6268 } 6269 6270 meta->uninit_dynptr_regno = regno; 6271 } else /* MEM_RDONLY and None case from above */ { 6272 int err; 6273 6274 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 6275 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 6276 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 6277 return -EINVAL; 6278 } 6279 6280 if (!is_dynptr_reg_valid_init(env, reg, spi)) { 6281 verbose(env, 6282 "Expected an initialized dynptr as arg #%d\n", 6283 regno); 6284 return -EINVAL; 6285 } 6286 6287 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 6288 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 6289 const char *err_extra = ""; 6290 6291 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 6292 case DYNPTR_TYPE_LOCAL: 6293 err_extra = "local"; 6294 break; 6295 case DYNPTR_TYPE_RINGBUF: 6296 err_extra = "ringbuf"; 6297 break; 6298 default: 6299 err_extra = "<unknown>"; 6300 break; 6301 } 6302 verbose(env, 6303 "Expected a dynptr of type %s as arg #%d\n", 6304 err_extra, regno); 6305 return -EINVAL; 6306 } 6307 6308 err = mark_dynptr_read(env, reg); 6309 if (err) 6310 return err; 6311 } 6312 return 0; 6313 } 6314 6315 static bool arg_type_is_mem_size(enum bpf_arg_type type) 6316 { 6317 return type == ARG_CONST_SIZE || 6318 type == ARG_CONST_SIZE_OR_ZERO; 6319 } 6320 6321 static bool arg_type_is_release(enum bpf_arg_type type) 6322 { 6323 return type & OBJ_RELEASE; 6324 } 6325 6326 static bool arg_type_is_dynptr(enum bpf_arg_type type) 6327 { 6328 return base_type(type) == ARG_PTR_TO_DYNPTR; 6329 } 6330 6331 static int int_ptr_type_to_size(enum bpf_arg_type type) 6332 { 6333 if (type == ARG_PTR_TO_INT) 6334 return sizeof(u32); 6335 else if (type == ARG_PTR_TO_LONG) 6336 return sizeof(u64); 6337 6338 return -EINVAL; 6339 } 6340 6341 static int resolve_map_arg_type(struct bpf_verifier_env *env, 6342 const struct bpf_call_arg_meta *meta, 6343 enum bpf_arg_type *arg_type) 6344 { 6345 if (!meta->map_ptr) { 6346 /* kernel subsystem misconfigured verifier */ 6347 verbose(env, "invalid map_ptr to access map->type\n"); 6348 return -EACCES; 6349 } 6350 6351 switch (meta->map_ptr->map_type) { 6352 case BPF_MAP_TYPE_SOCKMAP: 6353 case BPF_MAP_TYPE_SOCKHASH: 6354 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 6355 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 6356 } else { 6357 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 6358 return -EINVAL; 6359 } 6360 break; 6361 case BPF_MAP_TYPE_BLOOM_FILTER: 6362 if (meta->func_id == BPF_FUNC_map_peek_elem) 6363 *arg_type = ARG_PTR_TO_MAP_VALUE; 6364 break; 6365 default: 6366 break; 6367 } 6368 return 0; 6369 } 6370 6371 struct bpf_reg_types { 6372 const enum bpf_reg_type types[10]; 6373 u32 *btf_id; 6374 }; 6375 6376 static const struct bpf_reg_types sock_types = { 6377 .types = { 6378 PTR_TO_SOCK_COMMON, 6379 PTR_TO_SOCKET, 6380 PTR_TO_TCP_SOCK, 6381 PTR_TO_XDP_SOCK, 6382 }, 6383 }; 6384 6385 #ifdef CONFIG_NET 6386 static const struct bpf_reg_types btf_id_sock_common_types = { 6387 .types = { 6388 PTR_TO_SOCK_COMMON, 6389 PTR_TO_SOCKET, 6390 PTR_TO_TCP_SOCK, 6391 PTR_TO_XDP_SOCK, 6392 PTR_TO_BTF_ID, 6393 PTR_TO_BTF_ID | PTR_TRUSTED, 6394 }, 6395 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 6396 }; 6397 #endif 6398 6399 static const struct bpf_reg_types mem_types = { 6400 .types = { 6401 PTR_TO_STACK, 6402 PTR_TO_PACKET, 6403 PTR_TO_PACKET_META, 6404 PTR_TO_MAP_KEY, 6405 PTR_TO_MAP_VALUE, 6406 PTR_TO_MEM, 6407 PTR_TO_MEM | MEM_RINGBUF, 6408 PTR_TO_BUF, 6409 }, 6410 }; 6411 6412 static const struct bpf_reg_types int_ptr_types = { 6413 .types = { 6414 PTR_TO_STACK, 6415 PTR_TO_PACKET, 6416 PTR_TO_PACKET_META, 6417 PTR_TO_MAP_KEY, 6418 PTR_TO_MAP_VALUE, 6419 }, 6420 }; 6421 6422 static const struct bpf_reg_types spin_lock_types = { 6423 .types = { 6424 PTR_TO_MAP_VALUE, 6425 PTR_TO_BTF_ID | MEM_ALLOC, 6426 } 6427 }; 6428 6429 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 6430 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 6431 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 6432 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 6433 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 6434 static const struct bpf_reg_types btf_ptr_types = { 6435 .types = { 6436 PTR_TO_BTF_ID, 6437 PTR_TO_BTF_ID | PTR_TRUSTED, 6438 PTR_TO_BTF_ID | MEM_RCU, 6439 }, 6440 }; 6441 static const struct bpf_reg_types percpu_btf_ptr_types = { 6442 .types = { 6443 PTR_TO_BTF_ID | MEM_PERCPU, 6444 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 6445 } 6446 }; 6447 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 6448 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 6449 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 6450 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 6451 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 6452 static const struct bpf_reg_types dynptr_types = { 6453 .types = { 6454 PTR_TO_STACK, 6455 CONST_PTR_TO_DYNPTR, 6456 } 6457 }; 6458 6459 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 6460 [ARG_PTR_TO_MAP_KEY] = &mem_types, 6461 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 6462 [ARG_CONST_SIZE] = &scalar_types, 6463 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 6464 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 6465 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 6466 [ARG_PTR_TO_CTX] = &context_types, 6467 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 6468 #ifdef CONFIG_NET 6469 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 6470 #endif 6471 [ARG_PTR_TO_SOCKET] = &fullsock_types, 6472 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 6473 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 6474 [ARG_PTR_TO_MEM] = &mem_types, 6475 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 6476 [ARG_PTR_TO_INT] = &int_ptr_types, 6477 [ARG_PTR_TO_LONG] = &int_ptr_types, 6478 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 6479 [ARG_PTR_TO_FUNC] = &func_ptr_types, 6480 [ARG_PTR_TO_STACK] = &stack_ptr_types, 6481 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 6482 [ARG_PTR_TO_TIMER] = &timer_types, 6483 [ARG_PTR_TO_KPTR] = &kptr_types, 6484 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 6485 }; 6486 6487 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 6488 enum bpf_arg_type arg_type, 6489 const u32 *arg_btf_id, 6490 struct bpf_call_arg_meta *meta) 6491 { 6492 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6493 enum bpf_reg_type expected, type = reg->type; 6494 const struct bpf_reg_types *compatible; 6495 int i, j; 6496 6497 compatible = compatible_reg_types[base_type(arg_type)]; 6498 if (!compatible) { 6499 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 6500 return -EFAULT; 6501 } 6502 6503 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 6504 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 6505 * 6506 * Same for MAYBE_NULL: 6507 * 6508 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 6509 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 6510 * 6511 * Therefore we fold these flags depending on the arg_type before comparison. 6512 */ 6513 if (arg_type & MEM_RDONLY) 6514 type &= ~MEM_RDONLY; 6515 if (arg_type & PTR_MAYBE_NULL) 6516 type &= ~PTR_MAYBE_NULL; 6517 6518 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 6519 expected = compatible->types[i]; 6520 if (expected == NOT_INIT) 6521 break; 6522 6523 if (type == expected) 6524 goto found; 6525 } 6526 6527 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 6528 for (j = 0; j + 1 < i; j++) 6529 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 6530 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 6531 return -EACCES; 6532 6533 found: 6534 if (base_type(reg->type) != PTR_TO_BTF_ID) 6535 return 0; 6536 6537 switch ((int)reg->type) { 6538 case PTR_TO_BTF_ID: 6539 case PTR_TO_BTF_ID | PTR_TRUSTED: 6540 case PTR_TO_BTF_ID | MEM_RCU: 6541 { 6542 /* For bpf_sk_release, it needs to match against first member 6543 * 'struct sock_common', hence make an exception for it. This 6544 * allows bpf_sk_release to work for multiple socket types. 6545 */ 6546 bool strict_type_match = arg_type_is_release(arg_type) && 6547 meta->func_id != BPF_FUNC_sk_release; 6548 6549 if (!arg_btf_id) { 6550 if (!compatible->btf_id) { 6551 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 6552 return -EFAULT; 6553 } 6554 arg_btf_id = compatible->btf_id; 6555 } 6556 6557 if (meta->func_id == BPF_FUNC_kptr_xchg) { 6558 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 6559 return -EACCES; 6560 } else { 6561 if (arg_btf_id == BPF_PTR_POISON) { 6562 verbose(env, "verifier internal error:"); 6563 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 6564 regno); 6565 return -EACCES; 6566 } 6567 6568 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 6569 btf_vmlinux, *arg_btf_id, 6570 strict_type_match)) { 6571 verbose(env, "R%d is of type %s but %s is expected\n", 6572 regno, kernel_type_name(reg->btf, reg->btf_id), 6573 kernel_type_name(btf_vmlinux, *arg_btf_id)); 6574 return -EACCES; 6575 } 6576 } 6577 break; 6578 } 6579 case PTR_TO_BTF_ID | MEM_ALLOC: 6580 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) { 6581 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 6582 return -EFAULT; 6583 } 6584 /* Handled by helper specific checks */ 6585 break; 6586 case PTR_TO_BTF_ID | MEM_PERCPU: 6587 case PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED: 6588 /* Handled by helper specific checks */ 6589 break; 6590 default: 6591 verbose(env, "verifier internal error: invalid PTR_TO_BTF_ID register for type match\n"); 6592 return -EFAULT; 6593 } 6594 return 0; 6595 } 6596 6597 static struct btf_field * 6598 reg_find_field_offset(const struct bpf_reg_state *reg, s32 off, u32 fields) 6599 { 6600 struct btf_field *field; 6601 struct btf_record *rec; 6602 6603 rec = reg_btf_record(reg); 6604 if (!rec) 6605 return NULL; 6606 6607 field = btf_record_find(rec, off, fields); 6608 if (!field) 6609 return NULL; 6610 6611 return field; 6612 } 6613 6614 int check_func_arg_reg_off(struct bpf_verifier_env *env, 6615 const struct bpf_reg_state *reg, int regno, 6616 enum bpf_arg_type arg_type) 6617 { 6618 u32 type = reg->type; 6619 6620 /* When referenced register is passed to release function, its fixed 6621 * offset must be 0. 6622 * 6623 * We will check arg_type_is_release reg has ref_obj_id when storing 6624 * meta->release_regno. 6625 */ 6626 if (arg_type_is_release(arg_type)) { 6627 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 6628 * may not directly point to the object being released, but to 6629 * dynptr pointing to such object, which might be at some offset 6630 * on the stack. In that case, we simply to fallback to the 6631 * default handling. 6632 */ 6633 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 6634 return 0; 6635 6636 if ((type_is_ptr_alloc_obj(type) || type_is_non_owning_ref(type)) && reg->off) { 6637 if (reg_find_field_offset(reg, reg->off, BPF_GRAPH_NODE_OR_ROOT)) 6638 return __check_ptr_off_reg(env, reg, regno, true); 6639 6640 verbose(env, "R%d must have zero offset when passed to release func\n", 6641 regno); 6642 verbose(env, "No graph node or root found at R%d type:%s off:%d\n", regno, 6643 kernel_type_name(reg->btf, reg->btf_id), reg->off); 6644 return -EINVAL; 6645 } 6646 6647 /* Doing check_ptr_off_reg check for the offset will catch this 6648 * because fixed_off_ok is false, but checking here allows us 6649 * to give the user a better error message. 6650 */ 6651 if (reg->off) { 6652 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 6653 regno); 6654 return -EINVAL; 6655 } 6656 return __check_ptr_off_reg(env, reg, regno, false); 6657 } 6658 6659 switch (type) { 6660 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 6661 case PTR_TO_STACK: 6662 case PTR_TO_PACKET: 6663 case PTR_TO_PACKET_META: 6664 case PTR_TO_MAP_KEY: 6665 case PTR_TO_MAP_VALUE: 6666 case PTR_TO_MEM: 6667 case PTR_TO_MEM | MEM_RDONLY: 6668 case PTR_TO_MEM | MEM_RINGBUF: 6669 case PTR_TO_BUF: 6670 case PTR_TO_BUF | MEM_RDONLY: 6671 case SCALAR_VALUE: 6672 return 0; 6673 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 6674 * fixed offset. 6675 */ 6676 case PTR_TO_BTF_ID: 6677 case PTR_TO_BTF_ID | MEM_ALLOC: 6678 case PTR_TO_BTF_ID | PTR_TRUSTED: 6679 case PTR_TO_BTF_ID | MEM_RCU: 6680 case PTR_TO_BTF_ID | MEM_ALLOC | NON_OWN_REF: 6681 /* When referenced PTR_TO_BTF_ID is passed to release function, 6682 * its fixed offset must be 0. In the other cases, fixed offset 6683 * can be non-zero. This was already checked above. So pass 6684 * fixed_off_ok as true to allow fixed offset for all other 6685 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 6686 * still need to do checks instead of returning. 6687 */ 6688 return __check_ptr_off_reg(env, reg, regno, true); 6689 default: 6690 return __check_ptr_off_reg(env, reg, regno, false); 6691 } 6692 } 6693 6694 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 6695 { 6696 struct bpf_func_state *state = func(env, reg); 6697 int spi; 6698 6699 if (reg->type == CONST_PTR_TO_DYNPTR) 6700 return reg->id; 6701 spi = dynptr_get_spi(env, reg); 6702 if (spi < 0) 6703 return spi; 6704 return state->stack[spi].spilled_ptr.id; 6705 } 6706 6707 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 6708 { 6709 struct bpf_func_state *state = func(env, reg); 6710 int spi; 6711 6712 if (reg->type == CONST_PTR_TO_DYNPTR) 6713 return reg->ref_obj_id; 6714 spi = dynptr_get_spi(env, reg); 6715 if (spi < 0) 6716 return spi; 6717 return state->stack[spi].spilled_ptr.ref_obj_id; 6718 } 6719 6720 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 6721 struct bpf_call_arg_meta *meta, 6722 const struct bpf_func_proto *fn) 6723 { 6724 u32 regno = BPF_REG_1 + arg; 6725 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6726 enum bpf_arg_type arg_type = fn->arg_type[arg]; 6727 enum bpf_reg_type type = reg->type; 6728 u32 *arg_btf_id = NULL; 6729 int err = 0; 6730 6731 if (arg_type == ARG_DONTCARE) 6732 return 0; 6733 6734 err = check_reg_arg(env, regno, SRC_OP); 6735 if (err) 6736 return err; 6737 6738 if (arg_type == ARG_ANYTHING) { 6739 if (is_pointer_value(env, regno)) { 6740 verbose(env, "R%d leaks addr into helper function\n", 6741 regno); 6742 return -EACCES; 6743 } 6744 return 0; 6745 } 6746 6747 if (type_is_pkt_pointer(type) && 6748 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 6749 verbose(env, "helper access to the packet is not allowed\n"); 6750 return -EACCES; 6751 } 6752 6753 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 6754 err = resolve_map_arg_type(env, meta, &arg_type); 6755 if (err) 6756 return err; 6757 } 6758 6759 if (register_is_null(reg) && type_may_be_null(arg_type)) 6760 /* A NULL register has a SCALAR_VALUE type, so skip 6761 * type checking. 6762 */ 6763 goto skip_type_check; 6764 6765 /* arg_btf_id and arg_size are in a union. */ 6766 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 6767 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 6768 arg_btf_id = fn->arg_btf_id[arg]; 6769 6770 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 6771 if (err) 6772 return err; 6773 6774 err = check_func_arg_reg_off(env, reg, regno, arg_type); 6775 if (err) 6776 return err; 6777 6778 skip_type_check: 6779 if (arg_type_is_release(arg_type)) { 6780 if (arg_type_is_dynptr(arg_type)) { 6781 struct bpf_func_state *state = func(env, reg); 6782 int spi; 6783 6784 /* Only dynptr created on stack can be released, thus 6785 * the get_spi and stack state checks for spilled_ptr 6786 * should only be done before process_dynptr_func for 6787 * PTR_TO_STACK. 6788 */ 6789 if (reg->type == PTR_TO_STACK) { 6790 spi = dynptr_get_spi(env, reg); 6791 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 6792 verbose(env, "arg %d is an unacquired reference\n", regno); 6793 return -EINVAL; 6794 } 6795 } else { 6796 verbose(env, "cannot release unowned const bpf_dynptr\n"); 6797 return -EINVAL; 6798 } 6799 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 6800 verbose(env, "R%d must be referenced when passed to release function\n", 6801 regno); 6802 return -EINVAL; 6803 } 6804 if (meta->release_regno) { 6805 verbose(env, "verifier internal error: more than one release argument\n"); 6806 return -EFAULT; 6807 } 6808 meta->release_regno = regno; 6809 } 6810 6811 if (reg->ref_obj_id) { 6812 if (meta->ref_obj_id) { 6813 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 6814 regno, reg->ref_obj_id, 6815 meta->ref_obj_id); 6816 return -EFAULT; 6817 } 6818 meta->ref_obj_id = reg->ref_obj_id; 6819 } 6820 6821 switch (base_type(arg_type)) { 6822 case ARG_CONST_MAP_PTR: 6823 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 6824 if (meta->map_ptr) { 6825 /* Use map_uid (which is unique id of inner map) to reject: 6826 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 6827 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 6828 * if (inner_map1 && inner_map2) { 6829 * timer = bpf_map_lookup_elem(inner_map1); 6830 * if (timer) 6831 * // mismatch would have been allowed 6832 * bpf_timer_init(timer, inner_map2); 6833 * } 6834 * 6835 * Comparing map_ptr is enough to distinguish normal and outer maps. 6836 */ 6837 if (meta->map_ptr != reg->map_ptr || 6838 meta->map_uid != reg->map_uid) { 6839 verbose(env, 6840 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 6841 meta->map_uid, reg->map_uid); 6842 return -EINVAL; 6843 } 6844 } 6845 meta->map_ptr = reg->map_ptr; 6846 meta->map_uid = reg->map_uid; 6847 break; 6848 case ARG_PTR_TO_MAP_KEY: 6849 /* bpf_map_xxx(..., map_ptr, ..., key) call: 6850 * check that [key, key + map->key_size) are within 6851 * stack limits and initialized 6852 */ 6853 if (!meta->map_ptr) { 6854 /* in function declaration map_ptr must come before 6855 * map_key, so that it's verified and known before 6856 * we have to check map_key here. Otherwise it means 6857 * that kernel subsystem misconfigured verifier 6858 */ 6859 verbose(env, "invalid map_ptr to access map->key\n"); 6860 return -EACCES; 6861 } 6862 err = check_helper_mem_access(env, regno, 6863 meta->map_ptr->key_size, false, 6864 NULL); 6865 break; 6866 case ARG_PTR_TO_MAP_VALUE: 6867 if (type_may_be_null(arg_type) && register_is_null(reg)) 6868 return 0; 6869 6870 /* bpf_map_xxx(..., map_ptr, ..., value) call: 6871 * check [value, value + map->value_size) validity 6872 */ 6873 if (!meta->map_ptr) { 6874 /* kernel subsystem misconfigured verifier */ 6875 verbose(env, "invalid map_ptr to access map->value\n"); 6876 return -EACCES; 6877 } 6878 meta->raw_mode = arg_type & MEM_UNINIT; 6879 err = check_helper_mem_access(env, regno, 6880 meta->map_ptr->value_size, false, 6881 meta); 6882 break; 6883 case ARG_PTR_TO_PERCPU_BTF_ID: 6884 if (!reg->btf_id) { 6885 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 6886 return -EACCES; 6887 } 6888 meta->ret_btf = reg->btf; 6889 meta->ret_btf_id = reg->btf_id; 6890 break; 6891 case ARG_PTR_TO_SPIN_LOCK: 6892 if (in_rbtree_lock_required_cb(env)) { 6893 verbose(env, "can't spin_{lock,unlock} in rbtree cb\n"); 6894 return -EACCES; 6895 } 6896 if (meta->func_id == BPF_FUNC_spin_lock) { 6897 err = process_spin_lock(env, regno, true); 6898 if (err) 6899 return err; 6900 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 6901 err = process_spin_lock(env, regno, false); 6902 if (err) 6903 return err; 6904 } else { 6905 verbose(env, "verifier internal error\n"); 6906 return -EFAULT; 6907 } 6908 break; 6909 case ARG_PTR_TO_TIMER: 6910 err = process_timer_func(env, regno, meta); 6911 if (err) 6912 return err; 6913 break; 6914 case ARG_PTR_TO_FUNC: 6915 meta->subprogno = reg->subprogno; 6916 break; 6917 case ARG_PTR_TO_MEM: 6918 /* The access to this pointer is only checked when we hit the 6919 * next is_mem_size argument below. 6920 */ 6921 meta->raw_mode = arg_type & MEM_UNINIT; 6922 if (arg_type & MEM_FIXED_SIZE) { 6923 err = check_helper_mem_access(env, regno, 6924 fn->arg_size[arg], false, 6925 meta); 6926 } 6927 break; 6928 case ARG_CONST_SIZE: 6929 err = check_mem_size_reg(env, reg, regno, false, meta); 6930 break; 6931 case ARG_CONST_SIZE_OR_ZERO: 6932 err = check_mem_size_reg(env, reg, regno, true, meta); 6933 break; 6934 case ARG_PTR_TO_DYNPTR: 6935 err = process_dynptr_func(env, regno, arg_type, meta); 6936 if (err) 6937 return err; 6938 break; 6939 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 6940 if (!tnum_is_const(reg->var_off)) { 6941 verbose(env, "R%d is not a known constant'\n", 6942 regno); 6943 return -EACCES; 6944 } 6945 meta->mem_size = reg->var_off.value; 6946 err = mark_chain_precision(env, regno); 6947 if (err) 6948 return err; 6949 break; 6950 case ARG_PTR_TO_INT: 6951 case ARG_PTR_TO_LONG: 6952 { 6953 int size = int_ptr_type_to_size(arg_type); 6954 6955 err = check_helper_mem_access(env, regno, size, false, meta); 6956 if (err) 6957 return err; 6958 err = check_ptr_alignment(env, reg, 0, size, true); 6959 break; 6960 } 6961 case ARG_PTR_TO_CONST_STR: 6962 { 6963 struct bpf_map *map = reg->map_ptr; 6964 int map_off; 6965 u64 map_addr; 6966 char *str_ptr; 6967 6968 if (!bpf_map_is_rdonly(map)) { 6969 verbose(env, "R%d does not point to a readonly map'\n", regno); 6970 return -EACCES; 6971 } 6972 6973 if (!tnum_is_const(reg->var_off)) { 6974 verbose(env, "R%d is not a constant address'\n", regno); 6975 return -EACCES; 6976 } 6977 6978 if (!map->ops->map_direct_value_addr) { 6979 verbose(env, "no direct value access support for this map type\n"); 6980 return -EACCES; 6981 } 6982 6983 err = check_map_access(env, regno, reg->off, 6984 map->value_size - reg->off, false, 6985 ACCESS_HELPER); 6986 if (err) 6987 return err; 6988 6989 map_off = reg->off + reg->var_off.value; 6990 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 6991 if (err) { 6992 verbose(env, "direct value access on string failed\n"); 6993 return err; 6994 } 6995 6996 str_ptr = (char *)(long)(map_addr); 6997 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 6998 verbose(env, "string is not zero-terminated\n"); 6999 return -EINVAL; 7000 } 7001 break; 7002 } 7003 case ARG_PTR_TO_KPTR: 7004 err = process_kptr_func(env, regno, meta); 7005 if (err) 7006 return err; 7007 break; 7008 } 7009 7010 return err; 7011 } 7012 7013 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 7014 { 7015 enum bpf_attach_type eatype = env->prog->expected_attach_type; 7016 enum bpf_prog_type type = resolve_prog_type(env->prog); 7017 7018 if (func_id != BPF_FUNC_map_update_elem) 7019 return false; 7020 7021 /* It's not possible to get access to a locked struct sock in these 7022 * contexts, so updating is safe. 7023 */ 7024 switch (type) { 7025 case BPF_PROG_TYPE_TRACING: 7026 if (eatype == BPF_TRACE_ITER) 7027 return true; 7028 break; 7029 case BPF_PROG_TYPE_SOCKET_FILTER: 7030 case BPF_PROG_TYPE_SCHED_CLS: 7031 case BPF_PROG_TYPE_SCHED_ACT: 7032 case BPF_PROG_TYPE_XDP: 7033 case BPF_PROG_TYPE_SK_REUSEPORT: 7034 case BPF_PROG_TYPE_FLOW_DISSECTOR: 7035 case BPF_PROG_TYPE_SK_LOOKUP: 7036 return true; 7037 default: 7038 break; 7039 } 7040 7041 verbose(env, "cannot update sockmap in this context\n"); 7042 return false; 7043 } 7044 7045 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 7046 { 7047 return env->prog->jit_requested && 7048 bpf_jit_supports_subprog_tailcalls(); 7049 } 7050 7051 static int check_map_func_compatibility(struct bpf_verifier_env *env, 7052 struct bpf_map *map, int func_id) 7053 { 7054 if (!map) 7055 return 0; 7056 7057 /* We need a two way check, first is from map perspective ... */ 7058 switch (map->map_type) { 7059 case BPF_MAP_TYPE_PROG_ARRAY: 7060 if (func_id != BPF_FUNC_tail_call) 7061 goto error; 7062 break; 7063 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 7064 if (func_id != BPF_FUNC_perf_event_read && 7065 func_id != BPF_FUNC_perf_event_output && 7066 func_id != BPF_FUNC_skb_output && 7067 func_id != BPF_FUNC_perf_event_read_value && 7068 func_id != BPF_FUNC_xdp_output) 7069 goto error; 7070 break; 7071 case BPF_MAP_TYPE_RINGBUF: 7072 if (func_id != BPF_FUNC_ringbuf_output && 7073 func_id != BPF_FUNC_ringbuf_reserve && 7074 func_id != BPF_FUNC_ringbuf_query && 7075 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 7076 func_id != BPF_FUNC_ringbuf_submit_dynptr && 7077 func_id != BPF_FUNC_ringbuf_discard_dynptr) 7078 goto error; 7079 break; 7080 case BPF_MAP_TYPE_USER_RINGBUF: 7081 if (func_id != BPF_FUNC_user_ringbuf_drain) 7082 goto error; 7083 break; 7084 case BPF_MAP_TYPE_STACK_TRACE: 7085 if (func_id != BPF_FUNC_get_stackid) 7086 goto error; 7087 break; 7088 case BPF_MAP_TYPE_CGROUP_ARRAY: 7089 if (func_id != BPF_FUNC_skb_under_cgroup && 7090 func_id != BPF_FUNC_current_task_under_cgroup) 7091 goto error; 7092 break; 7093 case BPF_MAP_TYPE_CGROUP_STORAGE: 7094 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 7095 if (func_id != BPF_FUNC_get_local_storage) 7096 goto error; 7097 break; 7098 case BPF_MAP_TYPE_DEVMAP: 7099 case BPF_MAP_TYPE_DEVMAP_HASH: 7100 if (func_id != BPF_FUNC_redirect_map && 7101 func_id != BPF_FUNC_map_lookup_elem) 7102 goto error; 7103 break; 7104 /* Restrict bpf side of cpumap and xskmap, open when use-cases 7105 * appear. 7106 */ 7107 case BPF_MAP_TYPE_CPUMAP: 7108 if (func_id != BPF_FUNC_redirect_map) 7109 goto error; 7110 break; 7111 case BPF_MAP_TYPE_XSKMAP: 7112 if (func_id != BPF_FUNC_redirect_map && 7113 func_id != BPF_FUNC_map_lookup_elem) 7114 goto error; 7115 break; 7116 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 7117 case BPF_MAP_TYPE_HASH_OF_MAPS: 7118 if (func_id != BPF_FUNC_map_lookup_elem) 7119 goto error; 7120 break; 7121 case BPF_MAP_TYPE_SOCKMAP: 7122 if (func_id != BPF_FUNC_sk_redirect_map && 7123 func_id != BPF_FUNC_sock_map_update && 7124 func_id != BPF_FUNC_map_delete_elem && 7125 func_id != BPF_FUNC_msg_redirect_map && 7126 func_id != BPF_FUNC_sk_select_reuseport && 7127 func_id != BPF_FUNC_map_lookup_elem && 7128 !may_update_sockmap(env, func_id)) 7129 goto error; 7130 break; 7131 case BPF_MAP_TYPE_SOCKHASH: 7132 if (func_id != BPF_FUNC_sk_redirect_hash && 7133 func_id != BPF_FUNC_sock_hash_update && 7134 func_id != BPF_FUNC_map_delete_elem && 7135 func_id != BPF_FUNC_msg_redirect_hash && 7136 func_id != BPF_FUNC_sk_select_reuseport && 7137 func_id != BPF_FUNC_map_lookup_elem && 7138 !may_update_sockmap(env, func_id)) 7139 goto error; 7140 break; 7141 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 7142 if (func_id != BPF_FUNC_sk_select_reuseport) 7143 goto error; 7144 break; 7145 case BPF_MAP_TYPE_QUEUE: 7146 case BPF_MAP_TYPE_STACK: 7147 if (func_id != BPF_FUNC_map_peek_elem && 7148 func_id != BPF_FUNC_map_pop_elem && 7149 func_id != BPF_FUNC_map_push_elem) 7150 goto error; 7151 break; 7152 case BPF_MAP_TYPE_SK_STORAGE: 7153 if (func_id != BPF_FUNC_sk_storage_get && 7154 func_id != BPF_FUNC_sk_storage_delete) 7155 goto error; 7156 break; 7157 case BPF_MAP_TYPE_INODE_STORAGE: 7158 if (func_id != BPF_FUNC_inode_storage_get && 7159 func_id != BPF_FUNC_inode_storage_delete) 7160 goto error; 7161 break; 7162 case BPF_MAP_TYPE_TASK_STORAGE: 7163 if (func_id != BPF_FUNC_task_storage_get && 7164 func_id != BPF_FUNC_task_storage_delete) 7165 goto error; 7166 break; 7167 case BPF_MAP_TYPE_CGRP_STORAGE: 7168 if (func_id != BPF_FUNC_cgrp_storage_get && 7169 func_id != BPF_FUNC_cgrp_storage_delete) 7170 goto error; 7171 break; 7172 case BPF_MAP_TYPE_BLOOM_FILTER: 7173 if (func_id != BPF_FUNC_map_peek_elem && 7174 func_id != BPF_FUNC_map_push_elem) 7175 goto error; 7176 break; 7177 default: 7178 break; 7179 } 7180 7181 /* ... and second from the function itself. */ 7182 switch (func_id) { 7183 case BPF_FUNC_tail_call: 7184 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 7185 goto error; 7186 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 7187 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 7188 return -EINVAL; 7189 } 7190 break; 7191 case BPF_FUNC_perf_event_read: 7192 case BPF_FUNC_perf_event_output: 7193 case BPF_FUNC_perf_event_read_value: 7194 case BPF_FUNC_skb_output: 7195 case BPF_FUNC_xdp_output: 7196 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 7197 goto error; 7198 break; 7199 case BPF_FUNC_ringbuf_output: 7200 case BPF_FUNC_ringbuf_reserve: 7201 case BPF_FUNC_ringbuf_query: 7202 case BPF_FUNC_ringbuf_reserve_dynptr: 7203 case BPF_FUNC_ringbuf_submit_dynptr: 7204 case BPF_FUNC_ringbuf_discard_dynptr: 7205 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 7206 goto error; 7207 break; 7208 case BPF_FUNC_user_ringbuf_drain: 7209 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 7210 goto error; 7211 break; 7212 case BPF_FUNC_get_stackid: 7213 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 7214 goto error; 7215 break; 7216 case BPF_FUNC_current_task_under_cgroup: 7217 case BPF_FUNC_skb_under_cgroup: 7218 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 7219 goto error; 7220 break; 7221 case BPF_FUNC_redirect_map: 7222 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 7223 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 7224 map->map_type != BPF_MAP_TYPE_CPUMAP && 7225 map->map_type != BPF_MAP_TYPE_XSKMAP) 7226 goto error; 7227 break; 7228 case BPF_FUNC_sk_redirect_map: 7229 case BPF_FUNC_msg_redirect_map: 7230 case BPF_FUNC_sock_map_update: 7231 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 7232 goto error; 7233 break; 7234 case BPF_FUNC_sk_redirect_hash: 7235 case BPF_FUNC_msg_redirect_hash: 7236 case BPF_FUNC_sock_hash_update: 7237 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 7238 goto error; 7239 break; 7240 case BPF_FUNC_get_local_storage: 7241 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 7242 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 7243 goto error; 7244 break; 7245 case BPF_FUNC_sk_select_reuseport: 7246 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 7247 map->map_type != BPF_MAP_TYPE_SOCKMAP && 7248 map->map_type != BPF_MAP_TYPE_SOCKHASH) 7249 goto error; 7250 break; 7251 case BPF_FUNC_map_pop_elem: 7252 if (map->map_type != BPF_MAP_TYPE_QUEUE && 7253 map->map_type != BPF_MAP_TYPE_STACK) 7254 goto error; 7255 break; 7256 case BPF_FUNC_map_peek_elem: 7257 case BPF_FUNC_map_push_elem: 7258 if (map->map_type != BPF_MAP_TYPE_QUEUE && 7259 map->map_type != BPF_MAP_TYPE_STACK && 7260 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 7261 goto error; 7262 break; 7263 case BPF_FUNC_map_lookup_percpu_elem: 7264 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 7265 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 7266 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 7267 goto error; 7268 break; 7269 case BPF_FUNC_sk_storage_get: 7270 case BPF_FUNC_sk_storage_delete: 7271 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 7272 goto error; 7273 break; 7274 case BPF_FUNC_inode_storage_get: 7275 case BPF_FUNC_inode_storage_delete: 7276 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 7277 goto error; 7278 break; 7279 case BPF_FUNC_task_storage_get: 7280 case BPF_FUNC_task_storage_delete: 7281 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 7282 goto error; 7283 break; 7284 case BPF_FUNC_cgrp_storage_get: 7285 case BPF_FUNC_cgrp_storage_delete: 7286 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 7287 goto error; 7288 break; 7289 default: 7290 break; 7291 } 7292 7293 return 0; 7294 error: 7295 verbose(env, "cannot pass map_type %d into func %s#%d\n", 7296 map->map_type, func_id_name(func_id), func_id); 7297 return -EINVAL; 7298 } 7299 7300 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 7301 { 7302 int count = 0; 7303 7304 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 7305 count++; 7306 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 7307 count++; 7308 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 7309 count++; 7310 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 7311 count++; 7312 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 7313 count++; 7314 7315 /* We only support one arg being in raw mode at the moment, 7316 * which is sufficient for the helper functions we have 7317 * right now. 7318 */ 7319 return count <= 1; 7320 } 7321 7322 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 7323 { 7324 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 7325 bool has_size = fn->arg_size[arg] != 0; 7326 bool is_next_size = false; 7327 7328 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 7329 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 7330 7331 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 7332 return is_next_size; 7333 7334 return has_size == is_next_size || is_next_size == is_fixed; 7335 } 7336 7337 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 7338 { 7339 /* bpf_xxx(..., buf, len) call will access 'len' 7340 * bytes from memory 'buf'. Both arg types need 7341 * to be paired, so make sure there's no buggy 7342 * helper function specification. 7343 */ 7344 if (arg_type_is_mem_size(fn->arg1_type) || 7345 check_args_pair_invalid(fn, 0) || 7346 check_args_pair_invalid(fn, 1) || 7347 check_args_pair_invalid(fn, 2) || 7348 check_args_pair_invalid(fn, 3) || 7349 check_args_pair_invalid(fn, 4)) 7350 return false; 7351 7352 return true; 7353 } 7354 7355 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 7356 { 7357 int i; 7358 7359 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 7360 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 7361 return !!fn->arg_btf_id[i]; 7362 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 7363 return fn->arg_btf_id[i] == BPF_PTR_POISON; 7364 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 7365 /* arg_btf_id and arg_size are in a union. */ 7366 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 7367 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 7368 return false; 7369 } 7370 7371 return true; 7372 } 7373 7374 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 7375 { 7376 return check_raw_mode_ok(fn) && 7377 check_arg_pair_ok(fn) && 7378 check_btf_id_ok(fn) ? 0 : -EINVAL; 7379 } 7380 7381 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 7382 * are now invalid, so turn them into unknown SCALAR_VALUE. 7383 */ 7384 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 7385 { 7386 struct bpf_func_state *state; 7387 struct bpf_reg_state *reg; 7388 7389 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 7390 if (reg_is_pkt_pointer_any(reg)) 7391 mark_reg_invalid(env, reg); 7392 })); 7393 } 7394 7395 enum { 7396 AT_PKT_END = -1, 7397 BEYOND_PKT_END = -2, 7398 }; 7399 7400 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 7401 { 7402 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7403 struct bpf_reg_state *reg = &state->regs[regn]; 7404 7405 if (reg->type != PTR_TO_PACKET) 7406 /* PTR_TO_PACKET_META is not supported yet */ 7407 return; 7408 7409 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 7410 * How far beyond pkt_end it goes is unknown. 7411 * if (!range_open) it's the case of pkt >= pkt_end 7412 * if (range_open) it's the case of pkt > pkt_end 7413 * hence this pointer is at least 1 byte bigger than pkt_end 7414 */ 7415 if (range_open) 7416 reg->range = BEYOND_PKT_END; 7417 else 7418 reg->range = AT_PKT_END; 7419 } 7420 7421 /* The pointer with the specified id has released its reference to kernel 7422 * resources. Identify all copies of the same pointer and clear the reference. 7423 */ 7424 static int release_reference(struct bpf_verifier_env *env, 7425 int ref_obj_id) 7426 { 7427 struct bpf_func_state *state; 7428 struct bpf_reg_state *reg; 7429 int err; 7430 7431 err = release_reference_state(cur_func(env), ref_obj_id); 7432 if (err) 7433 return err; 7434 7435 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 7436 if (reg->ref_obj_id == ref_obj_id) 7437 mark_reg_invalid(env, reg); 7438 })); 7439 7440 return 0; 7441 } 7442 7443 static void invalidate_non_owning_refs(struct bpf_verifier_env *env) 7444 { 7445 struct bpf_func_state *unused; 7446 struct bpf_reg_state *reg; 7447 7448 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 7449 if (type_is_non_owning_ref(reg->type)) 7450 mark_reg_invalid(env, reg); 7451 })); 7452 } 7453 7454 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 7455 struct bpf_reg_state *regs) 7456 { 7457 int i; 7458 7459 /* after the call registers r0 - r5 were scratched */ 7460 for (i = 0; i < CALLER_SAVED_REGS; i++) { 7461 mark_reg_not_init(env, regs, caller_saved[i]); 7462 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 7463 } 7464 } 7465 7466 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 7467 struct bpf_func_state *caller, 7468 struct bpf_func_state *callee, 7469 int insn_idx); 7470 7471 static int set_callee_state(struct bpf_verifier_env *env, 7472 struct bpf_func_state *caller, 7473 struct bpf_func_state *callee, int insn_idx); 7474 7475 static bool is_callback_calling_kfunc(u32 btf_id); 7476 7477 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7478 int *insn_idx, int subprog, 7479 set_callee_state_fn set_callee_state_cb) 7480 { 7481 struct bpf_verifier_state *state = env->cur_state; 7482 struct bpf_func_info_aux *func_info_aux; 7483 struct bpf_func_state *caller, *callee; 7484 int err; 7485 bool is_global = false; 7486 7487 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 7488 verbose(env, "the call stack of %d frames is too deep\n", 7489 state->curframe + 2); 7490 return -E2BIG; 7491 } 7492 7493 caller = state->frame[state->curframe]; 7494 if (state->frame[state->curframe + 1]) { 7495 verbose(env, "verifier bug. Frame %d already allocated\n", 7496 state->curframe + 1); 7497 return -EFAULT; 7498 } 7499 7500 func_info_aux = env->prog->aux->func_info_aux; 7501 if (func_info_aux) 7502 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 7503 err = btf_check_subprog_call(env, subprog, caller->regs); 7504 if (err == -EFAULT) 7505 return err; 7506 if (is_global) { 7507 if (err) { 7508 verbose(env, "Caller passes invalid args into func#%d\n", 7509 subprog); 7510 return err; 7511 } else { 7512 if (env->log.level & BPF_LOG_LEVEL) 7513 verbose(env, 7514 "Func#%d is global and valid. Skipping.\n", 7515 subprog); 7516 clear_caller_saved_regs(env, caller->regs); 7517 7518 /* All global functions return a 64-bit SCALAR_VALUE */ 7519 mark_reg_unknown(env, caller->regs, BPF_REG_0); 7520 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 7521 7522 /* continue with next insn after call */ 7523 return 0; 7524 } 7525 } 7526 7527 /* set_callee_state is used for direct subprog calls, but we are 7528 * interested in validating only BPF helpers that can call subprogs as 7529 * callbacks 7530 */ 7531 if (set_callee_state_cb != set_callee_state) { 7532 if (bpf_pseudo_kfunc_call(insn) && 7533 !is_callback_calling_kfunc(insn->imm)) { 7534 verbose(env, "verifier bug: kfunc %s#%d not marked as callback-calling\n", 7535 func_id_name(insn->imm), insn->imm); 7536 return -EFAULT; 7537 } else if (!bpf_pseudo_kfunc_call(insn) && 7538 !is_callback_calling_function(insn->imm)) { /* helper */ 7539 verbose(env, "verifier bug: helper %s#%d not marked as callback-calling\n", 7540 func_id_name(insn->imm), insn->imm); 7541 return -EFAULT; 7542 } 7543 } 7544 7545 if (insn->code == (BPF_JMP | BPF_CALL) && 7546 insn->src_reg == 0 && 7547 insn->imm == BPF_FUNC_timer_set_callback) { 7548 struct bpf_verifier_state *async_cb; 7549 7550 /* there is no real recursion here. timer callbacks are async */ 7551 env->subprog_info[subprog].is_async_cb = true; 7552 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 7553 *insn_idx, subprog); 7554 if (!async_cb) 7555 return -EFAULT; 7556 callee = async_cb->frame[0]; 7557 callee->async_entry_cnt = caller->async_entry_cnt + 1; 7558 7559 /* Convert bpf_timer_set_callback() args into timer callback args */ 7560 err = set_callee_state_cb(env, caller, callee, *insn_idx); 7561 if (err) 7562 return err; 7563 7564 clear_caller_saved_regs(env, caller->regs); 7565 mark_reg_unknown(env, caller->regs, BPF_REG_0); 7566 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 7567 /* continue with next insn after call */ 7568 return 0; 7569 } 7570 7571 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 7572 if (!callee) 7573 return -ENOMEM; 7574 state->frame[state->curframe + 1] = callee; 7575 7576 /* callee cannot access r0, r6 - r9 for reading and has to write 7577 * into its own stack before reading from it. 7578 * callee can read/write into caller's stack 7579 */ 7580 init_func_state(env, callee, 7581 /* remember the callsite, it will be used by bpf_exit */ 7582 *insn_idx /* callsite */, 7583 state->curframe + 1 /* frameno within this callchain */, 7584 subprog /* subprog number within this prog */); 7585 7586 /* Transfer references to the callee */ 7587 err = copy_reference_state(callee, caller); 7588 if (err) 7589 goto err_out; 7590 7591 err = set_callee_state_cb(env, caller, callee, *insn_idx); 7592 if (err) 7593 goto err_out; 7594 7595 clear_caller_saved_regs(env, caller->regs); 7596 7597 /* only increment it after check_reg_arg() finished */ 7598 state->curframe++; 7599 7600 /* and go analyze first insn of the callee */ 7601 *insn_idx = env->subprog_info[subprog].start - 1; 7602 7603 if (env->log.level & BPF_LOG_LEVEL) { 7604 verbose(env, "caller:\n"); 7605 print_verifier_state(env, caller, true); 7606 verbose(env, "callee:\n"); 7607 print_verifier_state(env, callee, true); 7608 } 7609 return 0; 7610 7611 err_out: 7612 free_func_state(callee); 7613 state->frame[state->curframe + 1] = NULL; 7614 return err; 7615 } 7616 7617 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 7618 struct bpf_func_state *caller, 7619 struct bpf_func_state *callee) 7620 { 7621 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 7622 * void *callback_ctx, u64 flags); 7623 * callback_fn(struct bpf_map *map, void *key, void *value, 7624 * void *callback_ctx); 7625 */ 7626 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 7627 7628 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 7629 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7630 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 7631 7632 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 7633 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 7634 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 7635 7636 /* pointer to stack or null */ 7637 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 7638 7639 /* unused */ 7640 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7641 return 0; 7642 } 7643 7644 static int set_callee_state(struct bpf_verifier_env *env, 7645 struct bpf_func_state *caller, 7646 struct bpf_func_state *callee, int insn_idx) 7647 { 7648 int i; 7649 7650 /* copy r1 - r5 args that callee can access. The copy includes parent 7651 * pointers, which connects us up to the liveness chain 7652 */ 7653 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 7654 callee->regs[i] = caller->regs[i]; 7655 return 0; 7656 } 7657 7658 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7659 int *insn_idx) 7660 { 7661 int subprog, target_insn; 7662 7663 target_insn = *insn_idx + insn->imm + 1; 7664 subprog = find_subprog(env, target_insn); 7665 if (subprog < 0) { 7666 verbose(env, "verifier bug. No program starts at insn %d\n", 7667 target_insn); 7668 return -EFAULT; 7669 } 7670 7671 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 7672 } 7673 7674 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 7675 struct bpf_func_state *caller, 7676 struct bpf_func_state *callee, 7677 int insn_idx) 7678 { 7679 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 7680 struct bpf_map *map; 7681 int err; 7682 7683 if (bpf_map_ptr_poisoned(insn_aux)) { 7684 verbose(env, "tail_call abusing map_ptr\n"); 7685 return -EINVAL; 7686 } 7687 7688 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 7689 if (!map->ops->map_set_for_each_callback_args || 7690 !map->ops->map_for_each_callback) { 7691 verbose(env, "callback function not allowed for map\n"); 7692 return -ENOTSUPP; 7693 } 7694 7695 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 7696 if (err) 7697 return err; 7698 7699 callee->in_callback_fn = true; 7700 callee->callback_ret_range = tnum_range(0, 1); 7701 return 0; 7702 } 7703 7704 static int set_loop_callback_state(struct bpf_verifier_env *env, 7705 struct bpf_func_state *caller, 7706 struct bpf_func_state *callee, 7707 int insn_idx) 7708 { 7709 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 7710 * u64 flags); 7711 * callback_fn(u32 index, void *callback_ctx); 7712 */ 7713 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 7714 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 7715 7716 /* unused */ 7717 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 7718 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7719 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7720 7721 callee->in_callback_fn = true; 7722 callee->callback_ret_range = tnum_range(0, 1); 7723 return 0; 7724 } 7725 7726 static int set_timer_callback_state(struct bpf_verifier_env *env, 7727 struct bpf_func_state *caller, 7728 struct bpf_func_state *callee, 7729 int insn_idx) 7730 { 7731 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 7732 7733 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 7734 * callback_fn(struct bpf_map *map, void *key, void *value); 7735 */ 7736 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 7737 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 7738 callee->regs[BPF_REG_1].map_ptr = map_ptr; 7739 7740 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 7741 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7742 callee->regs[BPF_REG_2].map_ptr = map_ptr; 7743 7744 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 7745 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 7746 callee->regs[BPF_REG_3].map_ptr = map_ptr; 7747 7748 /* unused */ 7749 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7750 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7751 callee->in_async_callback_fn = true; 7752 callee->callback_ret_range = tnum_range(0, 1); 7753 return 0; 7754 } 7755 7756 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 7757 struct bpf_func_state *caller, 7758 struct bpf_func_state *callee, 7759 int insn_idx) 7760 { 7761 /* bpf_find_vma(struct task_struct *task, u64 addr, 7762 * void *callback_fn, void *callback_ctx, u64 flags) 7763 * (callback_fn)(struct task_struct *task, 7764 * struct vm_area_struct *vma, void *callback_ctx); 7765 */ 7766 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 7767 7768 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 7769 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7770 callee->regs[BPF_REG_2].btf = btf_vmlinux; 7771 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 7772 7773 /* pointer to stack or null */ 7774 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 7775 7776 /* unused */ 7777 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7778 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7779 callee->in_callback_fn = true; 7780 callee->callback_ret_range = tnum_range(0, 1); 7781 return 0; 7782 } 7783 7784 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 7785 struct bpf_func_state *caller, 7786 struct bpf_func_state *callee, 7787 int insn_idx) 7788 { 7789 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 7790 * callback_ctx, u64 flags); 7791 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 7792 */ 7793 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 7794 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 7795 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 7796 7797 /* unused */ 7798 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 7799 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7800 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7801 7802 callee->in_callback_fn = true; 7803 callee->callback_ret_range = tnum_range(0, 1); 7804 return 0; 7805 } 7806 7807 static int set_rbtree_add_callback_state(struct bpf_verifier_env *env, 7808 struct bpf_func_state *caller, 7809 struct bpf_func_state *callee, 7810 int insn_idx) 7811 { 7812 /* void bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node, 7813 * bool (less)(struct bpf_rb_node *a, const struct bpf_rb_node *b)); 7814 * 7815 * 'struct bpf_rb_node *node' arg to bpf_rbtree_add is the same PTR_TO_BTF_ID w/ offset 7816 * that 'less' callback args will be receiving. However, 'node' arg was release_reference'd 7817 * by this point, so look at 'root' 7818 */ 7819 struct btf_field *field; 7820 7821 field = reg_find_field_offset(&caller->regs[BPF_REG_1], caller->regs[BPF_REG_1].off, 7822 BPF_RB_ROOT); 7823 if (!field || !field->graph_root.value_btf_id) 7824 return -EFAULT; 7825 7826 mark_reg_graph_node(callee->regs, BPF_REG_1, &field->graph_root); 7827 ref_set_non_owning(env, &callee->regs[BPF_REG_1]); 7828 mark_reg_graph_node(callee->regs, BPF_REG_2, &field->graph_root); 7829 ref_set_non_owning(env, &callee->regs[BPF_REG_2]); 7830 7831 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 7832 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7833 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7834 callee->in_callback_fn = true; 7835 callee->callback_ret_range = tnum_range(0, 1); 7836 return 0; 7837 } 7838 7839 static bool is_rbtree_lock_required_kfunc(u32 btf_id); 7840 7841 /* Are we currently verifying the callback for a rbtree helper that must 7842 * be called with lock held? If so, no need to complain about unreleased 7843 * lock 7844 */ 7845 static bool in_rbtree_lock_required_cb(struct bpf_verifier_env *env) 7846 { 7847 struct bpf_verifier_state *state = env->cur_state; 7848 struct bpf_insn *insn = env->prog->insnsi; 7849 struct bpf_func_state *callee; 7850 int kfunc_btf_id; 7851 7852 if (!state->curframe) 7853 return false; 7854 7855 callee = state->frame[state->curframe]; 7856 7857 if (!callee->in_callback_fn) 7858 return false; 7859 7860 kfunc_btf_id = insn[callee->callsite].imm; 7861 return is_rbtree_lock_required_kfunc(kfunc_btf_id); 7862 } 7863 7864 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 7865 { 7866 struct bpf_verifier_state *state = env->cur_state; 7867 struct bpf_func_state *caller, *callee; 7868 struct bpf_reg_state *r0; 7869 int err; 7870 7871 callee = state->frame[state->curframe]; 7872 r0 = &callee->regs[BPF_REG_0]; 7873 if (r0->type == PTR_TO_STACK) { 7874 /* technically it's ok to return caller's stack pointer 7875 * (or caller's caller's pointer) back to the caller, 7876 * since these pointers are valid. Only current stack 7877 * pointer will be invalid as soon as function exits, 7878 * but let's be conservative 7879 */ 7880 verbose(env, "cannot return stack pointer to the caller\n"); 7881 return -EINVAL; 7882 } 7883 7884 caller = state->frame[state->curframe - 1]; 7885 if (callee->in_callback_fn) { 7886 /* enforce R0 return value range [0, 1]. */ 7887 struct tnum range = callee->callback_ret_range; 7888 7889 if (r0->type != SCALAR_VALUE) { 7890 verbose(env, "R0 not a scalar value\n"); 7891 return -EACCES; 7892 } 7893 if (!tnum_in(range, r0->var_off)) { 7894 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 7895 return -EINVAL; 7896 } 7897 } else { 7898 /* return to the caller whatever r0 had in the callee */ 7899 caller->regs[BPF_REG_0] = *r0; 7900 } 7901 7902 /* callback_fn frame should have released its own additions to parent's 7903 * reference state at this point, or check_reference_leak would 7904 * complain, hence it must be the same as the caller. There is no need 7905 * to copy it back. 7906 */ 7907 if (!callee->in_callback_fn) { 7908 /* Transfer references to the caller */ 7909 err = copy_reference_state(caller, callee); 7910 if (err) 7911 return err; 7912 } 7913 7914 *insn_idx = callee->callsite + 1; 7915 if (env->log.level & BPF_LOG_LEVEL) { 7916 verbose(env, "returning from callee:\n"); 7917 print_verifier_state(env, callee, true); 7918 verbose(env, "to caller at %d:\n", *insn_idx); 7919 print_verifier_state(env, caller, true); 7920 } 7921 /* clear everything in the callee */ 7922 free_func_state(callee); 7923 state->frame[state->curframe--] = NULL; 7924 return 0; 7925 } 7926 7927 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 7928 int func_id, 7929 struct bpf_call_arg_meta *meta) 7930 { 7931 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 7932 7933 if (ret_type != RET_INTEGER || 7934 (func_id != BPF_FUNC_get_stack && 7935 func_id != BPF_FUNC_get_task_stack && 7936 func_id != BPF_FUNC_probe_read_str && 7937 func_id != BPF_FUNC_probe_read_kernel_str && 7938 func_id != BPF_FUNC_probe_read_user_str)) 7939 return; 7940 7941 ret_reg->smax_value = meta->msize_max_value; 7942 ret_reg->s32_max_value = meta->msize_max_value; 7943 ret_reg->smin_value = -MAX_ERRNO; 7944 ret_reg->s32_min_value = -MAX_ERRNO; 7945 reg_bounds_sync(ret_reg); 7946 } 7947 7948 static int 7949 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 7950 int func_id, int insn_idx) 7951 { 7952 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 7953 struct bpf_map *map = meta->map_ptr; 7954 7955 if (func_id != BPF_FUNC_tail_call && 7956 func_id != BPF_FUNC_map_lookup_elem && 7957 func_id != BPF_FUNC_map_update_elem && 7958 func_id != BPF_FUNC_map_delete_elem && 7959 func_id != BPF_FUNC_map_push_elem && 7960 func_id != BPF_FUNC_map_pop_elem && 7961 func_id != BPF_FUNC_map_peek_elem && 7962 func_id != BPF_FUNC_for_each_map_elem && 7963 func_id != BPF_FUNC_redirect_map && 7964 func_id != BPF_FUNC_map_lookup_percpu_elem) 7965 return 0; 7966 7967 if (map == NULL) { 7968 verbose(env, "kernel subsystem misconfigured verifier\n"); 7969 return -EINVAL; 7970 } 7971 7972 /* In case of read-only, some additional restrictions 7973 * need to be applied in order to prevent altering the 7974 * state of the map from program side. 7975 */ 7976 if ((map->map_flags & BPF_F_RDONLY_PROG) && 7977 (func_id == BPF_FUNC_map_delete_elem || 7978 func_id == BPF_FUNC_map_update_elem || 7979 func_id == BPF_FUNC_map_push_elem || 7980 func_id == BPF_FUNC_map_pop_elem)) { 7981 verbose(env, "write into map forbidden\n"); 7982 return -EACCES; 7983 } 7984 7985 if (!BPF_MAP_PTR(aux->map_ptr_state)) 7986 bpf_map_ptr_store(aux, meta->map_ptr, 7987 !meta->map_ptr->bypass_spec_v1); 7988 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 7989 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 7990 !meta->map_ptr->bypass_spec_v1); 7991 return 0; 7992 } 7993 7994 static int 7995 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 7996 int func_id, int insn_idx) 7997 { 7998 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 7999 struct bpf_reg_state *regs = cur_regs(env), *reg; 8000 struct bpf_map *map = meta->map_ptr; 8001 u64 val, max; 8002 int err; 8003 8004 if (func_id != BPF_FUNC_tail_call) 8005 return 0; 8006 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 8007 verbose(env, "kernel subsystem misconfigured verifier\n"); 8008 return -EINVAL; 8009 } 8010 8011 reg = ®s[BPF_REG_3]; 8012 val = reg->var_off.value; 8013 max = map->max_entries; 8014 8015 if (!(register_is_const(reg) && val < max)) { 8016 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 8017 return 0; 8018 } 8019 8020 err = mark_chain_precision(env, BPF_REG_3); 8021 if (err) 8022 return err; 8023 if (bpf_map_key_unseen(aux)) 8024 bpf_map_key_store(aux, val); 8025 else if (!bpf_map_key_poisoned(aux) && 8026 bpf_map_key_immediate(aux) != val) 8027 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 8028 return 0; 8029 } 8030 8031 static int check_reference_leak(struct bpf_verifier_env *env) 8032 { 8033 struct bpf_func_state *state = cur_func(env); 8034 bool refs_lingering = false; 8035 int i; 8036 8037 if (state->frameno && !state->in_callback_fn) 8038 return 0; 8039 8040 for (i = 0; i < state->acquired_refs; i++) { 8041 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 8042 continue; 8043 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 8044 state->refs[i].id, state->refs[i].insn_idx); 8045 refs_lingering = true; 8046 } 8047 return refs_lingering ? -EINVAL : 0; 8048 } 8049 8050 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 8051 struct bpf_reg_state *regs) 8052 { 8053 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 8054 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 8055 struct bpf_map *fmt_map = fmt_reg->map_ptr; 8056 struct bpf_bprintf_data data = {}; 8057 int err, fmt_map_off, num_args; 8058 u64 fmt_addr; 8059 char *fmt; 8060 8061 /* data must be an array of u64 */ 8062 if (data_len_reg->var_off.value % 8) 8063 return -EINVAL; 8064 num_args = data_len_reg->var_off.value / 8; 8065 8066 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 8067 * and map_direct_value_addr is set. 8068 */ 8069 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 8070 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 8071 fmt_map_off); 8072 if (err) { 8073 verbose(env, "verifier bug\n"); 8074 return -EFAULT; 8075 } 8076 fmt = (char *)(long)fmt_addr + fmt_map_off; 8077 8078 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 8079 * can focus on validating the format specifiers. 8080 */ 8081 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 8082 if (err < 0) 8083 verbose(env, "Invalid format string\n"); 8084 8085 return err; 8086 } 8087 8088 static int check_get_func_ip(struct bpf_verifier_env *env) 8089 { 8090 enum bpf_prog_type type = resolve_prog_type(env->prog); 8091 int func_id = BPF_FUNC_get_func_ip; 8092 8093 if (type == BPF_PROG_TYPE_TRACING) { 8094 if (!bpf_prog_has_trampoline(env->prog)) { 8095 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 8096 func_id_name(func_id), func_id); 8097 return -ENOTSUPP; 8098 } 8099 return 0; 8100 } else if (type == BPF_PROG_TYPE_KPROBE) { 8101 return 0; 8102 } 8103 8104 verbose(env, "func %s#%d not supported for program type %d\n", 8105 func_id_name(func_id), func_id, type); 8106 return -ENOTSUPP; 8107 } 8108 8109 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 8110 { 8111 return &env->insn_aux_data[env->insn_idx]; 8112 } 8113 8114 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 8115 { 8116 struct bpf_reg_state *regs = cur_regs(env); 8117 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 8118 bool reg_is_null = register_is_null(reg); 8119 8120 if (reg_is_null) 8121 mark_chain_precision(env, BPF_REG_4); 8122 8123 return reg_is_null; 8124 } 8125 8126 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 8127 { 8128 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 8129 8130 if (!state->initialized) { 8131 state->initialized = 1; 8132 state->fit_for_inline = loop_flag_is_zero(env); 8133 state->callback_subprogno = subprogno; 8134 return; 8135 } 8136 8137 if (!state->fit_for_inline) 8138 return; 8139 8140 state->fit_for_inline = (loop_flag_is_zero(env) && 8141 state->callback_subprogno == subprogno); 8142 } 8143 8144 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 8145 int *insn_idx_p) 8146 { 8147 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 8148 const struct bpf_func_proto *fn = NULL; 8149 enum bpf_return_type ret_type; 8150 enum bpf_type_flag ret_flag; 8151 struct bpf_reg_state *regs; 8152 struct bpf_call_arg_meta meta; 8153 int insn_idx = *insn_idx_p; 8154 bool changes_data; 8155 int i, err, func_id; 8156 8157 /* find function prototype */ 8158 func_id = insn->imm; 8159 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 8160 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 8161 func_id); 8162 return -EINVAL; 8163 } 8164 8165 if (env->ops->get_func_proto) 8166 fn = env->ops->get_func_proto(func_id, env->prog); 8167 if (!fn) { 8168 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 8169 func_id); 8170 return -EINVAL; 8171 } 8172 8173 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 8174 if (!env->prog->gpl_compatible && fn->gpl_only) { 8175 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 8176 return -EINVAL; 8177 } 8178 8179 if (fn->allowed && !fn->allowed(env->prog)) { 8180 verbose(env, "helper call is not allowed in probe\n"); 8181 return -EINVAL; 8182 } 8183 8184 if (!env->prog->aux->sleepable && fn->might_sleep) { 8185 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 8186 return -EINVAL; 8187 } 8188 8189 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 8190 changes_data = bpf_helper_changes_pkt_data(fn->func); 8191 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 8192 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 8193 func_id_name(func_id), func_id); 8194 return -EINVAL; 8195 } 8196 8197 memset(&meta, 0, sizeof(meta)); 8198 meta.pkt_access = fn->pkt_access; 8199 8200 err = check_func_proto(fn, func_id); 8201 if (err) { 8202 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 8203 func_id_name(func_id), func_id); 8204 return err; 8205 } 8206 8207 if (env->cur_state->active_rcu_lock) { 8208 if (fn->might_sleep) { 8209 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 8210 func_id_name(func_id), func_id); 8211 return -EINVAL; 8212 } 8213 8214 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 8215 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 8216 } 8217 8218 meta.func_id = func_id; 8219 /* check args */ 8220 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 8221 err = check_func_arg(env, i, &meta, fn); 8222 if (err) 8223 return err; 8224 } 8225 8226 err = record_func_map(env, &meta, func_id, insn_idx); 8227 if (err) 8228 return err; 8229 8230 err = record_func_key(env, &meta, func_id, insn_idx); 8231 if (err) 8232 return err; 8233 8234 /* Mark slots with STACK_MISC in case of raw mode, stack offset 8235 * is inferred from register state. 8236 */ 8237 for (i = 0; i < meta.access_size; i++) { 8238 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 8239 BPF_WRITE, -1, false); 8240 if (err) 8241 return err; 8242 } 8243 8244 regs = cur_regs(env); 8245 8246 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 8247 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr 8248 * is safe to do directly. 8249 */ 8250 if (meta.uninit_dynptr_regno) { 8251 if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) { 8252 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n"); 8253 return -EFAULT; 8254 } 8255 /* we write BPF_DW bits (8 bytes) at a time */ 8256 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 8257 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno, 8258 i, BPF_DW, BPF_WRITE, -1, false); 8259 if (err) 8260 return err; 8261 } 8262 8263 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno], 8264 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1], 8265 insn_idx); 8266 if (err) 8267 return err; 8268 } 8269 8270 if (meta.release_regno) { 8271 err = -EINVAL; 8272 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 8273 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 8274 * is safe to do directly. 8275 */ 8276 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 8277 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 8278 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 8279 return -EFAULT; 8280 } 8281 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 8282 } else if (meta.ref_obj_id) { 8283 err = release_reference(env, meta.ref_obj_id); 8284 } else if (register_is_null(®s[meta.release_regno])) { 8285 /* meta.ref_obj_id can only be 0 if register that is meant to be 8286 * released is NULL, which must be > R0. 8287 */ 8288 err = 0; 8289 } 8290 if (err) { 8291 verbose(env, "func %s#%d reference has not been acquired before\n", 8292 func_id_name(func_id), func_id); 8293 return err; 8294 } 8295 } 8296 8297 switch (func_id) { 8298 case BPF_FUNC_tail_call: 8299 err = check_reference_leak(env); 8300 if (err) { 8301 verbose(env, "tail_call would lead to reference leak\n"); 8302 return err; 8303 } 8304 break; 8305 case BPF_FUNC_get_local_storage: 8306 /* check that flags argument in get_local_storage(map, flags) is 0, 8307 * this is required because get_local_storage() can't return an error. 8308 */ 8309 if (!register_is_null(®s[BPF_REG_2])) { 8310 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 8311 return -EINVAL; 8312 } 8313 break; 8314 case BPF_FUNC_for_each_map_elem: 8315 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8316 set_map_elem_callback_state); 8317 break; 8318 case BPF_FUNC_timer_set_callback: 8319 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8320 set_timer_callback_state); 8321 break; 8322 case BPF_FUNC_find_vma: 8323 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8324 set_find_vma_callback_state); 8325 break; 8326 case BPF_FUNC_snprintf: 8327 err = check_bpf_snprintf_call(env, regs); 8328 break; 8329 case BPF_FUNC_loop: 8330 update_loop_inline_state(env, meta.subprogno); 8331 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8332 set_loop_callback_state); 8333 break; 8334 case BPF_FUNC_dynptr_from_mem: 8335 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 8336 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 8337 reg_type_str(env, regs[BPF_REG_1].type)); 8338 return -EACCES; 8339 } 8340 break; 8341 case BPF_FUNC_set_retval: 8342 if (prog_type == BPF_PROG_TYPE_LSM && 8343 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 8344 if (!env->prog->aux->attach_func_proto->type) { 8345 /* Make sure programs that attach to void 8346 * hooks don't try to modify return value. 8347 */ 8348 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 8349 return -EINVAL; 8350 } 8351 } 8352 break; 8353 case BPF_FUNC_dynptr_data: 8354 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 8355 if (arg_type_is_dynptr(fn->arg_type[i])) { 8356 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i]; 8357 int id, ref_obj_id; 8358 8359 if (meta.dynptr_id) { 8360 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 8361 return -EFAULT; 8362 } 8363 8364 if (meta.ref_obj_id) { 8365 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 8366 return -EFAULT; 8367 } 8368 8369 id = dynptr_id(env, reg); 8370 if (id < 0) { 8371 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 8372 return id; 8373 } 8374 8375 ref_obj_id = dynptr_ref_obj_id(env, reg); 8376 if (ref_obj_id < 0) { 8377 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 8378 return ref_obj_id; 8379 } 8380 8381 meta.dynptr_id = id; 8382 meta.ref_obj_id = ref_obj_id; 8383 break; 8384 } 8385 } 8386 if (i == MAX_BPF_FUNC_REG_ARGS) { 8387 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n"); 8388 return -EFAULT; 8389 } 8390 break; 8391 case BPF_FUNC_user_ringbuf_drain: 8392 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8393 set_user_ringbuf_callback_state); 8394 break; 8395 } 8396 8397 if (err) 8398 return err; 8399 8400 /* reset caller saved regs */ 8401 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8402 mark_reg_not_init(env, regs, caller_saved[i]); 8403 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8404 } 8405 8406 /* helper call returns 64-bit value. */ 8407 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8408 8409 /* update return register (already marked as written above) */ 8410 ret_type = fn->ret_type; 8411 ret_flag = type_flag(ret_type); 8412 8413 switch (base_type(ret_type)) { 8414 case RET_INTEGER: 8415 /* sets type to SCALAR_VALUE */ 8416 mark_reg_unknown(env, regs, BPF_REG_0); 8417 break; 8418 case RET_VOID: 8419 regs[BPF_REG_0].type = NOT_INIT; 8420 break; 8421 case RET_PTR_TO_MAP_VALUE: 8422 /* There is no offset yet applied, variable or fixed */ 8423 mark_reg_known_zero(env, regs, BPF_REG_0); 8424 /* remember map_ptr, so that check_map_access() 8425 * can check 'value_size' boundary of memory access 8426 * to map element returned from bpf_map_lookup_elem() 8427 */ 8428 if (meta.map_ptr == NULL) { 8429 verbose(env, 8430 "kernel subsystem misconfigured verifier\n"); 8431 return -EINVAL; 8432 } 8433 regs[BPF_REG_0].map_ptr = meta.map_ptr; 8434 regs[BPF_REG_0].map_uid = meta.map_uid; 8435 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 8436 if (!type_may_be_null(ret_type) && 8437 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 8438 regs[BPF_REG_0].id = ++env->id_gen; 8439 } 8440 break; 8441 case RET_PTR_TO_SOCKET: 8442 mark_reg_known_zero(env, regs, BPF_REG_0); 8443 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 8444 break; 8445 case RET_PTR_TO_SOCK_COMMON: 8446 mark_reg_known_zero(env, regs, BPF_REG_0); 8447 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 8448 break; 8449 case RET_PTR_TO_TCP_SOCK: 8450 mark_reg_known_zero(env, regs, BPF_REG_0); 8451 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 8452 break; 8453 case RET_PTR_TO_MEM: 8454 mark_reg_known_zero(env, regs, BPF_REG_0); 8455 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 8456 regs[BPF_REG_0].mem_size = meta.mem_size; 8457 break; 8458 case RET_PTR_TO_MEM_OR_BTF_ID: 8459 { 8460 const struct btf_type *t; 8461 8462 mark_reg_known_zero(env, regs, BPF_REG_0); 8463 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 8464 if (!btf_type_is_struct(t)) { 8465 u32 tsize; 8466 const struct btf_type *ret; 8467 const char *tname; 8468 8469 /* resolve the type size of ksym. */ 8470 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 8471 if (IS_ERR(ret)) { 8472 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 8473 verbose(env, "unable to resolve the size of type '%s': %ld\n", 8474 tname, PTR_ERR(ret)); 8475 return -EINVAL; 8476 } 8477 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 8478 regs[BPF_REG_0].mem_size = tsize; 8479 } else { 8480 /* MEM_RDONLY may be carried from ret_flag, but it 8481 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 8482 * it will confuse the check of PTR_TO_BTF_ID in 8483 * check_mem_access(). 8484 */ 8485 ret_flag &= ~MEM_RDONLY; 8486 8487 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 8488 regs[BPF_REG_0].btf = meta.ret_btf; 8489 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 8490 } 8491 break; 8492 } 8493 case RET_PTR_TO_BTF_ID: 8494 { 8495 struct btf *ret_btf; 8496 int ret_btf_id; 8497 8498 mark_reg_known_zero(env, regs, BPF_REG_0); 8499 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 8500 if (func_id == BPF_FUNC_kptr_xchg) { 8501 ret_btf = meta.kptr_field->kptr.btf; 8502 ret_btf_id = meta.kptr_field->kptr.btf_id; 8503 } else { 8504 if (fn->ret_btf_id == BPF_PTR_POISON) { 8505 verbose(env, "verifier internal error:"); 8506 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 8507 func_id_name(func_id)); 8508 return -EINVAL; 8509 } 8510 ret_btf = btf_vmlinux; 8511 ret_btf_id = *fn->ret_btf_id; 8512 } 8513 if (ret_btf_id == 0) { 8514 verbose(env, "invalid return type %u of func %s#%d\n", 8515 base_type(ret_type), func_id_name(func_id), 8516 func_id); 8517 return -EINVAL; 8518 } 8519 regs[BPF_REG_0].btf = ret_btf; 8520 regs[BPF_REG_0].btf_id = ret_btf_id; 8521 break; 8522 } 8523 default: 8524 verbose(env, "unknown return type %u of func %s#%d\n", 8525 base_type(ret_type), func_id_name(func_id), func_id); 8526 return -EINVAL; 8527 } 8528 8529 if (type_may_be_null(regs[BPF_REG_0].type)) 8530 regs[BPF_REG_0].id = ++env->id_gen; 8531 8532 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 8533 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 8534 func_id_name(func_id), func_id); 8535 return -EFAULT; 8536 } 8537 8538 if (is_dynptr_ref_function(func_id)) 8539 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 8540 8541 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 8542 /* For release_reference() */ 8543 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 8544 } else if (is_acquire_function(func_id, meta.map_ptr)) { 8545 int id = acquire_reference_state(env, insn_idx); 8546 8547 if (id < 0) 8548 return id; 8549 /* For mark_ptr_or_null_reg() */ 8550 regs[BPF_REG_0].id = id; 8551 /* For release_reference() */ 8552 regs[BPF_REG_0].ref_obj_id = id; 8553 } 8554 8555 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 8556 8557 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 8558 if (err) 8559 return err; 8560 8561 if ((func_id == BPF_FUNC_get_stack || 8562 func_id == BPF_FUNC_get_task_stack) && 8563 !env->prog->has_callchain_buf) { 8564 const char *err_str; 8565 8566 #ifdef CONFIG_PERF_EVENTS 8567 err = get_callchain_buffers(sysctl_perf_event_max_stack); 8568 err_str = "cannot get callchain buffer for func %s#%d\n"; 8569 #else 8570 err = -ENOTSUPP; 8571 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 8572 #endif 8573 if (err) { 8574 verbose(env, err_str, func_id_name(func_id), func_id); 8575 return err; 8576 } 8577 8578 env->prog->has_callchain_buf = true; 8579 } 8580 8581 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 8582 env->prog->call_get_stack = true; 8583 8584 if (func_id == BPF_FUNC_get_func_ip) { 8585 if (check_get_func_ip(env)) 8586 return -ENOTSUPP; 8587 env->prog->call_get_func_ip = true; 8588 } 8589 8590 if (changes_data) 8591 clear_all_pkt_pointers(env); 8592 return 0; 8593 } 8594 8595 /* mark_btf_func_reg_size() is used when the reg size is determined by 8596 * the BTF func_proto's return value size and argument. 8597 */ 8598 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 8599 size_t reg_size) 8600 { 8601 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 8602 8603 if (regno == BPF_REG_0) { 8604 /* Function return value */ 8605 reg->live |= REG_LIVE_WRITTEN; 8606 reg->subreg_def = reg_size == sizeof(u64) ? 8607 DEF_NOT_SUBREG : env->insn_idx + 1; 8608 } else { 8609 /* Function argument */ 8610 if (reg_size == sizeof(u64)) { 8611 mark_insn_zext(env, reg); 8612 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 8613 } else { 8614 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 8615 } 8616 } 8617 } 8618 8619 struct bpf_kfunc_call_arg_meta { 8620 /* In parameters */ 8621 struct btf *btf; 8622 u32 func_id; 8623 u32 kfunc_flags; 8624 const struct btf_type *func_proto; 8625 const char *func_name; 8626 /* Out parameters */ 8627 u32 ref_obj_id; 8628 u8 release_regno; 8629 bool r0_rdonly; 8630 u32 ret_btf_id; 8631 u64 r0_size; 8632 u32 subprogno; 8633 struct { 8634 u64 value; 8635 bool found; 8636 } arg_constant; 8637 struct { 8638 struct btf *btf; 8639 u32 btf_id; 8640 } arg_obj_drop; 8641 struct { 8642 struct btf_field *field; 8643 } arg_list_head; 8644 struct { 8645 struct btf_field *field; 8646 } arg_rbtree_root; 8647 }; 8648 8649 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 8650 { 8651 return meta->kfunc_flags & KF_ACQUIRE; 8652 } 8653 8654 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 8655 { 8656 return meta->kfunc_flags & KF_RET_NULL; 8657 } 8658 8659 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 8660 { 8661 return meta->kfunc_flags & KF_RELEASE; 8662 } 8663 8664 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 8665 { 8666 return meta->kfunc_flags & KF_TRUSTED_ARGS; 8667 } 8668 8669 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 8670 { 8671 return meta->kfunc_flags & KF_SLEEPABLE; 8672 } 8673 8674 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 8675 { 8676 return meta->kfunc_flags & KF_DESTRUCTIVE; 8677 } 8678 8679 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 8680 { 8681 return meta->kfunc_flags & KF_RCU; 8682 } 8683 8684 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg) 8685 { 8686 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET); 8687 } 8688 8689 static bool __kfunc_param_match_suffix(const struct btf *btf, 8690 const struct btf_param *arg, 8691 const char *suffix) 8692 { 8693 int suffix_len = strlen(suffix), len; 8694 const char *param_name; 8695 8696 /* In the future, this can be ported to use BTF tagging */ 8697 param_name = btf_name_by_offset(btf, arg->name_off); 8698 if (str_is_empty(param_name)) 8699 return false; 8700 len = strlen(param_name); 8701 if (len < suffix_len) 8702 return false; 8703 param_name += len - suffix_len; 8704 return !strncmp(param_name, suffix, suffix_len); 8705 } 8706 8707 static bool is_kfunc_arg_mem_size(const struct btf *btf, 8708 const struct btf_param *arg, 8709 const struct bpf_reg_state *reg) 8710 { 8711 const struct btf_type *t; 8712 8713 t = btf_type_skip_modifiers(btf, arg->type, NULL); 8714 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 8715 return false; 8716 8717 return __kfunc_param_match_suffix(btf, arg, "__sz"); 8718 } 8719 8720 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 8721 { 8722 return __kfunc_param_match_suffix(btf, arg, "__k"); 8723 } 8724 8725 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 8726 { 8727 return __kfunc_param_match_suffix(btf, arg, "__ign"); 8728 } 8729 8730 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 8731 { 8732 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 8733 } 8734 8735 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 8736 const struct btf_param *arg, 8737 const char *name) 8738 { 8739 int len, target_len = strlen(name); 8740 const char *param_name; 8741 8742 param_name = btf_name_by_offset(btf, arg->name_off); 8743 if (str_is_empty(param_name)) 8744 return false; 8745 len = strlen(param_name); 8746 if (len != target_len) 8747 return false; 8748 if (strcmp(param_name, name)) 8749 return false; 8750 8751 return true; 8752 } 8753 8754 enum { 8755 KF_ARG_DYNPTR_ID, 8756 KF_ARG_LIST_HEAD_ID, 8757 KF_ARG_LIST_NODE_ID, 8758 KF_ARG_RB_ROOT_ID, 8759 KF_ARG_RB_NODE_ID, 8760 }; 8761 8762 BTF_ID_LIST(kf_arg_btf_ids) 8763 BTF_ID(struct, bpf_dynptr_kern) 8764 BTF_ID(struct, bpf_list_head) 8765 BTF_ID(struct, bpf_list_node) 8766 BTF_ID(struct, bpf_rb_root) 8767 BTF_ID(struct, bpf_rb_node) 8768 8769 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 8770 const struct btf_param *arg, int type) 8771 { 8772 const struct btf_type *t; 8773 u32 res_id; 8774 8775 t = btf_type_skip_modifiers(btf, arg->type, NULL); 8776 if (!t) 8777 return false; 8778 if (!btf_type_is_ptr(t)) 8779 return false; 8780 t = btf_type_skip_modifiers(btf, t->type, &res_id); 8781 if (!t) 8782 return false; 8783 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 8784 } 8785 8786 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 8787 { 8788 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 8789 } 8790 8791 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 8792 { 8793 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 8794 } 8795 8796 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 8797 { 8798 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 8799 } 8800 8801 static bool is_kfunc_arg_rbtree_root(const struct btf *btf, const struct btf_param *arg) 8802 { 8803 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_ROOT_ID); 8804 } 8805 8806 static bool is_kfunc_arg_rbtree_node(const struct btf *btf, const struct btf_param *arg) 8807 { 8808 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_RB_NODE_ID); 8809 } 8810 8811 static bool is_kfunc_arg_callback(struct bpf_verifier_env *env, const struct btf *btf, 8812 const struct btf_param *arg) 8813 { 8814 const struct btf_type *t; 8815 8816 t = btf_type_resolve_func_ptr(btf, arg->type, NULL); 8817 if (!t) 8818 return false; 8819 8820 return true; 8821 } 8822 8823 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 8824 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 8825 const struct btf *btf, 8826 const struct btf_type *t, int rec) 8827 { 8828 const struct btf_type *member_type; 8829 const struct btf_member *member; 8830 u32 i; 8831 8832 if (!btf_type_is_struct(t)) 8833 return false; 8834 8835 for_each_member(i, t, member) { 8836 const struct btf_array *array; 8837 8838 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 8839 if (btf_type_is_struct(member_type)) { 8840 if (rec >= 3) { 8841 verbose(env, "max struct nesting depth exceeded\n"); 8842 return false; 8843 } 8844 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 8845 return false; 8846 continue; 8847 } 8848 if (btf_type_is_array(member_type)) { 8849 array = btf_array(member_type); 8850 if (!array->nelems) 8851 return false; 8852 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 8853 if (!btf_type_is_scalar(member_type)) 8854 return false; 8855 continue; 8856 } 8857 if (!btf_type_is_scalar(member_type)) 8858 return false; 8859 } 8860 return true; 8861 } 8862 8863 8864 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 8865 #ifdef CONFIG_NET 8866 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 8867 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8868 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 8869 #endif 8870 }; 8871 8872 enum kfunc_ptr_arg_type { 8873 KF_ARG_PTR_TO_CTX, 8874 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 8875 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */ 8876 KF_ARG_PTR_TO_DYNPTR, 8877 KF_ARG_PTR_TO_LIST_HEAD, 8878 KF_ARG_PTR_TO_LIST_NODE, 8879 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 8880 KF_ARG_PTR_TO_MEM, 8881 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 8882 KF_ARG_PTR_TO_CALLBACK, 8883 KF_ARG_PTR_TO_RB_ROOT, 8884 KF_ARG_PTR_TO_RB_NODE, 8885 }; 8886 8887 enum special_kfunc_type { 8888 KF_bpf_obj_new_impl, 8889 KF_bpf_obj_drop_impl, 8890 KF_bpf_list_push_front, 8891 KF_bpf_list_push_back, 8892 KF_bpf_list_pop_front, 8893 KF_bpf_list_pop_back, 8894 KF_bpf_cast_to_kern_ctx, 8895 KF_bpf_rdonly_cast, 8896 KF_bpf_rcu_read_lock, 8897 KF_bpf_rcu_read_unlock, 8898 KF_bpf_rbtree_remove, 8899 KF_bpf_rbtree_add, 8900 KF_bpf_rbtree_first, 8901 }; 8902 8903 BTF_SET_START(special_kfunc_set) 8904 BTF_ID(func, bpf_obj_new_impl) 8905 BTF_ID(func, bpf_obj_drop_impl) 8906 BTF_ID(func, bpf_list_push_front) 8907 BTF_ID(func, bpf_list_push_back) 8908 BTF_ID(func, bpf_list_pop_front) 8909 BTF_ID(func, bpf_list_pop_back) 8910 BTF_ID(func, bpf_cast_to_kern_ctx) 8911 BTF_ID(func, bpf_rdonly_cast) 8912 BTF_ID(func, bpf_rbtree_remove) 8913 BTF_ID(func, bpf_rbtree_add) 8914 BTF_ID(func, bpf_rbtree_first) 8915 BTF_SET_END(special_kfunc_set) 8916 8917 BTF_ID_LIST(special_kfunc_list) 8918 BTF_ID(func, bpf_obj_new_impl) 8919 BTF_ID(func, bpf_obj_drop_impl) 8920 BTF_ID(func, bpf_list_push_front) 8921 BTF_ID(func, bpf_list_push_back) 8922 BTF_ID(func, bpf_list_pop_front) 8923 BTF_ID(func, bpf_list_pop_back) 8924 BTF_ID(func, bpf_cast_to_kern_ctx) 8925 BTF_ID(func, bpf_rdonly_cast) 8926 BTF_ID(func, bpf_rcu_read_lock) 8927 BTF_ID(func, bpf_rcu_read_unlock) 8928 BTF_ID(func, bpf_rbtree_remove) 8929 BTF_ID(func, bpf_rbtree_add) 8930 BTF_ID(func, bpf_rbtree_first) 8931 8932 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 8933 { 8934 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 8935 } 8936 8937 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 8938 { 8939 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 8940 } 8941 8942 static enum kfunc_ptr_arg_type 8943 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 8944 struct bpf_kfunc_call_arg_meta *meta, 8945 const struct btf_type *t, const struct btf_type *ref_t, 8946 const char *ref_tname, const struct btf_param *args, 8947 int argno, int nargs) 8948 { 8949 u32 regno = argno + 1; 8950 struct bpf_reg_state *regs = cur_regs(env); 8951 struct bpf_reg_state *reg = ®s[regno]; 8952 bool arg_mem_size = false; 8953 8954 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 8955 return KF_ARG_PTR_TO_CTX; 8956 8957 /* In this function, we verify the kfunc's BTF as per the argument type, 8958 * leaving the rest of the verification with respect to the register 8959 * type to our caller. When a set of conditions hold in the BTF type of 8960 * arguments, we resolve it to a known kfunc_ptr_arg_type. 8961 */ 8962 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 8963 return KF_ARG_PTR_TO_CTX; 8964 8965 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 8966 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 8967 8968 if (is_kfunc_arg_kptr_get(meta, argno)) { 8969 if (!btf_type_is_ptr(ref_t)) { 8970 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n"); 8971 return -EINVAL; 8972 } 8973 ref_t = btf_type_by_id(meta->btf, ref_t->type); 8974 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off); 8975 if (!btf_type_is_struct(ref_t)) { 8976 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n", 8977 meta->func_name, btf_type_str(ref_t), ref_tname); 8978 return -EINVAL; 8979 } 8980 return KF_ARG_PTR_TO_KPTR; 8981 } 8982 8983 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 8984 return KF_ARG_PTR_TO_DYNPTR; 8985 8986 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 8987 return KF_ARG_PTR_TO_LIST_HEAD; 8988 8989 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 8990 return KF_ARG_PTR_TO_LIST_NODE; 8991 8992 if (is_kfunc_arg_rbtree_root(meta->btf, &args[argno])) 8993 return KF_ARG_PTR_TO_RB_ROOT; 8994 8995 if (is_kfunc_arg_rbtree_node(meta->btf, &args[argno])) 8996 return KF_ARG_PTR_TO_RB_NODE; 8997 8998 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 8999 if (!btf_type_is_struct(ref_t)) { 9000 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 9001 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 9002 return -EINVAL; 9003 } 9004 return KF_ARG_PTR_TO_BTF_ID; 9005 } 9006 9007 if (is_kfunc_arg_callback(env, meta->btf, &args[argno])) 9008 return KF_ARG_PTR_TO_CALLBACK; 9009 9010 if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])) 9011 arg_mem_size = true; 9012 9013 /* This is the catch all argument type of register types supported by 9014 * check_helper_mem_access. However, we only allow when argument type is 9015 * pointer to scalar, or struct composed (recursively) of scalars. When 9016 * arg_mem_size is true, the pointer can be void *. 9017 */ 9018 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 9019 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 9020 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 9021 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 9022 return -EINVAL; 9023 } 9024 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 9025 } 9026 9027 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 9028 struct bpf_reg_state *reg, 9029 const struct btf_type *ref_t, 9030 const char *ref_tname, u32 ref_id, 9031 struct bpf_kfunc_call_arg_meta *meta, 9032 int argno) 9033 { 9034 const struct btf_type *reg_ref_t; 9035 bool strict_type_match = false; 9036 const struct btf *reg_btf; 9037 const char *reg_ref_tname; 9038 u32 reg_ref_id; 9039 9040 if (base_type(reg->type) == PTR_TO_BTF_ID) { 9041 reg_btf = reg->btf; 9042 reg_ref_id = reg->btf_id; 9043 } else { 9044 reg_btf = btf_vmlinux; 9045 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 9046 } 9047 9048 /* Enforce strict type matching for calls to kfuncs that are acquiring 9049 * or releasing a reference, or are no-cast aliases. We do _not_ 9050 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 9051 * as we want to enable BPF programs to pass types that are bitwise 9052 * equivalent without forcing them to explicitly cast with something 9053 * like bpf_cast_to_kern_ctx(). 9054 * 9055 * For example, say we had a type like the following: 9056 * 9057 * struct bpf_cpumask { 9058 * cpumask_t cpumask; 9059 * refcount_t usage; 9060 * }; 9061 * 9062 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 9063 * to a struct cpumask, so it would be safe to pass a struct 9064 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 9065 * 9066 * The philosophy here is similar to how we allow scalars of different 9067 * types to be passed to kfuncs as long as the size is the same. The 9068 * only difference here is that we're simply allowing 9069 * btf_struct_ids_match() to walk the struct at the 0th offset, and 9070 * resolve types. 9071 */ 9072 if (is_kfunc_acquire(meta) || 9073 (is_kfunc_release(meta) && reg->ref_obj_id) || 9074 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 9075 strict_type_match = true; 9076 9077 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 9078 9079 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 9080 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 9081 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 9082 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 9083 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 9084 btf_type_str(reg_ref_t), reg_ref_tname); 9085 return -EINVAL; 9086 } 9087 return 0; 9088 } 9089 9090 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env, 9091 struct bpf_reg_state *reg, 9092 const struct btf_type *ref_t, 9093 const char *ref_tname, 9094 struct bpf_kfunc_call_arg_meta *meta, 9095 int argno) 9096 { 9097 struct btf_field *kptr_field; 9098 9099 /* check_func_arg_reg_off allows var_off for 9100 * PTR_TO_MAP_VALUE, but we need fixed offset to find 9101 * off_desc. 9102 */ 9103 if (!tnum_is_const(reg->var_off)) { 9104 verbose(env, "arg#0 must have constant offset\n"); 9105 return -EINVAL; 9106 } 9107 9108 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR); 9109 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) { 9110 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n", 9111 reg->off + reg->var_off.value); 9112 return -EINVAL; 9113 } 9114 9115 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf, 9116 kptr_field->kptr.btf_id, true)) { 9117 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n", 9118 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 9119 return -EINVAL; 9120 } 9121 return 0; 9122 } 9123 9124 static int ref_set_non_owning(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 9125 { 9126 struct bpf_verifier_state *state = env->cur_state; 9127 9128 if (!state->active_lock.ptr) { 9129 verbose(env, "verifier internal error: ref_set_non_owning w/o active lock\n"); 9130 return -EFAULT; 9131 } 9132 9133 if (type_flag(reg->type) & NON_OWN_REF) { 9134 verbose(env, "verifier internal error: NON_OWN_REF already set\n"); 9135 return -EFAULT; 9136 } 9137 9138 reg->type |= NON_OWN_REF; 9139 return 0; 9140 } 9141 9142 static int ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 ref_obj_id) 9143 { 9144 struct bpf_func_state *state, *unused; 9145 struct bpf_reg_state *reg; 9146 int i; 9147 9148 state = cur_func(env); 9149 9150 if (!ref_obj_id) { 9151 verbose(env, "verifier internal error: ref_obj_id is zero for " 9152 "owning -> non-owning conversion\n"); 9153 return -EFAULT; 9154 } 9155 9156 for (i = 0; i < state->acquired_refs; i++) { 9157 if (state->refs[i].id != ref_obj_id) 9158 continue; 9159 9160 /* Clear ref_obj_id here so release_reference doesn't clobber 9161 * the whole reg 9162 */ 9163 bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({ 9164 if (reg->ref_obj_id == ref_obj_id) { 9165 reg->ref_obj_id = 0; 9166 ref_set_non_owning(env, reg); 9167 } 9168 })); 9169 return 0; 9170 } 9171 9172 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 9173 return -EFAULT; 9174 } 9175 9176 /* Implementation details: 9177 * 9178 * Each register points to some region of memory, which we define as an 9179 * allocation. Each allocation may embed a bpf_spin_lock which protects any 9180 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 9181 * allocation. The lock and the data it protects are colocated in the same 9182 * memory region. 9183 * 9184 * Hence, everytime a register holds a pointer value pointing to such 9185 * allocation, the verifier preserves a unique reg->id for it. 9186 * 9187 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 9188 * bpf_spin_lock is called. 9189 * 9190 * To enable this, lock state in the verifier captures two values: 9191 * active_lock.ptr = Register's type specific pointer 9192 * active_lock.id = A unique ID for each register pointer value 9193 * 9194 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 9195 * supported register types. 9196 * 9197 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 9198 * allocated objects is the reg->btf pointer. 9199 * 9200 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 9201 * can establish the provenance of the map value statically for each distinct 9202 * lookup into such maps. They always contain a single map value hence unique 9203 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 9204 * 9205 * So, in case of global variables, they use array maps with max_entries = 1, 9206 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 9207 * into the same map value as max_entries is 1, as described above). 9208 * 9209 * In case of inner map lookups, the inner map pointer has same map_ptr as the 9210 * outer map pointer (in verifier context), but each lookup into an inner map 9211 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 9212 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 9213 * will get different reg->id assigned to each lookup, hence different 9214 * active_lock.id. 9215 * 9216 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 9217 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 9218 * returned from bpf_obj_new. Each allocation receives a new reg->id. 9219 */ 9220 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 9221 { 9222 void *ptr; 9223 u32 id; 9224 9225 switch ((int)reg->type) { 9226 case PTR_TO_MAP_VALUE: 9227 ptr = reg->map_ptr; 9228 break; 9229 case PTR_TO_BTF_ID | MEM_ALLOC: 9230 ptr = reg->btf; 9231 break; 9232 default: 9233 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 9234 return -EFAULT; 9235 } 9236 id = reg->id; 9237 9238 if (!env->cur_state->active_lock.ptr) 9239 return -EINVAL; 9240 if (env->cur_state->active_lock.ptr != ptr || 9241 env->cur_state->active_lock.id != id) { 9242 verbose(env, "held lock and object are not in the same allocation\n"); 9243 return -EINVAL; 9244 } 9245 return 0; 9246 } 9247 9248 static bool is_bpf_list_api_kfunc(u32 btf_id) 9249 { 9250 return btf_id == special_kfunc_list[KF_bpf_list_push_front] || 9251 btf_id == special_kfunc_list[KF_bpf_list_push_back] || 9252 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 9253 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 9254 } 9255 9256 static bool is_bpf_rbtree_api_kfunc(u32 btf_id) 9257 { 9258 return btf_id == special_kfunc_list[KF_bpf_rbtree_add] || 9259 btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 9260 btf_id == special_kfunc_list[KF_bpf_rbtree_first]; 9261 } 9262 9263 static bool is_bpf_graph_api_kfunc(u32 btf_id) 9264 { 9265 return is_bpf_list_api_kfunc(btf_id) || is_bpf_rbtree_api_kfunc(btf_id); 9266 } 9267 9268 static bool is_callback_calling_kfunc(u32 btf_id) 9269 { 9270 return btf_id == special_kfunc_list[KF_bpf_rbtree_add]; 9271 } 9272 9273 static bool is_rbtree_lock_required_kfunc(u32 btf_id) 9274 { 9275 return is_bpf_rbtree_api_kfunc(btf_id); 9276 } 9277 9278 static bool check_kfunc_is_graph_root_api(struct bpf_verifier_env *env, 9279 enum btf_field_type head_field_type, 9280 u32 kfunc_btf_id) 9281 { 9282 bool ret; 9283 9284 switch (head_field_type) { 9285 case BPF_LIST_HEAD: 9286 ret = is_bpf_list_api_kfunc(kfunc_btf_id); 9287 break; 9288 case BPF_RB_ROOT: 9289 ret = is_bpf_rbtree_api_kfunc(kfunc_btf_id); 9290 break; 9291 default: 9292 verbose(env, "verifier internal error: unexpected graph root argument type %s\n", 9293 btf_field_type_name(head_field_type)); 9294 return false; 9295 } 9296 9297 if (!ret) 9298 verbose(env, "verifier internal error: %s head arg for unknown kfunc\n", 9299 btf_field_type_name(head_field_type)); 9300 return ret; 9301 } 9302 9303 static bool check_kfunc_is_graph_node_api(struct bpf_verifier_env *env, 9304 enum btf_field_type node_field_type, 9305 u32 kfunc_btf_id) 9306 { 9307 bool ret; 9308 9309 switch (node_field_type) { 9310 case BPF_LIST_NODE: 9311 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_front] || 9312 kfunc_btf_id == special_kfunc_list[KF_bpf_list_push_back]); 9313 break; 9314 case BPF_RB_NODE: 9315 ret = (kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_remove] || 9316 kfunc_btf_id == special_kfunc_list[KF_bpf_rbtree_add]); 9317 break; 9318 default: 9319 verbose(env, "verifier internal error: unexpected graph node argument type %s\n", 9320 btf_field_type_name(node_field_type)); 9321 return false; 9322 } 9323 9324 if (!ret) 9325 verbose(env, "verifier internal error: %s node arg for unknown kfunc\n", 9326 btf_field_type_name(node_field_type)); 9327 return ret; 9328 } 9329 9330 static int 9331 __process_kf_arg_ptr_to_graph_root(struct bpf_verifier_env *env, 9332 struct bpf_reg_state *reg, u32 regno, 9333 struct bpf_kfunc_call_arg_meta *meta, 9334 enum btf_field_type head_field_type, 9335 struct btf_field **head_field) 9336 { 9337 const char *head_type_name; 9338 struct btf_field *field; 9339 struct btf_record *rec; 9340 u32 head_off; 9341 9342 if (meta->btf != btf_vmlinux) { 9343 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 9344 return -EFAULT; 9345 } 9346 9347 if (!check_kfunc_is_graph_root_api(env, head_field_type, meta->func_id)) 9348 return -EFAULT; 9349 9350 head_type_name = btf_field_type_name(head_field_type); 9351 if (!tnum_is_const(reg->var_off)) { 9352 verbose(env, 9353 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 9354 regno, head_type_name); 9355 return -EINVAL; 9356 } 9357 9358 rec = reg_btf_record(reg); 9359 head_off = reg->off + reg->var_off.value; 9360 field = btf_record_find(rec, head_off, head_field_type); 9361 if (!field) { 9362 verbose(env, "%s not found at offset=%u\n", head_type_name, head_off); 9363 return -EINVAL; 9364 } 9365 9366 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 9367 if (check_reg_allocation_locked(env, reg)) { 9368 verbose(env, "bpf_spin_lock at off=%d must be held for %s\n", 9369 rec->spin_lock_off, head_type_name); 9370 return -EINVAL; 9371 } 9372 9373 if (*head_field) { 9374 verbose(env, "verifier internal error: repeating %s arg\n", head_type_name); 9375 return -EFAULT; 9376 } 9377 *head_field = field; 9378 return 0; 9379 } 9380 9381 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 9382 struct bpf_reg_state *reg, u32 regno, 9383 struct bpf_kfunc_call_arg_meta *meta) 9384 { 9385 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_LIST_HEAD, 9386 &meta->arg_list_head.field); 9387 } 9388 9389 static int process_kf_arg_ptr_to_rbtree_root(struct bpf_verifier_env *env, 9390 struct bpf_reg_state *reg, u32 regno, 9391 struct bpf_kfunc_call_arg_meta *meta) 9392 { 9393 return __process_kf_arg_ptr_to_graph_root(env, reg, regno, meta, BPF_RB_ROOT, 9394 &meta->arg_rbtree_root.field); 9395 } 9396 9397 static int 9398 __process_kf_arg_ptr_to_graph_node(struct bpf_verifier_env *env, 9399 struct bpf_reg_state *reg, u32 regno, 9400 struct bpf_kfunc_call_arg_meta *meta, 9401 enum btf_field_type head_field_type, 9402 enum btf_field_type node_field_type, 9403 struct btf_field **node_field) 9404 { 9405 const char *node_type_name; 9406 const struct btf_type *et, *t; 9407 struct btf_field *field; 9408 u32 node_off; 9409 9410 if (meta->btf != btf_vmlinux) { 9411 verbose(env, "verifier internal error: unexpected btf mismatch in kfunc call\n"); 9412 return -EFAULT; 9413 } 9414 9415 if (!check_kfunc_is_graph_node_api(env, node_field_type, meta->func_id)) 9416 return -EFAULT; 9417 9418 node_type_name = btf_field_type_name(node_field_type); 9419 if (!tnum_is_const(reg->var_off)) { 9420 verbose(env, 9421 "R%d doesn't have constant offset. %s has to be at the constant offset\n", 9422 regno, node_type_name); 9423 return -EINVAL; 9424 } 9425 9426 node_off = reg->off + reg->var_off.value; 9427 field = reg_find_field_offset(reg, node_off, node_field_type); 9428 if (!field || field->offset != node_off) { 9429 verbose(env, "%s not found at offset=%u\n", node_type_name, node_off); 9430 return -EINVAL; 9431 } 9432 9433 field = *node_field; 9434 9435 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 9436 t = btf_type_by_id(reg->btf, reg->btf_id); 9437 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 9438 field->graph_root.value_btf_id, true)) { 9439 verbose(env, "operation on %s expects arg#1 %s at offset=%d " 9440 "in struct %s, but arg is at offset=%d in struct %s\n", 9441 btf_field_type_name(head_field_type), 9442 btf_field_type_name(node_field_type), 9443 field->graph_root.node_offset, 9444 btf_name_by_offset(field->graph_root.btf, et->name_off), 9445 node_off, btf_name_by_offset(reg->btf, t->name_off)); 9446 return -EINVAL; 9447 } 9448 9449 if (node_off != field->graph_root.node_offset) { 9450 verbose(env, "arg#1 offset=%d, but expected %s at offset=%d in struct %s\n", 9451 node_off, btf_field_type_name(node_field_type), 9452 field->graph_root.node_offset, 9453 btf_name_by_offset(field->graph_root.btf, et->name_off)); 9454 return -EINVAL; 9455 } 9456 9457 return 0; 9458 } 9459 9460 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 9461 struct bpf_reg_state *reg, u32 regno, 9462 struct bpf_kfunc_call_arg_meta *meta) 9463 { 9464 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 9465 BPF_LIST_HEAD, BPF_LIST_NODE, 9466 &meta->arg_list_head.field); 9467 } 9468 9469 static int process_kf_arg_ptr_to_rbtree_node(struct bpf_verifier_env *env, 9470 struct bpf_reg_state *reg, u32 regno, 9471 struct bpf_kfunc_call_arg_meta *meta) 9472 { 9473 return __process_kf_arg_ptr_to_graph_node(env, reg, regno, meta, 9474 BPF_RB_ROOT, BPF_RB_NODE, 9475 &meta->arg_rbtree_root.field); 9476 } 9477 9478 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta) 9479 { 9480 const char *func_name = meta->func_name, *ref_tname; 9481 const struct btf *btf = meta->btf; 9482 const struct btf_param *args; 9483 u32 i, nargs; 9484 int ret; 9485 9486 args = (const struct btf_param *)(meta->func_proto + 1); 9487 nargs = btf_type_vlen(meta->func_proto); 9488 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 9489 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 9490 MAX_BPF_FUNC_REG_ARGS); 9491 return -EINVAL; 9492 } 9493 9494 /* Check that BTF function arguments match actual types that the 9495 * verifier sees. 9496 */ 9497 for (i = 0; i < nargs; i++) { 9498 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 9499 const struct btf_type *t, *ref_t, *resolve_ret; 9500 enum bpf_arg_type arg_type = ARG_DONTCARE; 9501 u32 regno = i + 1, ref_id, type_size; 9502 bool is_ret_buf_sz = false; 9503 int kf_arg_type; 9504 9505 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 9506 9507 if (is_kfunc_arg_ignore(btf, &args[i])) 9508 continue; 9509 9510 if (btf_type_is_scalar(t)) { 9511 if (reg->type != SCALAR_VALUE) { 9512 verbose(env, "R%d is not a scalar\n", regno); 9513 return -EINVAL; 9514 } 9515 9516 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 9517 if (meta->arg_constant.found) { 9518 verbose(env, "verifier internal error: only one constant argument permitted\n"); 9519 return -EFAULT; 9520 } 9521 if (!tnum_is_const(reg->var_off)) { 9522 verbose(env, "R%d must be a known constant\n", regno); 9523 return -EINVAL; 9524 } 9525 ret = mark_chain_precision(env, regno); 9526 if (ret < 0) 9527 return ret; 9528 meta->arg_constant.found = true; 9529 meta->arg_constant.value = reg->var_off.value; 9530 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 9531 meta->r0_rdonly = true; 9532 is_ret_buf_sz = true; 9533 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 9534 is_ret_buf_sz = true; 9535 } 9536 9537 if (is_ret_buf_sz) { 9538 if (meta->r0_size) { 9539 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 9540 return -EINVAL; 9541 } 9542 9543 if (!tnum_is_const(reg->var_off)) { 9544 verbose(env, "R%d is not a const\n", regno); 9545 return -EINVAL; 9546 } 9547 9548 meta->r0_size = reg->var_off.value; 9549 ret = mark_chain_precision(env, regno); 9550 if (ret) 9551 return ret; 9552 } 9553 continue; 9554 } 9555 9556 if (!btf_type_is_ptr(t)) { 9557 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 9558 return -EINVAL; 9559 } 9560 9561 if (is_kfunc_trusted_args(meta) && 9562 (register_is_null(reg) || type_may_be_null(reg->type))) { 9563 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 9564 return -EACCES; 9565 } 9566 9567 if (reg->ref_obj_id) { 9568 if (is_kfunc_release(meta) && meta->ref_obj_id) { 9569 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 9570 regno, reg->ref_obj_id, 9571 meta->ref_obj_id); 9572 return -EFAULT; 9573 } 9574 meta->ref_obj_id = reg->ref_obj_id; 9575 if (is_kfunc_release(meta)) 9576 meta->release_regno = regno; 9577 } 9578 9579 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 9580 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 9581 9582 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 9583 if (kf_arg_type < 0) 9584 return kf_arg_type; 9585 9586 switch (kf_arg_type) { 9587 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 9588 case KF_ARG_PTR_TO_BTF_ID: 9589 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 9590 break; 9591 9592 if (!is_trusted_reg(reg)) { 9593 if (!is_kfunc_rcu(meta)) { 9594 verbose(env, "R%d must be referenced or trusted\n", regno); 9595 return -EINVAL; 9596 } 9597 if (!is_rcu_reg(reg)) { 9598 verbose(env, "R%d must be a rcu pointer\n", regno); 9599 return -EINVAL; 9600 } 9601 } 9602 9603 fallthrough; 9604 case KF_ARG_PTR_TO_CTX: 9605 /* Trusted arguments have the same offset checks as release arguments */ 9606 arg_type |= OBJ_RELEASE; 9607 break; 9608 case KF_ARG_PTR_TO_KPTR: 9609 case KF_ARG_PTR_TO_DYNPTR: 9610 case KF_ARG_PTR_TO_LIST_HEAD: 9611 case KF_ARG_PTR_TO_LIST_NODE: 9612 case KF_ARG_PTR_TO_RB_ROOT: 9613 case KF_ARG_PTR_TO_RB_NODE: 9614 case KF_ARG_PTR_TO_MEM: 9615 case KF_ARG_PTR_TO_MEM_SIZE: 9616 case KF_ARG_PTR_TO_CALLBACK: 9617 /* Trusted by default */ 9618 break; 9619 default: 9620 WARN_ON_ONCE(1); 9621 return -EFAULT; 9622 } 9623 9624 if (is_kfunc_release(meta) && reg->ref_obj_id) 9625 arg_type |= OBJ_RELEASE; 9626 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 9627 if (ret < 0) 9628 return ret; 9629 9630 switch (kf_arg_type) { 9631 case KF_ARG_PTR_TO_CTX: 9632 if (reg->type != PTR_TO_CTX) { 9633 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 9634 return -EINVAL; 9635 } 9636 9637 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 9638 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 9639 if (ret < 0) 9640 return -EINVAL; 9641 meta->ret_btf_id = ret; 9642 } 9643 break; 9644 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 9645 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9646 verbose(env, "arg#%d expected pointer to allocated object\n", i); 9647 return -EINVAL; 9648 } 9649 if (!reg->ref_obj_id) { 9650 verbose(env, "allocated object must be referenced\n"); 9651 return -EINVAL; 9652 } 9653 if (meta->btf == btf_vmlinux && 9654 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 9655 meta->arg_obj_drop.btf = reg->btf; 9656 meta->arg_obj_drop.btf_id = reg->btf_id; 9657 } 9658 break; 9659 case KF_ARG_PTR_TO_KPTR: 9660 if (reg->type != PTR_TO_MAP_VALUE) { 9661 verbose(env, "arg#0 expected pointer to map value\n"); 9662 return -EINVAL; 9663 } 9664 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i); 9665 if (ret < 0) 9666 return ret; 9667 break; 9668 case KF_ARG_PTR_TO_DYNPTR: 9669 if (reg->type != PTR_TO_STACK && 9670 reg->type != CONST_PTR_TO_DYNPTR) { 9671 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 9672 return -EINVAL; 9673 } 9674 9675 ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL); 9676 if (ret < 0) 9677 return ret; 9678 break; 9679 case KF_ARG_PTR_TO_LIST_HEAD: 9680 if (reg->type != PTR_TO_MAP_VALUE && 9681 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9682 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 9683 return -EINVAL; 9684 } 9685 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 9686 verbose(env, "allocated object must be referenced\n"); 9687 return -EINVAL; 9688 } 9689 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 9690 if (ret < 0) 9691 return ret; 9692 break; 9693 case KF_ARG_PTR_TO_RB_ROOT: 9694 if (reg->type != PTR_TO_MAP_VALUE && 9695 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9696 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 9697 return -EINVAL; 9698 } 9699 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 9700 verbose(env, "allocated object must be referenced\n"); 9701 return -EINVAL; 9702 } 9703 ret = process_kf_arg_ptr_to_rbtree_root(env, reg, regno, meta); 9704 if (ret < 0) 9705 return ret; 9706 break; 9707 case KF_ARG_PTR_TO_LIST_NODE: 9708 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9709 verbose(env, "arg#%d expected pointer to allocated object\n", i); 9710 return -EINVAL; 9711 } 9712 if (!reg->ref_obj_id) { 9713 verbose(env, "allocated object must be referenced\n"); 9714 return -EINVAL; 9715 } 9716 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 9717 if (ret < 0) 9718 return ret; 9719 break; 9720 case KF_ARG_PTR_TO_RB_NODE: 9721 if (meta->func_id == special_kfunc_list[KF_bpf_rbtree_remove]) { 9722 if (!type_is_non_owning_ref(reg->type) || reg->ref_obj_id) { 9723 verbose(env, "rbtree_remove node input must be non-owning ref\n"); 9724 return -EINVAL; 9725 } 9726 if (in_rbtree_lock_required_cb(env)) { 9727 verbose(env, "rbtree_remove not allowed in rbtree cb\n"); 9728 return -EINVAL; 9729 } 9730 } else { 9731 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9732 verbose(env, "arg#%d expected pointer to allocated object\n", i); 9733 return -EINVAL; 9734 } 9735 if (!reg->ref_obj_id) { 9736 verbose(env, "allocated object must be referenced\n"); 9737 return -EINVAL; 9738 } 9739 } 9740 9741 ret = process_kf_arg_ptr_to_rbtree_node(env, reg, regno, meta); 9742 if (ret < 0) 9743 return ret; 9744 break; 9745 case KF_ARG_PTR_TO_BTF_ID: 9746 /* Only base_type is checked, further checks are done here */ 9747 if ((base_type(reg->type) != PTR_TO_BTF_ID || 9748 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 9749 !reg2btf_ids[base_type(reg->type)]) { 9750 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 9751 verbose(env, "expected %s or socket\n", 9752 reg_type_str(env, base_type(reg->type) | 9753 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 9754 return -EINVAL; 9755 } 9756 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 9757 if (ret < 0) 9758 return ret; 9759 break; 9760 case KF_ARG_PTR_TO_MEM: 9761 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 9762 if (IS_ERR(resolve_ret)) { 9763 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 9764 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 9765 return -EINVAL; 9766 } 9767 ret = check_mem_reg(env, reg, regno, type_size); 9768 if (ret < 0) 9769 return ret; 9770 break; 9771 case KF_ARG_PTR_TO_MEM_SIZE: 9772 ret = check_kfunc_mem_size_reg(env, ®s[regno + 1], regno + 1); 9773 if (ret < 0) { 9774 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 9775 return ret; 9776 } 9777 /* Skip next '__sz' argument */ 9778 i++; 9779 break; 9780 case KF_ARG_PTR_TO_CALLBACK: 9781 meta->subprogno = reg->subprogno; 9782 break; 9783 } 9784 } 9785 9786 if (is_kfunc_release(meta) && !meta->release_regno) { 9787 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 9788 func_name); 9789 return -EINVAL; 9790 } 9791 9792 return 0; 9793 } 9794 9795 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9796 int *insn_idx_p) 9797 { 9798 const struct btf_type *t, *func, *func_proto, *ptr_type; 9799 u32 i, nargs, func_id, ptr_type_id, release_ref_obj_id; 9800 struct bpf_reg_state *regs = cur_regs(env); 9801 const char *func_name, *ptr_type_name; 9802 bool sleepable, rcu_lock, rcu_unlock; 9803 struct bpf_kfunc_call_arg_meta meta; 9804 int err, insn_idx = *insn_idx_p; 9805 const struct btf_param *args; 9806 const struct btf_type *ret_t; 9807 struct btf *desc_btf; 9808 u32 *kfunc_flags; 9809 9810 /* skip for now, but return error when we find this in fixup_kfunc_call */ 9811 if (!insn->imm) 9812 return 0; 9813 9814 desc_btf = find_kfunc_desc_btf(env, insn->off); 9815 if (IS_ERR(desc_btf)) 9816 return PTR_ERR(desc_btf); 9817 9818 func_id = insn->imm; 9819 func = btf_type_by_id(desc_btf, func_id); 9820 func_name = btf_name_by_offset(desc_btf, func->name_off); 9821 func_proto = btf_type_by_id(desc_btf, func->type); 9822 9823 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id); 9824 if (!kfunc_flags) { 9825 verbose(env, "calling kernel function %s is not allowed\n", 9826 func_name); 9827 return -EACCES; 9828 } 9829 9830 /* Prepare kfunc call metadata */ 9831 memset(&meta, 0, sizeof(meta)); 9832 meta.btf = desc_btf; 9833 meta.func_id = func_id; 9834 meta.kfunc_flags = *kfunc_flags; 9835 meta.func_proto = func_proto; 9836 meta.func_name = func_name; 9837 9838 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 9839 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 9840 return -EACCES; 9841 } 9842 9843 sleepable = is_kfunc_sleepable(&meta); 9844 if (sleepable && !env->prog->aux->sleepable) { 9845 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 9846 return -EACCES; 9847 } 9848 9849 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 9850 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 9851 if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) { 9852 verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name); 9853 return -EACCES; 9854 } 9855 9856 if (env->cur_state->active_rcu_lock) { 9857 struct bpf_func_state *state; 9858 struct bpf_reg_state *reg; 9859 9860 if (rcu_lock) { 9861 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 9862 return -EINVAL; 9863 } else if (rcu_unlock) { 9864 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9865 if (reg->type & MEM_RCU) { 9866 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 9867 reg->type |= PTR_UNTRUSTED; 9868 } 9869 })); 9870 env->cur_state->active_rcu_lock = false; 9871 } else if (sleepable) { 9872 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 9873 return -EACCES; 9874 } 9875 } else if (rcu_lock) { 9876 env->cur_state->active_rcu_lock = true; 9877 } else if (rcu_unlock) { 9878 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 9879 return -EINVAL; 9880 } 9881 9882 /* Check the arguments */ 9883 err = check_kfunc_args(env, &meta); 9884 if (err < 0) 9885 return err; 9886 /* In case of release function, we get register number of refcounted 9887 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 9888 */ 9889 if (meta.release_regno) { 9890 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 9891 if (err) { 9892 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 9893 func_name, func_id); 9894 return err; 9895 } 9896 } 9897 9898 if (meta.func_id == special_kfunc_list[KF_bpf_list_push_front] || 9899 meta.func_id == special_kfunc_list[KF_bpf_list_push_back] || 9900 meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) { 9901 release_ref_obj_id = regs[BPF_REG_2].ref_obj_id; 9902 err = ref_convert_owning_non_owning(env, release_ref_obj_id); 9903 if (err) { 9904 verbose(env, "kfunc %s#%d conversion of owning ref to non-owning failed\n", 9905 func_name, func_id); 9906 return err; 9907 } 9908 9909 err = release_reference(env, release_ref_obj_id); 9910 if (err) { 9911 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 9912 func_name, func_id); 9913 return err; 9914 } 9915 } 9916 9917 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_add]) { 9918 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 9919 set_rbtree_add_callback_state); 9920 if (err) { 9921 verbose(env, "kfunc %s#%d failed callback verification\n", 9922 func_name, func_id); 9923 return err; 9924 } 9925 } 9926 9927 for (i = 0; i < CALLER_SAVED_REGS; i++) 9928 mark_reg_not_init(env, regs, caller_saved[i]); 9929 9930 /* Check return type */ 9931 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL); 9932 9933 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 9934 /* Only exception is bpf_obj_new_impl */ 9935 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) { 9936 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 9937 return -EINVAL; 9938 } 9939 } 9940 9941 if (btf_type_is_scalar(t)) { 9942 mark_reg_unknown(env, regs, BPF_REG_0); 9943 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 9944 } else if (btf_type_is_ptr(t)) { 9945 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 9946 9947 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 9948 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 9949 struct btf *ret_btf; 9950 u32 ret_btf_id; 9951 9952 if (unlikely(!bpf_global_ma_set)) 9953 return -ENOMEM; 9954 9955 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 9956 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 9957 return -EINVAL; 9958 } 9959 9960 ret_btf = env->prog->aux->btf; 9961 ret_btf_id = meta.arg_constant.value; 9962 9963 /* This may be NULL due to user not supplying a BTF */ 9964 if (!ret_btf) { 9965 verbose(env, "bpf_obj_new requires prog BTF\n"); 9966 return -EINVAL; 9967 } 9968 9969 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 9970 if (!ret_t || !__btf_type_is_struct(ret_t)) { 9971 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 9972 return -EINVAL; 9973 } 9974 9975 mark_reg_known_zero(env, regs, BPF_REG_0); 9976 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 9977 regs[BPF_REG_0].btf = ret_btf; 9978 regs[BPF_REG_0].btf_id = ret_btf_id; 9979 9980 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size; 9981 env->insn_aux_data[insn_idx].kptr_struct_meta = 9982 btf_find_struct_meta(ret_btf, ret_btf_id); 9983 } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 9984 env->insn_aux_data[insn_idx].kptr_struct_meta = 9985 btf_find_struct_meta(meta.arg_obj_drop.btf, 9986 meta.arg_obj_drop.btf_id); 9987 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 9988 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 9989 struct btf_field *field = meta.arg_list_head.field; 9990 9991 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 9992 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove] || 9993 meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 9994 struct btf_field *field = meta.arg_rbtree_root.field; 9995 9996 mark_reg_graph_node(regs, BPF_REG_0, &field->graph_root); 9997 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 9998 mark_reg_known_zero(env, regs, BPF_REG_0); 9999 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 10000 regs[BPF_REG_0].btf = desc_btf; 10001 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 10002 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 10003 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 10004 if (!ret_t || !btf_type_is_struct(ret_t)) { 10005 verbose(env, 10006 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 10007 return -EINVAL; 10008 } 10009 10010 mark_reg_known_zero(env, regs, BPF_REG_0); 10011 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 10012 regs[BPF_REG_0].btf = desc_btf; 10013 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 10014 } else { 10015 verbose(env, "kernel function %s unhandled dynamic return type\n", 10016 meta.func_name); 10017 return -EFAULT; 10018 } 10019 } else if (!__btf_type_is_struct(ptr_type)) { 10020 if (!meta.r0_size) { 10021 ptr_type_name = btf_name_by_offset(desc_btf, 10022 ptr_type->name_off); 10023 verbose(env, 10024 "kernel function %s returns pointer type %s %s is not supported\n", 10025 func_name, 10026 btf_type_str(ptr_type), 10027 ptr_type_name); 10028 return -EINVAL; 10029 } 10030 10031 mark_reg_known_zero(env, regs, BPF_REG_0); 10032 regs[BPF_REG_0].type = PTR_TO_MEM; 10033 regs[BPF_REG_0].mem_size = meta.r0_size; 10034 10035 if (meta.r0_rdonly) 10036 regs[BPF_REG_0].type |= MEM_RDONLY; 10037 10038 /* Ensures we don't access the memory after a release_reference() */ 10039 if (meta.ref_obj_id) 10040 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 10041 } else { 10042 mark_reg_known_zero(env, regs, BPF_REG_0); 10043 regs[BPF_REG_0].btf = desc_btf; 10044 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 10045 regs[BPF_REG_0].btf_id = ptr_type_id; 10046 } 10047 10048 if (is_kfunc_ret_null(&meta)) { 10049 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 10050 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 10051 regs[BPF_REG_0].id = ++env->id_gen; 10052 } 10053 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 10054 if (is_kfunc_acquire(&meta)) { 10055 int id = acquire_reference_state(env, insn_idx); 10056 10057 if (id < 0) 10058 return id; 10059 if (is_kfunc_ret_null(&meta)) 10060 regs[BPF_REG_0].id = id; 10061 regs[BPF_REG_0].ref_obj_id = id; 10062 } else if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_first]) { 10063 ref_set_non_owning(env, ®s[BPF_REG_0]); 10064 } 10065 10066 if (meta.func_id == special_kfunc_list[KF_bpf_rbtree_remove]) 10067 invalidate_non_owning_refs(env); 10068 10069 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 10070 regs[BPF_REG_0].id = ++env->id_gen; 10071 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */ 10072 10073 nargs = btf_type_vlen(func_proto); 10074 args = (const struct btf_param *)(func_proto + 1); 10075 for (i = 0; i < nargs; i++) { 10076 u32 regno = i + 1; 10077 10078 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 10079 if (btf_type_is_ptr(t)) 10080 mark_btf_func_reg_size(env, regno, sizeof(void *)); 10081 else 10082 /* scalar. ensured by btf_check_kfunc_arg_match() */ 10083 mark_btf_func_reg_size(env, regno, t->size); 10084 } 10085 10086 return 0; 10087 } 10088 10089 static bool signed_add_overflows(s64 a, s64 b) 10090 { 10091 /* Do the add in u64, where overflow is well-defined */ 10092 s64 res = (s64)((u64)a + (u64)b); 10093 10094 if (b < 0) 10095 return res > a; 10096 return res < a; 10097 } 10098 10099 static bool signed_add32_overflows(s32 a, s32 b) 10100 { 10101 /* Do the add in u32, where overflow is well-defined */ 10102 s32 res = (s32)((u32)a + (u32)b); 10103 10104 if (b < 0) 10105 return res > a; 10106 return res < a; 10107 } 10108 10109 static bool signed_sub_overflows(s64 a, s64 b) 10110 { 10111 /* Do the sub in u64, where overflow is well-defined */ 10112 s64 res = (s64)((u64)a - (u64)b); 10113 10114 if (b < 0) 10115 return res < a; 10116 return res > a; 10117 } 10118 10119 static bool signed_sub32_overflows(s32 a, s32 b) 10120 { 10121 /* Do the sub in u32, where overflow is well-defined */ 10122 s32 res = (s32)((u32)a - (u32)b); 10123 10124 if (b < 0) 10125 return res < a; 10126 return res > a; 10127 } 10128 10129 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 10130 const struct bpf_reg_state *reg, 10131 enum bpf_reg_type type) 10132 { 10133 bool known = tnum_is_const(reg->var_off); 10134 s64 val = reg->var_off.value; 10135 s64 smin = reg->smin_value; 10136 10137 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 10138 verbose(env, "math between %s pointer and %lld is not allowed\n", 10139 reg_type_str(env, type), val); 10140 return false; 10141 } 10142 10143 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 10144 verbose(env, "%s pointer offset %d is not allowed\n", 10145 reg_type_str(env, type), reg->off); 10146 return false; 10147 } 10148 10149 if (smin == S64_MIN) { 10150 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 10151 reg_type_str(env, type)); 10152 return false; 10153 } 10154 10155 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 10156 verbose(env, "value %lld makes %s pointer be out of bounds\n", 10157 smin, reg_type_str(env, type)); 10158 return false; 10159 } 10160 10161 return true; 10162 } 10163 10164 enum { 10165 REASON_BOUNDS = -1, 10166 REASON_TYPE = -2, 10167 REASON_PATHS = -3, 10168 REASON_LIMIT = -4, 10169 REASON_STACK = -5, 10170 }; 10171 10172 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 10173 u32 *alu_limit, bool mask_to_left) 10174 { 10175 u32 max = 0, ptr_limit = 0; 10176 10177 switch (ptr_reg->type) { 10178 case PTR_TO_STACK: 10179 /* Offset 0 is out-of-bounds, but acceptable start for the 10180 * left direction, see BPF_REG_FP. Also, unknown scalar 10181 * offset where we would need to deal with min/max bounds is 10182 * currently prohibited for unprivileged. 10183 */ 10184 max = MAX_BPF_STACK + mask_to_left; 10185 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 10186 break; 10187 case PTR_TO_MAP_VALUE: 10188 max = ptr_reg->map_ptr->value_size; 10189 ptr_limit = (mask_to_left ? 10190 ptr_reg->smin_value : 10191 ptr_reg->umax_value) + ptr_reg->off; 10192 break; 10193 default: 10194 return REASON_TYPE; 10195 } 10196 10197 if (ptr_limit >= max) 10198 return REASON_LIMIT; 10199 *alu_limit = ptr_limit; 10200 return 0; 10201 } 10202 10203 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 10204 const struct bpf_insn *insn) 10205 { 10206 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 10207 } 10208 10209 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 10210 u32 alu_state, u32 alu_limit) 10211 { 10212 /* If we arrived here from different branches with different 10213 * state or limits to sanitize, then this won't work. 10214 */ 10215 if (aux->alu_state && 10216 (aux->alu_state != alu_state || 10217 aux->alu_limit != alu_limit)) 10218 return REASON_PATHS; 10219 10220 /* Corresponding fixup done in do_misc_fixups(). */ 10221 aux->alu_state = alu_state; 10222 aux->alu_limit = alu_limit; 10223 return 0; 10224 } 10225 10226 static int sanitize_val_alu(struct bpf_verifier_env *env, 10227 struct bpf_insn *insn) 10228 { 10229 struct bpf_insn_aux_data *aux = cur_aux(env); 10230 10231 if (can_skip_alu_sanitation(env, insn)) 10232 return 0; 10233 10234 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 10235 } 10236 10237 static bool sanitize_needed(u8 opcode) 10238 { 10239 return opcode == BPF_ADD || opcode == BPF_SUB; 10240 } 10241 10242 struct bpf_sanitize_info { 10243 struct bpf_insn_aux_data aux; 10244 bool mask_to_left; 10245 }; 10246 10247 static struct bpf_verifier_state * 10248 sanitize_speculative_path(struct bpf_verifier_env *env, 10249 const struct bpf_insn *insn, 10250 u32 next_idx, u32 curr_idx) 10251 { 10252 struct bpf_verifier_state *branch; 10253 struct bpf_reg_state *regs; 10254 10255 branch = push_stack(env, next_idx, curr_idx, true); 10256 if (branch && insn) { 10257 regs = branch->frame[branch->curframe]->regs; 10258 if (BPF_SRC(insn->code) == BPF_K) { 10259 mark_reg_unknown(env, regs, insn->dst_reg); 10260 } else if (BPF_SRC(insn->code) == BPF_X) { 10261 mark_reg_unknown(env, regs, insn->dst_reg); 10262 mark_reg_unknown(env, regs, insn->src_reg); 10263 } 10264 } 10265 return branch; 10266 } 10267 10268 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 10269 struct bpf_insn *insn, 10270 const struct bpf_reg_state *ptr_reg, 10271 const struct bpf_reg_state *off_reg, 10272 struct bpf_reg_state *dst_reg, 10273 struct bpf_sanitize_info *info, 10274 const bool commit_window) 10275 { 10276 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 10277 struct bpf_verifier_state *vstate = env->cur_state; 10278 bool off_is_imm = tnum_is_const(off_reg->var_off); 10279 bool off_is_neg = off_reg->smin_value < 0; 10280 bool ptr_is_dst_reg = ptr_reg == dst_reg; 10281 u8 opcode = BPF_OP(insn->code); 10282 u32 alu_state, alu_limit; 10283 struct bpf_reg_state tmp; 10284 bool ret; 10285 int err; 10286 10287 if (can_skip_alu_sanitation(env, insn)) 10288 return 0; 10289 10290 /* We already marked aux for masking from non-speculative 10291 * paths, thus we got here in the first place. We only care 10292 * to explore bad access from here. 10293 */ 10294 if (vstate->speculative) 10295 goto do_sim; 10296 10297 if (!commit_window) { 10298 if (!tnum_is_const(off_reg->var_off) && 10299 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 10300 return REASON_BOUNDS; 10301 10302 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 10303 (opcode == BPF_SUB && !off_is_neg); 10304 } 10305 10306 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 10307 if (err < 0) 10308 return err; 10309 10310 if (commit_window) { 10311 /* In commit phase we narrow the masking window based on 10312 * the observed pointer move after the simulated operation. 10313 */ 10314 alu_state = info->aux.alu_state; 10315 alu_limit = abs(info->aux.alu_limit - alu_limit); 10316 } else { 10317 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 10318 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 10319 alu_state |= ptr_is_dst_reg ? 10320 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 10321 10322 /* Limit pruning on unknown scalars to enable deep search for 10323 * potential masking differences from other program paths. 10324 */ 10325 if (!off_is_imm) 10326 env->explore_alu_limits = true; 10327 } 10328 10329 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 10330 if (err < 0) 10331 return err; 10332 do_sim: 10333 /* If we're in commit phase, we're done here given we already 10334 * pushed the truncated dst_reg into the speculative verification 10335 * stack. 10336 * 10337 * Also, when register is a known constant, we rewrite register-based 10338 * operation to immediate-based, and thus do not need masking (and as 10339 * a consequence, do not need to simulate the zero-truncation either). 10340 */ 10341 if (commit_window || off_is_imm) 10342 return 0; 10343 10344 /* Simulate and find potential out-of-bounds access under 10345 * speculative execution from truncation as a result of 10346 * masking when off was not within expected range. If off 10347 * sits in dst, then we temporarily need to move ptr there 10348 * to simulate dst (== 0) +/-= ptr. Needed, for example, 10349 * for cases where we use K-based arithmetic in one direction 10350 * and truncated reg-based in the other in order to explore 10351 * bad access. 10352 */ 10353 if (!ptr_is_dst_reg) { 10354 tmp = *dst_reg; 10355 copy_register_state(dst_reg, ptr_reg); 10356 } 10357 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 10358 env->insn_idx); 10359 if (!ptr_is_dst_reg && ret) 10360 *dst_reg = tmp; 10361 return !ret ? REASON_STACK : 0; 10362 } 10363 10364 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 10365 { 10366 struct bpf_verifier_state *vstate = env->cur_state; 10367 10368 /* If we simulate paths under speculation, we don't update the 10369 * insn as 'seen' such that when we verify unreachable paths in 10370 * the non-speculative domain, sanitize_dead_code() can still 10371 * rewrite/sanitize them. 10372 */ 10373 if (!vstate->speculative) 10374 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 10375 } 10376 10377 static int sanitize_err(struct bpf_verifier_env *env, 10378 const struct bpf_insn *insn, int reason, 10379 const struct bpf_reg_state *off_reg, 10380 const struct bpf_reg_state *dst_reg) 10381 { 10382 static const char *err = "pointer arithmetic with it prohibited for !root"; 10383 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 10384 u32 dst = insn->dst_reg, src = insn->src_reg; 10385 10386 switch (reason) { 10387 case REASON_BOUNDS: 10388 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 10389 off_reg == dst_reg ? dst : src, err); 10390 break; 10391 case REASON_TYPE: 10392 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 10393 off_reg == dst_reg ? src : dst, err); 10394 break; 10395 case REASON_PATHS: 10396 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 10397 dst, op, err); 10398 break; 10399 case REASON_LIMIT: 10400 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 10401 dst, op, err); 10402 break; 10403 case REASON_STACK: 10404 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 10405 dst, err); 10406 break; 10407 default: 10408 verbose(env, "verifier internal error: unknown reason (%d)\n", 10409 reason); 10410 break; 10411 } 10412 10413 return -EACCES; 10414 } 10415 10416 /* check that stack access falls within stack limits and that 'reg' doesn't 10417 * have a variable offset. 10418 * 10419 * Variable offset is prohibited for unprivileged mode for simplicity since it 10420 * requires corresponding support in Spectre masking for stack ALU. See also 10421 * retrieve_ptr_limit(). 10422 * 10423 * 10424 * 'off' includes 'reg->off'. 10425 */ 10426 static int check_stack_access_for_ptr_arithmetic( 10427 struct bpf_verifier_env *env, 10428 int regno, 10429 const struct bpf_reg_state *reg, 10430 int off) 10431 { 10432 if (!tnum_is_const(reg->var_off)) { 10433 char tn_buf[48]; 10434 10435 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 10436 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 10437 regno, tn_buf, off); 10438 return -EACCES; 10439 } 10440 10441 if (off >= 0 || off < -MAX_BPF_STACK) { 10442 verbose(env, "R%d stack pointer arithmetic goes out of range, " 10443 "prohibited for !root; off=%d\n", regno, off); 10444 return -EACCES; 10445 } 10446 10447 return 0; 10448 } 10449 10450 static int sanitize_check_bounds(struct bpf_verifier_env *env, 10451 const struct bpf_insn *insn, 10452 const struct bpf_reg_state *dst_reg) 10453 { 10454 u32 dst = insn->dst_reg; 10455 10456 /* For unprivileged we require that resulting offset must be in bounds 10457 * in order to be able to sanitize access later on. 10458 */ 10459 if (env->bypass_spec_v1) 10460 return 0; 10461 10462 switch (dst_reg->type) { 10463 case PTR_TO_STACK: 10464 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 10465 dst_reg->off + dst_reg->var_off.value)) 10466 return -EACCES; 10467 break; 10468 case PTR_TO_MAP_VALUE: 10469 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 10470 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 10471 "prohibited for !root\n", dst); 10472 return -EACCES; 10473 } 10474 break; 10475 default: 10476 break; 10477 } 10478 10479 return 0; 10480 } 10481 10482 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 10483 * Caller should also handle BPF_MOV case separately. 10484 * If we return -EACCES, caller may want to try again treating pointer as a 10485 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 10486 */ 10487 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 10488 struct bpf_insn *insn, 10489 const struct bpf_reg_state *ptr_reg, 10490 const struct bpf_reg_state *off_reg) 10491 { 10492 struct bpf_verifier_state *vstate = env->cur_state; 10493 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 10494 struct bpf_reg_state *regs = state->regs, *dst_reg; 10495 bool known = tnum_is_const(off_reg->var_off); 10496 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 10497 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 10498 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 10499 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 10500 struct bpf_sanitize_info info = {}; 10501 u8 opcode = BPF_OP(insn->code); 10502 u32 dst = insn->dst_reg; 10503 int ret; 10504 10505 dst_reg = ®s[dst]; 10506 10507 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 10508 smin_val > smax_val || umin_val > umax_val) { 10509 /* Taint dst register if offset had invalid bounds derived from 10510 * e.g. dead branches. 10511 */ 10512 __mark_reg_unknown(env, dst_reg); 10513 return 0; 10514 } 10515 10516 if (BPF_CLASS(insn->code) != BPF_ALU64) { 10517 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 10518 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 10519 __mark_reg_unknown(env, dst_reg); 10520 return 0; 10521 } 10522 10523 verbose(env, 10524 "R%d 32-bit pointer arithmetic prohibited\n", 10525 dst); 10526 return -EACCES; 10527 } 10528 10529 if (ptr_reg->type & PTR_MAYBE_NULL) { 10530 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 10531 dst, reg_type_str(env, ptr_reg->type)); 10532 return -EACCES; 10533 } 10534 10535 switch (base_type(ptr_reg->type)) { 10536 case CONST_PTR_TO_MAP: 10537 /* smin_val represents the known value */ 10538 if (known && smin_val == 0 && opcode == BPF_ADD) 10539 break; 10540 fallthrough; 10541 case PTR_TO_PACKET_END: 10542 case PTR_TO_SOCKET: 10543 case PTR_TO_SOCK_COMMON: 10544 case PTR_TO_TCP_SOCK: 10545 case PTR_TO_XDP_SOCK: 10546 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 10547 dst, reg_type_str(env, ptr_reg->type)); 10548 return -EACCES; 10549 default: 10550 break; 10551 } 10552 10553 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 10554 * The id may be overwritten later if we create a new variable offset. 10555 */ 10556 dst_reg->type = ptr_reg->type; 10557 dst_reg->id = ptr_reg->id; 10558 10559 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 10560 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 10561 return -EINVAL; 10562 10563 /* pointer types do not carry 32-bit bounds at the moment. */ 10564 __mark_reg32_unbounded(dst_reg); 10565 10566 if (sanitize_needed(opcode)) { 10567 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 10568 &info, false); 10569 if (ret < 0) 10570 return sanitize_err(env, insn, ret, off_reg, dst_reg); 10571 } 10572 10573 switch (opcode) { 10574 case BPF_ADD: 10575 /* We can take a fixed offset as long as it doesn't overflow 10576 * the s32 'off' field 10577 */ 10578 if (known && (ptr_reg->off + smin_val == 10579 (s64)(s32)(ptr_reg->off + smin_val))) { 10580 /* pointer += K. Accumulate it into fixed offset */ 10581 dst_reg->smin_value = smin_ptr; 10582 dst_reg->smax_value = smax_ptr; 10583 dst_reg->umin_value = umin_ptr; 10584 dst_reg->umax_value = umax_ptr; 10585 dst_reg->var_off = ptr_reg->var_off; 10586 dst_reg->off = ptr_reg->off + smin_val; 10587 dst_reg->raw = ptr_reg->raw; 10588 break; 10589 } 10590 /* A new variable offset is created. Note that off_reg->off 10591 * == 0, since it's a scalar. 10592 * dst_reg gets the pointer type and since some positive 10593 * integer value was added to the pointer, give it a new 'id' 10594 * if it's a PTR_TO_PACKET. 10595 * this creates a new 'base' pointer, off_reg (variable) gets 10596 * added into the variable offset, and we copy the fixed offset 10597 * from ptr_reg. 10598 */ 10599 if (signed_add_overflows(smin_ptr, smin_val) || 10600 signed_add_overflows(smax_ptr, smax_val)) { 10601 dst_reg->smin_value = S64_MIN; 10602 dst_reg->smax_value = S64_MAX; 10603 } else { 10604 dst_reg->smin_value = smin_ptr + smin_val; 10605 dst_reg->smax_value = smax_ptr + smax_val; 10606 } 10607 if (umin_ptr + umin_val < umin_ptr || 10608 umax_ptr + umax_val < umax_ptr) { 10609 dst_reg->umin_value = 0; 10610 dst_reg->umax_value = U64_MAX; 10611 } else { 10612 dst_reg->umin_value = umin_ptr + umin_val; 10613 dst_reg->umax_value = umax_ptr + umax_val; 10614 } 10615 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 10616 dst_reg->off = ptr_reg->off; 10617 dst_reg->raw = ptr_reg->raw; 10618 if (reg_is_pkt_pointer(ptr_reg)) { 10619 dst_reg->id = ++env->id_gen; 10620 /* something was added to pkt_ptr, set range to zero */ 10621 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 10622 } 10623 break; 10624 case BPF_SUB: 10625 if (dst_reg == off_reg) { 10626 /* scalar -= pointer. Creates an unknown scalar */ 10627 verbose(env, "R%d tried to subtract pointer from scalar\n", 10628 dst); 10629 return -EACCES; 10630 } 10631 /* We don't allow subtraction from FP, because (according to 10632 * test_verifier.c test "invalid fp arithmetic", JITs might not 10633 * be able to deal with it. 10634 */ 10635 if (ptr_reg->type == PTR_TO_STACK) { 10636 verbose(env, "R%d subtraction from stack pointer prohibited\n", 10637 dst); 10638 return -EACCES; 10639 } 10640 if (known && (ptr_reg->off - smin_val == 10641 (s64)(s32)(ptr_reg->off - smin_val))) { 10642 /* pointer -= K. Subtract it from fixed offset */ 10643 dst_reg->smin_value = smin_ptr; 10644 dst_reg->smax_value = smax_ptr; 10645 dst_reg->umin_value = umin_ptr; 10646 dst_reg->umax_value = umax_ptr; 10647 dst_reg->var_off = ptr_reg->var_off; 10648 dst_reg->id = ptr_reg->id; 10649 dst_reg->off = ptr_reg->off - smin_val; 10650 dst_reg->raw = ptr_reg->raw; 10651 break; 10652 } 10653 /* A new variable offset is created. If the subtrahend is known 10654 * nonnegative, then any reg->range we had before is still good. 10655 */ 10656 if (signed_sub_overflows(smin_ptr, smax_val) || 10657 signed_sub_overflows(smax_ptr, smin_val)) { 10658 /* Overflow possible, we know nothing */ 10659 dst_reg->smin_value = S64_MIN; 10660 dst_reg->smax_value = S64_MAX; 10661 } else { 10662 dst_reg->smin_value = smin_ptr - smax_val; 10663 dst_reg->smax_value = smax_ptr - smin_val; 10664 } 10665 if (umin_ptr < umax_val) { 10666 /* Overflow possible, we know nothing */ 10667 dst_reg->umin_value = 0; 10668 dst_reg->umax_value = U64_MAX; 10669 } else { 10670 /* Cannot overflow (as long as bounds are consistent) */ 10671 dst_reg->umin_value = umin_ptr - umax_val; 10672 dst_reg->umax_value = umax_ptr - umin_val; 10673 } 10674 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 10675 dst_reg->off = ptr_reg->off; 10676 dst_reg->raw = ptr_reg->raw; 10677 if (reg_is_pkt_pointer(ptr_reg)) { 10678 dst_reg->id = ++env->id_gen; 10679 /* something was added to pkt_ptr, set range to zero */ 10680 if (smin_val < 0) 10681 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 10682 } 10683 break; 10684 case BPF_AND: 10685 case BPF_OR: 10686 case BPF_XOR: 10687 /* bitwise ops on pointers are troublesome, prohibit. */ 10688 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 10689 dst, bpf_alu_string[opcode >> 4]); 10690 return -EACCES; 10691 default: 10692 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 10693 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 10694 dst, bpf_alu_string[opcode >> 4]); 10695 return -EACCES; 10696 } 10697 10698 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 10699 return -EINVAL; 10700 reg_bounds_sync(dst_reg); 10701 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 10702 return -EACCES; 10703 if (sanitize_needed(opcode)) { 10704 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 10705 &info, true); 10706 if (ret < 0) 10707 return sanitize_err(env, insn, ret, off_reg, dst_reg); 10708 } 10709 10710 return 0; 10711 } 10712 10713 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 10714 struct bpf_reg_state *src_reg) 10715 { 10716 s32 smin_val = src_reg->s32_min_value; 10717 s32 smax_val = src_reg->s32_max_value; 10718 u32 umin_val = src_reg->u32_min_value; 10719 u32 umax_val = src_reg->u32_max_value; 10720 10721 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 10722 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 10723 dst_reg->s32_min_value = S32_MIN; 10724 dst_reg->s32_max_value = S32_MAX; 10725 } else { 10726 dst_reg->s32_min_value += smin_val; 10727 dst_reg->s32_max_value += smax_val; 10728 } 10729 if (dst_reg->u32_min_value + umin_val < umin_val || 10730 dst_reg->u32_max_value + umax_val < umax_val) { 10731 dst_reg->u32_min_value = 0; 10732 dst_reg->u32_max_value = U32_MAX; 10733 } else { 10734 dst_reg->u32_min_value += umin_val; 10735 dst_reg->u32_max_value += umax_val; 10736 } 10737 } 10738 10739 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 10740 struct bpf_reg_state *src_reg) 10741 { 10742 s64 smin_val = src_reg->smin_value; 10743 s64 smax_val = src_reg->smax_value; 10744 u64 umin_val = src_reg->umin_value; 10745 u64 umax_val = src_reg->umax_value; 10746 10747 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 10748 signed_add_overflows(dst_reg->smax_value, smax_val)) { 10749 dst_reg->smin_value = S64_MIN; 10750 dst_reg->smax_value = S64_MAX; 10751 } else { 10752 dst_reg->smin_value += smin_val; 10753 dst_reg->smax_value += smax_val; 10754 } 10755 if (dst_reg->umin_value + umin_val < umin_val || 10756 dst_reg->umax_value + umax_val < umax_val) { 10757 dst_reg->umin_value = 0; 10758 dst_reg->umax_value = U64_MAX; 10759 } else { 10760 dst_reg->umin_value += umin_val; 10761 dst_reg->umax_value += umax_val; 10762 } 10763 } 10764 10765 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 10766 struct bpf_reg_state *src_reg) 10767 { 10768 s32 smin_val = src_reg->s32_min_value; 10769 s32 smax_val = src_reg->s32_max_value; 10770 u32 umin_val = src_reg->u32_min_value; 10771 u32 umax_val = src_reg->u32_max_value; 10772 10773 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 10774 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 10775 /* Overflow possible, we know nothing */ 10776 dst_reg->s32_min_value = S32_MIN; 10777 dst_reg->s32_max_value = S32_MAX; 10778 } else { 10779 dst_reg->s32_min_value -= smax_val; 10780 dst_reg->s32_max_value -= smin_val; 10781 } 10782 if (dst_reg->u32_min_value < umax_val) { 10783 /* Overflow possible, we know nothing */ 10784 dst_reg->u32_min_value = 0; 10785 dst_reg->u32_max_value = U32_MAX; 10786 } else { 10787 /* Cannot overflow (as long as bounds are consistent) */ 10788 dst_reg->u32_min_value -= umax_val; 10789 dst_reg->u32_max_value -= umin_val; 10790 } 10791 } 10792 10793 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 10794 struct bpf_reg_state *src_reg) 10795 { 10796 s64 smin_val = src_reg->smin_value; 10797 s64 smax_val = src_reg->smax_value; 10798 u64 umin_val = src_reg->umin_value; 10799 u64 umax_val = src_reg->umax_value; 10800 10801 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 10802 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 10803 /* Overflow possible, we know nothing */ 10804 dst_reg->smin_value = S64_MIN; 10805 dst_reg->smax_value = S64_MAX; 10806 } else { 10807 dst_reg->smin_value -= smax_val; 10808 dst_reg->smax_value -= smin_val; 10809 } 10810 if (dst_reg->umin_value < umax_val) { 10811 /* Overflow possible, we know nothing */ 10812 dst_reg->umin_value = 0; 10813 dst_reg->umax_value = U64_MAX; 10814 } else { 10815 /* Cannot overflow (as long as bounds are consistent) */ 10816 dst_reg->umin_value -= umax_val; 10817 dst_reg->umax_value -= umin_val; 10818 } 10819 } 10820 10821 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 10822 struct bpf_reg_state *src_reg) 10823 { 10824 s32 smin_val = src_reg->s32_min_value; 10825 u32 umin_val = src_reg->u32_min_value; 10826 u32 umax_val = src_reg->u32_max_value; 10827 10828 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 10829 /* Ain't nobody got time to multiply that sign */ 10830 __mark_reg32_unbounded(dst_reg); 10831 return; 10832 } 10833 /* Both values are positive, so we can work with unsigned and 10834 * copy the result to signed (unless it exceeds S32_MAX). 10835 */ 10836 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 10837 /* Potential overflow, we know nothing */ 10838 __mark_reg32_unbounded(dst_reg); 10839 return; 10840 } 10841 dst_reg->u32_min_value *= umin_val; 10842 dst_reg->u32_max_value *= umax_val; 10843 if (dst_reg->u32_max_value > S32_MAX) { 10844 /* Overflow possible, we know nothing */ 10845 dst_reg->s32_min_value = S32_MIN; 10846 dst_reg->s32_max_value = S32_MAX; 10847 } else { 10848 dst_reg->s32_min_value = dst_reg->u32_min_value; 10849 dst_reg->s32_max_value = dst_reg->u32_max_value; 10850 } 10851 } 10852 10853 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 10854 struct bpf_reg_state *src_reg) 10855 { 10856 s64 smin_val = src_reg->smin_value; 10857 u64 umin_val = src_reg->umin_value; 10858 u64 umax_val = src_reg->umax_value; 10859 10860 if (smin_val < 0 || dst_reg->smin_value < 0) { 10861 /* Ain't nobody got time to multiply that sign */ 10862 __mark_reg64_unbounded(dst_reg); 10863 return; 10864 } 10865 /* Both values are positive, so we can work with unsigned and 10866 * copy the result to signed (unless it exceeds S64_MAX). 10867 */ 10868 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 10869 /* Potential overflow, we know nothing */ 10870 __mark_reg64_unbounded(dst_reg); 10871 return; 10872 } 10873 dst_reg->umin_value *= umin_val; 10874 dst_reg->umax_value *= umax_val; 10875 if (dst_reg->umax_value > S64_MAX) { 10876 /* Overflow possible, we know nothing */ 10877 dst_reg->smin_value = S64_MIN; 10878 dst_reg->smax_value = S64_MAX; 10879 } else { 10880 dst_reg->smin_value = dst_reg->umin_value; 10881 dst_reg->smax_value = dst_reg->umax_value; 10882 } 10883 } 10884 10885 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 10886 struct bpf_reg_state *src_reg) 10887 { 10888 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10889 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10890 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10891 s32 smin_val = src_reg->s32_min_value; 10892 u32 umax_val = src_reg->u32_max_value; 10893 10894 if (src_known && dst_known) { 10895 __mark_reg32_known(dst_reg, var32_off.value); 10896 return; 10897 } 10898 10899 /* We get our minimum from the var_off, since that's inherently 10900 * bitwise. Our maximum is the minimum of the operands' maxima. 10901 */ 10902 dst_reg->u32_min_value = var32_off.value; 10903 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 10904 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 10905 /* Lose signed bounds when ANDing negative numbers, 10906 * ain't nobody got time for that. 10907 */ 10908 dst_reg->s32_min_value = S32_MIN; 10909 dst_reg->s32_max_value = S32_MAX; 10910 } else { 10911 /* ANDing two positives gives a positive, so safe to 10912 * cast result into s64. 10913 */ 10914 dst_reg->s32_min_value = dst_reg->u32_min_value; 10915 dst_reg->s32_max_value = dst_reg->u32_max_value; 10916 } 10917 } 10918 10919 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 10920 struct bpf_reg_state *src_reg) 10921 { 10922 bool src_known = tnum_is_const(src_reg->var_off); 10923 bool dst_known = tnum_is_const(dst_reg->var_off); 10924 s64 smin_val = src_reg->smin_value; 10925 u64 umax_val = src_reg->umax_value; 10926 10927 if (src_known && dst_known) { 10928 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10929 return; 10930 } 10931 10932 /* We get our minimum from the var_off, since that's inherently 10933 * bitwise. Our maximum is the minimum of the operands' maxima. 10934 */ 10935 dst_reg->umin_value = dst_reg->var_off.value; 10936 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 10937 if (dst_reg->smin_value < 0 || smin_val < 0) { 10938 /* Lose signed bounds when ANDing negative numbers, 10939 * ain't nobody got time for that. 10940 */ 10941 dst_reg->smin_value = S64_MIN; 10942 dst_reg->smax_value = S64_MAX; 10943 } else { 10944 /* ANDing two positives gives a positive, so safe to 10945 * cast result into s64. 10946 */ 10947 dst_reg->smin_value = dst_reg->umin_value; 10948 dst_reg->smax_value = dst_reg->umax_value; 10949 } 10950 /* We may learn something more from the var_off */ 10951 __update_reg_bounds(dst_reg); 10952 } 10953 10954 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 10955 struct bpf_reg_state *src_reg) 10956 { 10957 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10958 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10959 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10960 s32 smin_val = src_reg->s32_min_value; 10961 u32 umin_val = src_reg->u32_min_value; 10962 10963 if (src_known && dst_known) { 10964 __mark_reg32_known(dst_reg, var32_off.value); 10965 return; 10966 } 10967 10968 /* We get our maximum from the var_off, and our minimum is the 10969 * maximum of the operands' minima 10970 */ 10971 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 10972 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 10973 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 10974 /* Lose signed bounds when ORing negative numbers, 10975 * ain't nobody got time for that. 10976 */ 10977 dst_reg->s32_min_value = S32_MIN; 10978 dst_reg->s32_max_value = S32_MAX; 10979 } else { 10980 /* ORing two positives gives a positive, so safe to 10981 * cast result into s64. 10982 */ 10983 dst_reg->s32_min_value = dst_reg->u32_min_value; 10984 dst_reg->s32_max_value = dst_reg->u32_max_value; 10985 } 10986 } 10987 10988 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 10989 struct bpf_reg_state *src_reg) 10990 { 10991 bool src_known = tnum_is_const(src_reg->var_off); 10992 bool dst_known = tnum_is_const(dst_reg->var_off); 10993 s64 smin_val = src_reg->smin_value; 10994 u64 umin_val = src_reg->umin_value; 10995 10996 if (src_known && dst_known) { 10997 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10998 return; 10999 } 11000 11001 /* We get our maximum from the var_off, and our minimum is the 11002 * maximum of the operands' minima 11003 */ 11004 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 11005 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 11006 if (dst_reg->smin_value < 0 || smin_val < 0) { 11007 /* Lose signed bounds when ORing negative numbers, 11008 * ain't nobody got time for that. 11009 */ 11010 dst_reg->smin_value = S64_MIN; 11011 dst_reg->smax_value = S64_MAX; 11012 } else { 11013 /* ORing two positives gives a positive, so safe to 11014 * cast result into s64. 11015 */ 11016 dst_reg->smin_value = dst_reg->umin_value; 11017 dst_reg->smax_value = dst_reg->umax_value; 11018 } 11019 /* We may learn something more from the var_off */ 11020 __update_reg_bounds(dst_reg); 11021 } 11022 11023 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 11024 struct bpf_reg_state *src_reg) 11025 { 11026 bool src_known = tnum_subreg_is_const(src_reg->var_off); 11027 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 11028 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 11029 s32 smin_val = src_reg->s32_min_value; 11030 11031 if (src_known && dst_known) { 11032 __mark_reg32_known(dst_reg, var32_off.value); 11033 return; 11034 } 11035 11036 /* We get both minimum and maximum from the var32_off. */ 11037 dst_reg->u32_min_value = var32_off.value; 11038 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 11039 11040 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 11041 /* XORing two positive sign numbers gives a positive, 11042 * so safe to cast u32 result into s32. 11043 */ 11044 dst_reg->s32_min_value = dst_reg->u32_min_value; 11045 dst_reg->s32_max_value = dst_reg->u32_max_value; 11046 } else { 11047 dst_reg->s32_min_value = S32_MIN; 11048 dst_reg->s32_max_value = S32_MAX; 11049 } 11050 } 11051 11052 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 11053 struct bpf_reg_state *src_reg) 11054 { 11055 bool src_known = tnum_is_const(src_reg->var_off); 11056 bool dst_known = tnum_is_const(dst_reg->var_off); 11057 s64 smin_val = src_reg->smin_value; 11058 11059 if (src_known && dst_known) { 11060 /* dst_reg->var_off.value has been updated earlier */ 11061 __mark_reg_known(dst_reg, dst_reg->var_off.value); 11062 return; 11063 } 11064 11065 /* We get both minimum and maximum from the var_off. */ 11066 dst_reg->umin_value = dst_reg->var_off.value; 11067 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 11068 11069 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 11070 /* XORing two positive sign numbers gives a positive, 11071 * so safe to cast u64 result into s64. 11072 */ 11073 dst_reg->smin_value = dst_reg->umin_value; 11074 dst_reg->smax_value = dst_reg->umax_value; 11075 } else { 11076 dst_reg->smin_value = S64_MIN; 11077 dst_reg->smax_value = S64_MAX; 11078 } 11079 11080 __update_reg_bounds(dst_reg); 11081 } 11082 11083 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 11084 u64 umin_val, u64 umax_val) 11085 { 11086 /* We lose all sign bit information (except what we can pick 11087 * up from var_off) 11088 */ 11089 dst_reg->s32_min_value = S32_MIN; 11090 dst_reg->s32_max_value = S32_MAX; 11091 /* If we might shift our top bit out, then we know nothing */ 11092 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 11093 dst_reg->u32_min_value = 0; 11094 dst_reg->u32_max_value = U32_MAX; 11095 } else { 11096 dst_reg->u32_min_value <<= umin_val; 11097 dst_reg->u32_max_value <<= umax_val; 11098 } 11099 } 11100 11101 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 11102 struct bpf_reg_state *src_reg) 11103 { 11104 u32 umax_val = src_reg->u32_max_value; 11105 u32 umin_val = src_reg->u32_min_value; 11106 /* u32 alu operation will zext upper bits */ 11107 struct tnum subreg = tnum_subreg(dst_reg->var_off); 11108 11109 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 11110 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 11111 /* Not required but being careful mark reg64 bounds as unknown so 11112 * that we are forced to pick them up from tnum and zext later and 11113 * if some path skips this step we are still safe. 11114 */ 11115 __mark_reg64_unbounded(dst_reg); 11116 __update_reg32_bounds(dst_reg); 11117 } 11118 11119 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 11120 u64 umin_val, u64 umax_val) 11121 { 11122 /* Special case <<32 because it is a common compiler pattern to sign 11123 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 11124 * positive we know this shift will also be positive so we can track 11125 * bounds correctly. Otherwise we lose all sign bit information except 11126 * what we can pick up from var_off. Perhaps we can generalize this 11127 * later to shifts of any length. 11128 */ 11129 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 11130 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 11131 else 11132 dst_reg->smax_value = S64_MAX; 11133 11134 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 11135 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 11136 else 11137 dst_reg->smin_value = S64_MIN; 11138 11139 /* If we might shift our top bit out, then we know nothing */ 11140 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 11141 dst_reg->umin_value = 0; 11142 dst_reg->umax_value = U64_MAX; 11143 } else { 11144 dst_reg->umin_value <<= umin_val; 11145 dst_reg->umax_value <<= umax_val; 11146 } 11147 } 11148 11149 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 11150 struct bpf_reg_state *src_reg) 11151 { 11152 u64 umax_val = src_reg->umax_value; 11153 u64 umin_val = src_reg->umin_value; 11154 11155 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 11156 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 11157 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 11158 11159 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 11160 /* We may learn something more from the var_off */ 11161 __update_reg_bounds(dst_reg); 11162 } 11163 11164 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 11165 struct bpf_reg_state *src_reg) 11166 { 11167 struct tnum subreg = tnum_subreg(dst_reg->var_off); 11168 u32 umax_val = src_reg->u32_max_value; 11169 u32 umin_val = src_reg->u32_min_value; 11170 11171 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 11172 * be negative, then either: 11173 * 1) src_reg might be zero, so the sign bit of the result is 11174 * unknown, so we lose our signed bounds 11175 * 2) it's known negative, thus the unsigned bounds capture the 11176 * signed bounds 11177 * 3) the signed bounds cross zero, so they tell us nothing 11178 * about the result 11179 * If the value in dst_reg is known nonnegative, then again the 11180 * unsigned bounds capture the signed bounds. 11181 * Thus, in all cases it suffices to blow away our signed bounds 11182 * and rely on inferring new ones from the unsigned bounds and 11183 * var_off of the result. 11184 */ 11185 dst_reg->s32_min_value = S32_MIN; 11186 dst_reg->s32_max_value = S32_MAX; 11187 11188 dst_reg->var_off = tnum_rshift(subreg, umin_val); 11189 dst_reg->u32_min_value >>= umax_val; 11190 dst_reg->u32_max_value >>= umin_val; 11191 11192 __mark_reg64_unbounded(dst_reg); 11193 __update_reg32_bounds(dst_reg); 11194 } 11195 11196 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 11197 struct bpf_reg_state *src_reg) 11198 { 11199 u64 umax_val = src_reg->umax_value; 11200 u64 umin_val = src_reg->umin_value; 11201 11202 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 11203 * be negative, then either: 11204 * 1) src_reg might be zero, so the sign bit of the result is 11205 * unknown, so we lose our signed bounds 11206 * 2) it's known negative, thus the unsigned bounds capture the 11207 * signed bounds 11208 * 3) the signed bounds cross zero, so they tell us nothing 11209 * about the result 11210 * If the value in dst_reg is known nonnegative, then again the 11211 * unsigned bounds capture the signed bounds. 11212 * Thus, in all cases it suffices to blow away our signed bounds 11213 * and rely on inferring new ones from the unsigned bounds and 11214 * var_off of the result. 11215 */ 11216 dst_reg->smin_value = S64_MIN; 11217 dst_reg->smax_value = S64_MAX; 11218 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 11219 dst_reg->umin_value >>= umax_val; 11220 dst_reg->umax_value >>= umin_val; 11221 11222 /* Its not easy to operate on alu32 bounds here because it depends 11223 * on bits being shifted in. Take easy way out and mark unbounded 11224 * so we can recalculate later from tnum. 11225 */ 11226 __mark_reg32_unbounded(dst_reg); 11227 __update_reg_bounds(dst_reg); 11228 } 11229 11230 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 11231 struct bpf_reg_state *src_reg) 11232 { 11233 u64 umin_val = src_reg->u32_min_value; 11234 11235 /* Upon reaching here, src_known is true and 11236 * umax_val is equal to umin_val. 11237 */ 11238 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 11239 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 11240 11241 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 11242 11243 /* blow away the dst_reg umin_value/umax_value and rely on 11244 * dst_reg var_off to refine the result. 11245 */ 11246 dst_reg->u32_min_value = 0; 11247 dst_reg->u32_max_value = U32_MAX; 11248 11249 __mark_reg64_unbounded(dst_reg); 11250 __update_reg32_bounds(dst_reg); 11251 } 11252 11253 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 11254 struct bpf_reg_state *src_reg) 11255 { 11256 u64 umin_val = src_reg->umin_value; 11257 11258 /* Upon reaching here, src_known is true and umax_val is equal 11259 * to umin_val. 11260 */ 11261 dst_reg->smin_value >>= umin_val; 11262 dst_reg->smax_value >>= umin_val; 11263 11264 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 11265 11266 /* blow away the dst_reg umin_value/umax_value and rely on 11267 * dst_reg var_off to refine the result. 11268 */ 11269 dst_reg->umin_value = 0; 11270 dst_reg->umax_value = U64_MAX; 11271 11272 /* Its not easy to operate on alu32 bounds here because it depends 11273 * on bits being shifted in from upper 32-bits. Take easy way out 11274 * and mark unbounded so we can recalculate later from tnum. 11275 */ 11276 __mark_reg32_unbounded(dst_reg); 11277 __update_reg_bounds(dst_reg); 11278 } 11279 11280 /* WARNING: This function does calculations on 64-bit values, but the actual 11281 * execution may occur on 32-bit values. Therefore, things like bitshifts 11282 * need extra checks in the 32-bit case. 11283 */ 11284 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 11285 struct bpf_insn *insn, 11286 struct bpf_reg_state *dst_reg, 11287 struct bpf_reg_state src_reg) 11288 { 11289 struct bpf_reg_state *regs = cur_regs(env); 11290 u8 opcode = BPF_OP(insn->code); 11291 bool src_known; 11292 s64 smin_val, smax_val; 11293 u64 umin_val, umax_val; 11294 s32 s32_min_val, s32_max_val; 11295 u32 u32_min_val, u32_max_val; 11296 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 11297 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 11298 int ret; 11299 11300 smin_val = src_reg.smin_value; 11301 smax_val = src_reg.smax_value; 11302 umin_val = src_reg.umin_value; 11303 umax_val = src_reg.umax_value; 11304 11305 s32_min_val = src_reg.s32_min_value; 11306 s32_max_val = src_reg.s32_max_value; 11307 u32_min_val = src_reg.u32_min_value; 11308 u32_max_val = src_reg.u32_max_value; 11309 11310 if (alu32) { 11311 src_known = tnum_subreg_is_const(src_reg.var_off); 11312 if ((src_known && 11313 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 11314 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 11315 /* Taint dst register if offset had invalid bounds 11316 * derived from e.g. dead branches. 11317 */ 11318 __mark_reg_unknown(env, dst_reg); 11319 return 0; 11320 } 11321 } else { 11322 src_known = tnum_is_const(src_reg.var_off); 11323 if ((src_known && 11324 (smin_val != smax_val || umin_val != umax_val)) || 11325 smin_val > smax_val || umin_val > umax_val) { 11326 /* Taint dst register if offset had invalid bounds 11327 * derived from e.g. dead branches. 11328 */ 11329 __mark_reg_unknown(env, dst_reg); 11330 return 0; 11331 } 11332 } 11333 11334 if (!src_known && 11335 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 11336 __mark_reg_unknown(env, dst_reg); 11337 return 0; 11338 } 11339 11340 if (sanitize_needed(opcode)) { 11341 ret = sanitize_val_alu(env, insn); 11342 if (ret < 0) 11343 return sanitize_err(env, insn, ret, NULL, NULL); 11344 } 11345 11346 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 11347 * There are two classes of instructions: The first class we track both 11348 * alu32 and alu64 sign/unsigned bounds independently this provides the 11349 * greatest amount of precision when alu operations are mixed with jmp32 11350 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 11351 * and BPF_OR. This is possible because these ops have fairly easy to 11352 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 11353 * See alu32 verifier tests for examples. The second class of 11354 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 11355 * with regards to tracking sign/unsigned bounds because the bits may 11356 * cross subreg boundaries in the alu64 case. When this happens we mark 11357 * the reg unbounded in the subreg bound space and use the resulting 11358 * tnum to calculate an approximation of the sign/unsigned bounds. 11359 */ 11360 switch (opcode) { 11361 case BPF_ADD: 11362 scalar32_min_max_add(dst_reg, &src_reg); 11363 scalar_min_max_add(dst_reg, &src_reg); 11364 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 11365 break; 11366 case BPF_SUB: 11367 scalar32_min_max_sub(dst_reg, &src_reg); 11368 scalar_min_max_sub(dst_reg, &src_reg); 11369 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 11370 break; 11371 case BPF_MUL: 11372 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 11373 scalar32_min_max_mul(dst_reg, &src_reg); 11374 scalar_min_max_mul(dst_reg, &src_reg); 11375 break; 11376 case BPF_AND: 11377 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 11378 scalar32_min_max_and(dst_reg, &src_reg); 11379 scalar_min_max_and(dst_reg, &src_reg); 11380 break; 11381 case BPF_OR: 11382 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 11383 scalar32_min_max_or(dst_reg, &src_reg); 11384 scalar_min_max_or(dst_reg, &src_reg); 11385 break; 11386 case BPF_XOR: 11387 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 11388 scalar32_min_max_xor(dst_reg, &src_reg); 11389 scalar_min_max_xor(dst_reg, &src_reg); 11390 break; 11391 case BPF_LSH: 11392 if (umax_val >= insn_bitness) { 11393 /* Shifts greater than 31 or 63 are undefined. 11394 * This includes shifts by a negative number. 11395 */ 11396 mark_reg_unknown(env, regs, insn->dst_reg); 11397 break; 11398 } 11399 if (alu32) 11400 scalar32_min_max_lsh(dst_reg, &src_reg); 11401 else 11402 scalar_min_max_lsh(dst_reg, &src_reg); 11403 break; 11404 case BPF_RSH: 11405 if (umax_val >= insn_bitness) { 11406 /* Shifts greater than 31 or 63 are undefined. 11407 * This includes shifts by a negative number. 11408 */ 11409 mark_reg_unknown(env, regs, insn->dst_reg); 11410 break; 11411 } 11412 if (alu32) 11413 scalar32_min_max_rsh(dst_reg, &src_reg); 11414 else 11415 scalar_min_max_rsh(dst_reg, &src_reg); 11416 break; 11417 case BPF_ARSH: 11418 if (umax_val >= insn_bitness) { 11419 /* Shifts greater than 31 or 63 are undefined. 11420 * This includes shifts by a negative number. 11421 */ 11422 mark_reg_unknown(env, regs, insn->dst_reg); 11423 break; 11424 } 11425 if (alu32) 11426 scalar32_min_max_arsh(dst_reg, &src_reg); 11427 else 11428 scalar_min_max_arsh(dst_reg, &src_reg); 11429 break; 11430 default: 11431 mark_reg_unknown(env, regs, insn->dst_reg); 11432 break; 11433 } 11434 11435 /* ALU32 ops are zero extended into 64bit register */ 11436 if (alu32) 11437 zext_32_to_64(dst_reg); 11438 reg_bounds_sync(dst_reg); 11439 return 0; 11440 } 11441 11442 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 11443 * and var_off. 11444 */ 11445 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 11446 struct bpf_insn *insn) 11447 { 11448 struct bpf_verifier_state *vstate = env->cur_state; 11449 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 11450 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 11451 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 11452 u8 opcode = BPF_OP(insn->code); 11453 int err; 11454 11455 dst_reg = ®s[insn->dst_reg]; 11456 src_reg = NULL; 11457 if (dst_reg->type != SCALAR_VALUE) 11458 ptr_reg = dst_reg; 11459 else 11460 /* Make sure ID is cleared otherwise dst_reg min/max could be 11461 * incorrectly propagated into other registers by find_equal_scalars() 11462 */ 11463 dst_reg->id = 0; 11464 if (BPF_SRC(insn->code) == BPF_X) { 11465 src_reg = ®s[insn->src_reg]; 11466 if (src_reg->type != SCALAR_VALUE) { 11467 if (dst_reg->type != SCALAR_VALUE) { 11468 /* Combining two pointers by any ALU op yields 11469 * an arbitrary scalar. Disallow all math except 11470 * pointer subtraction 11471 */ 11472 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 11473 mark_reg_unknown(env, regs, insn->dst_reg); 11474 return 0; 11475 } 11476 verbose(env, "R%d pointer %s pointer prohibited\n", 11477 insn->dst_reg, 11478 bpf_alu_string[opcode >> 4]); 11479 return -EACCES; 11480 } else { 11481 /* scalar += pointer 11482 * This is legal, but we have to reverse our 11483 * src/dest handling in computing the range 11484 */ 11485 err = mark_chain_precision(env, insn->dst_reg); 11486 if (err) 11487 return err; 11488 return adjust_ptr_min_max_vals(env, insn, 11489 src_reg, dst_reg); 11490 } 11491 } else if (ptr_reg) { 11492 /* pointer += scalar */ 11493 err = mark_chain_precision(env, insn->src_reg); 11494 if (err) 11495 return err; 11496 return adjust_ptr_min_max_vals(env, insn, 11497 dst_reg, src_reg); 11498 } else if (dst_reg->precise) { 11499 /* if dst_reg is precise, src_reg should be precise as well */ 11500 err = mark_chain_precision(env, insn->src_reg); 11501 if (err) 11502 return err; 11503 } 11504 } else { 11505 /* Pretend the src is a reg with a known value, since we only 11506 * need to be able to read from this state. 11507 */ 11508 off_reg.type = SCALAR_VALUE; 11509 __mark_reg_known(&off_reg, insn->imm); 11510 src_reg = &off_reg; 11511 if (ptr_reg) /* pointer += K */ 11512 return adjust_ptr_min_max_vals(env, insn, 11513 ptr_reg, src_reg); 11514 } 11515 11516 /* Got here implies adding two SCALAR_VALUEs */ 11517 if (WARN_ON_ONCE(ptr_reg)) { 11518 print_verifier_state(env, state, true); 11519 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 11520 return -EINVAL; 11521 } 11522 if (WARN_ON(!src_reg)) { 11523 print_verifier_state(env, state, true); 11524 verbose(env, "verifier internal error: no src_reg\n"); 11525 return -EINVAL; 11526 } 11527 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 11528 } 11529 11530 /* check validity of 32-bit and 64-bit arithmetic operations */ 11531 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 11532 { 11533 struct bpf_reg_state *regs = cur_regs(env); 11534 u8 opcode = BPF_OP(insn->code); 11535 int err; 11536 11537 if (opcode == BPF_END || opcode == BPF_NEG) { 11538 if (opcode == BPF_NEG) { 11539 if (BPF_SRC(insn->code) != BPF_K || 11540 insn->src_reg != BPF_REG_0 || 11541 insn->off != 0 || insn->imm != 0) { 11542 verbose(env, "BPF_NEG uses reserved fields\n"); 11543 return -EINVAL; 11544 } 11545 } else { 11546 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 11547 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 11548 BPF_CLASS(insn->code) == BPF_ALU64) { 11549 verbose(env, "BPF_END uses reserved fields\n"); 11550 return -EINVAL; 11551 } 11552 } 11553 11554 /* check src operand */ 11555 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11556 if (err) 11557 return err; 11558 11559 if (is_pointer_value(env, insn->dst_reg)) { 11560 verbose(env, "R%d pointer arithmetic prohibited\n", 11561 insn->dst_reg); 11562 return -EACCES; 11563 } 11564 11565 /* check dest operand */ 11566 err = check_reg_arg(env, insn->dst_reg, DST_OP); 11567 if (err) 11568 return err; 11569 11570 } else if (opcode == BPF_MOV) { 11571 11572 if (BPF_SRC(insn->code) == BPF_X) { 11573 if (insn->imm != 0 || insn->off != 0) { 11574 verbose(env, "BPF_MOV uses reserved fields\n"); 11575 return -EINVAL; 11576 } 11577 11578 /* check src operand */ 11579 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11580 if (err) 11581 return err; 11582 } else { 11583 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 11584 verbose(env, "BPF_MOV uses reserved fields\n"); 11585 return -EINVAL; 11586 } 11587 } 11588 11589 /* check dest operand, mark as required later */ 11590 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 11591 if (err) 11592 return err; 11593 11594 if (BPF_SRC(insn->code) == BPF_X) { 11595 struct bpf_reg_state *src_reg = regs + insn->src_reg; 11596 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 11597 11598 if (BPF_CLASS(insn->code) == BPF_ALU64) { 11599 /* case: R1 = R2 11600 * copy register state to dest reg 11601 */ 11602 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 11603 /* Assign src and dst registers the same ID 11604 * that will be used by find_equal_scalars() 11605 * to propagate min/max range. 11606 */ 11607 src_reg->id = ++env->id_gen; 11608 copy_register_state(dst_reg, src_reg); 11609 dst_reg->live |= REG_LIVE_WRITTEN; 11610 dst_reg->subreg_def = DEF_NOT_SUBREG; 11611 } else { 11612 /* R1 = (u32) R2 */ 11613 if (is_pointer_value(env, insn->src_reg)) { 11614 verbose(env, 11615 "R%d partial copy of pointer\n", 11616 insn->src_reg); 11617 return -EACCES; 11618 } else if (src_reg->type == SCALAR_VALUE) { 11619 copy_register_state(dst_reg, src_reg); 11620 /* Make sure ID is cleared otherwise 11621 * dst_reg min/max could be incorrectly 11622 * propagated into src_reg by find_equal_scalars() 11623 */ 11624 dst_reg->id = 0; 11625 dst_reg->live |= REG_LIVE_WRITTEN; 11626 dst_reg->subreg_def = env->insn_idx + 1; 11627 } else { 11628 mark_reg_unknown(env, regs, 11629 insn->dst_reg); 11630 } 11631 zext_32_to_64(dst_reg); 11632 reg_bounds_sync(dst_reg); 11633 } 11634 } else { 11635 /* case: R = imm 11636 * remember the value we stored into this reg 11637 */ 11638 /* clear any state __mark_reg_known doesn't set */ 11639 mark_reg_unknown(env, regs, insn->dst_reg); 11640 regs[insn->dst_reg].type = SCALAR_VALUE; 11641 if (BPF_CLASS(insn->code) == BPF_ALU64) { 11642 __mark_reg_known(regs + insn->dst_reg, 11643 insn->imm); 11644 } else { 11645 __mark_reg_known(regs + insn->dst_reg, 11646 (u32)insn->imm); 11647 } 11648 } 11649 11650 } else if (opcode > BPF_END) { 11651 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 11652 return -EINVAL; 11653 11654 } else { /* all other ALU ops: and, sub, xor, add, ... */ 11655 11656 if (BPF_SRC(insn->code) == BPF_X) { 11657 if (insn->imm != 0 || insn->off != 0) { 11658 verbose(env, "BPF_ALU uses reserved fields\n"); 11659 return -EINVAL; 11660 } 11661 /* check src1 operand */ 11662 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11663 if (err) 11664 return err; 11665 } else { 11666 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 11667 verbose(env, "BPF_ALU uses reserved fields\n"); 11668 return -EINVAL; 11669 } 11670 } 11671 11672 /* check src2 operand */ 11673 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11674 if (err) 11675 return err; 11676 11677 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 11678 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 11679 verbose(env, "div by zero\n"); 11680 return -EINVAL; 11681 } 11682 11683 if ((opcode == BPF_LSH || opcode == BPF_RSH || 11684 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 11685 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 11686 11687 if (insn->imm < 0 || insn->imm >= size) { 11688 verbose(env, "invalid shift %d\n", insn->imm); 11689 return -EINVAL; 11690 } 11691 } 11692 11693 /* check dest operand */ 11694 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 11695 if (err) 11696 return err; 11697 11698 return adjust_reg_min_max_vals(env, insn); 11699 } 11700 11701 return 0; 11702 } 11703 11704 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 11705 struct bpf_reg_state *dst_reg, 11706 enum bpf_reg_type type, 11707 bool range_right_open) 11708 { 11709 struct bpf_func_state *state; 11710 struct bpf_reg_state *reg; 11711 int new_range; 11712 11713 if (dst_reg->off < 0 || 11714 (dst_reg->off == 0 && range_right_open)) 11715 /* This doesn't give us any range */ 11716 return; 11717 11718 if (dst_reg->umax_value > MAX_PACKET_OFF || 11719 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 11720 /* Risk of overflow. For instance, ptr + (1<<63) may be less 11721 * than pkt_end, but that's because it's also less than pkt. 11722 */ 11723 return; 11724 11725 new_range = dst_reg->off; 11726 if (range_right_open) 11727 new_range++; 11728 11729 /* Examples for register markings: 11730 * 11731 * pkt_data in dst register: 11732 * 11733 * r2 = r3; 11734 * r2 += 8; 11735 * if (r2 > pkt_end) goto <handle exception> 11736 * <access okay> 11737 * 11738 * r2 = r3; 11739 * r2 += 8; 11740 * if (r2 < pkt_end) goto <access okay> 11741 * <handle exception> 11742 * 11743 * Where: 11744 * r2 == dst_reg, pkt_end == src_reg 11745 * r2=pkt(id=n,off=8,r=0) 11746 * r3=pkt(id=n,off=0,r=0) 11747 * 11748 * pkt_data in src register: 11749 * 11750 * r2 = r3; 11751 * r2 += 8; 11752 * if (pkt_end >= r2) goto <access okay> 11753 * <handle exception> 11754 * 11755 * r2 = r3; 11756 * r2 += 8; 11757 * if (pkt_end <= r2) goto <handle exception> 11758 * <access okay> 11759 * 11760 * Where: 11761 * pkt_end == dst_reg, r2 == src_reg 11762 * r2=pkt(id=n,off=8,r=0) 11763 * r3=pkt(id=n,off=0,r=0) 11764 * 11765 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 11766 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 11767 * and [r3, r3 + 8-1) respectively is safe to access depending on 11768 * the check. 11769 */ 11770 11771 /* If our ids match, then we must have the same max_value. And we 11772 * don't care about the other reg's fixed offset, since if it's too big 11773 * the range won't allow anything. 11774 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 11775 */ 11776 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 11777 if (reg->type == type && reg->id == dst_reg->id) 11778 /* keep the maximum range already checked */ 11779 reg->range = max(reg->range, new_range); 11780 })); 11781 } 11782 11783 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 11784 { 11785 struct tnum subreg = tnum_subreg(reg->var_off); 11786 s32 sval = (s32)val; 11787 11788 switch (opcode) { 11789 case BPF_JEQ: 11790 if (tnum_is_const(subreg)) 11791 return !!tnum_equals_const(subreg, val); 11792 break; 11793 case BPF_JNE: 11794 if (tnum_is_const(subreg)) 11795 return !tnum_equals_const(subreg, val); 11796 break; 11797 case BPF_JSET: 11798 if ((~subreg.mask & subreg.value) & val) 11799 return 1; 11800 if (!((subreg.mask | subreg.value) & val)) 11801 return 0; 11802 break; 11803 case BPF_JGT: 11804 if (reg->u32_min_value > val) 11805 return 1; 11806 else if (reg->u32_max_value <= val) 11807 return 0; 11808 break; 11809 case BPF_JSGT: 11810 if (reg->s32_min_value > sval) 11811 return 1; 11812 else if (reg->s32_max_value <= sval) 11813 return 0; 11814 break; 11815 case BPF_JLT: 11816 if (reg->u32_max_value < val) 11817 return 1; 11818 else if (reg->u32_min_value >= val) 11819 return 0; 11820 break; 11821 case BPF_JSLT: 11822 if (reg->s32_max_value < sval) 11823 return 1; 11824 else if (reg->s32_min_value >= sval) 11825 return 0; 11826 break; 11827 case BPF_JGE: 11828 if (reg->u32_min_value >= val) 11829 return 1; 11830 else if (reg->u32_max_value < val) 11831 return 0; 11832 break; 11833 case BPF_JSGE: 11834 if (reg->s32_min_value >= sval) 11835 return 1; 11836 else if (reg->s32_max_value < sval) 11837 return 0; 11838 break; 11839 case BPF_JLE: 11840 if (reg->u32_max_value <= val) 11841 return 1; 11842 else if (reg->u32_min_value > val) 11843 return 0; 11844 break; 11845 case BPF_JSLE: 11846 if (reg->s32_max_value <= sval) 11847 return 1; 11848 else if (reg->s32_min_value > sval) 11849 return 0; 11850 break; 11851 } 11852 11853 return -1; 11854 } 11855 11856 11857 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 11858 { 11859 s64 sval = (s64)val; 11860 11861 switch (opcode) { 11862 case BPF_JEQ: 11863 if (tnum_is_const(reg->var_off)) 11864 return !!tnum_equals_const(reg->var_off, val); 11865 break; 11866 case BPF_JNE: 11867 if (tnum_is_const(reg->var_off)) 11868 return !tnum_equals_const(reg->var_off, val); 11869 break; 11870 case BPF_JSET: 11871 if ((~reg->var_off.mask & reg->var_off.value) & val) 11872 return 1; 11873 if (!((reg->var_off.mask | reg->var_off.value) & val)) 11874 return 0; 11875 break; 11876 case BPF_JGT: 11877 if (reg->umin_value > val) 11878 return 1; 11879 else if (reg->umax_value <= val) 11880 return 0; 11881 break; 11882 case BPF_JSGT: 11883 if (reg->smin_value > sval) 11884 return 1; 11885 else if (reg->smax_value <= sval) 11886 return 0; 11887 break; 11888 case BPF_JLT: 11889 if (reg->umax_value < val) 11890 return 1; 11891 else if (reg->umin_value >= val) 11892 return 0; 11893 break; 11894 case BPF_JSLT: 11895 if (reg->smax_value < sval) 11896 return 1; 11897 else if (reg->smin_value >= sval) 11898 return 0; 11899 break; 11900 case BPF_JGE: 11901 if (reg->umin_value >= val) 11902 return 1; 11903 else if (reg->umax_value < val) 11904 return 0; 11905 break; 11906 case BPF_JSGE: 11907 if (reg->smin_value >= sval) 11908 return 1; 11909 else if (reg->smax_value < sval) 11910 return 0; 11911 break; 11912 case BPF_JLE: 11913 if (reg->umax_value <= val) 11914 return 1; 11915 else if (reg->umin_value > val) 11916 return 0; 11917 break; 11918 case BPF_JSLE: 11919 if (reg->smax_value <= sval) 11920 return 1; 11921 else if (reg->smin_value > sval) 11922 return 0; 11923 break; 11924 } 11925 11926 return -1; 11927 } 11928 11929 /* compute branch direction of the expression "if (reg opcode val) goto target;" 11930 * and return: 11931 * 1 - branch will be taken and "goto target" will be executed 11932 * 0 - branch will not be taken and fall-through to next insn 11933 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 11934 * range [0,10] 11935 */ 11936 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 11937 bool is_jmp32) 11938 { 11939 if (__is_pointer_value(false, reg)) { 11940 if (!reg_type_not_null(reg->type)) 11941 return -1; 11942 11943 /* If pointer is valid tests against zero will fail so we can 11944 * use this to direct branch taken. 11945 */ 11946 if (val != 0) 11947 return -1; 11948 11949 switch (opcode) { 11950 case BPF_JEQ: 11951 return 0; 11952 case BPF_JNE: 11953 return 1; 11954 default: 11955 return -1; 11956 } 11957 } 11958 11959 if (is_jmp32) 11960 return is_branch32_taken(reg, val, opcode); 11961 return is_branch64_taken(reg, val, opcode); 11962 } 11963 11964 static int flip_opcode(u32 opcode) 11965 { 11966 /* How can we transform "a <op> b" into "b <op> a"? */ 11967 static const u8 opcode_flip[16] = { 11968 /* these stay the same */ 11969 [BPF_JEQ >> 4] = BPF_JEQ, 11970 [BPF_JNE >> 4] = BPF_JNE, 11971 [BPF_JSET >> 4] = BPF_JSET, 11972 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 11973 [BPF_JGE >> 4] = BPF_JLE, 11974 [BPF_JGT >> 4] = BPF_JLT, 11975 [BPF_JLE >> 4] = BPF_JGE, 11976 [BPF_JLT >> 4] = BPF_JGT, 11977 [BPF_JSGE >> 4] = BPF_JSLE, 11978 [BPF_JSGT >> 4] = BPF_JSLT, 11979 [BPF_JSLE >> 4] = BPF_JSGE, 11980 [BPF_JSLT >> 4] = BPF_JSGT 11981 }; 11982 return opcode_flip[opcode >> 4]; 11983 } 11984 11985 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 11986 struct bpf_reg_state *src_reg, 11987 u8 opcode) 11988 { 11989 struct bpf_reg_state *pkt; 11990 11991 if (src_reg->type == PTR_TO_PACKET_END) { 11992 pkt = dst_reg; 11993 } else if (dst_reg->type == PTR_TO_PACKET_END) { 11994 pkt = src_reg; 11995 opcode = flip_opcode(opcode); 11996 } else { 11997 return -1; 11998 } 11999 12000 if (pkt->range >= 0) 12001 return -1; 12002 12003 switch (opcode) { 12004 case BPF_JLE: 12005 /* pkt <= pkt_end */ 12006 fallthrough; 12007 case BPF_JGT: 12008 /* pkt > pkt_end */ 12009 if (pkt->range == BEYOND_PKT_END) 12010 /* pkt has at last one extra byte beyond pkt_end */ 12011 return opcode == BPF_JGT; 12012 break; 12013 case BPF_JLT: 12014 /* pkt < pkt_end */ 12015 fallthrough; 12016 case BPF_JGE: 12017 /* pkt >= pkt_end */ 12018 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 12019 return opcode == BPF_JGE; 12020 break; 12021 } 12022 return -1; 12023 } 12024 12025 /* Adjusts the register min/max values in the case that the dst_reg is the 12026 * variable register that we are working on, and src_reg is a constant or we're 12027 * simply doing a BPF_K check. 12028 * In JEQ/JNE cases we also adjust the var_off values. 12029 */ 12030 static void reg_set_min_max(struct bpf_reg_state *true_reg, 12031 struct bpf_reg_state *false_reg, 12032 u64 val, u32 val32, 12033 u8 opcode, bool is_jmp32) 12034 { 12035 struct tnum false_32off = tnum_subreg(false_reg->var_off); 12036 struct tnum false_64off = false_reg->var_off; 12037 struct tnum true_32off = tnum_subreg(true_reg->var_off); 12038 struct tnum true_64off = true_reg->var_off; 12039 s64 sval = (s64)val; 12040 s32 sval32 = (s32)val32; 12041 12042 /* If the dst_reg is a pointer, we can't learn anything about its 12043 * variable offset from the compare (unless src_reg were a pointer into 12044 * the same object, but we don't bother with that. 12045 * Since false_reg and true_reg have the same type by construction, we 12046 * only need to check one of them for pointerness. 12047 */ 12048 if (__is_pointer_value(false, false_reg)) 12049 return; 12050 12051 switch (opcode) { 12052 /* JEQ/JNE comparison doesn't change the register equivalence. 12053 * 12054 * r1 = r2; 12055 * if (r1 == 42) goto label; 12056 * ... 12057 * label: // here both r1 and r2 are known to be 42. 12058 * 12059 * Hence when marking register as known preserve it's ID. 12060 */ 12061 case BPF_JEQ: 12062 if (is_jmp32) { 12063 __mark_reg32_known(true_reg, val32); 12064 true_32off = tnum_subreg(true_reg->var_off); 12065 } else { 12066 ___mark_reg_known(true_reg, val); 12067 true_64off = true_reg->var_off; 12068 } 12069 break; 12070 case BPF_JNE: 12071 if (is_jmp32) { 12072 __mark_reg32_known(false_reg, val32); 12073 false_32off = tnum_subreg(false_reg->var_off); 12074 } else { 12075 ___mark_reg_known(false_reg, val); 12076 false_64off = false_reg->var_off; 12077 } 12078 break; 12079 case BPF_JSET: 12080 if (is_jmp32) { 12081 false_32off = tnum_and(false_32off, tnum_const(~val32)); 12082 if (is_power_of_2(val32)) 12083 true_32off = tnum_or(true_32off, 12084 tnum_const(val32)); 12085 } else { 12086 false_64off = tnum_and(false_64off, tnum_const(~val)); 12087 if (is_power_of_2(val)) 12088 true_64off = tnum_or(true_64off, 12089 tnum_const(val)); 12090 } 12091 break; 12092 case BPF_JGE: 12093 case BPF_JGT: 12094 { 12095 if (is_jmp32) { 12096 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 12097 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 12098 12099 false_reg->u32_max_value = min(false_reg->u32_max_value, 12100 false_umax); 12101 true_reg->u32_min_value = max(true_reg->u32_min_value, 12102 true_umin); 12103 } else { 12104 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 12105 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 12106 12107 false_reg->umax_value = min(false_reg->umax_value, false_umax); 12108 true_reg->umin_value = max(true_reg->umin_value, true_umin); 12109 } 12110 break; 12111 } 12112 case BPF_JSGE: 12113 case BPF_JSGT: 12114 { 12115 if (is_jmp32) { 12116 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 12117 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 12118 12119 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 12120 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 12121 } else { 12122 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 12123 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 12124 12125 false_reg->smax_value = min(false_reg->smax_value, false_smax); 12126 true_reg->smin_value = max(true_reg->smin_value, true_smin); 12127 } 12128 break; 12129 } 12130 case BPF_JLE: 12131 case BPF_JLT: 12132 { 12133 if (is_jmp32) { 12134 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 12135 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 12136 12137 false_reg->u32_min_value = max(false_reg->u32_min_value, 12138 false_umin); 12139 true_reg->u32_max_value = min(true_reg->u32_max_value, 12140 true_umax); 12141 } else { 12142 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 12143 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 12144 12145 false_reg->umin_value = max(false_reg->umin_value, false_umin); 12146 true_reg->umax_value = min(true_reg->umax_value, true_umax); 12147 } 12148 break; 12149 } 12150 case BPF_JSLE: 12151 case BPF_JSLT: 12152 { 12153 if (is_jmp32) { 12154 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 12155 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 12156 12157 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 12158 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 12159 } else { 12160 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 12161 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 12162 12163 false_reg->smin_value = max(false_reg->smin_value, false_smin); 12164 true_reg->smax_value = min(true_reg->smax_value, true_smax); 12165 } 12166 break; 12167 } 12168 default: 12169 return; 12170 } 12171 12172 if (is_jmp32) { 12173 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 12174 tnum_subreg(false_32off)); 12175 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 12176 tnum_subreg(true_32off)); 12177 __reg_combine_32_into_64(false_reg); 12178 __reg_combine_32_into_64(true_reg); 12179 } else { 12180 false_reg->var_off = false_64off; 12181 true_reg->var_off = true_64off; 12182 __reg_combine_64_into_32(false_reg); 12183 __reg_combine_64_into_32(true_reg); 12184 } 12185 } 12186 12187 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 12188 * the variable reg. 12189 */ 12190 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 12191 struct bpf_reg_state *false_reg, 12192 u64 val, u32 val32, 12193 u8 opcode, bool is_jmp32) 12194 { 12195 opcode = flip_opcode(opcode); 12196 /* This uses zero as "not present in table"; luckily the zero opcode, 12197 * BPF_JA, can't get here. 12198 */ 12199 if (opcode) 12200 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 12201 } 12202 12203 /* Regs are known to be equal, so intersect their min/max/var_off */ 12204 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 12205 struct bpf_reg_state *dst_reg) 12206 { 12207 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 12208 dst_reg->umin_value); 12209 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 12210 dst_reg->umax_value); 12211 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 12212 dst_reg->smin_value); 12213 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 12214 dst_reg->smax_value); 12215 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 12216 dst_reg->var_off); 12217 reg_bounds_sync(src_reg); 12218 reg_bounds_sync(dst_reg); 12219 } 12220 12221 static void reg_combine_min_max(struct bpf_reg_state *true_src, 12222 struct bpf_reg_state *true_dst, 12223 struct bpf_reg_state *false_src, 12224 struct bpf_reg_state *false_dst, 12225 u8 opcode) 12226 { 12227 switch (opcode) { 12228 case BPF_JEQ: 12229 __reg_combine_min_max(true_src, true_dst); 12230 break; 12231 case BPF_JNE: 12232 __reg_combine_min_max(false_src, false_dst); 12233 break; 12234 } 12235 } 12236 12237 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 12238 struct bpf_reg_state *reg, u32 id, 12239 bool is_null) 12240 { 12241 if (type_may_be_null(reg->type) && reg->id == id && 12242 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 12243 /* Old offset (both fixed and variable parts) should have been 12244 * known-zero, because we don't allow pointer arithmetic on 12245 * pointers that might be NULL. If we see this happening, don't 12246 * convert the register. 12247 * 12248 * But in some cases, some helpers that return local kptrs 12249 * advance offset for the returned pointer. In those cases, it 12250 * is fine to expect to see reg->off. 12251 */ 12252 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 12253 return; 12254 if (!(type_is_ptr_alloc_obj(reg->type) || type_is_non_owning_ref(reg->type)) && 12255 WARN_ON_ONCE(reg->off)) 12256 return; 12257 12258 if (is_null) { 12259 reg->type = SCALAR_VALUE; 12260 /* We don't need id and ref_obj_id from this point 12261 * onwards anymore, thus we should better reset it, 12262 * so that state pruning has chances to take effect. 12263 */ 12264 reg->id = 0; 12265 reg->ref_obj_id = 0; 12266 12267 return; 12268 } 12269 12270 mark_ptr_not_null_reg(reg); 12271 12272 if (!reg_may_point_to_spin_lock(reg)) { 12273 /* For not-NULL ptr, reg->ref_obj_id will be reset 12274 * in release_reference(). 12275 * 12276 * reg->id is still used by spin_lock ptr. Other 12277 * than spin_lock ptr type, reg->id can be reset. 12278 */ 12279 reg->id = 0; 12280 } 12281 } 12282 } 12283 12284 /* The logic is similar to find_good_pkt_pointers(), both could eventually 12285 * be folded together at some point. 12286 */ 12287 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 12288 bool is_null) 12289 { 12290 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 12291 struct bpf_reg_state *regs = state->regs, *reg; 12292 u32 ref_obj_id = regs[regno].ref_obj_id; 12293 u32 id = regs[regno].id; 12294 12295 if (ref_obj_id && ref_obj_id == id && is_null) 12296 /* regs[regno] is in the " == NULL" branch. 12297 * No one could have freed the reference state before 12298 * doing the NULL check. 12299 */ 12300 WARN_ON_ONCE(release_reference_state(state, id)); 12301 12302 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 12303 mark_ptr_or_null_reg(state, reg, id, is_null); 12304 })); 12305 } 12306 12307 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 12308 struct bpf_reg_state *dst_reg, 12309 struct bpf_reg_state *src_reg, 12310 struct bpf_verifier_state *this_branch, 12311 struct bpf_verifier_state *other_branch) 12312 { 12313 if (BPF_SRC(insn->code) != BPF_X) 12314 return false; 12315 12316 /* Pointers are always 64-bit. */ 12317 if (BPF_CLASS(insn->code) == BPF_JMP32) 12318 return false; 12319 12320 switch (BPF_OP(insn->code)) { 12321 case BPF_JGT: 12322 if ((dst_reg->type == PTR_TO_PACKET && 12323 src_reg->type == PTR_TO_PACKET_END) || 12324 (dst_reg->type == PTR_TO_PACKET_META && 12325 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 12326 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 12327 find_good_pkt_pointers(this_branch, dst_reg, 12328 dst_reg->type, false); 12329 mark_pkt_end(other_branch, insn->dst_reg, true); 12330 } else if ((dst_reg->type == PTR_TO_PACKET_END && 12331 src_reg->type == PTR_TO_PACKET) || 12332 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 12333 src_reg->type == PTR_TO_PACKET_META)) { 12334 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 12335 find_good_pkt_pointers(other_branch, src_reg, 12336 src_reg->type, true); 12337 mark_pkt_end(this_branch, insn->src_reg, false); 12338 } else { 12339 return false; 12340 } 12341 break; 12342 case BPF_JLT: 12343 if ((dst_reg->type == PTR_TO_PACKET && 12344 src_reg->type == PTR_TO_PACKET_END) || 12345 (dst_reg->type == PTR_TO_PACKET_META && 12346 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 12347 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 12348 find_good_pkt_pointers(other_branch, dst_reg, 12349 dst_reg->type, true); 12350 mark_pkt_end(this_branch, insn->dst_reg, false); 12351 } else if ((dst_reg->type == PTR_TO_PACKET_END && 12352 src_reg->type == PTR_TO_PACKET) || 12353 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 12354 src_reg->type == PTR_TO_PACKET_META)) { 12355 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 12356 find_good_pkt_pointers(this_branch, src_reg, 12357 src_reg->type, false); 12358 mark_pkt_end(other_branch, insn->src_reg, true); 12359 } else { 12360 return false; 12361 } 12362 break; 12363 case BPF_JGE: 12364 if ((dst_reg->type == PTR_TO_PACKET && 12365 src_reg->type == PTR_TO_PACKET_END) || 12366 (dst_reg->type == PTR_TO_PACKET_META && 12367 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 12368 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 12369 find_good_pkt_pointers(this_branch, dst_reg, 12370 dst_reg->type, true); 12371 mark_pkt_end(other_branch, insn->dst_reg, false); 12372 } else if ((dst_reg->type == PTR_TO_PACKET_END && 12373 src_reg->type == PTR_TO_PACKET) || 12374 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 12375 src_reg->type == PTR_TO_PACKET_META)) { 12376 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 12377 find_good_pkt_pointers(other_branch, src_reg, 12378 src_reg->type, false); 12379 mark_pkt_end(this_branch, insn->src_reg, true); 12380 } else { 12381 return false; 12382 } 12383 break; 12384 case BPF_JLE: 12385 if ((dst_reg->type == PTR_TO_PACKET && 12386 src_reg->type == PTR_TO_PACKET_END) || 12387 (dst_reg->type == PTR_TO_PACKET_META && 12388 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 12389 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 12390 find_good_pkt_pointers(other_branch, dst_reg, 12391 dst_reg->type, false); 12392 mark_pkt_end(this_branch, insn->dst_reg, true); 12393 } else if ((dst_reg->type == PTR_TO_PACKET_END && 12394 src_reg->type == PTR_TO_PACKET) || 12395 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 12396 src_reg->type == PTR_TO_PACKET_META)) { 12397 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 12398 find_good_pkt_pointers(this_branch, src_reg, 12399 src_reg->type, true); 12400 mark_pkt_end(other_branch, insn->src_reg, false); 12401 } else { 12402 return false; 12403 } 12404 break; 12405 default: 12406 return false; 12407 } 12408 12409 return true; 12410 } 12411 12412 static void find_equal_scalars(struct bpf_verifier_state *vstate, 12413 struct bpf_reg_state *known_reg) 12414 { 12415 struct bpf_func_state *state; 12416 struct bpf_reg_state *reg; 12417 12418 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 12419 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 12420 copy_register_state(reg, known_reg); 12421 })); 12422 } 12423 12424 static int check_cond_jmp_op(struct bpf_verifier_env *env, 12425 struct bpf_insn *insn, int *insn_idx) 12426 { 12427 struct bpf_verifier_state *this_branch = env->cur_state; 12428 struct bpf_verifier_state *other_branch; 12429 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 12430 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 12431 struct bpf_reg_state *eq_branch_regs; 12432 u8 opcode = BPF_OP(insn->code); 12433 bool is_jmp32; 12434 int pred = -1; 12435 int err; 12436 12437 /* Only conditional jumps are expected to reach here. */ 12438 if (opcode == BPF_JA || opcode > BPF_JSLE) { 12439 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 12440 return -EINVAL; 12441 } 12442 12443 if (BPF_SRC(insn->code) == BPF_X) { 12444 if (insn->imm != 0) { 12445 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 12446 return -EINVAL; 12447 } 12448 12449 /* check src1 operand */ 12450 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12451 if (err) 12452 return err; 12453 12454 if (is_pointer_value(env, insn->src_reg)) { 12455 verbose(env, "R%d pointer comparison prohibited\n", 12456 insn->src_reg); 12457 return -EACCES; 12458 } 12459 src_reg = ®s[insn->src_reg]; 12460 } else { 12461 if (insn->src_reg != BPF_REG_0) { 12462 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 12463 return -EINVAL; 12464 } 12465 } 12466 12467 /* check src2 operand */ 12468 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 12469 if (err) 12470 return err; 12471 12472 dst_reg = ®s[insn->dst_reg]; 12473 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 12474 12475 if (BPF_SRC(insn->code) == BPF_K) { 12476 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 12477 } else if (src_reg->type == SCALAR_VALUE && 12478 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 12479 pred = is_branch_taken(dst_reg, 12480 tnum_subreg(src_reg->var_off).value, 12481 opcode, 12482 is_jmp32); 12483 } else if (src_reg->type == SCALAR_VALUE && 12484 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 12485 pred = is_branch_taken(dst_reg, 12486 src_reg->var_off.value, 12487 opcode, 12488 is_jmp32); 12489 } else if (reg_is_pkt_pointer_any(dst_reg) && 12490 reg_is_pkt_pointer_any(src_reg) && 12491 !is_jmp32) { 12492 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 12493 } 12494 12495 if (pred >= 0) { 12496 /* If we get here with a dst_reg pointer type it is because 12497 * above is_branch_taken() special cased the 0 comparison. 12498 */ 12499 if (!__is_pointer_value(false, dst_reg)) 12500 err = mark_chain_precision(env, insn->dst_reg); 12501 if (BPF_SRC(insn->code) == BPF_X && !err && 12502 !__is_pointer_value(false, src_reg)) 12503 err = mark_chain_precision(env, insn->src_reg); 12504 if (err) 12505 return err; 12506 } 12507 12508 if (pred == 1) { 12509 /* Only follow the goto, ignore fall-through. If needed, push 12510 * the fall-through branch for simulation under speculative 12511 * execution. 12512 */ 12513 if (!env->bypass_spec_v1 && 12514 !sanitize_speculative_path(env, insn, *insn_idx + 1, 12515 *insn_idx)) 12516 return -EFAULT; 12517 *insn_idx += insn->off; 12518 return 0; 12519 } else if (pred == 0) { 12520 /* Only follow the fall-through branch, since that's where the 12521 * program will go. If needed, push the goto branch for 12522 * simulation under speculative execution. 12523 */ 12524 if (!env->bypass_spec_v1 && 12525 !sanitize_speculative_path(env, insn, 12526 *insn_idx + insn->off + 1, 12527 *insn_idx)) 12528 return -EFAULT; 12529 return 0; 12530 } 12531 12532 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 12533 false); 12534 if (!other_branch) 12535 return -EFAULT; 12536 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 12537 12538 /* detect if we are comparing against a constant value so we can adjust 12539 * our min/max values for our dst register. 12540 * this is only legit if both are scalars (or pointers to the same 12541 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 12542 * because otherwise the different base pointers mean the offsets aren't 12543 * comparable. 12544 */ 12545 if (BPF_SRC(insn->code) == BPF_X) { 12546 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 12547 12548 if (dst_reg->type == SCALAR_VALUE && 12549 src_reg->type == SCALAR_VALUE) { 12550 if (tnum_is_const(src_reg->var_off) || 12551 (is_jmp32 && 12552 tnum_is_const(tnum_subreg(src_reg->var_off)))) 12553 reg_set_min_max(&other_branch_regs[insn->dst_reg], 12554 dst_reg, 12555 src_reg->var_off.value, 12556 tnum_subreg(src_reg->var_off).value, 12557 opcode, is_jmp32); 12558 else if (tnum_is_const(dst_reg->var_off) || 12559 (is_jmp32 && 12560 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 12561 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 12562 src_reg, 12563 dst_reg->var_off.value, 12564 tnum_subreg(dst_reg->var_off).value, 12565 opcode, is_jmp32); 12566 else if (!is_jmp32 && 12567 (opcode == BPF_JEQ || opcode == BPF_JNE)) 12568 /* Comparing for equality, we can combine knowledge */ 12569 reg_combine_min_max(&other_branch_regs[insn->src_reg], 12570 &other_branch_regs[insn->dst_reg], 12571 src_reg, dst_reg, opcode); 12572 if (src_reg->id && 12573 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 12574 find_equal_scalars(this_branch, src_reg); 12575 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 12576 } 12577 12578 } 12579 } else if (dst_reg->type == SCALAR_VALUE) { 12580 reg_set_min_max(&other_branch_regs[insn->dst_reg], 12581 dst_reg, insn->imm, (u32)insn->imm, 12582 opcode, is_jmp32); 12583 } 12584 12585 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 12586 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 12587 find_equal_scalars(this_branch, dst_reg); 12588 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 12589 } 12590 12591 /* if one pointer register is compared to another pointer 12592 * register check if PTR_MAYBE_NULL could be lifted. 12593 * E.g. register A - maybe null 12594 * register B - not null 12595 * for JNE A, B, ... - A is not null in the false branch; 12596 * for JEQ A, B, ... - A is not null in the true branch. 12597 * 12598 * Since PTR_TO_BTF_ID points to a kernel struct that does 12599 * not need to be null checked by the BPF program, i.e., 12600 * could be null even without PTR_MAYBE_NULL marking, so 12601 * only propagate nullness when neither reg is that type. 12602 */ 12603 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 12604 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 12605 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 12606 base_type(src_reg->type) != PTR_TO_BTF_ID && 12607 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 12608 eq_branch_regs = NULL; 12609 switch (opcode) { 12610 case BPF_JEQ: 12611 eq_branch_regs = other_branch_regs; 12612 break; 12613 case BPF_JNE: 12614 eq_branch_regs = regs; 12615 break; 12616 default: 12617 /* do nothing */ 12618 break; 12619 } 12620 if (eq_branch_regs) { 12621 if (type_may_be_null(src_reg->type)) 12622 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 12623 else 12624 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 12625 } 12626 } 12627 12628 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 12629 * NOTE: these optimizations below are related with pointer comparison 12630 * which will never be JMP32. 12631 */ 12632 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 12633 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 12634 type_may_be_null(dst_reg->type)) { 12635 /* Mark all identical registers in each branch as either 12636 * safe or unknown depending R == 0 or R != 0 conditional. 12637 */ 12638 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 12639 opcode == BPF_JNE); 12640 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 12641 opcode == BPF_JEQ); 12642 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 12643 this_branch, other_branch) && 12644 is_pointer_value(env, insn->dst_reg)) { 12645 verbose(env, "R%d pointer comparison prohibited\n", 12646 insn->dst_reg); 12647 return -EACCES; 12648 } 12649 if (env->log.level & BPF_LOG_LEVEL) 12650 print_insn_state(env, this_branch->frame[this_branch->curframe]); 12651 return 0; 12652 } 12653 12654 /* verify BPF_LD_IMM64 instruction */ 12655 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 12656 { 12657 struct bpf_insn_aux_data *aux = cur_aux(env); 12658 struct bpf_reg_state *regs = cur_regs(env); 12659 struct bpf_reg_state *dst_reg; 12660 struct bpf_map *map; 12661 int err; 12662 12663 if (BPF_SIZE(insn->code) != BPF_DW) { 12664 verbose(env, "invalid BPF_LD_IMM insn\n"); 12665 return -EINVAL; 12666 } 12667 if (insn->off != 0) { 12668 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 12669 return -EINVAL; 12670 } 12671 12672 err = check_reg_arg(env, insn->dst_reg, DST_OP); 12673 if (err) 12674 return err; 12675 12676 dst_reg = ®s[insn->dst_reg]; 12677 if (insn->src_reg == 0) { 12678 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 12679 12680 dst_reg->type = SCALAR_VALUE; 12681 __mark_reg_known(®s[insn->dst_reg], imm); 12682 return 0; 12683 } 12684 12685 /* All special src_reg cases are listed below. From this point onwards 12686 * we either succeed and assign a corresponding dst_reg->type after 12687 * zeroing the offset, or fail and reject the program. 12688 */ 12689 mark_reg_known_zero(env, regs, insn->dst_reg); 12690 12691 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 12692 dst_reg->type = aux->btf_var.reg_type; 12693 switch (base_type(dst_reg->type)) { 12694 case PTR_TO_MEM: 12695 dst_reg->mem_size = aux->btf_var.mem_size; 12696 break; 12697 case PTR_TO_BTF_ID: 12698 dst_reg->btf = aux->btf_var.btf; 12699 dst_reg->btf_id = aux->btf_var.btf_id; 12700 break; 12701 default: 12702 verbose(env, "bpf verifier is misconfigured\n"); 12703 return -EFAULT; 12704 } 12705 return 0; 12706 } 12707 12708 if (insn->src_reg == BPF_PSEUDO_FUNC) { 12709 struct bpf_prog_aux *aux = env->prog->aux; 12710 u32 subprogno = find_subprog(env, 12711 env->insn_idx + insn->imm + 1); 12712 12713 if (!aux->func_info) { 12714 verbose(env, "missing btf func_info\n"); 12715 return -EINVAL; 12716 } 12717 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 12718 verbose(env, "callback function not static\n"); 12719 return -EINVAL; 12720 } 12721 12722 dst_reg->type = PTR_TO_FUNC; 12723 dst_reg->subprogno = subprogno; 12724 return 0; 12725 } 12726 12727 map = env->used_maps[aux->map_index]; 12728 dst_reg->map_ptr = map; 12729 12730 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 12731 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 12732 dst_reg->type = PTR_TO_MAP_VALUE; 12733 dst_reg->off = aux->map_off; 12734 WARN_ON_ONCE(map->max_entries != 1); 12735 /* We want reg->id to be same (0) as map_value is not distinct */ 12736 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 12737 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 12738 dst_reg->type = CONST_PTR_TO_MAP; 12739 } else { 12740 verbose(env, "bpf verifier is misconfigured\n"); 12741 return -EINVAL; 12742 } 12743 12744 return 0; 12745 } 12746 12747 static bool may_access_skb(enum bpf_prog_type type) 12748 { 12749 switch (type) { 12750 case BPF_PROG_TYPE_SOCKET_FILTER: 12751 case BPF_PROG_TYPE_SCHED_CLS: 12752 case BPF_PROG_TYPE_SCHED_ACT: 12753 return true; 12754 default: 12755 return false; 12756 } 12757 } 12758 12759 /* verify safety of LD_ABS|LD_IND instructions: 12760 * - they can only appear in the programs where ctx == skb 12761 * - since they are wrappers of function calls, they scratch R1-R5 registers, 12762 * preserve R6-R9, and store return value into R0 12763 * 12764 * Implicit input: 12765 * ctx == skb == R6 == CTX 12766 * 12767 * Explicit input: 12768 * SRC == any register 12769 * IMM == 32-bit immediate 12770 * 12771 * Output: 12772 * R0 - 8/16/32-bit skb data converted to cpu endianness 12773 */ 12774 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 12775 { 12776 struct bpf_reg_state *regs = cur_regs(env); 12777 static const int ctx_reg = BPF_REG_6; 12778 u8 mode = BPF_MODE(insn->code); 12779 int i, err; 12780 12781 if (!may_access_skb(resolve_prog_type(env->prog))) { 12782 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 12783 return -EINVAL; 12784 } 12785 12786 if (!env->ops->gen_ld_abs) { 12787 verbose(env, "bpf verifier is misconfigured\n"); 12788 return -EINVAL; 12789 } 12790 12791 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 12792 BPF_SIZE(insn->code) == BPF_DW || 12793 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 12794 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 12795 return -EINVAL; 12796 } 12797 12798 /* check whether implicit source operand (register R6) is readable */ 12799 err = check_reg_arg(env, ctx_reg, SRC_OP); 12800 if (err) 12801 return err; 12802 12803 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 12804 * gen_ld_abs() may terminate the program at runtime, leading to 12805 * reference leak. 12806 */ 12807 err = check_reference_leak(env); 12808 if (err) { 12809 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 12810 return err; 12811 } 12812 12813 if (env->cur_state->active_lock.ptr) { 12814 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 12815 return -EINVAL; 12816 } 12817 12818 if (env->cur_state->active_rcu_lock) { 12819 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 12820 return -EINVAL; 12821 } 12822 12823 if (regs[ctx_reg].type != PTR_TO_CTX) { 12824 verbose(env, 12825 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 12826 return -EINVAL; 12827 } 12828 12829 if (mode == BPF_IND) { 12830 /* check explicit source operand */ 12831 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12832 if (err) 12833 return err; 12834 } 12835 12836 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 12837 if (err < 0) 12838 return err; 12839 12840 /* reset caller saved regs to unreadable */ 12841 for (i = 0; i < CALLER_SAVED_REGS; i++) { 12842 mark_reg_not_init(env, regs, caller_saved[i]); 12843 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 12844 } 12845 12846 /* mark destination R0 register as readable, since it contains 12847 * the value fetched from the packet. 12848 * Already marked as written above. 12849 */ 12850 mark_reg_unknown(env, regs, BPF_REG_0); 12851 /* ld_abs load up to 32-bit skb data. */ 12852 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 12853 return 0; 12854 } 12855 12856 static int check_return_code(struct bpf_verifier_env *env) 12857 { 12858 struct tnum enforce_attach_type_range = tnum_unknown; 12859 const struct bpf_prog *prog = env->prog; 12860 struct bpf_reg_state *reg; 12861 struct tnum range = tnum_range(0, 1); 12862 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12863 int err; 12864 struct bpf_func_state *frame = env->cur_state->frame[0]; 12865 const bool is_subprog = frame->subprogno; 12866 12867 /* LSM and struct_ops func-ptr's return type could be "void" */ 12868 if (!is_subprog) { 12869 switch (prog_type) { 12870 case BPF_PROG_TYPE_LSM: 12871 if (prog->expected_attach_type == BPF_LSM_CGROUP) 12872 /* See below, can be 0 or 0-1 depending on hook. */ 12873 break; 12874 fallthrough; 12875 case BPF_PROG_TYPE_STRUCT_OPS: 12876 if (!prog->aux->attach_func_proto->type) 12877 return 0; 12878 break; 12879 default: 12880 break; 12881 } 12882 } 12883 12884 /* eBPF calling convention is such that R0 is used 12885 * to return the value from eBPF program. 12886 * Make sure that it's readable at this time 12887 * of bpf_exit, which means that program wrote 12888 * something into it earlier 12889 */ 12890 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 12891 if (err) 12892 return err; 12893 12894 if (is_pointer_value(env, BPF_REG_0)) { 12895 verbose(env, "R0 leaks addr as return value\n"); 12896 return -EACCES; 12897 } 12898 12899 reg = cur_regs(env) + BPF_REG_0; 12900 12901 if (frame->in_async_callback_fn) { 12902 /* enforce return zero from async callbacks like timer */ 12903 if (reg->type != SCALAR_VALUE) { 12904 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 12905 reg_type_str(env, reg->type)); 12906 return -EINVAL; 12907 } 12908 12909 if (!tnum_in(tnum_const(0), reg->var_off)) { 12910 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 12911 return -EINVAL; 12912 } 12913 return 0; 12914 } 12915 12916 if (is_subprog) { 12917 if (reg->type != SCALAR_VALUE) { 12918 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 12919 reg_type_str(env, reg->type)); 12920 return -EINVAL; 12921 } 12922 return 0; 12923 } 12924 12925 switch (prog_type) { 12926 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 12927 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 12928 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 12929 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 12930 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 12931 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 12932 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 12933 range = tnum_range(1, 1); 12934 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 12935 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 12936 range = tnum_range(0, 3); 12937 break; 12938 case BPF_PROG_TYPE_CGROUP_SKB: 12939 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 12940 range = tnum_range(0, 3); 12941 enforce_attach_type_range = tnum_range(2, 3); 12942 } 12943 break; 12944 case BPF_PROG_TYPE_CGROUP_SOCK: 12945 case BPF_PROG_TYPE_SOCK_OPS: 12946 case BPF_PROG_TYPE_CGROUP_DEVICE: 12947 case BPF_PROG_TYPE_CGROUP_SYSCTL: 12948 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 12949 break; 12950 case BPF_PROG_TYPE_RAW_TRACEPOINT: 12951 if (!env->prog->aux->attach_btf_id) 12952 return 0; 12953 range = tnum_const(0); 12954 break; 12955 case BPF_PROG_TYPE_TRACING: 12956 switch (env->prog->expected_attach_type) { 12957 case BPF_TRACE_FENTRY: 12958 case BPF_TRACE_FEXIT: 12959 range = tnum_const(0); 12960 break; 12961 case BPF_TRACE_RAW_TP: 12962 case BPF_MODIFY_RETURN: 12963 return 0; 12964 case BPF_TRACE_ITER: 12965 break; 12966 default: 12967 return -ENOTSUPP; 12968 } 12969 break; 12970 case BPF_PROG_TYPE_SK_LOOKUP: 12971 range = tnum_range(SK_DROP, SK_PASS); 12972 break; 12973 12974 case BPF_PROG_TYPE_LSM: 12975 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 12976 /* Regular BPF_PROG_TYPE_LSM programs can return 12977 * any value. 12978 */ 12979 return 0; 12980 } 12981 if (!env->prog->aux->attach_func_proto->type) { 12982 /* Make sure programs that attach to void 12983 * hooks don't try to modify return value. 12984 */ 12985 range = tnum_range(1, 1); 12986 } 12987 break; 12988 12989 case BPF_PROG_TYPE_EXT: 12990 /* freplace program can return anything as its return value 12991 * depends on the to-be-replaced kernel func or bpf program. 12992 */ 12993 default: 12994 return 0; 12995 } 12996 12997 if (reg->type != SCALAR_VALUE) { 12998 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 12999 reg_type_str(env, reg->type)); 13000 return -EINVAL; 13001 } 13002 13003 if (!tnum_in(range, reg->var_off)) { 13004 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 13005 if (prog->expected_attach_type == BPF_LSM_CGROUP && 13006 prog_type == BPF_PROG_TYPE_LSM && 13007 !prog->aux->attach_func_proto->type) 13008 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 13009 return -EINVAL; 13010 } 13011 13012 if (!tnum_is_unknown(enforce_attach_type_range) && 13013 tnum_in(enforce_attach_type_range, reg->var_off)) 13014 env->prog->enforce_expected_attach_type = 1; 13015 return 0; 13016 } 13017 13018 /* non-recursive DFS pseudo code 13019 * 1 procedure DFS-iterative(G,v): 13020 * 2 label v as discovered 13021 * 3 let S be a stack 13022 * 4 S.push(v) 13023 * 5 while S is not empty 13024 * 6 t <- S.peek() 13025 * 7 if t is what we're looking for: 13026 * 8 return t 13027 * 9 for all edges e in G.adjacentEdges(t) do 13028 * 10 if edge e is already labelled 13029 * 11 continue with the next edge 13030 * 12 w <- G.adjacentVertex(t,e) 13031 * 13 if vertex w is not discovered and not explored 13032 * 14 label e as tree-edge 13033 * 15 label w as discovered 13034 * 16 S.push(w) 13035 * 17 continue at 5 13036 * 18 else if vertex w is discovered 13037 * 19 label e as back-edge 13038 * 20 else 13039 * 21 // vertex w is explored 13040 * 22 label e as forward- or cross-edge 13041 * 23 label t as explored 13042 * 24 S.pop() 13043 * 13044 * convention: 13045 * 0x10 - discovered 13046 * 0x11 - discovered and fall-through edge labelled 13047 * 0x12 - discovered and fall-through and branch edges labelled 13048 * 0x20 - explored 13049 */ 13050 13051 enum { 13052 DISCOVERED = 0x10, 13053 EXPLORED = 0x20, 13054 FALLTHROUGH = 1, 13055 BRANCH = 2, 13056 }; 13057 13058 static u32 state_htab_size(struct bpf_verifier_env *env) 13059 { 13060 return env->prog->len; 13061 } 13062 13063 static struct bpf_verifier_state_list **explored_state( 13064 struct bpf_verifier_env *env, 13065 int idx) 13066 { 13067 struct bpf_verifier_state *cur = env->cur_state; 13068 struct bpf_func_state *state = cur->frame[cur->curframe]; 13069 13070 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 13071 } 13072 13073 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 13074 { 13075 env->insn_aux_data[idx].prune_point = true; 13076 } 13077 13078 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 13079 { 13080 return env->insn_aux_data[insn_idx].prune_point; 13081 } 13082 13083 enum { 13084 DONE_EXPLORING = 0, 13085 KEEP_EXPLORING = 1, 13086 }; 13087 13088 /* t, w, e - match pseudo-code above: 13089 * t - index of current instruction 13090 * w - next instruction 13091 * e - edge 13092 */ 13093 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 13094 bool loop_ok) 13095 { 13096 int *insn_stack = env->cfg.insn_stack; 13097 int *insn_state = env->cfg.insn_state; 13098 13099 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 13100 return DONE_EXPLORING; 13101 13102 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 13103 return DONE_EXPLORING; 13104 13105 if (w < 0 || w >= env->prog->len) { 13106 verbose_linfo(env, t, "%d: ", t); 13107 verbose(env, "jump out of range from insn %d to %d\n", t, w); 13108 return -EINVAL; 13109 } 13110 13111 if (e == BRANCH) { 13112 /* mark branch target for state pruning */ 13113 mark_prune_point(env, w); 13114 mark_jmp_point(env, w); 13115 } 13116 13117 if (insn_state[w] == 0) { 13118 /* tree-edge */ 13119 insn_state[t] = DISCOVERED | e; 13120 insn_state[w] = DISCOVERED; 13121 if (env->cfg.cur_stack >= env->prog->len) 13122 return -E2BIG; 13123 insn_stack[env->cfg.cur_stack++] = w; 13124 return KEEP_EXPLORING; 13125 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 13126 if (loop_ok && env->bpf_capable) 13127 return DONE_EXPLORING; 13128 verbose_linfo(env, t, "%d: ", t); 13129 verbose_linfo(env, w, "%d: ", w); 13130 verbose(env, "back-edge from insn %d to %d\n", t, w); 13131 return -EINVAL; 13132 } else if (insn_state[w] == EXPLORED) { 13133 /* forward- or cross-edge */ 13134 insn_state[t] = DISCOVERED | e; 13135 } else { 13136 verbose(env, "insn state internal bug\n"); 13137 return -EFAULT; 13138 } 13139 return DONE_EXPLORING; 13140 } 13141 13142 static int visit_func_call_insn(int t, struct bpf_insn *insns, 13143 struct bpf_verifier_env *env, 13144 bool visit_callee) 13145 { 13146 int ret; 13147 13148 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 13149 if (ret) 13150 return ret; 13151 13152 mark_prune_point(env, t + 1); 13153 /* when we exit from subprog, we need to record non-linear history */ 13154 mark_jmp_point(env, t + 1); 13155 13156 if (visit_callee) { 13157 mark_prune_point(env, t); 13158 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 13159 /* It's ok to allow recursion from CFG point of 13160 * view. __check_func_call() will do the actual 13161 * check. 13162 */ 13163 bpf_pseudo_func(insns + t)); 13164 } 13165 return ret; 13166 } 13167 13168 /* Visits the instruction at index t and returns one of the following: 13169 * < 0 - an error occurred 13170 * DONE_EXPLORING - the instruction was fully explored 13171 * KEEP_EXPLORING - there is still work to be done before it is fully explored 13172 */ 13173 static int visit_insn(int t, struct bpf_verifier_env *env) 13174 { 13175 struct bpf_insn *insns = env->prog->insnsi; 13176 int ret; 13177 13178 if (bpf_pseudo_func(insns + t)) 13179 return visit_func_call_insn(t, insns, env, true); 13180 13181 /* All non-branch instructions have a single fall-through edge. */ 13182 if (BPF_CLASS(insns[t].code) != BPF_JMP && 13183 BPF_CLASS(insns[t].code) != BPF_JMP32) 13184 return push_insn(t, t + 1, FALLTHROUGH, env, false); 13185 13186 switch (BPF_OP(insns[t].code)) { 13187 case BPF_EXIT: 13188 return DONE_EXPLORING; 13189 13190 case BPF_CALL: 13191 if (insns[t].imm == BPF_FUNC_timer_set_callback) 13192 /* Mark this call insn as a prune point to trigger 13193 * is_state_visited() check before call itself is 13194 * processed by __check_func_call(). Otherwise new 13195 * async state will be pushed for further exploration. 13196 */ 13197 mark_prune_point(env, t); 13198 return visit_func_call_insn(t, insns, env, 13199 insns[t].src_reg == BPF_PSEUDO_CALL); 13200 13201 case BPF_JA: 13202 if (BPF_SRC(insns[t].code) != BPF_K) 13203 return -EINVAL; 13204 13205 /* unconditional jump with single edge */ 13206 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env, 13207 true); 13208 if (ret) 13209 return ret; 13210 13211 mark_prune_point(env, t + insns[t].off + 1); 13212 mark_jmp_point(env, t + insns[t].off + 1); 13213 13214 return ret; 13215 13216 default: 13217 /* conditional jump with two edges */ 13218 mark_prune_point(env, t); 13219 13220 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 13221 if (ret) 13222 return ret; 13223 13224 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true); 13225 } 13226 } 13227 13228 /* non-recursive depth-first-search to detect loops in BPF program 13229 * loop == back-edge in directed graph 13230 */ 13231 static int check_cfg(struct bpf_verifier_env *env) 13232 { 13233 int insn_cnt = env->prog->len; 13234 int *insn_stack, *insn_state; 13235 int ret = 0; 13236 int i; 13237 13238 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 13239 if (!insn_state) 13240 return -ENOMEM; 13241 13242 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 13243 if (!insn_stack) { 13244 kvfree(insn_state); 13245 return -ENOMEM; 13246 } 13247 13248 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 13249 insn_stack[0] = 0; /* 0 is the first instruction */ 13250 env->cfg.cur_stack = 1; 13251 13252 while (env->cfg.cur_stack > 0) { 13253 int t = insn_stack[env->cfg.cur_stack - 1]; 13254 13255 ret = visit_insn(t, env); 13256 switch (ret) { 13257 case DONE_EXPLORING: 13258 insn_state[t] = EXPLORED; 13259 env->cfg.cur_stack--; 13260 break; 13261 case KEEP_EXPLORING: 13262 break; 13263 default: 13264 if (ret > 0) { 13265 verbose(env, "visit_insn internal bug\n"); 13266 ret = -EFAULT; 13267 } 13268 goto err_free; 13269 } 13270 } 13271 13272 if (env->cfg.cur_stack < 0) { 13273 verbose(env, "pop stack internal bug\n"); 13274 ret = -EFAULT; 13275 goto err_free; 13276 } 13277 13278 for (i = 0; i < insn_cnt; i++) { 13279 if (insn_state[i] != EXPLORED) { 13280 verbose(env, "unreachable insn %d\n", i); 13281 ret = -EINVAL; 13282 goto err_free; 13283 } 13284 } 13285 ret = 0; /* cfg looks good */ 13286 13287 err_free: 13288 kvfree(insn_state); 13289 kvfree(insn_stack); 13290 env->cfg.insn_state = env->cfg.insn_stack = NULL; 13291 return ret; 13292 } 13293 13294 static int check_abnormal_return(struct bpf_verifier_env *env) 13295 { 13296 int i; 13297 13298 for (i = 1; i < env->subprog_cnt; i++) { 13299 if (env->subprog_info[i].has_ld_abs) { 13300 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 13301 return -EINVAL; 13302 } 13303 if (env->subprog_info[i].has_tail_call) { 13304 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 13305 return -EINVAL; 13306 } 13307 } 13308 return 0; 13309 } 13310 13311 /* The minimum supported BTF func info size */ 13312 #define MIN_BPF_FUNCINFO_SIZE 8 13313 #define MAX_FUNCINFO_REC_SIZE 252 13314 13315 static int check_btf_func(struct bpf_verifier_env *env, 13316 const union bpf_attr *attr, 13317 bpfptr_t uattr) 13318 { 13319 const struct btf_type *type, *func_proto, *ret_type; 13320 u32 i, nfuncs, urec_size, min_size; 13321 u32 krec_size = sizeof(struct bpf_func_info); 13322 struct bpf_func_info *krecord; 13323 struct bpf_func_info_aux *info_aux = NULL; 13324 struct bpf_prog *prog; 13325 const struct btf *btf; 13326 bpfptr_t urecord; 13327 u32 prev_offset = 0; 13328 bool scalar_return; 13329 int ret = -ENOMEM; 13330 13331 nfuncs = attr->func_info_cnt; 13332 if (!nfuncs) { 13333 if (check_abnormal_return(env)) 13334 return -EINVAL; 13335 return 0; 13336 } 13337 13338 if (nfuncs != env->subprog_cnt) { 13339 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 13340 return -EINVAL; 13341 } 13342 13343 urec_size = attr->func_info_rec_size; 13344 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 13345 urec_size > MAX_FUNCINFO_REC_SIZE || 13346 urec_size % sizeof(u32)) { 13347 verbose(env, "invalid func info rec size %u\n", urec_size); 13348 return -EINVAL; 13349 } 13350 13351 prog = env->prog; 13352 btf = prog->aux->btf; 13353 13354 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 13355 min_size = min_t(u32, krec_size, urec_size); 13356 13357 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 13358 if (!krecord) 13359 return -ENOMEM; 13360 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 13361 if (!info_aux) 13362 goto err_free; 13363 13364 for (i = 0; i < nfuncs; i++) { 13365 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 13366 if (ret) { 13367 if (ret == -E2BIG) { 13368 verbose(env, "nonzero tailing record in func info"); 13369 /* set the size kernel expects so loader can zero 13370 * out the rest of the record. 13371 */ 13372 if (copy_to_bpfptr_offset(uattr, 13373 offsetof(union bpf_attr, func_info_rec_size), 13374 &min_size, sizeof(min_size))) 13375 ret = -EFAULT; 13376 } 13377 goto err_free; 13378 } 13379 13380 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 13381 ret = -EFAULT; 13382 goto err_free; 13383 } 13384 13385 /* check insn_off */ 13386 ret = -EINVAL; 13387 if (i == 0) { 13388 if (krecord[i].insn_off) { 13389 verbose(env, 13390 "nonzero insn_off %u for the first func info record", 13391 krecord[i].insn_off); 13392 goto err_free; 13393 } 13394 } else if (krecord[i].insn_off <= prev_offset) { 13395 verbose(env, 13396 "same or smaller insn offset (%u) than previous func info record (%u)", 13397 krecord[i].insn_off, prev_offset); 13398 goto err_free; 13399 } 13400 13401 if (env->subprog_info[i].start != krecord[i].insn_off) { 13402 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 13403 goto err_free; 13404 } 13405 13406 /* check type_id */ 13407 type = btf_type_by_id(btf, krecord[i].type_id); 13408 if (!type || !btf_type_is_func(type)) { 13409 verbose(env, "invalid type id %d in func info", 13410 krecord[i].type_id); 13411 goto err_free; 13412 } 13413 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 13414 13415 func_proto = btf_type_by_id(btf, type->type); 13416 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 13417 /* btf_func_check() already verified it during BTF load */ 13418 goto err_free; 13419 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 13420 scalar_return = 13421 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 13422 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 13423 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 13424 goto err_free; 13425 } 13426 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 13427 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 13428 goto err_free; 13429 } 13430 13431 prev_offset = krecord[i].insn_off; 13432 bpfptr_add(&urecord, urec_size); 13433 } 13434 13435 prog->aux->func_info = krecord; 13436 prog->aux->func_info_cnt = nfuncs; 13437 prog->aux->func_info_aux = info_aux; 13438 return 0; 13439 13440 err_free: 13441 kvfree(krecord); 13442 kfree(info_aux); 13443 return ret; 13444 } 13445 13446 static void adjust_btf_func(struct bpf_verifier_env *env) 13447 { 13448 struct bpf_prog_aux *aux = env->prog->aux; 13449 int i; 13450 13451 if (!aux->func_info) 13452 return; 13453 13454 for (i = 0; i < env->subprog_cnt; i++) 13455 aux->func_info[i].insn_off = env->subprog_info[i].start; 13456 } 13457 13458 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 13459 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 13460 13461 static int check_btf_line(struct bpf_verifier_env *env, 13462 const union bpf_attr *attr, 13463 bpfptr_t uattr) 13464 { 13465 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 13466 struct bpf_subprog_info *sub; 13467 struct bpf_line_info *linfo; 13468 struct bpf_prog *prog; 13469 const struct btf *btf; 13470 bpfptr_t ulinfo; 13471 int err; 13472 13473 nr_linfo = attr->line_info_cnt; 13474 if (!nr_linfo) 13475 return 0; 13476 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 13477 return -EINVAL; 13478 13479 rec_size = attr->line_info_rec_size; 13480 if (rec_size < MIN_BPF_LINEINFO_SIZE || 13481 rec_size > MAX_LINEINFO_REC_SIZE || 13482 rec_size & (sizeof(u32) - 1)) 13483 return -EINVAL; 13484 13485 /* Need to zero it in case the userspace may 13486 * pass in a smaller bpf_line_info object. 13487 */ 13488 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 13489 GFP_KERNEL | __GFP_NOWARN); 13490 if (!linfo) 13491 return -ENOMEM; 13492 13493 prog = env->prog; 13494 btf = prog->aux->btf; 13495 13496 s = 0; 13497 sub = env->subprog_info; 13498 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 13499 expected_size = sizeof(struct bpf_line_info); 13500 ncopy = min_t(u32, expected_size, rec_size); 13501 for (i = 0; i < nr_linfo; i++) { 13502 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 13503 if (err) { 13504 if (err == -E2BIG) { 13505 verbose(env, "nonzero tailing record in line_info"); 13506 if (copy_to_bpfptr_offset(uattr, 13507 offsetof(union bpf_attr, line_info_rec_size), 13508 &expected_size, sizeof(expected_size))) 13509 err = -EFAULT; 13510 } 13511 goto err_free; 13512 } 13513 13514 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 13515 err = -EFAULT; 13516 goto err_free; 13517 } 13518 13519 /* 13520 * Check insn_off to ensure 13521 * 1) strictly increasing AND 13522 * 2) bounded by prog->len 13523 * 13524 * The linfo[0].insn_off == 0 check logically falls into 13525 * the later "missing bpf_line_info for func..." case 13526 * because the first linfo[0].insn_off must be the 13527 * first sub also and the first sub must have 13528 * subprog_info[0].start == 0. 13529 */ 13530 if ((i && linfo[i].insn_off <= prev_offset) || 13531 linfo[i].insn_off >= prog->len) { 13532 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 13533 i, linfo[i].insn_off, prev_offset, 13534 prog->len); 13535 err = -EINVAL; 13536 goto err_free; 13537 } 13538 13539 if (!prog->insnsi[linfo[i].insn_off].code) { 13540 verbose(env, 13541 "Invalid insn code at line_info[%u].insn_off\n", 13542 i); 13543 err = -EINVAL; 13544 goto err_free; 13545 } 13546 13547 if (!btf_name_by_offset(btf, linfo[i].line_off) || 13548 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 13549 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 13550 err = -EINVAL; 13551 goto err_free; 13552 } 13553 13554 if (s != env->subprog_cnt) { 13555 if (linfo[i].insn_off == sub[s].start) { 13556 sub[s].linfo_idx = i; 13557 s++; 13558 } else if (sub[s].start < linfo[i].insn_off) { 13559 verbose(env, "missing bpf_line_info for func#%u\n", s); 13560 err = -EINVAL; 13561 goto err_free; 13562 } 13563 } 13564 13565 prev_offset = linfo[i].insn_off; 13566 bpfptr_add(&ulinfo, rec_size); 13567 } 13568 13569 if (s != env->subprog_cnt) { 13570 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 13571 env->subprog_cnt - s, s); 13572 err = -EINVAL; 13573 goto err_free; 13574 } 13575 13576 prog->aux->linfo = linfo; 13577 prog->aux->nr_linfo = nr_linfo; 13578 13579 return 0; 13580 13581 err_free: 13582 kvfree(linfo); 13583 return err; 13584 } 13585 13586 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 13587 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 13588 13589 static int check_core_relo(struct bpf_verifier_env *env, 13590 const union bpf_attr *attr, 13591 bpfptr_t uattr) 13592 { 13593 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 13594 struct bpf_core_relo core_relo = {}; 13595 struct bpf_prog *prog = env->prog; 13596 const struct btf *btf = prog->aux->btf; 13597 struct bpf_core_ctx ctx = { 13598 .log = &env->log, 13599 .btf = btf, 13600 }; 13601 bpfptr_t u_core_relo; 13602 int err; 13603 13604 nr_core_relo = attr->core_relo_cnt; 13605 if (!nr_core_relo) 13606 return 0; 13607 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 13608 return -EINVAL; 13609 13610 rec_size = attr->core_relo_rec_size; 13611 if (rec_size < MIN_CORE_RELO_SIZE || 13612 rec_size > MAX_CORE_RELO_SIZE || 13613 rec_size % sizeof(u32)) 13614 return -EINVAL; 13615 13616 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 13617 expected_size = sizeof(struct bpf_core_relo); 13618 ncopy = min_t(u32, expected_size, rec_size); 13619 13620 /* Unlike func_info and line_info, copy and apply each CO-RE 13621 * relocation record one at a time. 13622 */ 13623 for (i = 0; i < nr_core_relo; i++) { 13624 /* future proofing when sizeof(bpf_core_relo) changes */ 13625 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 13626 if (err) { 13627 if (err == -E2BIG) { 13628 verbose(env, "nonzero tailing record in core_relo"); 13629 if (copy_to_bpfptr_offset(uattr, 13630 offsetof(union bpf_attr, core_relo_rec_size), 13631 &expected_size, sizeof(expected_size))) 13632 err = -EFAULT; 13633 } 13634 break; 13635 } 13636 13637 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 13638 err = -EFAULT; 13639 break; 13640 } 13641 13642 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 13643 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 13644 i, core_relo.insn_off, prog->len); 13645 err = -EINVAL; 13646 break; 13647 } 13648 13649 err = bpf_core_apply(&ctx, &core_relo, i, 13650 &prog->insnsi[core_relo.insn_off / 8]); 13651 if (err) 13652 break; 13653 bpfptr_add(&u_core_relo, rec_size); 13654 } 13655 return err; 13656 } 13657 13658 static int check_btf_info(struct bpf_verifier_env *env, 13659 const union bpf_attr *attr, 13660 bpfptr_t uattr) 13661 { 13662 struct btf *btf; 13663 int err; 13664 13665 if (!attr->func_info_cnt && !attr->line_info_cnt) { 13666 if (check_abnormal_return(env)) 13667 return -EINVAL; 13668 return 0; 13669 } 13670 13671 btf = btf_get_by_fd(attr->prog_btf_fd); 13672 if (IS_ERR(btf)) 13673 return PTR_ERR(btf); 13674 if (btf_is_kernel(btf)) { 13675 btf_put(btf); 13676 return -EACCES; 13677 } 13678 env->prog->aux->btf = btf; 13679 13680 err = check_btf_func(env, attr, uattr); 13681 if (err) 13682 return err; 13683 13684 err = check_btf_line(env, attr, uattr); 13685 if (err) 13686 return err; 13687 13688 err = check_core_relo(env, attr, uattr); 13689 if (err) 13690 return err; 13691 13692 return 0; 13693 } 13694 13695 /* check %cur's range satisfies %old's */ 13696 static bool range_within(struct bpf_reg_state *old, 13697 struct bpf_reg_state *cur) 13698 { 13699 return old->umin_value <= cur->umin_value && 13700 old->umax_value >= cur->umax_value && 13701 old->smin_value <= cur->smin_value && 13702 old->smax_value >= cur->smax_value && 13703 old->u32_min_value <= cur->u32_min_value && 13704 old->u32_max_value >= cur->u32_max_value && 13705 old->s32_min_value <= cur->s32_min_value && 13706 old->s32_max_value >= cur->s32_max_value; 13707 } 13708 13709 /* If in the old state two registers had the same id, then they need to have 13710 * the same id in the new state as well. But that id could be different from 13711 * the old state, so we need to track the mapping from old to new ids. 13712 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 13713 * regs with old id 5 must also have new id 9 for the new state to be safe. But 13714 * regs with a different old id could still have new id 9, we don't care about 13715 * that. 13716 * So we look through our idmap to see if this old id has been seen before. If 13717 * so, we require the new id to match; otherwise, we add the id pair to the map. 13718 */ 13719 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap) 13720 { 13721 unsigned int i; 13722 13723 /* either both IDs should be set or both should be zero */ 13724 if (!!old_id != !!cur_id) 13725 return false; 13726 13727 if (old_id == 0) /* cur_id == 0 as well */ 13728 return true; 13729 13730 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 13731 if (!idmap[i].old) { 13732 /* Reached an empty slot; haven't seen this id before */ 13733 idmap[i].old = old_id; 13734 idmap[i].cur = cur_id; 13735 return true; 13736 } 13737 if (idmap[i].old == old_id) 13738 return idmap[i].cur == cur_id; 13739 } 13740 /* We ran out of idmap slots, which should be impossible */ 13741 WARN_ON_ONCE(1); 13742 return false; 13743 } 13744 13745 static void clean_func_state(struct bpf_verifier_env *env, 13746 struct bpf_func_state *st) 13747 { 13748 enum bpf_reg_liveness live; 13749 int i, j; 13750 13751 for (i = 0; i < BPF_REG_FP; i++) { 13752 live = st->regs[i].live; 13753 /* liveness must not touch this register anymore */ 13754 st->regs[i].live |= REG_LIVE_DONE; 13755 if (!(live & REG_LIVE_READ)) 13756 /* since the register is unused, clear its state 13757 * to make further comparison simpler 13758 */ 13759 __mark_reg_not_init(env, &st->regs[i]); 13760 } 13761 13762 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 13763 live = st->stack[i].spilled_ptr.live; 13764 /* liveness must not touch this stack slot anymore */ 13765 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 13766 if (!(live & REG_LIVE_READ)) { 13767 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 13768 for (j = 0; j < BPF_REG_SIZE; j++) 13769 st->stack[i].slot_type[j] = STACK_INVALID; 13770 } 13771 } 13772 } 13773 13774 static void clean_verifier_state(struct bpf_verifier_env *env, 13775 struct bpf_verifier_state *st) 13776 { 13777 int i; 13778 13779 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 13780 /* all regs in this state in all frames were already marked */ 13781 return; 13782 13783 for (i = 0; i <= st->curframe; i++) 13784 clean_func_state(env, st->frame[i]); 13785 } 13786 13787 /* the parentage chains form a tree. 13788 * the verifier states are added to state lists at given insn and 13789 * pushed into state stack for future exploration. 13790 * when the verifier reaches bpf_exit insn some of the verifer states 13791 * stored in the state lists have their final liveness state already, 13792 * but a lot of states will get revised from liveness point of view when 13793 * the verifier explores other branches. 13794 * Example: 13795 * 1: r0 = 1 13796 * 2: if r1 == 100 goto pc+1 13797 * 3: r0 = 2 13798 * 4: exit 13799 * when the verifier reaches exit insn the register r0 in the state list of 13800 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 13801 * of insn 2 and goes exploring further. At the insn 4 it will walk the 13802 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 13803 * 13804 * Since the verifier pushes the branch states as it sees them while exploring 13805 * the program the condition of walking the branch instruction for the second 13806 * time means that all states below this branch were already explored and 13807 * their final liveness marks are already propagated. 13808 * Hence when the verifier completes the search of state list in is_state_visited() 13809 * we can call this clean_live_states() function to mark all liveness states 13810 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 13811 * will not be used. 13812 * This function also clears the registers and stack for states that !READ 13813 * to simplify state merging. 13814 * 13815 * Important note here that walking the same branch instruction in the callee 13816 * doesn't meant that the states are DONE. The verifier has to compare 13817 * the callsites 13818 */ 13819 static void clean_live_states(struct bpf_verifier_env *env, int insn, 13820 struct bpf_verifier_state *cur) 13821 { 13822 struct bpf_verifier_state_list *sl; 13823 int i; 13824 13825 sl = *explored_state(env, insn); 13826 while (sl) { 13827 if (sl->state.branches) 13828 goto next; 13829 if (sl->state.insn_idx != insn || 13830 sl->state.curframe != cur->curframe) 13831 goto next; 13832 for (i = 0; i <= cur->curframe; i++) 13833 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 13834 goto next; 13835 clean_verifier_state(env, &sl->state); 13836 next: 13837 sl = sl->next; 13838 } 13839 } 13840 13841 static bool regs_exact(const struct bpf_reg_state *rold, 13842 const struct bpf_reg_state *rcur, 13843 struct bpf_id_pair *idmap) 13844 { 13845 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 13846 check_ids(rold->id, rcur->id, idmap) && 13847 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 13848 } 13849 13850 /* Returns true if (rold safe implies rcur safe) */ 13851 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 13852 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap) 13853 { 13854 if (!(rold->live & REG_LIVE_READ)) 13855 /* explored state didn't use this */ 13856 return true; 13857 if (rold->type == NOT_INIT) 13858 /* explored state can't have used this */ 13859 return true; 13860 if (rcur->type == NOT_INIT) 13861 return false; 13862 13863 /* Enforce that register types have to match exactly, including their 13864 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 13865 * rule. 13866 * 13867 * One can make a point that using a pointer register as unbounded 13868 * SCALAR would be technically acceptable, but this could lead to 13869 * pointer leaks because scalars are allowed to leak while pointers 13870 * are not. We could make this safe in special cases if root is 13871 * calling us, but it's probably not worth the hassle. 13872 * 13873 * Also, register types that are *not* MAYBE_NULL could technically be 13874 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 13875 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 13876 * to the same map). 13877 * However, if the old MAYBE_NULL register then got NULL checked, 13878 * doing so could have affected others with the same id, and we can't 13879 * check for that because we lost the id when we converted to 13880 * a non-MAYBE_NULL variant. 13881 * So, as a general rule we don't allow mixing MAYBE_NULL and 13882 * non-MAYBE_NULL registers as well. 13883 */ 13884 if (rold->type != rcur->type) 13885 return false; 13886 13887 switch (base_type(rold->type)) { 13888 case SCALAR_VALUE: 13889 if (regs_exact(rold, rcur, idmap)) 13890 return true; 13891 if (env->explore_alu_limits) 13892 return false; 13893 if (!rold->precise) 13894 return true; 13895 /* new val must satisfy old val knowledge */ 13896 return range_within(rold, rcur) && 13897 tnum_in(rold->var_off, rcur->var_off); 13898 case PTR_TO_MAP_KEY: 13899 case PTR_TO_MAP_VALUE: 13900 /* If the new min/max/var_off satisfy the old ones and 13901 * everything else matches, we are OK. 13902 */ 13903 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 13904 range_within(rold, rcur) && 13905 tnum_in(rold->var_off, rcur->var_off) && 13906 check_ids(rold->id, rcur->id, idmap); 13907 case PTR_TO_PACKET_META: 13908 case PTR_TO_PACKET: 13909 /* We must have at least as much range as the old ptr 13910 * did, so that any accesses which were safe before are 13911 * still safe. This is true even if old range < old off, 13912 * since someone could have accessed through (ptr - k), or 13913 * even done ptr -= k in a register, to get a safe access. 13914 */ 13915 if (rold->range > rcur->range) 13916 return false; 13917 /* If the offsets don't match, we can't trust our alignment; 13918 * nor can we be sure that we won't fall out of range. 13919 */ 13920 if (rold->off != rcur->off) 13921 return false; 13922 /* id relations must be preserved */ 13923 if (!check_ids(rold->id, rcur->id, idmap)) 13924 return false; 13925 /* new val must satisfy old val knowledge */ 13926 return range_within(rold, rcur) && 13927 tnum_in(rold->var_off, rcur->var_off); 13928 case PTR_TO_STACK: 13929 /* two stack pointers are equal only if they're pointing to 13930 * the same stack frame, since fp-8 in foo != fp-8 in bar 13931 */ 13932 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 13933 default: 13934 return regs_exact(rold, rcur, idmap); 13935 } 13936 } 13937 13938 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 13939 struct bpf_func_state *cur, struct bpf_id_pair *idmap) 13940 { 13941 int i, spi; 13942 13943 /* walk slots of the explored stack and ignore any additional 13944 * slots in the current stack, since explored(safe) state 13945 * didn't use them 13946 */ 13947 for (i = 0; i < old->allocated_stack; i++) { 13948 spi = i / BPF_REG_SIZE; 13949 13950 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 13951 i += BPF_REG_SIZE - 1; 13952 /* explored state didn't use this */ 13953 continue; 13954 } 13955 13956 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 13957 continue; 13958 13959 if (env->allow_uninit_stack && 13960 old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC) 13961 continue; 13962 13963 /* explored stack has more populated slots than current stack 13964 * and these slots were used 13965 */ 13966 if (i >= cur->allocated_stack) 13967 return false; 13968 13969 /* if old state was safe with misc data in the stack 13970 * it will be safe with zero-initialized stack. 13971 * The opposite is not true 13972 */ 13973 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 13974 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 13975 continue; 13976 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 13977 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 13978 /* Ex: old explored (safe) state has STACK_SPILL in 13979 * this stack slot, but current has STACK_MISC -> 13980 * this verifier states are not equivalent, 13981 * return false to continue verification of this path 13982 */ 13983 return false; 13984 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 13985 continue; 13986 /* Both old and cur are having same slot_type */ 13987 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 13988 case STACK_SPILL: 13989 /* when explored and current stack slot are both storing 13990 * spilled registers, check that stored pointers types 13991 * are the same as well. 13992 * Ex: explored safe path could have stored 13993 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 13994 * but current path has stored: 13995 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 13996 * such verifier states are not equivalent. 13997 * return false to continue verification of this path 13998 */ 13999 if (!regsafe(env, &old->stack[spi].spilled_ptr, 14000 &cur->stack[spi].spilled_ptr, idmap)) 14001 return false; 14002 break; 14003 case STACK_DYNPTR: 14004 { 14005 const struct bpf_reg_state *old_reg, *cur_reg; 14006 14007 old_reg = &old->stack[spi].spilled_ptr; 14008 cur_reg = &cur->stack[spi].spilled_ptr; 14009 if (old_reg->dynptr.type != cur_reg->dynptr.type || 14010 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 14011 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 14012 return false; 14013 break; 14014 } 14015 case STACK_MISC: 14016 case STACK_ZERO: 14017 case STACK_INVALID: 14018 continue; 14019 /* Ensure that new unhandled slot types return false by default */ 14020 default: 14021 return false; 14022 } 14023 } 14024 return true; 14025 } 14026 14027 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 14028 struct bpf_id_pair *idmap) 14029 { 14030 int i; 14031 14032 if (old->acquired_refs != cur->acquired_refs) 14033 return false; 14034 14035 for (i = 0; i < old->acquired_refs; i++) { 14036 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 14037 return false; 14038 } 14039 14040 return true; 14041 } 14042 14043 /* compare two verifier states 14044 * 14045 * all states stored in state_list are known to be valid, since 14046 * verifier reached 'bpf_exit' instruction through them 14047 * 14048 * this function is called when verifier exploring different branches of 14049 * execution popped from the state stack. If it sees an old state that has 14050 * more strict register state and more strict stack state then this execution 14051 * branch doesn't need to be explored further, since verifier already 14052 * concluded that more strict state leads to valid finish. 14053 * 14054 * Therefore two states are equivalent if register state is more conservative 14055 * and explored stack state is more conservative than the current one. 14056 * Example: 14057 * explored current 14058 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 14059 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 14060 * 14061 * In other words if current stack state (one being explored) has more 14062 * valid slots than old one that already passed validation, it means 14063 * the verifier can stop exploring and conclude that current state is valid too 14064 * 14065 * Similarly with registers. If explored state has register type as invalid 14066 * whereas register type in current state is meaningful, it means that 14067 * the current state will reach 'bpf_exit' instruction safely 14068 */ 14069 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 14070 struct bpf_func_state *cur) 14071 { 14072 int i; 14073 14074 for (i = 0; i < MAX_BPF_REG; i++) 14075 if (!regsafe(env, &old->regs[i], &cur->regs[i], 14076 env->idmap_scratch)) 14077 return false; 14078 14079 if (!stacksafe(env, old, cur, env->idmap_scratch)) 14080 return false; 14081 14082 if (!refsafe(old, cur, env->idmap_scratch)) 14083 return false; 14084 14085 return true; 14086 } 14087 14088 static bool states_equal(struct bpf_verifier_env *env, 14089 struct bpf_verifier_state *old, 14090 struct bpf_verifier_state *cur) 14091 { 14092 int i; 14093 14094 if (old->curframe != cur->curframe) 14095 return false; 14096 14097 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch)); 14098 14099 /* Verification state from speculative execution simulation 14100 * must never prune a non-speculative execution one. 14101 */ 14102 if (old->speculative && !cur->speculative) 14103 return false; 14104 14105 if (old->active_lock.ptr != cur->active_lock.ptr) 14106 return false; 14107 14108 /* Old and cur active_lock's have to be either both present 14109 * or both absent. 14110 */ 14111 if (!!old->active_lock.id != !!cur->active_lock.id) 14112 return false; 14113 14114 if (old->active_lock.id && 14115 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch)) 14116 return false; 14117 14118 if (old->active_rcu_lock != cur->active_rcu_lock) 14119 return false; 14120 14121 /* for states to be equal callsites have to be the same 14122 * and all frame states need to be equivalent 14123 */ 14124 for (i = 0; i <= old->curframe; i++) { 14125 if (old->frame[i]->callsite != cur->frame[i]->callsite) 14126 return false; 14127 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 14128 return false; 14129 } 14130 return true; 14131 } 14132 14133 /* Return 0 if no propagation happened. Return negative error code if error 14134 * happened. Otherwise, return the propagated bit. 14135 */ 14136 static int propagate_liveness_reg(struct bpf_verifier_env *env, 14137 struct bpf_reg_state *reg, 14138 struct bpf_reg_state *parent_reg) 14139 { 14140 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 14141 u8 flag = reg->live & REG_LIVE_READ; 14142 int err; 14143 14144 /* When comes here, read flags of PARENT_REG or REG could be any of 14145 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 14146 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 14147 */ 14148 if (parent_flag == REG_LIVE_READ64 || 14149 /* Or if there is no read flag from REG. */ 14150 !flag || 14151 /* Or if the read flag from REG is the same as PARENT_REG. */ 14152 parent_flag == flag) 14153 return 0; 14154 14155 err = mark_reg_read(env, reg, parent_reg, flag); 14156 if (err) 14157 return err; 14158 14159 return flag; 14160 } 14161 14162 /* A write screens off any subsequent reads; but write marks come from the 14163 * straight-line code between a state and its parent. When we arrive at an 14164 * equivalent state (jump target or such) we didn't arrive by the straight-line 14165 * code, so read marks in the state must propagate to the parent regardless 14166 * of the state's write marks. That's what 'parent == state->parent' comparison 14167 * in mark_reg_read() is for. 14168 */ 14169 static int propagate_liveness(struct bpf_verifier_env *env, 14170 const struct bpf_verifier_state *vstate, 14171 struct bpf_verifier_state *vparent) 14172 { 14173 struct bpf_reg_state *state_reg, *parent_reg; 14174 struct bpf_func_state *state, *parent; 14175 int i, frame, err = 0; 14176 14177 if (vparent->curframe != vstate->curframe) { 14178 WARN(1, "propagate_live: parent frame %d current frame %d\n", 14179 vparent->curframe, vstate->curframe); 14180 return -EFAULT; 14181 } 14182 /* Propagate read liveness of registers... */ 14183 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 14184 for (frame = 0; frame <= vstate->curframe; frame++) { 14185 parent = vparent->frame[frame]; 14186 state = vstate->frame[frame]; 14187 parent_reg = parent->regs; 14188 state_reg = state->regs; 14189 /* We don't need to worry about FP liveness, it's read-only */ 14190 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 14191 err = propagate_liveness_reg(env, &state_reg[i], 14192 &parent_reg[i]); 14193 if (err < 0) 14194 return err; 14195 if (err == REG_LIVE_READ64) 14196 mark_insn_zext(env, &parent_reg[i]); 14197 } 14198 14199 /* Propagate stack slots. */ 14200 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 14201 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 14202 parent_reg = &parent->stack[i].spilled_ptr; 14203 state_reg = &state->stack[i].spilled_ptr; 14204 err = propagate_liveness_reg(env, state_reg, 14205 parent_reg); 14206 if (err < 0) 14207 return err; 14208 } 14209 } 14210 return 0; 14211 } 14212 14213 /* find precise scalars in the previous equivalent state and 14214 * propagate them into the current state 14215 */ 14216 static int propagate_precision(struct bpf_verifier_env *env, 14217 const struct bpf_verifier_state *old) 14218 { 14219 struct bpf_reg_state *state_reg; 14220 struct bpf_func_state *state; 14221 int i, err = 0, fr; 14222 14223 for (fr = old->curframe; fr >= 0; fr--) { 14224 state = old->frame[fr]; 14225 state_reg = state->regs; 14226 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 14227 if (state_reg->type != SCALAR_VALUE || 14228 !state_reg->precise) 14229 continue; 14230 if (env->log.level & BPF_LOG_LEVEL2) 14231 verbose(env, "frame %d: propagating r%d\n", i, fr); 14232 err = mark_chain_precision_frame(env, fr, i); 14233 if (err < 0) 14234 return err; 14235 } 14236 14237 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 14238 if (!is_spilled_reg(&state->stack[i])) 14239 continue; 14240 state_reg = &state->stack[i].spilled_ptr; 14241 if (state_reg->type != SCALAR_VALUE || 14242 !state_reg->precise) 14243 continue; 14244 if (env->log.level & BPF_LOG_LEVEL2) 14245 verbose(env, "frame %d: propagating fp%d\n", 14246 (-i - 1) * BPF_REG_SIZE, fr); 14247 err = mark_chain_precision_stack_frame(env, fr, i); 14248 if (err < 0) 14249 return err; 14250 } 14251 } 14252 return 0; 14253 } 14254 14255 static bool states_maybe_looping(struct bpf_verifier_state *old, 14256 struct bpf_verifier_state *cur) 14257 { 14258 struct bpf_func_state *fold, *fcur; 14259 int i, fr = cur->curframe; 14260 14261 if (old->curframe != fr) 14262 return false; 14263 14264 fold = old->frame[fr]; 14265 fcur = cur->frame[fr]; 14266 for (i = 0; i < MAX_BPF_REG; i++) 14267 if (memcmp(&fold->regs[i], &fcur->regs[i], 14268 offsetof(struct bpf_reg_state, parent))) 14269 return false; 14270 return true; 14271 } 14272 14273 14274 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 14275 { 14276 struct bpf_verifier_state_list *new_sl; 14277 struct bpf_verifier_state_list *sl, **pprev; 14278 struct bpf_verifier_state *cur = env->cur_state, *new; 14279 int i, j, err, states_cnt = 0; 14280 bool add_new_state = env->test_state_freq ? true : false; 14281 14282 /* bpf progs typically have pruning point every 4 instructions 14283 * http://vger.kernel.org/bpfconf2019.html#session-1 14284 * Do not add new state for future pruning if the verifier hasn't seen 14285 * at least 2 jumps and at least 8 instructions. 14286 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 14287 * In tests that amounts to up to 50% reduction into total verifier 14288 * memory consumption and 20% verifier time speedup. 14289 */ 14290 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 14291 env->insn_processed - env->prev_insn_processed >= 8) 14292 add_new_state = true; 14293 14294 pprev = explored_state(env, insn_idx); 14295 sl = *pprev; 14296 14297 clean_live_states(env, insn_idx, cur); 14298 14299 while (sl) { 14300 states_cnt++; 14301 if (sl->state.insn_idx != insn_idx) 14302 goto next; 14303 14304 if (sl->state.branches) { 14305 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 14306 14307 if (frame->in_async_callback_fn && 14308 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 14309 /* Different async_entry_cnt means that the verifier is 14310 * processing another entry into async callback. 14311 * Seeing the same state is not an indication of infinite 14312 * loop or infinite recursion. 14313 * But finding the same state doesn't mean that it's safe 14314 * to stop processing the current state. The previous state 14315 * hasn't yet reached bpf_exit, since state.branches > 0. 14316 * Checking in_async_callback_fn alone is not enough either. 14317 * Since the verifier still needs to catch infinite loops 14318 * inside async callbacks. 14319 */ 14320 } else if (states_maybe_looping(&sl->state, cur) && 14321 states_equal(env, &sl->state, cur)) { 14322 verbose_linfo(env, insn_idx, "; "); 14323 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 14324 return -EINVAL; 14325 } 14326 /* if the verifier is processing a loop, avoid adding new state 14327 * too often, since different loop iterations have distinct 14328 * states and may not help future pruning. 14329 * This threshold shouldn't be too low to make sure that 14330 * a loop with large bound will be rejected quickly. 14331 * The most abusive loop will be: 14332 * r1 += 1 14333 * if r1 < 1000000 goto pc-2 14334 * 1M insn_procssed limit / 100 == 10k peak states. 14335 * This threshold shouldn't be too high either, since states 14336 * at the end of the loop are likely to be useful in pruning. 14337 */ 14338 if (env->jmps_processed - env->prev_jmps_processed < 20 && 14339 env->insn_processed - env->prev_insn_processed < 100) 14340 add_new_state = false; 14341 goto miss; 14342 } 14343 if (states_equal(env, &sl->state, cur)) { 14344 sl->hit_cnt++; 14345 /* reached equivalent register/stack state, 14346 * prune the search. 14347 * Registers read by the continuation are read by us. 14348 * If we have any write marks in env->cur_state, they 14349 * will prevent corresponding reads in the continuation 14350 * from reaching our parent (an explored_state). Our 14351 * own state will get the read marks recorded, but 14352 * they'll be immediately forgotten as we're pruning 14353 * this state and will pop a new one. 14354 */ 14355 err = propagate_liveness(env, &sl->state, cur); 14356 14357 /* if previous state reached the exit with precision and 14358 * current state is equivalent to it (except precsion marks) 14359 * the precision needs to be propagated back in 14360 * the current state. 14361 */ 14362 err = err ? : push_jmp_history(env, cur); 14363 err = err ? : propagate_precision(env, &sl->state); 14364 if (err) 14365 return err; 14366 return 1; 14367 } 14368 miss: 14369 /* when new state is not going to be added do not increase miss count. 14370 * Otherwise several loop iterations will remove the state 14371 * recorded earlier. The goal of these heuristics is to have 14372 * states from some iterations of the loop (some in the beginning 14373 * and some at the end) to help pruning. 14374 */ 14375 if (add_new_state) 14376 sl->miss_cnt++; 14377 /* heuristic to determine whether this state is beneficial 14378 * to keep checking from state equivalence point of view. 14379 * Higher numbers increase max_states_per_insn and verification time, 14380 * but do not meaningfully decrease insn_processed. 14381 */ 14382 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 14383 /* the state is unlikely to be useful. Remove it to 14384 * speed up verification 14385 */ 14386 *pprev = sl->next; 14387 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 14388 u32 br = sl->state.branches; 14389 14390 WARN_ONCE(br, 14391 "BUG live_done but branches_to_explore %d\n", 14392 br); 14393 free_verifier_state(&sl->state, false); 14394 kfree(sl); 14395 env->peak_states--; 14396 } else { 14397 /* cannot free this state, since parentage chain may 14398 * walk it later. Add it for free_list instead to 14399 * be freed at the end of verification 14400 */ 14401 sl->next = env->free_list; 14402 env->free_list = sl; 14403 } 14404 sl = *pprev; 14405 continue; 14406 } 14407 next: 14408 pprev = &sl->next; 14409 sl = *pprev; 14410 } 14411 14412 if (env->max_states_per_insn < states_cnt) 14413 env->max_states_per_insn = states_cnt; 14414 14415 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 14416 return 0; 14417 14418 if (!add_new_state) 14419 return 0; 14420 14421 /* There were no equivalent states, remember the current one. 14422 * Technically the current state is not proven to be safe yet, 14423 * but it will either reach outer most bpf_exit (which means it's safe) 14424 * or it will be rejected. When there are no loops the verifier won't be 14425 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 14426 * again on the way to bpf_exit. 14427 * When looping the sl->state.branches will be > 0 and this state 14428 * will not be considered for equivalence until branches == 0. 14429 */ 14430 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 14431 if (!new_sl) 14432 return -ENOMEM; 14433 env->total_states++; 14434 env->peak_states++; 14435 env->prev_jmps_processed = env->jmps_processed; 14436 env->prev_insn_processed = env->insn_processed; 14437 14438 /* forget precise markings we inherited, see __mark_chain_precision */ 14439 if (env->bpf_capable) 14440 mark_all_scalars_imprecise(env, cur); 14441 14442 /* add new state to the head of linked list */ 14443 new = &new_sl->state; 14444 err = copy_verifier_state(new, cur); 14445 if (err) { 14446 free_verifier_state(new, false); 14447 kfree(new_sl); 14448 return err; 14449 } 14450 new->insn_idx = insn_idx; 14451 WARN_ONCE(new->branches != 1, 14452 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 14453 14454 cur->parent = new; 14455 cur->first_insn_idx = insn_idx; 14456 clear_jmp_history(cur); 14457 new_sl->next = *explored_state(env, insn_idx); 14458 *explored_state(env, insn_idx) = new_sl; 14459 /* connect new state to parentage chain. Current frame needs all 14460 * registers connected. Only r6 - r9 of the callers are alive (pushed 14461 * to the stack implicitly by JITs) so in callers' frames connect just 14462 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 14463 * the state of the call instruction (with WRITTEN set), and r0 comes 14464 * from callee with its full parentage chain, anyway. 14465 */ 14466 /* clear write marks in current state: the writes we did are not writes 14467 * our child did, so they don't screen off its reads from us. 14468 * (There are no read marks in current state, because reads always mark 14469 * their parent and current state never has children yet. Only 14470 * explored_states can get read marks.) 14471 */ 14472 for (j = 0; j <= cur->curframe; j++) { 14473 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 14474 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 14475 for (i = 0; i < BPF_REG_FP; i++) 14476 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 14477 } 14478 14479 /* all stack frames are accessible from callee, clear them all */ 14480 for (j = 0; j <= cur->curframe; j++) { 14481 struct bpf_func_state *frame = cur->frame[j]; 14482 struct bpf_func_state *newframe = new->frame[j]; 14483 14484 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 14485 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 14486 frame->stack[i].spilled_ptr.parent = 14487 &newframe->stack[i].spilled_ptr; 14488 } 14489 } 14490 return 0; 14491 } 14492 14493 /* Return true if it's OK to have the same insn return a different type. */ 14494 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 14495 { 14496 switch (base_type(type)) { 14497 case PTR_TO_CTX: 14498 case PTR_TO_SOCKET: 14499 case PTR_TO_SOCK_COMMON: 14500 case PTR_TO_TCP_SOCK: 14501 case PTR_TO_XDP_SOCK: 14502 case PTR_TO_BTF_ID: 14503 return false; 14504 default: 14505 return true; 14506 } 14507 } 14508 14509 /* If an instruction was previously used with particular pointer types, then we 14510 * need to be careful to avoid cases such as the below, where it may be ok 14511 * for one branch accessing the pointer, but not ok for the other branch: 14512 * 14513 * R1 = sock_ptr 14514 * goto X; 14515 * ... 14516 * R1 = some_other_valid_ptr; 14517 * goto X; 14518 * ... 14519 * R2 = *(u32 *)(R1 + 0); 14520 */ 14521 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 14522 { 14523 return src != prev && (!reg_type_mismatch_ok(src) || 14524 !reg_type_mismatch_ok(prev)); 14525 } 14526 14527 static int do_check(struct bpf_verifier_env *env) 14528 { 14529 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 14530 struct bpf_verifier_state *state = env->cur_state; 14531 struct bpf_insn *insns = env->prog->insnsi; 14532 struct bpf_reg_state *regs; 14533 int insn_cnt = env->prog->len; 14534 bool do_print_state = false; 14535 int prev_insn_idx = -1; 14536 14537 for (;;) { 14538 struct bpf_insn *insn; 14539 u8 class; 14540 int err; 14541 14542 env->prev_insn_idx = prev_insn_idx; 14543 if (env->insn_idx >= insn_cnt) { 14544 verbose(env, "invalid insn idx %d insn_cnt %d\n", 14545 env->insn_idx, insn_cnt); 14546 return -EFAULT; 14547 } 14548 14549 insn = &insns[env->insn_idx]; 14550 class = BPF_CLASS(insn->code); 14551 14552 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 14553 verbose(env, 14554 "BPF program is too large. Processed %d insn\n", 14555 env->insn_processed); 14556 return -E2BIG; 14557 } 14558 14559 state->last_insn_idx = env->prev_insn_idx; 14560 14561 if (is_prune_point(env, env->insn_idx)) { 14562 err = is_state_visited(env, env->insn_idx); 14563 if (err < 0) 14564 return err; 14565 if (err == 1) { 14566 /* found equivalent state, can prune the search */ 14567 if (env->log.level & BPF_LOG_LEVEL) { 14568 if (do_print_state) 14569 verbose(env, "\nfrom %d to %d%s: safe\n", 14570 env->prev_insn_idx, env->insn_idx, 14571 env->cur_state->speculative ? 14572 " (speculative execution)" : ""); 14573 else 14574 verbose(env, "%d: safe\n", env->insn_idx); 14575 } 14576 goto process_bpf_exit; 14577 } 14578 } 14579 14580 if (is_jmp_point(env, env->insn_idx)) { 14581 err = push_jmp_history(env, state); 14582 if (err) 14583 return err; 14584 } 14585 14586 if (signal_pending(current)) 14587 return -EAGAIN; 14588 14589 if (need_resched()) 14590 cond_resched(); 14591 14592 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 14593 verbose(env, "\nfrom %d to %d%s:", 14594 env->prev_insn_idx, env->insn_idx, 14595 env->cur_state->speculative ? 14596 " (speculative execution)" : ""); 14597 print_verifier_state(env, state->frame[state->curframe], true); 14598 do_print_state = false; 14599 } 14600 14601 if (env->log.level & BPF_LOG_LEVEL) { 14602 const struct bpf_insn_cbs cbs = { 14603 .cb_call = disasm_kfunc_name, 14604 .cb_print = verbose, 14605 .private_data = env, 14606 }; 14607 14608 if (verifier_state_scratched(env)) 14609 print_insn_state(env, state->frame[state->curframe]); 14610 14611 verbose_linfo(env, env->insn_idx, "; "); 14612 env->prev_log_len = env->log.len_used; 14613 verbose(env, "%d: ", env->insn_idx); 14614 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 14615 env->prev_insn_print_len = env->log.len_used - env->prev_log_len; 14616 env->prev_log_len = env->log.len_used; 14617 } 14618 14619 if (bpf_prog_is_offloaded(env->prog->aux)) { 14620 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 14621 env->prev_insn_idx); 14622 if (err) 14623 return err; 14624 } 14625 14626 regs = cur_regs(env); 14627 sanitize_mark_insn_seen(env); 14628 prev_insn_idx = env->insn_idx; 14629 14630 if (class == BPF_ALU || class == BPF_ALU64) { 14631 err = check_alu_op(env, insn); 14632 if (err) 14633 return err; 14634 14635 } else if (class == BPF_LDX) { 14636 enum bpf_reg_type *prev_src_type, src_reg_type; 14637 14638 /* check for reserved fields is already done */ 14639 14640 /* check src operand */ 14641 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14642 if (err) 14643 return err; 14644 14645 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14646 if (err) 14647 return err; 14648 14649 src_reg_type = regs[insn->src_reg].type; 14650 14651 /* check that memory (src_reg + off) is readable, 14652 * the state of dst_reg will be updated by this func 14653 */ 14654 err = check_mem_access(env, env->insn_idx, insn->src_reg, 14655 insn->off, BPF_SIZE(insn->code), 14656 BPF_READ, insn->dst_reg, false); 14657 if (err) 14658 return err; 14659 14660 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 14661 14662 if (*prev_src_type == NOT_INIT) { 14663 /* saw a valid insn 14664 * dst_reg = *(u32 *)(src_reg + off) 14665 * save type to validate intersecting paths 14666 */ 14667 *prev_src_type = src_reg_type; 14668 14669 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 14670 /* ABuser program is trying to use the same insn 14671 * dst_reg = *(u32*) (src_reg + off) 14672 * with different pointer types: 14673 * src_reg == ctx in one branch and 14674 * src_reg == stack|map in some other branch. 14675 * Reject it. 14676 */ 14677 verbose(env, "same insn cannot be used with different pointers\n"); 14678 return -EINVAL; 14679 } 14680 14681 } else if (class == BPF_STX) { 14682 enum bpf_reg_type *prev_dst_type, dst_reg_type; 14683 14684 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 14685 err = check_atomic(env, env->insn_idx, insn); 14686 if (err) 14687 return err; 14688 env->insn_idx++; 14689 continue; 14690 } 14691 14692 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 14693 verbose(env, "BPF_STX uses reserved fields\n"); 14694 return -EINVAL; 14695 } 14696 14697 /* check src1 operand */ 14698 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14699 if (err) 14700 return err; 14701 /* check src2 operand */ 14702 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14703 if (err) 14704 return err; 14705 14706 dst_reg_type = regs[insn->dst_reg].type; 14707 14708 /* check that memory (dst_reg + off) is writeable */ 14709 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 14710 insn->off, BPF_SIZE(insn->code), 14711 BPF_WRITE, insn->src_reg, false); 14712 if (err) 14713 return err; 14714 14715 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 14716 14717 if (*prev_dst_type == NOT_INIT) { 14718 *prev_dst_type = dst_reg_type; 14719 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 14720 verbose(env, "same insn cannot be used with different pointers\n"); 14721 return -EINVAL; 14722 } 14723 14724 } else if (class == BPF_ST) { 14725 if (BPF_MODE(insn->code) != BPF_MEM || 14726 insn->src_reg != BPF_REG_0) { 14727 verbose(env, "BPF_ST uses reserved fields\n"); 14728 return -EINVAL; 14729 } 14730 /* check src operand */ 14731 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14732 if (err) 14733 return err; 14734 14735 if (is_ctx_reg(env, insn->dst_reg)) { 14736 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 14737 insn->dst_reg, 14738 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 14739 return -EACCES; 14740 } 14741 14742 /* check that memory (dst_reg + off) is writeable */ 14743 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 14744 insn->off, BPF_SIZE(insn->code), 14745 BPF_WRITE, -1, false); 14746 if (err) 14747 return err; 14748 14749 } else if (class == BPF_JMP || class == BPF_JMP32) { 14750 u8 opcode = BPF_OP(insn->code); 14751 14752 env->jmps_processed++; 14753 if (opcode == BPF_CALL) { 14754 if (BPF_SRC(insn->code) != BPF_K || 14755 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 14756 && insn->off != 0) || 14757 (insn->src_reg != BPF_REG_0 && 14758 insn->src_reg != BPF_PSEUDO_CALL && 14759 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 14760 insn->dst_reg != BPF_REG_0 || 14761 class == BPF_JMP32) { 14762 verbose(env, "BPF_CALL uses reserved fields\n"); 14763 return -EINVAL; 14764 } 14765 14766 if (env->cur_state->active_lock.ptr) { 14767 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 14768 (insn->src_reg == BPF_PSEUDO_CALL) || 14769 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 14770 (insn->off != 0 || !is_bpf_graph_api_kfunc(insn->imm)))) { 14771 verbose(env, "function calls are not allowed while holding a lock\n"); 14772 return -EINVAL; 14773 } 14774 } 14775 if (insn->src_reg == BPF_PSEUDO_CALL) 14776 err = check_func_call(env, insn, &env->insn_idx); 14777 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 14778 err = check_kfunc_call(env, insn, &env->insn_idx); 14779 else 14780 err = check_helper_call(env, insn, &env->insn_idx); 14781 if (err) 14782 return err; 14783 } else if (opcode == BPF_JA) { 14784 if (BPF_SRC(insn->code) != BPF_K || 14785 insn->imm != 0 || 14786 insn->src_reg != BPF_REG_0 || 14787 insn->dst_reg != BPF_REG_0 || 14788 class == BPF_JMP32) { 14789 verbose(env, "BPF_JA uses reserved fields\n"); 14790 return -EINVAL; 14791 } 14792 14793 env->insn_idx += insn->off + 1; 14794 continue; 14795 14796 } else if (opcode == BPF_EXIT) { 14797 if (BPF_SRC(insn->code) != BPF_K || 14798 insn->imm != 0 || 14799 insn->src_reg != BPF_REG_0 || 14800 insn->dst_reg != BPF_REG_0 || 14801 class == BPF_JMP32) { 14802 verbose(env, "BPF_EXIT uses reserved fields\n"); 14803 return -EINVAL; 14804 } 14805 14806 if (env->cur_state->active_lock.ptr && 14807 !in_rbtree_lock_required_cb(env)) { 14808 verbose(env, "bpf_spin_unlock is missing\n"); 14809 return -EINVAL; 14810 } 14811 14812 if (env->cur_state->active_rcu_lock) { 14813 verbose(env, "bpf_rcu_read_unlock is missing\n"); 14814 return -EINVAL; 14815 } 14816 14817 /* We must do check_reference_leak here before 14818 * prepare_func_exit to handle the case when 14819 * state->curframe > 0, it may be a callback 14820 * function, for which reference_state must 14821 * match caller reference state when it exits. 14822 */ 14823 err = check_reference_leak(env); 14824 if (err) 14825 return err; 14826 14827 if (state->curframe) { 14828 /* exit from nested function */ 14829 err = prepare_func_exit(env, &env->insn_idx); 14830 if (err) 14831 return err; 14832 do_print_state = true; 14833 continue; 14834 } 14835 14836 err = check_return_code(env); 14837 if (err) 14838 return err; 14839 process_bpf_exit: 14840 mark_verifier_state_scratched(env); 14841 update_branch_counts(env, env->cur_state); 14842 err = pop_stack(env, &prev_insn_idx, 14843 &env->insn_idx, pop_log); 14844 if (err < 0) { 14845 if (err != -ENOENT) 14846 return err; 14847 break; 14848 } else { 14849 do_print_state = true; 14850 continue; 14851 } 14852 } else { 14853 err = check_cond_jmp_op(env, insn, &env->insn_idx); 14854 if (err) 14855 return err; 14856 } 14857 } else if (class == BPF_LD) { 14858 u8 mode = BPF_MODE(insn->code); 14859 14860 if (mode == BPF_ABS || mode == BPF_IND) { 14861 err = check_ld_abs(env, insn); 14862 if (err) 14863 return err; 14864 14865 } else if (mode == BPF_IMM) { 14866 err = check_ld_imm(env, insn); 14867 if (err) 14868 return err; 14869 14870 env->insn_idx++; 14871 sanitize_mark_insn_seen(env); 14872 } else { 14873 verbose(env, "invalid BPF_LD mode\n"); 14874 return -EINVAL; 14875 } 14876 } else { 14877 verbose(env, "unknown insn class %d\n", class); 14878 return -EINVAL; 14879 } 14880 14881 env->insn_idx++; 14882 } 14883 14884 return 0; 14885 } 14886 14887 static int find_btf_percpu_datasec(struct btf *btf) 14888 { 14889 const struct btf_type *t; 14890 const char *tname; 14891 int i, n; 14892 14893 /* 14894 * Both vmlinux and module each have their own ".data..percpu" 14895 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 14896 * types to look at only module's own BTF types. 14897 */ 14898 n = btf_nr_types(btf); 14899 if (btf_is_module(btf)) 14900 i = btf_nr_types(btf_vmlinux); 14901 else 14902 i = 1; 14903 14904 for(; i < n; i++) { 14905 t = btf_type_by_id(btf, i); 14906 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 14907 continue; 14908 14909 tname = btf_name_by_offset(btf, t->name_off); 14910 if (!strcmp(tname, ".data..percpu")) 14911 return i; 14912 } 14913 14914 return -ENOENT; 14915 } 14916 14917 /* replace pseudo btf_id with kernel symbol address */ 14918 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 14919 struct bpf_insn *insn, 14920 struct bpf_insn_aux_data *aux) 14921 { 14922 const struct btf_var_secinfo *vsi; 14923 const struct btf_type *datasec; 14924 struct btf_mod_pair *btf_mod; 14925 const struct btf_type *t; 14926 const char *sym_name; 14927 bool percpu = false; 14928 u32 type, id = insn->imm; 14929 struct btf *btf; 14930 s32 datasec_id; 14931 u64 addr; 14932 int i, btf_fd, err; 14933 14934 btf_fd = insn[1].imm; 14935 if (btf_fd) { 14936 btf = btf_get_by_fd(btf_fd); 14937 if (IS_ERR(btf)) { 14938 verbose(env, "invalid module BTF object FD specified.\n"); 14939 return -EINVAL; 14940 } 14941 } else { 14942 if (!btf_vmlinux) { 14943 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 14944 return -EINVAL; 14945 } 14946 btf = btf_vmlinux; 14947 btf_get(btf); 14948 } 14949 14950 t = btf_type_by_id(btf, id); 14951 if (!t) { 14952 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 14953 err = -ENOENT; 14954 goto err_put; 14955 } 14956 14957 if (!btf_type_is_var(t)) { 14958 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id); 14959 err = -EINVAL; 14960 goto err_put; 14961 } 14962 14963 sym_name = btf_name_by_offset(btf, t->name_off); 14964 addr = kallsyms_lookup_name(sym_name); 14965 if (!addr) { 14966 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 14967 sym_name); 14968 err = -ENOENT; 14969 goto err_put; 14970 } 14971 14972 datasec_id = find_btf_percpu_datasec(btf); 14973 if (datasec_id > 0) { 14974 datasec = btf_type_by_id(btf, datasec_id); 14975 for_each_vsi(i, datasec, vsi) { 14976 if (vsi->type == id) { 14977 percpu = true; 14978 break; 14979 } 14980 } 14981 } 14982 14983 insn[0].imm = (u32)addr; 14984 insn[1].imm = addr >> 32; 14985 14986 type = t->type; 14987 t = btf_type_skip_modifiers(btf, type, NULL); 14988 if (percpu) { 14989 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 14990 aux->btf_var.btf = btf; 14991 aux->btf_var.btf_id = type; 14992 } else if (!btf_type_is_struct(t)) { 14993 const struct btf_type *ret; 14994 const char *tname; 14995 u32 tsize; 14996 14997 /* resolve the type size of ksym. */ 14998 ret = btf_resolve_size(btf, t, &tsize); 14999 if (IS_ERR(ret)) { 15000 tname = btf_name_by_offset(btf, t->name_off); 15001 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 15002 tname, PTR_ERR(ret)); 15003 err = -EINVAL; 15004 goto err_put; 15005 } 15006 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 15007 aux->btf_var.mem_size = tsize; 15008 } else { 15009 aux->btf_var.reg_type = PTR_TO_BTF_ID; 15010 aux->btf_var.btf = btf; 15011 aux->btf_var.btf_id = type; 15012 } 15013 15014 /* check whether we recorded this BTF (and maybe module) already */ 15015 for (i = 0; i < env->used_btf_cnt; i++) { 15016 if (env->used_btfs[i].btf == btf) { 15017 btf_put(btf); 15018 return 0; 15019 } 15020 } 15021 15022 if (env->used_btf_cnt >= MAX_USED_BTFS) { 15023 err = -E2BIG; 15024 goto err_put; 15025 } 15026 15027 btf_mod = &env->used_btfs[env->used_btf_cnt]; 15028 btf_mod->btf = btf; 15029 btf_mod->module = NULL; 15030 15031 /* if we reference variables from kernel module, bump its refcount */ 15032 if (btf_is_module(btf)) { 15033 btf_mod->module = btf_try_get_module(btf); 15034 if (!btf_mod->module) { 15035 err = -ENXIO; 15036 goto err_put; 15037 } 15038 } 15039 15040 env->used_btf_cnt++; 15041 15042 return 0; 15043 err_put: 15044 btf_put(btf); 15045 return err; 15046 } 15047 15048 static bool is_tracing_prog_type(enum bpf_prog_type type) 15049 { 15050 switch (type) { 15051 case BPF_PROG_TYPE_KPROBE: 15052 case BPF_PROG_TYPE_TRACEPOINT: 15053 case BPF_PROG_TYPE_PERF_EVENT: 15054 case BPF_PROG_TYPE_RAW_TRACEPOINT: 15055 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 15056 return true; 15057 default: 15058 return false; 15059 } 15060 } 15061 15062 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 15063 struct bpf_map *map, 15064 struct bpf_prog *prog) 15065 15066 { 15067 enum bpf_prog_type prog_type = resolve_prog_type(prog); 15068 15069 if (btf_record_has_field(map->record, BPF_LIST_HEAD) || 15070 btf_record_has_field(map->record, BPF_RB_ROOT)) { 15071 if (is_tracing_prog_type(prog_type)) { 15072 verbose(env, "tracing progs cannot use bpf_{list_head,rb_root} yet\n"); 15073 return -EINVAL; 15074 } 15075 } 15076 15077 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 15078 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 15079 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 15080 return -EINVAL; 15081 } 15082 15083 if (is_tracing_prog_type(prog_type)) { 15084 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 15085 return -EINVAL; 15086 } 15087 15088 if (prog->aux->sleepable) { 15089 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 15090 return -EINVAL; 15091 } 15092 } 15093 15094 if (btf_record_has_field(map->record, BPF_TIMER)) { 15095 if (is_tracing_prog_type(prog_type)) { 15096 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 15097 return -EINVAL; 15098 } 15099 } 15100 15101 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 15102 !bpf_offload_prog_map_match(prog, map)) { 15103 verbose(env, "offload device mismatch between prog and map\n"); 15104 return -EINVAL; 15105 } 15106 15107 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 15108 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 15109 return -EINVAL; 15110 } 15111 15112 if (prog->aux->sleepable) 15113 switch (map->map_type) { 15114 case BPF_MAP_TYPE_HASH: 15115 case BPF_MAP_TYPE_LRU_HASH: 15116 case BPF_MAP_TYPE_ARRAY: 15117 case BPF_MAP_TYPE_PERCPU_HASH: 15118 case BPF_MAP_TYPE_PERCPU_ARRAY: 15119 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 15120 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 15121 case BPF_MAP_TYPE_HASH_OF_MAPS: 15122 case BPF_MAP_TYPE_RINGBUF: 15123 case BPF_MAP_TYPE_USER_RINGBUF: 15124 case BPF_MAP_TYPE_INODE_STORAGE: 15125 case BPF_MAP_TYPE_SK_STORAGE: 15126 case BPF_MAP_TYPE_TASK_STORAGE: 15127 case BPF_MAP_TYPE_CGRP_STORAGE: 15128 break; 15129 default: 15130 verbose(env, 15131 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 15132 return -EINVAL; 15133 } 15134 15135 return 0; 15136 } 15137 15138 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 15139 { 15140 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 15141 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 15142 } 15143 15144 /* find and rewrite pseudo imm in ld_imm64 instructions: 15145 * 15146 * 1. if it accesses map FD, replace it with actual map pointer. 15147 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 15148 * 15149 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 15150 */ 15151 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 15152 { 15153 struct bpf_insn *insn = env->prog->insnsi; 15154 int insn_cnt = env->prog->len; 15155 int i, j, err; 15156 15157 err = bpf_prog_calc_tag(env->prog); 15158 if (err) 15159 return err; 15160 15161 for (i = 0; i < insn_cnt; i++, insn++) { 15162 if (BPF_CLASS(insn->code) == BPF_LDX && 15163 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 15164 verbose(env, "BPF_LDX uses reserved fields\n"); 15165 return -EINVAL; 15166 } 15167 15168 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 15169 struct bpf_insn_aux_data *aux; 15170 struct bpf_map *map; 15171 struct fd f; 15172 u64 addr; 15173 u32 fd; 15174 15175 if (i == insn_cnt - 1 || insn[1].code != 0 || 15176 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 15177 insn[1].off != 0) { 15178 verbose(env, "invalid bpf_ld_imm64 insn\n"); 15179 return -EINVAL; 15180 } 15181 15182 if (insn[0].src_reg == 0) 15183 /* valid generic load 64-bit imm */ 15184 goto next_insn; 15185 15186 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 15187 aux = &env->insn_aux_data[i]; 15188 err = check_pseudo_btf_id(env, insn, aux); 15189 if (err) 15190 return err; 15191 goto next_insn; 15192 } 15193 15194 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 15195 aux = &env->insn_aux_data[i]; 15196 aux->ptr_type = PTR_TO_FUNC; 15197 goto next_insn; 15198 } 15199 15200 /* In final convert_pseudo_ld_imm64() step, this is 15201 * converted into regular 64-bit imm load insn. 15202 */ 15203 switch (insn[0].src_reg) { 15204 case BPF_PSEUDO_MAP_VALUE: 15205 case BPF_PSEUDO_MAP_IDX_VALUE: 15206 break; 15207 case BPF_PSEUDO_MAP_FD: 15208 case BPF_PSEUDO_MAP_IDX: 15209 if (insn[1].imm == 0) 15210 break; 15211 fallthrough; 15212 default: 15213 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 15214 return -EINVAL; 15215 } 15216 15217 switch (insn[0].src_reg) { 15218 case BPF_PSEUDO_MAP_IDX_VALUE: 15219 case BPF_PSEUDO_MAP_IDX: 15220 if (bpfptr_is_null(env->fd_array)) { 15221 verbose(env, "fd_idx without fd_array is invalid\n"); 15222 return -EPROTO; 15223 } 15224 if (copy_from_bpfptr_offset(&fd, env->fd_array, 15225 insn[0].imm * sizeof(fd), 15226 sizeof(fd))) 15227 return -EFAULT; 15228 break; 15229 default: 15230 fd = insn[0].imm; 15231 break; 15232 } 15233 15234 f = fdget(fd); 15235 map = __bpf_map_get(f); 15236 if (IS_ERR(map)) { 15237 verbose(env, "fd %d is not pointing to valid bpf_map\n", 15238 insn[0].imm); 15239 return PTR_ERR(map); 15240 } 15241 15242 err = check_map_prog_compatibility(env, map, env->prog); 15243 if (err) { 15244 fdput(f); 15245 return err; 15246 } 15247 15248 aux = &env->insn_aux_data[i]; 15249 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 15250 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 15251 addr = (unsigned long)map; 15252 } else { 15253 u32 off = insn[1].imm; 15254 15255 if (off >= BPF_MAX_VAR_OFF) { 15256 verbose(env, "direct value offset of %u is not allowed\n", off); 15257 fdput(f); 15258 return -EINVAL; 15259 } 15260 15261 if (!map->ops->map_direct_value_addr) { 15262 verbose(env, "no direct value access support for this map type\n"); 15263 fdput(f); 15264 return -EINVAL; 15265 } 15266 15267 err = map->ops->map_direct_value_addr(map, &addr, off); 15268 if (err) { 15269 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 15270 map->value_size, off); 15271 fdput(f); 15272 return err; 15273 } 15274 15275 aux->map_off = off; 15276 addr += off; 15277 } 15278 15279 insn[0].imm = (u32)addr; 15280 insn[1].imm = addr >> 32; 15281 15282 /* check whether we recorded this map already */ 15283 for (j = 0; j < env->used_map_cnt; j++) { 15284 if (env->used_maps[j] == map) { 15285 aux->map_index = j; 15286 fdput(f); 15287 goto next_insn; 15288 } 15289 } 15290 15291 if (env->used_map_cnt >= MAX_USED_MAPS) { 15292 fdput(f); 15293 return -E2BIG; 15294 } 15295 15296 /* hold the map. If the program is rejected by verifier, 15297 * the map will be released by release_maps() or it 15298 * will be used by the valid program until it's unloaded 15299 * and all maps are released in free_used_maps() 15300 */ 15301 bpf_map_inc(map); 15302 15303 aux->map_index = env->used_map_cnt; 15304 env->used_maps[env->used_map_cnt++] = map; 15305 15306 if (bpf_map_is_cgroup_storage(map) && 15307 bpf_cgroup_storage_assign(env->prog->aux, map)) { 15308 verbose(env, "only one cgroup storage of each type is allowed\n"); 15309 fdput(f); 15310 return -EBUSY; 15311 } 15312 15313 fdput(f); 15314 next_insn: 15315 insn++; 15316 i++; 15317 continue; 15318 } 15319 15320 /* Basic sanity check before we invest more work here. */ 15321 if (!bpf_opcode_in_insntable(insn->code)) { 15322 verbose(env, "unknown opcode %02x\n", insn->code); 15323 return -EINVAL; 15324 } 15325 } 15326 15327 /* now all pseudo BPF_LD_IMM64 instructions load valid 15328 * 'struct bpf_map *' into a register instead of user map_fd. 15329 * These pointers will be used later by verifier to validate map access. 15330 */ 15331 return 0; 15332 } 15333 15334 /* drop refcnt of maps used by the rejected program */ 15335 static void release_maps(struct bpf_verifier_env *env) 15336 { 15337 __bpf_free_used_maps(env->prog->aux, env->used_maps, 15338 env->used_map_cnt); 15339 } 15340 15341 /* drop refcnt of maps used by the rejected program */ 15342 static void release_btfs(struct bpf_verifier_env *env) 15343 { 15344 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 15345 env->used_btf_cnt); 15346 } 15347 15348 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 15349 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 15350 { 15351 struct bpf_insn *insn = env->prog->insnsi; 15352 int insn_cnt = env->prog->len; 15353 int i; 15354 15355 for (i = 0; i < insn_cnt; i++, insn++) { 15356 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 15357 continue; 15358 if (insn->src_reg == BPF_PSEUDO_FUNC) 15359 continue; 15360 insn->src_reg = 0; 15361 } 15362 } 15363 15364 /* single env->prog->insni[off] instruction was replaced with the range 15365 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 15366 * [0, off) and [off, end) to new locations, so the patched range stays zero 15367 */ 15368 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 15369 struct bpf_insn_aux_data *new_data, 15370 struct bpf_prog *new_prog, u32 off, u32 cnt) 15371 { 15372 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 15373 struct bpf_insn *insn = new_prog->insnsi; 15374 u32 old_seen = old_data[off].seen; 15375 u32 prog_len; 15376 int i; 15377 15378 /* aux info at OFF always needs adjustment, no matter fast path 15379 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 15380 * original insn at old prog. 15381 */ 15382 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 15383 15384 if (cnt == 1) 15385 return; 15386 prog_len = new_prog->len; 15387 15388 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 15389 memcpy(new_data + off + cnt - 1, old_data + off, 15390 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 15391 for (i = off; i < off + cnt - 1; i++) { 15392 /* Expand insni[off]'s seen count to the patched range. */ 15393 new_data[i].seen = old_seen; 15394 new_data[i].zext_dst = insn_has_def32(env, insn + i); 15395 } 15396 env->insn_aux_data = new_data; 15397 vfree(old_data); 15398 } 15399 15400 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 15401 { 15402 int i; 15403 15404 if (len == 1) 15405 return; 15406 /* NOTE: fake 'exit' subprog should be updated as well. */ 15407 for (i = 0; i <= env->subprog_cnt; i++) { 15408 if (env->subprog_info[i].start <= off) 15409 continue; 15410 env->subprog_info[i].start += len - 1; 15411 } 15412 } 15413 15414 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 15415 { 15416 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 15417 int i, sz = prog->aux->size_poke_tab; 15418 struct bpf_jit_poke_descriptor *desc; 15419 15420 for (i = 0; i < sz; i++) { 15421 desc = &tab[i]; 15422 if (desc->insn_idx <= off) 15423 continue; 15424 desc->insn_idx += len - 1; 15425 } 15426 } 15427 15428 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 15429 const struct bpf_insn *patch, u32 len) 15430 { 15431 struct bpf_prog *new_prog; 15432 struct bpf_insn_aux_data *new_data = NULL; 15433 15434 if (len > 1) { 15435 new_data = vzalloc(array_size(env->prog->len + len - 1, 15436 sizeof(struct bpf_insn_aux_data))); 15437 if (!new_data) 15438 return NULL; 15439 } 15440 15441 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 15442 if (IS_ERR(new_prog)) { 15443 if (PTR_ERR(new_prog) == -ERANGE) 15444 verbose(env, 15445 "insn %d cannot be patched due to 16-bit range\n", 15446 env->insn_aux_data[off].orig_idx); 15447 vfree(new_data); 15448 return NULL; 15449 } 15450 adjust_insn_aux_data(env, new_data, new_prog, off, len); 15451 adjust_subprog_starts(env, off, len); 15452 adjust_poke_descs(new_prog, off, len); 15453 return new_prog; 15454 } 15455 15456 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 15457 u32 off, u32 cnt) 15458 { 15459 int i, j; 15460 15461 /* find first prog starting at or after off (first to remove) */ 15462 for (i = 0; i < env->subprog_cnt; i++) 15463 if (env->subprog_info[i].start >= off) 15464 break; 15465 /* find first prog starting at or after off + cnt (first to stay) */ 15466 for (j = i; j < env->subprog_cnt; j++) 15467 if (env->subprog_info[j].start >= off + cnt) 15468 break; 15469 /* if j doesn't start exactly at off + cnt, we are just removing 15470 * the front of previous prog 15471 */ 15472 if (env->subprog_info[j].start != off + cnt) 15473 j--; 15474 15475 if (j > i) { 15476 struct bpf_prog_aux *aux = env->prog->aux; 15477 int move; 15478 15479 /* move fake 'exit' subprog as well */ 15480 move = env->subprog_cnt + 1 - j; 15481 15482 memmove(env->subprog_info + i, 15483 env->subprog_info + j, 15484 sizeof(*env->subprog_info) * move); 15485 env->subprog_cnt -= j - i; 15486 15487 /* remove func_info */ 15488 if (aux->func_info) { 15489 move = aux->func_info_cnt - j; 15490 15491 memmove(aux->func_info + i, 15492 aux->func_info + j, 15493 sizeof(*aux->func_info) * move); 15494 aux->func_info_cnt -= j - i; 15495 /* func_info->insn_off is set after all code rewrites, 15496 * in adjust_btf_func() - no need to adjust 15497 */ 15498 } 15499 } else { 15500 /* convert i from "first prog to remove" to "first to adjust" */ 15501 if (env->subprog_info[i].start == off) 15502 i++; 15503 } 15504 15505 /* update fake 'exit' subprog as well */ 15506 for (; i <= env->subprog_cnt; i++) 15507 env->subprog_info[i].start -= cnt; 15508 15509 return 0; 15510 } 15511 15512 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 15513 u32 cnt) 15514 { 15515 struct bpf_prog *prog = env->prog; 15516 u32 i, l_off, l_cnt, nr_linfo; 15517 struct bpf_line_info *linfo; 15518 15519 nr_linfo = prog->aux->nr_linfo; 15520 if (!nr_linfo) 15521 return 0; 15522 15523 linfo = prog->aux->linfo; 15524 15525 /* find first line info to remove, count lines to be removed */ 15526 for (i = 0; i < nr_linfo; i++) 15527 if (linfo[i].insn_off >= off) 15528 break; 15529 15530 l_off = i; 15531 l_cnt = 0; 15532 for (; i < nr_linfo; i++) 15533 if (linfo[i].insn_off < off + cnt) 15534 l_cnt++; 15535 else 15536 break; 15537 15538 /* First live insn doesn't match first live linfo, it needs to "inherit" 15539 * last removed linfo. prog is already modified, so prog->len == off 15540 * means no live instructions after (tail of the program was removed). 15541 */ 15542 if (prog->len != off && l_cnt && 15543 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 15544 l_cnt--; 15545 linfo[--i].insn_off = off + cnt; 15546 } 15547 15548 /* remove the line info which refer to the removed instructions */ 15549 if (l_cnt) { 15550 memmove(linfo + l_off, linfo + i, 15551 sizeof(*linfo) * (nr_linfo - i)); 15552 15553 prog->aux->nr_linfo -= l_cnt; 15554 nr_linfo = prog->aux->nr_linfo; 15555 } 15556 15557 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 15558 for (i = l_off; i < nr_linfo; i++) 15559 linfo[i].insn_off -= cnt; 15560 15561 /* fix up all subprogs (incl. 'exit') which start >= off */ 15562 for (i = 0; i <= env->subprog_cnt; i++) 15563 if (env->subprog_info[i].linfo_idx > l_off) { 15564 /* program may have started in the removed region but 15565 * may not be fully removed 15566 */ 15567 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 15568 env->subprog_info[i].linfo_idx -= l_cnt; 15569 else 15570 env->subprog_info[i].linfo_idx = l_off; 15571 } 15572 15573 return 0; 15574 } 15575 15576 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 15577 { 15578 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15579 unsigned int orig_prog_len = env->prog->len; 15580 int err; 15581 15582 if (bpf_prog_is_offloaded(env->prog->aux)) 15583 bpf_prog_offload_remove_insns(env, off, cnt); 15584 15585 err = bpf_remove_insns(env->prog, off, cnt); 15586 if (err) 15587 return err; 15588 15589 err = adjust_subprog_starts_after_remove(env, off, cnt); 15590 if (err) 15591 return err; 15592 15593 err = bpf_adj_linfo_after_remove(env, off, cnt); 15594 if (err) 15595 return err; 15596 15597 memmove(aux_data + off, aux_data + off + cnt, 15598 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 15599 15600 return 0; 15601 } 15602 15603 /* The verifier does more data flow analysis than llvm and will not 15604 * explore branches that are dead at run time. Malicious programs can 15605 * have dead code too. Therefore replace all dead at-run-time code 15606 * with 'ja -1'. 15607 * 15608 * Just nops are not optimal, e.g. if they would sit at the end of the 15609 * program and through another bug we would manage to jump there, then 15610 * we'd execute beyond program memory otherwise. Returning exception 15611 * code also wouldn't work since we can have subprogs where the dead 15612 * code could be located. 15613 */ 15614 static void sanitize_dead_code(struct bpf_verifier_env *env) 15615 { 15616 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15617 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 15618 struct bpf_insn *insn = env->prog->insnsi; 15619 const int insn_cnt = env->prog->len; 15620 int i; 15621 15622 for (i = 0; i < insn_cnt; i++) { 15623 if (aux_data[i].seen) 15624 continue; 15625 memcpy(insn + i, &trap, sizeof(trap)); 15626 aux_data[i].zext_dst = false; 15627 } 15628 } 15629 15630 static bool insn_is_cond_jump(u8 code) 15631 { 15632 u8 op; 15633 15634 if (BPF_CLASS(code) == BPF_JMP32) 15635 return true; 15636 15637 if (BPF_CLASS(code) != BPF_JMP) 15638 return false; 15639 15640 op = BPF_OP(code); 15641 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 15642 } 15643 15644 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 15645 { 15646 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15647 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 15648 struct bpf_insn *insn = env->prog->insnsi; 15649 const int insn_cnt = env->prog->len; 15650 int i; 15651 15652 for (i = 0; i < insn_cnt; i++, insn++) { 15653 if (!insn_is_cond_jump(insn->code)) 15654 continue; 15655 15656 if (!aux_data[i + 1].seen) 15657 ja.off = insn->off; 15658 else if (!aux_data[i + 1 + insn->off].seen) 15659 ja.off = 0; 15660 else 15661 continue; 15662 15663 if (bpf_prog_is_offloaded(env->prog->aux)) 15664 bpf_prog_offload_replace_insn(env, i, &ja); 15665 15666 memcpy(insn, &ja, sizeof(ja)); 15667 } 15668 } 15669 15670 static int opt_remove_dead_code(struct bpf_verifier_env *env) 15671 { 15672 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15673 int insn_cnt = env->prog->len; 15674 int i, err; 15675 15676 for (i = 0; i < insn_cnt; i++) { 15677 int j; 15678 15679 j = 0; 15680 while (i + j < insn_cnt && !aux_data[i + j].seen) 15681 j++; 15682 if (!j) 15683 continue; 15684 15685 err = verifier_remove_insns(env, i, j); 15686 if (err) 15687 return err; 15688 insn_cnt = env->prog->len; 15689 } 15690 15691 return 0; 15692 } 15693 15694 static int opt_remove_nops(struct bpf_verifier_env *env) 15695 { 15696 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 15697 struct bpf_insn *insn = env->prog->insnsi; 15698 int insn_cnt = env->prog->len; 15699 int i, err; 15700 15701 for (i = 0; i < insn_cnt; i++) { 15702 if (memcmp(&insn[i], &ja, sizeof(ja))) 15703 continue; 15704 15705 err = verifier_remove_insns(env, i, 1); 15706 if (err) 15707 return err; 15708 insn_cnt--; 15709 i--; 15710 } 15711 15712 return 0; 15713 } 15714 15715 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 15716 const union bpf_attr *attr) 15717 { 15718 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 15719 struct bpf_insn_aux_data *aux = env->insn_aux_data; 15720 int i, patch_len, delta = 0, len = env->prog->len; 15721 struct bpf_insn *insns = env->prog->insnsi; 15722 struct bpf_prog *new_prog; 15723 bool rnd_hi32; 15724 15725 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 15726 zext_patch[1] = BPF_ZEXT_REG(0); 15727 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 15728 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 15729 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 15730 for (i = 0; i < len; i++) { 15731 int adj_idx = i + delta; 15732 struct bpf_insn insn; 15733 int load_reg; 15734 15735 insn = insns[adj_idx]; 15736 load_reg = insn_def_regno(&insn); 15737 if (!aux[adj_idx].zext_dst) { 15738 u8 code, class; 15739 u32 imm_rnd; 15740 15741 if (!rnd_hi32) 15742 continue; 15743 15744 code = insn.code; 15745 class = BPF_CLASS(code); 15746 if (load_reg == -1) 15747 continue; 15748 15749 /* NOTE: arg "reg" (the fourth one) is only used for 15750 * BPF_STX + SRC_OP, so it is safe to pass NULL 15751 * here. 15752 */ 15753 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 15754 if (class == BPF_LD && 15755 BPF_MODE(code) == BPF_IMM) 15756 i++; 15757 continue; 15758 } 15759 15760 /* ctx load could be transformed into wider load. */ 15761 if (class == BPF_LDX && 15762 aux[adj_idx].ptr_type == PTR_TO_CTX) 15763 continue; 15764 15765 imm_rnd = get_random_u32(); 15766 rnd_hi32_patch[0] = insn; 15767 rnd_hi32_patch[1].imm = imm_rnd; 15768 rnd_hi32_patch[3].dst_reg = load_reg; 15769 patch = rnd_hi32_patch; 15770 patch_len = 4; 15771 goto apply_patch_buffer; 15772 } 15773 15774 /* Add in an zero-extend instruction if a) the JIT has requested 15775 * it or b) it's a CMPXCHG. 15776 * 15777 * The latter is because: BPF_CMPXCHG always loads a value into 15778 * R0, therefore always zero-extends. However some archs' 15779 * equivalent instruction only does this load when the 15780 * comparison is successful. This detail of CMPXCHG is 15781 * orthogonal to the general zero-extension behaviour of the 15782 * CPU, so it's treated independently of bpf_jit_needs_zext. 15783 */ 15784 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 15785 continue; 15786 15787 /* Zero-extension is done by the caller. */ 15788 if (bpf_pseudo_kfunc_call(&insn)) 15789 continue; 15790 15791 if (WARN_ON(load_reg == -1)) { 15792 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 15793 return -EFAULT; 15794 } 15795 15796 zext_patch[0] = insn; 15797 zext_patch[1].dst_reg = load_reg; 15798 zext_patch[1].src_reg = load_reg; 15799 patch = zext_patch; 15800 patch_len = 2; 15801 apply_patch_buffer: 15802 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 15803 if (!new_prog) 15804 return -ENOMEM; 15805 env->prog = new_prog; 15806 insns = new_prog->insnsi; 15807 aux = env->insn_aux_data; 15808 delta += patch_len - 1; 15809 } 15810 15811 return 0; 15812 } 15813 15814 /* convert load instructions that access fields of a context type into a 15815 * sequence of instructions that access fields of the underlying structure: 15816 * struct __sk_buff -> struct sk_buff 15817 * struct bpf_sock_ops -> struct sock 15818 */ 15819 static int convert_ctx_accesses(struct bpf_verifier_env *env) 15820 { 15821 const struct bpf_verifier_ops *ops = env->ops; 15822 int i, cnt, size, ctx_field_size, delta = 0; 15823 const int insn_cnt = env->prog->len; 15824 struct bpf_insn insn_buf[16], *insn; 15825 u32 target_size, size_default, off; 15826 struct bpf_prog *new_prog; 15827 enum bpf_access_type type; 15828 bool is_narrower_load; 15829 15830 if (ops->gen_prologue || env->seen_direct_write) { 15831 if (!ops->gen_prologue) { 15832 verbose(env, "bpf verifier is misconfigured\n"); 15833 return -EINVAL; 15834 } 15835 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 15836 env->prog); 15837 if (cnt >= ARRAY_SIZE(insn_buf)) { 15838 verbose(env, "bpf verifier is misconfigured\n"); 15839 return -EINVAL; 15840 } else if (cnt) { 15841 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 15842 if (!new_prog) 15843 return -ENOMEM; 15844 15845 env->prog = new_prog; 15846 delta += cnt - 1; 15847 } 15848 } 15849 15850 if (bpf_prog_is_offloaded(env->prog->aux)) 15851 return 0; 15852 15853 insn = env->prog->insnsi + delta; 15854 15855 for (i = 0; i < insn_cnt; i++, insn++) { 15856 bpf_convert_ctx_access_t convert_ctx_access; 15857 bool ctx_access; 15858 15859 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 15860 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 15861 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 15862 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) { 15863 type = BPF_READ; 15864 ctx_access = true; 15865 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 15866 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 15867 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 15868 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 15869 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 15870 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 15871 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 15872 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 15873 type = BPF_WRITE; 15874 ctx_access = BPF_CLASS(insn->code) == BPF_STX; 15875 } else { 15876 continue; 15877 } 15878 15879 if (type == BPF_WRITE && 15880 env->insn_aux_data[i + delta].sanitize_stack_spill) { 15881 struct bpf_insn patch[] = { 15882 *insn, 15883 BPF_ST_NOSPEC(), 15884 }; 15885 15886 cnt = ARRAY_SIZE(patch); 15887 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 15888 if (!new_prog) 15889 return -ENOMEM; 15890 15891 delta += cnt - 1; 15892 env->prog = new_prog; 15893 insn = new_prog->insnsi + i + delta; 15894 continue; 15895 } 15896 15897 if (!ctx_access) 15898 continue; 15899 15900 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 15901 case PTR_TO_CTX: 15902 if (!ops->convert_ctx_access) 15903 continue; 15904 convert_ctx_access = ops->convert_ctx_access; 15905 break; 15906 case PTR_TO_SOCKET: 15907 case PTR_TO_SOCK_COMMON: 15908 convert_ctx_access = bpf_sock_convert_ctx_access; 15909 break; 15910 case PTR_TO_TCP_SOCK: 15911 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 15912 break; 15913 case PTR_TO_XDP_SOCK: 15914 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 15915 break; 15916 case PTR_TO_BTF_ID: 15917 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 15918 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 15919 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 15920 * be said once it is marked PTR_UNTRUSTED, hence we must handle 15921 * any faults for loads into such types. BPF_WRITE is disallowed 15922 * for this case. 15923 */ 15924 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 15925 if (type == BPF_READ) { 15926 insn->code = BPF_LDX | BPF_PROBE_MEM | 15927 BPF_SIZE((insn)->code); 15928 env->prog->aux->num_exentries++; 15929 } 15930 continue; 15931 default: 15932 continue; 15933 } 15934 15935 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 15936 size = BPF_LDST_BYTES(insn); 15937 15938 /* If the read access is a narrower load of the field, 15939 * convert to a 4/8-byte load, to minimum program type specific 15940 * convert_ctx_access changes. If conversion is successful, 15941 * we will apply proper mask to the result. 15942 */ 15943 is_narrower_load = size < ctx_field_size; 15944 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 15945 off = insn->off; 15946 if (is_narrower_load) { 15947 u8 size_code; 15948 15949 if (type == BPF_WRITE) { 15950 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 15951 return -EINVAL; 15952 } 15953 15954 size_code = BPF_H; 15955 if (ctx_field_size == 4) 15956 size_code = BPF_W; 15957 else if (ctx_field_size == 8) 15958 size_code = BPF_DW; 15959 15960 insn->off = off & ~(size_default - 1); 15961 insn->code = BPF_LDX | BPF_MEM | size_code; 15962 } 15963 15964 target_size = 0; 15965 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 15966 &target_size); 15967 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 15968 (ctx_field_size && !target_size)) { 15969 verbose(env, "bpf verifier is misconfigured\n"); 15970 return -EINVAL; 15971 } 15972 15973 if (is_narrower_load && size < target_size) { 15974 u8 shift = bpf_ctx_narrow_access_offset( 15975 off, size, size_default) * 8; 15976 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 15977 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 15978 return -EINVAL; 15979 } 15980 if (ctx_field_size <= 4) { 15981 if (shift) 15982 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 15983 insn->dst_reg, 15984 shift); 15985 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 15986 (1 << size * 8) - 1); 15987 } else { 15988 if (shift) 15989 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 15990 insn->dst_reg, 15991 shift); 15992 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 15993 (1ULL << size * 8) - 1); 15994 } 15995 } 15996 15997 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15998 if (!new_prog) 15999 return -ENOMEM; 16000 16001 delta += cnt - 1; 16002 16003 /* keep walking new program and skip insns we just inserted */ 16004 env->prog = new_prog; 16005 insn = new_prog->insnsi + i + delta; 16006 } 16007 16008 return 0; 16009 } 16010 16011 static int jit_subprogs(struct bpf_verifier_env *env) 16012 { 16013 struct bpf_prog *prog = env->prog, **func, *tmp; 16014 int i, j, subprog_start, subprog_end = 0, len, subprog; 16015 struct bpf_map *map_ptr; 16016 struct bpf_insn *insn; 16017 void *old_bpf_func; 16018 int err, num_exentries; 16019 16020 if (env->subprog_cnt <= 1) 16021 return 0; 16022 16023 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 16024 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 16025 continue; 16026 16027 /* Upon error here we cannot fall back to interpreter but 16028 * need a hard reject of the program. Thus -EFAULT is 16029 * propagated in any case. 16030 */ 16031 subprog = find_subprog(env, i + insn->imm + 1); 16032 if (subprog < 0) { 16033 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 16034 i + insn->imm + 1); 16035 return -EFAULT; 16036 } 16037 /* temporarily remember subprog id inside insn instead of 16038 * aux_data, since next loop will split up all insns into funcs 16039 */ 16040 insn->off = subprog; 16041 /* remember original imm in case JIT fails and fallback 16042 * to interpreter will be needed 16043 */ 16044 env->insn_aux_data[i].call_imm = insn->imm; 16045 /* point imm to __bpf_call_base+1 from JITs point of view */ 16046 insn->imm = 1; 16047 if (bpf_pseudo_func(insn)) 16048 /* jit (e.g. x86_64) may emit fewer instructions 16049 * if it learns a u32 imm is the same as a u64 imm. 16050 * Force a non zero here. 16051 */ 16052 insn[1].imm = 1; 16053 } 16054 16055 err = bpf_prog_alloc_jited_linfo(prog); 16056 if (err) 16057 goto out_undo_insn; 16058 16059 err = -ENOMEM; 16060 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 16061 if (!func) 16062 goto out_undo_insn; 16063 16064 for (i = 0; i < env->subprog_cnt; i++) { 16065 subprog_start = subprog_end; 16066 subprog_end = env->subprog_info[i + 1].start; 16067 16068 len = subprog_end - subprog_start; 16069 /* bpf_prog_run() doesn't call subprogs directly, 16070 * hence main prog stats include the runtime of subprogs. 16071 * subprogs don't have IDs and not reachable via prog_get_next_id 16072 * func[i]->stats will never be accessed and stays NULL 16073 */ 16074 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 16075 if (!func[i]) 16076 goto out_free; 16077 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 16078 len * sizeof(struct bpf_insn)); 16079 func[i]->type = prog->type; 16080 func[i]->len = len; 16081 if (bpf_prog_calc_tag(func[i])) 16082 goto out_free; 16083 func[i]->is_func = 1; 16084 func[i]->aux->func_idx = i; 16085 /* Below members will be freed only at prog->aux */ 16086 func[i]->aux->btf = prog->aux->btf; 16087 func[i]->aux->func_info = prog->aux->func_info; 16088 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 16089 func[i]->aux->poke_tab = prog->aux->poke_tab; 16090 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 16091 16092 for (j = 0; j < prog->aux->size_poke_tab; j++) { 16093 struct bpf_jit_poke_descriptor *poke; 16094 16095 poke = &prog->aux->poke_tab[j]; 16096 if (poke->insn_idx < subprog_end && 16097 poke->insn_idx >= subprog_start) 16098 poke->aux = func[i]->aux; 16099 } 16100 16101 func[i]->aux->name[0] = 'F'; 16102 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 16103 func[i]->jit_requested = 1; 16104 func[i]->blinding_requested = prog->blinding_requested; 16105 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 16106 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 16107 func[i]->aux->linfo = prog->aux->linfo; 16108 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 16109 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 16110 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 16111 num_exentries = 0; 16112 insn = func[i]->insnsi; 16113 for (j = 0; j < func[i]->len; j++, insn++) { 16114 if (BPF_CLASS(insn->code) == BPF_LDX && 16115 BPF_MODE(insn->code) == BPF_PROBE_MEM) 16116 num_exentries++; 16117 } 16118 func[i]->aux->num_exentries = num_exentries; 16119 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 16120 func[i] = bpf_int_jit_compile(func[i]); 16121 if (!func[i]->jited) { 16122 err = -ENOTSUPP; 16123 goto out_free; 16124 } 16125 cond_resched(); 16126 } 16127 16128 /* at this point all bpf functions were successfully JITed 16129 * now populate all bpf_calls with correct addresses and 16130 * run last pass of JIT 16131 */ 16132 for (i = 0; i < env->subprog_cnt; i++) { 16133 insn = func[i]->insnsi; 16134 for (j = 0; j < func[i]->len; j++, insn++) { 16135 if (bpf_pseudo_func(insn)) { 16136 subprog = insn->off; 16137 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 16138 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 16139 continue; 16140 } 16141 if (!bpf_pseudo_call(insn)) 16142 continue; 16143 subprog = insn->off; 16144 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 16145 } 16146 16147 /* we use the aux data to keep a list of the start addresses 16148 * of the JITed images for each function in the program 16149 * 16150 * for some architectures, such as powerpc64, the imm field 16151 * might not be large enough to hold the offset of the start 16152 * address of the callee's JITed image from __bpf_call_base 16153 * 16154 * in such cases, we can lookup the start address of a callee 16155 * by using its subprog id, available from the off field of 16156 * the call instruction, as an index for this list 16157 */ 16158 func[i]->aux->func = func; 16159 func[i]->aux->func_cnt = env->subprog_cnt; 16160 } 16161 for (i = 0; i < env->subprog_cnt; i++) { 16162 old_bpf_func = func[i]->bpf_func; 16163 tmp = bpf_int_jit_compile(func[i]); 16164 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 16165 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 16166 err = -ENOTSUPP; 16167 goto out_free; 16168 } 16169 cond_resched(); 16170 } 16171 16172 /* finally lock prog and jit images for all functions and 16173 * populate kallsysm 16174 */ 16175 for (i = 0; i < env->subprog_cnt; i++) { 16176 bpf_prog_lock_ro(func[i]); 16177 bpf_prog_kallsyms_add(func[i]); 16178 } 16179 16180 /* Last step: make now unused interpreter insns from main 16181 * prog consistent for later dump requests, so they can 16182 * later look the same as if they were interpreted only. 16183 */ 16184 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 16185 if (bpf_pseudo_func(insn)) { 16186 insn[0].imm = env->insn_aux_data[i].call_imm; 16187 insn[1].imm = insn->off; 16188 insn->off = 0; 16189 continue; 16190 } 16191 if (!bpf_pseudo_call(insn)) 16192 continue; 16193 insn->off = env->insn_aux_data[i].call_imm; 16194 subprog = find_subprog(env, i + insn->off + 1); 16195 insn->imm = subprog; 16196 } 16197 16198 prog->jited = 1; 16199 prog->bpf_func = func[0]->bpf_func; 16200 prog->jited_len = func[0]->jited_len; 16201 prog->aux->func = func; 16202 prog->aux->func_cnt = env->subprog_cnt; 16203 bpf_prog_jit_attempt_done(prog); 16204 return 0; 16205 out_free: 16206 /* We failed JIT'ing, so at this point we need to unregister poke 16207 * descriptors from subprogs, so that kernel is not attempting to 16208 * patch it anymore as we're freeing the subprog JIT memory. 16209 */ 16210 for (i = 0; i < prog->aux->size_poke_tab; i++) { 16211 map_ptr = prog->aux->poke_tab[i].tail_call.map; 16212 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 16213 } 16214 /* At this point we're guaranteed that poke descriptors are not 16215 * live anymore. We can just unlink its descriptor table as it's 16216 * released with the main prog. 16217 */ 16218 for (i = 0; i < env->subprog_cnt; i++) { 16219 if (!func[i]) 16220 continue; 16221 func[i]->aux->poke_tab = NULL; 16222 bpf_jit_free(func[i]); 16223 } 16224 kfree(func); 16225 out_undo_insn: 16226 /* cleanup main prog to be interpreted */ 16227 prog->jit_requested = 0; 16228 prog->blinding_requested = 0; 16229 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 16230 if (!bpf_pseudo_call(insn)) 16231 continue; 16232 insn->off = 0; 16233 insn->imm = env->insn_aux_data[i].call_imm; 16234 } 16235 bpf_prog_jit_attempt_done(prog); 16236 return err; 16237 } 16238 16239 static int fixup_call_args(struct bpf_verifier_env *env) 16240 { 16241 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 16242 struct bpf_prog *prog = env->prog; 16243 struct bpf_insn *insn = prog->insnsi; 16244 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 16245 int i, depth; 16246 #endif 16247 int err = 0; 16248 16249 if (env->prog->jit_requested && 16250 !bpf_prog_is_offloaded(env->prog->aux)) { 16251 err = jit_subprogs(env); 16252 if (err == 0) 16253 return 0; 16254 if (err == -EFAULT) 16255 return err; 16256 } 16257 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 16258 if (has_kfunc_call) { 16259 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 16260 return -EINVAL; 16261 } 16262 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 16263 /* When JIT fails the progs with bpf2bpf calls and tail_calls 16264 * have to be rejected, since interpreter doesn't support them yet. 16265 */ 16266 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 16267 return -EINVAL; 16268 } 16269 for (i = 0; i < prog->len; i++, insn++) { 16270 if (bpf_pseudo_func(insn)) { 16271 /* When JIT fails the progs with callback calls 16272 * have to be rejected, since interpreter doesn't support them yet. 16273 */ 16274 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 16275 return -EINVAL; 16276 } 16277 16278 if (!bpf_pseudo_call(insn)) 16279 continue; 16280 depth = get_callee_stack_depth(env, insn, i); 16281 if (depth < 0) 16282 return depth; 16283 bpf_patch_call_args(insn, depth); 16284 } 16285 err = 0; 16286 #endif 16287 return err; 16288 } 16289 16290 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 16291 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 16292 { 16293 const struct bpf_kfunc_desc *desc; 16294 void *xdp_kfunc; 16295 16296 if (!insn->imm) { 16297 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 16298 return -EINVAL; 16299 } 16300 16301 *cnt = 0; 16302 16303 if (bpf_dev_bound_kfunc_id(insn->imm)) { 16304 xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm); 16305 if (xdp_kfunc) { 16306 insn->imm = BPF_CALL_IMM(xdp_kfunc); 16307 return 0; 16308 } 16309 16310 /* fallback to default kfunc when not supported by netdev */ 16311 } 16312 16313 /* insn->imm has the btf func_id. Replace it with 16314 * an address (relative to __bpf_call_base). 16315 */ 16316 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 16317 if (!desc) { 16318 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 16319 insn->imm); 16320 return -EFAULT; 16321 } 16322 16323 insn->imm = desc->imm; 16324 if (insn->off) 16325 return 0; 16326 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 16327 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 16328 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 16329 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 16330 16331 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 16332 insn_buf[1] = addr[0]; 16333 insn_buf[2] = addr[1]; 16334 insn_buf[3] = *insn; 16335 *cnt = 4; 16336 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 16337 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 16338 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 16339 16340 insn_buf[0] = addr[0]; 16341 insn_buf[1] = addr[1]; 16342 insn_buf[2] = *insn; 16343 *cnt = 3; 16344 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 16345 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 16346 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 16347 *cnt = 1; 16348 } 16349 return 0; 16350 } 16351 16352 /* Do various post-verification rewrites in a single program pass. 16353 * These rewrites simplify JIT and interpreter implementations. 16354 */ 16355 static int do_misc_fixups(struct bpf_verifier_env *env) 16356 { 16357 struct bpf_prog *prog = env->prog; 16358 enum bpf_attach_type eatype = prog->expected_attach_type; 16359 enum bpf_prog_type prog_type = resolve_prog_type(prog); 16360 struct bpf_insn *insn = prog->insnsi; 16361 const struct bpf_func_proto *fn; 16362 const int insn_cnt = prog->len; 16363 const struct bpf_map_ops *ops; 16364 struct bpf_insn_aux_data *aux; 16365 struct bpf_insn insn_buf[16]; 16366 struct bpf_prog *new_prog; 16367 struct bpf_map *map_ptr; 16368 int i, ret, cnt, delta = 0; 16369 16370 for (i = 0; i < insn_cnt; i++, insn++) { 16371 /* Make divide-by-zero exceptions impossible. */ 16372 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 16373 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 16374 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 16375 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 16376 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 16377 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 16378 struct bpf_insn *patchlet; 16379 struct bpf_insn chk_and_div[] = { 16380 /* [R,W]x div 0 -> 0 */ 16381 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 16382 BPF_JNE | BPF_K, insn->src_reg, 16383 0, 2, 0), 16384 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 16385 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 16386 *insn, 16387 }; 16388 struct bpf_insn chk_and_mod[] = { 16389 /* [R,W]x mod 0 -> [R,W]x */ 16390 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 16391 BPF_JEQ | BPF_K, insn->src_reg, 16392 0, 1 + (is64 ? 0 : 1), 0), 16393 *insn, 16394 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 16395 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 16396 }; 16397 16398 patchlet = isdiv ? chk_and_div : chk_and_mod; 16399 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 16400 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 16401 16402 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 16403 if (!new_prog) 16404 return -ENOMEM; 16405 16406 delta += cnt - 1; 16407 env->prog = prog = new_prog; 16408 insn = new_prog->insnsi + i + delta; 16409 continue; 16410 } 16411 16412 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 16413 if (BPF_CLASS(insn->code) == BPF_LD && 16414 (BPF_MODE(insn->code) == BPF_ABS || 16415 BPF_MODE(insn->code) == BPF_IND)) { 16416 cnt = env->ops->gen_ld_abs(insn, insn_buf); 16417 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 16418 verbose(env, "bpf verifier is misconfigured\n"); 16419 return -EINVAL; 16420 } 16421 16422 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16423 if (!new_prog) 16424 return -ENOMEM; 16425 16426 delta += cnt - 1; 16427 env->prog = prog = new_prog; 16428 insn = new_prog->insnsi + i + delta; 16429 continue; 16430 } 16431 16432 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 16433 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 16434 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 16435 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 16436 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 16437 struct bpf_insn *patch = &insn_buf[0]; 16438 bool issrc, isneg, isimm; 16439 u32 off_reg; 16440 16441 aux = &env->insn_aux_data[i + delta]; 16442 if (!aux->alu_state || 16443 aux->alu_state == BPF_ALU_NON_POINTER) 16444 continue; 16445 16446 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 16447 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 16448 BPF_ALU_SANITIZE_SRC; 16449 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 16450 16451 off_reg = issrc ? insn->src_reg : insn->dst_reg; 16452 if (isimm) { 16453 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 16454 } else { 16455 if (isneg) 16456 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 16457 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 16458 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 16459 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 16460 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 16461 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 16462 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 16463 } 16464 if (!issrc) 16465 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 16466 insn->src_reg = BPF_REG_AX; 16467 if (isneg) 16468 insn->code = insn->code == code_add ? 16469 code_sub : code_add; 16470 *patch++ = *insn; 16471 if (issrc && isneg && !isimm) 16472 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 16473 cnt = patch - insn_buf; 16474 16475 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16476 if (!new_prog) 16477 return -ENOMEM; 16478 16479 delta += cnt - 1; 16480 env->prog = prog = new_prog; 16481 insn = new_prog->insnsi + i + delta; 16482 continue; 16483 } 16484 16485 if (insn->code != (BPF_JMP | BPF_CALL)) 16486 continue; 16487 if (insn->src_reg == BPF_PSEUDO_CALL) 16488 continue; 16489 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 16490 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 16491 if (ret) 16492 return ret; 16493 if (cnt == 0) 16494 continue; 16495 16496 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16497 if (!new_prog) 16498 return -ENOMEM; 16499 16500 delta += cnt - 1; 16501 env->prog = prog = new_prog; 16502 insn = new_prog->insnsi + i + delta; 16503 continue; 16504 } 16505 16506 if (insn->imm == BPF_FUNC_get_route_realm) 16507 prog->dst_needed = 1; 16508 if (insn->imm == BPF_FUNC_get_prandom_u32) 16509 bpf_user_rnd_init_once(); 16510 if (insn->imm == BPF_FUNC_override_return) 16511 prog->kprobe_override = 1; 16512 if (insn->imm == BPF_FUNC_tail_call) { 16513 /* If we tail call into other programs, we 16514 * cannot make any assumptions since they can 16515 * be replaced dynamically during runtime in 16516 * the program array. 16517 */ 16518 prog->cb_access = 1; 16519 if (!allow_tail_call_in_subprogs(env)) 16520 prog->aux->stack_depth = MAX_BPF_STACK; 16521 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 16522 16523 /* mark bpf_tail_call as different opcode to avoid 16524 * conditional branch in the interpreter for every normal 16525 * call and to prevent accidental JITing by JIT compiler 16526 * that doesn't support bpf_tail_call yet 16527 */ 16528 insn->imm = 0; 16529 insn->code = BPF_JMP | BPF_TAIL_CALL; 16530 16531 aux = &env->insn_aux_data[i + delta]; 16532 if (env->bpf_capable && !prog->blinding_requested && 16533 prog->jit_requested && 16534 !bpf_map_key_poisoned(aux) && 16535 !bpf_map_ptr_poisoned(aux) && 16536 !bpf_map_ptr_unpriv(aux)) { 16537 struct bpf_jit_poke_descriptor desc = { 16538 .reason = BPF_POKE_REASON_TAIL_CALL, 16539 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 16540 .tail_call.key = bpf_map_key_immediate(aux), 16541 .insn_idx = i + delta, 16542 }; 16543 16544 ret = bpf_jit_add_poke_descriptor(prog, &desc); 16545 if (ret < 0) { 16546 verbose(env, "adding tail call poke descriptor failed\n"); 16547 return ret; 16548 } 16549 16550 insn->imm = ret + 1; 16551 continue; 16552 } 16553 16554 if (!bpf_map_ptr_unpriv(aux)) 16555 continue; 16556 16557 /* instead of changing every JIT dealing with tail_call 16558 * emit two extra insns: 16559 * if (index >= max_entries) goto out; 16560 * index &= array->index_mask; 16561 * to avoid out-of-bounds cpu speculation 16562 */ 16563 if (bpf_map_ptr_poisoned(aux)) { 16564 verbose(env, "tail_call abusing map_ptr\n"); 16565 return -EINVAL; 16566 } 16567 16568 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 16569 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 16570 map_ptr->max_entries, 2); 16571 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 16572 container_of(map_ptr, 16573 struct bpf_array, 16574 map)->index_mask); 16575 insn_buf[2] = *insn; 16576 cnt = 3; 16577 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16578 if (!new_prog) 16579 return -ENOMEM; 16580 16581 delta += cnt - 1; 16582 env->prog = prog = new_prog; 16583 insn = new_prog->insnsi + i + delta; 16584 continue; 16585 } 16586 16587 if (insn->imm == BPF_FUNC_timer_set_callback) { 16588 /* The verifier will process callback_fn as many times as necessary 16589 * with different maps and the register states prepared by 16590 * set_timer_callback_state will be accurate. 16591 * 16592 * The following use case is valid: 16593 * map1 is shared by prog1, prog2, prog3. 16594 * prog1 calls bpf_timer_init for some map1 elements 16595 * prog2 calls bpf_timer_set_callback for some map1 elements. 16596 * Those that were not bpf_timer_init-ed will return -EINVAL. 16597 * prog3 calls bpf_timer_start for some map1 elements. 16598 * Those that were not both bpf_timer_init-ed and 16599 * bpf_timer_set_callback-ed will return -EINVAL. 16600 */ 16601 struct bpf_insn ld_addrs[2] = { 16602 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 16603 }; 16604 16605 insn_buf[0] = ld_addrs[0]; 16606 insn_buf[1] = ld_addrs[1]; 16607 insn_buf[2] = *insn; 16608 cnt = 3; 16609 16610 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16611 if (!new_prog) 16612 return -ENOMEM; 16613 16614 delta += cnt - 1; 16615 env->prog = prog = new_prog; 16616 insn = new_prog->insnsi + i + delta; 16617 goto patch_call_imm; 16618 } 16619 16620 if (is_storage_get_function(insn->imm)) { 16621 if (!env->prog->aux->sleepable || 16622 env->insn_aux_data[i + delta].storage_get_func_atomic) 16623 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 16624 else 16625 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 16626 insn_buf[1] = *insn; 16627 cnt = 2; 16628 16629 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16630 if (!new_prog) 16631 return -ENOMEM; 16632 16633 delta += cnt - 1; 16634 env->prog = prog = new_prog; 16635 insn = new_prog->insnsi + i + delta; 16636 goto patch_call_imm; 16637 } 16638 16639 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 16640 * and other inlining handlers are currently limited to 64 bit 16641 * only. 16642 */ 16643 if (prog->jit_requested && BITS_PER_LONG == 64 && 16644 (insn->imm == BPF_FUNC_map_lookup_elem || 16645 insn->imm == BPF_FUNC_map_update_elem || 16646 insn->imm == BPF_FUNC_map_delete_elem || 16647 insn->imm == BPF_FUNC_map_push_elem || 16648 insn->imm == BPF_FUNC_map_pop_elem || 16649 insn->imm == BPF_FUNC_map_peek_elem || 16650 insn->imm == BPF_FUNC_redirect_map || 16651 insn->imm == BPF_FUNC_for_each_map_elem || 16652 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 16653 aux = &env->insn_aux_data[i + delta]; 16654 if (bpf_map_ptr_poisoned(aux)) 16655 goto patch_call_imm; 16656 16657 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 16658 ops = map_ptr->ops; 16659 if (insn->imm == BPF_FUNC_map_lookup_elem && 16660 ops->map_gen_lookup) { 16661 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 16662 if (cnt == -EOPNOTSUPP) 16663 goto patch_map_ops_generic; 16664 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 16665 verbose(env, "bpf verifier is misconfigured\n"); 16666 return -EINVAL; 16667 } 16668 16669 new_prog = bpf_patch_insn_data(env, i + delta, 16670 insn_buf, cnt); 16671 if (!new_prog) 16672 return -ENOMEM; 16673 16674 delta += cnt - 1; 16675 env->prog = prog = new_prog; 16676 insn = new_prog->insnsi + i + delta; 16677 continue; 16678 } 16679 16680 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 16681 (void *(*)(struct bpf_map *map, void *key))NULL)); 16682 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 16683 (int (*)(struct bpf_map *map, void *key))NULL)); 16684 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 16685 (int (*)(struct bpf_map *map, void *key, void *value, 16686 u64 flags))NULL)); 16687 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 16688 (int (*)(struct bpf_map *map, void *value, 16689 u64 flags))NULL)); 16690 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 16691 (int (*)(struct bpf_map *map, void *value))NULL)); 16692 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 16693 (int (*)(struct bpf_map *map, void *value))NULL)); 16694 BUILD_BUG_ON(!__same_type(ops->map_redirect, 16695 (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 16696 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 16697 (int (*)(struct bpf_map *map, 16698 bpf_callback_t callback_fn, 16699 void *callback_ctx, 16700 u64 flags))NULL)); 16701 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 16702 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 16703 16704 patch_map_ops_generic: 16705 switch (insn->imm) { 16706 case BPF_FUNC_map_lookup_elem: 16707 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 16708 continue; 16709 case BPF_FUNC_map_update_elem: 16710 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 16711 continue; 16712 case BPF_FUNC_map_delete_elem: 16713 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 16714 continue; 16715 case BPF_FUNC_map_push_elem: 16716 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 16717 continue; 16718 case BPF_FUNC_map_pop_elem: 16719 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 16720 continue; 16721 case BPF_FUNC_map_peek_elem: 16722 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 16723 continue; 16724 case BPF_FUNC_redirect_map: 16725 insn->imm = BPF_CALL_IMM(ops->map_redirect); 16726 continue; 16727 case BPF_FUNC_for_each_map_elem: 16728 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 16729 continue; 16730 case BPF_FUNC_map_lookup_percpu_elem: 16731 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 16732 continue; 16733 } 16734 16735 goto patch_call_imm; 16736 } 16737 16738 /* Implement bpf_jiffies64 inline. */ 16739 if (prog->jit_requested && BITS_PER_LONG == 64 && 16740 insn->imm == BPF_FUNC_jiffies64) { 16741 struct bpf_insn ld_jiffies_addr[2] = { 16742 BPF_LD_IMM64(BPF_REG_0, 16743 (unsigned long)&jiffies), 16744 }; 16745 16746 insn_buf[0] = ld_jiffies_addr[0]; 16747 insn_buf[1] = ld_jiffies_addr[1]; 16748 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 16749 BPF_REG_0, 0); 16750 cnt = 3; 16751 16752 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 16753 cnt); 16754 if (!new_prog) 16755 return -ENOMEM; 16756 16757 delta += cnt - 1; 16758 env->prog = prog = new_prog; 16759 insn = new_prog->insnsi + i + delta; 16760 continue; 16761 } 16762 16763 /* Implement bpf_get_func_arg inline. */ 16764 if (prog_type == BPF_PROG_TYPE_TRACING && 16765 insn->imm == BPF_FUNC_get_func_arg) { 16766 /* Load nr_args from ctx - 8 */ 16767 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 16768 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 16769 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 16770 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 16771 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 16772 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 16773 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 16774 insn_buf[7] = BPF_JMP_A(1); 16775 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 16776 cnt = 9; 16777 16778 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16779 if (!new_prog) 16780 return -ENOMEM; 16781 16782 delta += cnt - 1; 16783 env->prog = prog = new_prog; 16784 insn = new_prog->insnsi + i + delta; 16785 continue; 16786 } 16787 16788 /* Implement bpf_get_func_ret inline. */ 16789 if (prog_type == BPF_PROG_TYPE_TRACING && 16790 insn->imm == BPF_FUNC_get_func_ret) { 16791 if (eatype == BPF_TRACE_FEXIT || 16792 eatype == BPF_MODIFY_RETURN) { 16793 /* Load nr_args from ctx - 8 */ 16794 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 16795 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 16796 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 16797 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 16798 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 16799 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 16800 cnt = 6; 16801 } else { 16802 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 16803 cnt = 1; 16804 } 16805 16806 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16807 if (!new_prog) 16808 return -ENOMEM; 16809 16810 delta += cnt - 1; 16811 env->prog = prog = new_prog; 16812 insn = new_prog->insnsi + i + delta; 16813 continue; 16814 } 16815 16816 /* Implement get_func_arg_cnt inline. */ 16817 if (prog_type == BPF_PROG_TYPE_TRACING && 16818 insn->imm == BPF_FUNC_get_func_arg_cnt) { 16819 /* Load nr_args from ctx - 8 */ 16820 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 16821 16822 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 16823 if (!new_prog) 16824 return -ENOMEM; 16825 16826 env->prog = prog = new_prog; 16827 insn = new_prog->insnsi + i + delta; 16828 continue; 16829 } 16830 16831 /* Implement bpf_get_func_ip inline. */ 16832 if (prog_type == BPF_PROG_TYPE_TRACING && 16833 insn->imm == BPF_FUNC_get_func_ip) { 16834 /* Load IP address from ctx - 16 */ 16835 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 16836 16837 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 16838 if (!new_prog) 16839 return -ENOMEM; 16840 16841 env->prog = prog = new_prog; 16842 insn = new_prog->insnsi + i + delta; 16843 continue; 16844 } 16845 16846 patch_call_imm: 16847 fn = env->ops->get_func_proto(insn->imm, env->prog); 16848 /* all functions that have prototype and verifier allowed 16849 * programs to call them, must be real in-kernel functions 16850 */ 16851 if (!fn->func) { 16852 verbose(env, 16853 "kernel subsystem misconfigured func %s#%d\n", 16854 func_id_name(insn->imm), insn->imm); 16855 return -EFAULT; 16856 } 16857 insn->imm = fn->func - __bpf_call_base; 16858 } 16859 16860 /* Since poke tab is now finalized, publish aux to tracker. */ 16861 for (i = 0; i < prog->aux->size_poke_tab; i++) { 16862 map_ptr = prog->aux->poke_tab[i].tail_call.map; 16863 if (!map_ptr->ops->map_poke_track || 16864 !map_ptr->ops->map_poke_untrack || 16865 !map_ptr->ops->map_poke_run) { 16866 verbose(env, "bpf verifier is misconfigured\n"); 16867 return -EINVAL; 16868 } 16869 16870 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 16871 if (ret < 0) { 16872 verbose(env, "tracking tail call prog failed\n"); 16873 return ret; 16874 } 16875 } 16876 16877 sort_kfunc_descs_by_imm(env->prog); 16878 16879 return 0; 16880 } 16881 16882 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 16883 int position, 16884 s32 stack_base, 16885 u32 callback_subprogno, 16886 u32 *cnt) 16887 { 16888 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 16889 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 16890 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 16891 int reg_loop_max = BPF_REG_6; 16892 int reg_loop_cnt = BPF_REG_7; 16893 int reg_loop_ctx = BPF_REG_8; 16894 16895 struct bpf_prog *new_prog; 16896 u32 callback_start; 16897 u32 call_insn_offset; 16898 s32 callback_offset; 16899 16900 /* This represents an inlined version of bpf_iter.c:bpf_loop, 16901 * be careful to modify this code in sync. 16902 */ 16903 struct bpf_insn insn_buf[] = { 16904 /* Return error and jump to the end of the patch if 16905 * expected number of iterations is too big. 16906 */ 16907 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 16908 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 16909 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 16910 /* spill R6, R7, R8 to use these as loop vars */ 16911 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 16912 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 16913 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 16914 /* initialize loop vars */ 16915 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 16916 BPF_MOV32_IMM(reg_loop_cnt, 0), 16917 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 16918 /* loop header, 16919 * if reg_loop_cnt >= reg_loop_max skip the loop body 16920 */ 16921 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 16922 /* callback call, 16923 * correct callback offset would be set after patching 16924 */ 16925 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 16926 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 16927 BPF_CALL_REL(0), 16928 /* increment loop counter */ 16929 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 16930 /* jump to loop header if callback returned 0 */ 16931 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 16932 /* return value of bpf_loop, 16933 * set R0 to the number of iterations 16934 */ 16935 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 16936 /* restore original values of R6, R7, R8 */ 16937 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 16938 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 16939 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 16940 }; 16941 16942 *cnt = ARRAY_SIZE(insn_buf); 16943 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 16944 if (!new_prog) 16945 return new_prog; 16946 16947 /* callback start is known only after patching */ 16948 callback_start = env->subprog_info[callback_subprogno].start; 16949 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 16950 call_insn_offset = position + 12; 16951 callback_offset = callback_start - call_insn_offset - 1; 16952 new_prog->insnsi[call_insn_offset].imm = callback_offset; 16953 16954 return new_prog; 16955 } 16956 16957 static bool is_bpf_loop_call(struct bpf_insn *insn) 16958 { 16959 return insn->code == (BPF_JMP | BPF_CALL) && 16960 insn->src_reg == 0 && 16961 insn->imm == BPF_FUNC_loop; 16962 } 16963 16964 /* For all sub-programs in the program (including main) check 16965 * insn_aux_data to see if there are bpf_loop calls that require 16966 * inlining. If such calls are found the calls are replaced with a 16967 * sequence of instructions produced by `inline_bpf_loop` function and 16968 * subprog stack_depth is increased by the size of 3 registers. 16969 * This stack space is used to spill values of the R6, R7, R8. These 16970 * registers are used to store the loop bound, counter and context 16971 * variables. 16972 */ 16973 static int optimize_bpf_loop(struct bpf_verifier_env *env) 16974 { 16975 struct bpf_subprog_info *subprogs = env->subprog_info; 16976 int i, cur_subprog = 0, cnt, delta = 0; 16977 struct bpf_insn *insn = env->prog->insnsi; 16978 int insn_cnt = env->prog->len; 16979 u16 stack_depth = subprogs[cur_subprog].stack_depth; 16980 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 16981 u16 stack_depth_extra = 0; 16982 16983 for (i = 0; i < insn_cnt; i++, insn++) { 16984 struct bpf_loop_inline_state *inline_state = 16985 &env->insn_aux_data[i + delta].loop_inline_state; 16986 16987 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 16988 struct bpf_prog *new_prog; 16989 16990 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 16991 new_prog = inline_bpf_loop(env, 16992 i + delta, 16993 -(stack_depth + stack_depth_extra), 16994 inline_state->callback_subprogno, 16995 &cnt); 16996 if (!new_prog) 16997 return -ENOMEM; 16998 16999 delta += cnt - 1; 17000 env->prog = new_prog; 17001 insn = new_prog->insnsi + i + delta; 17002 } 17003 17004 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 17005 subprogs[cur_subprog].stack_depth += stack_depth_extra; 17006 cur_subprog++; 17007 stack_depth = subprogs[cur_subprog].stack_depth; 17008 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 17009 stack_depth_extra = 0; 17010 } 17011 } 17012 17013 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 17014 17015 return 0; 17016 } 17017 17018 static void free_states(struct bpf_verifier_env *env) 17019 { 17020 struct bpf_verifier_state_list *sl, *sln; 17021 int i; 17022 17023 sl = env->free_list; 17024 while (sl) { 17025 sln = sl->next; 17026 free_verifier_state(&sl->state, false); 17027 kfree(sl); 17028 sl = sln; 17029 } 17030 env->free_list = NULL; 17031 17032 if (!env->explored_states) 17033 return; 17034 17035 for (i = 0; i < state_htab_size(env); i++) { 17036 sl = env->explored_states[i]; 17037 17038 while (sl) { 17039 sln = sl->next; 17040 free_verifier_state(&sl->state, false); 17041 kfree(sl); 17042 sl = sln; 17043 } 17044 env->explored_states[i] = NULL; 17045 } 17046 } 17047 17048 static int do_check_common(struct bpf_verifier_env *env, int subprog) 17049 { 17050 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 17051 struct bpf_verifier_state *state; 17052 struct bpf_reg_state *regs; 17053 int ret, i; 17054 17055 env->prev_linfo = NULL; 17056 env->pass_cnt++; 17057 17058 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 17059 if (!state) 17060 return -ENOMEM; 17061 state->curframe = 0; 17062 state->speculative = false; 17063 state->branches = 1; 17064 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 17065 if (!state->frame[0]) { 17066 kfree(state); 17067 return -ENOMEM; 17068 } 17069 env->cur_state = state; 17070 init_func_state(env, state->frame[0], 17071 BPF_MAIN_FUNC /* callsite */, 17072 0 /* frameno */, 17073 subprog); 17074 state->first_insn_idx = env->subprog_info[subprog].start; 17075 state->last_insn_idx = -1; 17076 17077 regs = state->frame[state->curframe]->regs; 17078 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 17079 ret = btf_prepare_func_args(env, subprog, regs); 17080 if (ret) 17081 goto out; 17082 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 17083 if (regs[i].type == PTR_TO_CTX) 17084 mark_reg_known_zero(env, regs, i); 17085 else if (regs[i].type == SCALAR_VALUE) 17086 mark_reg_unknown(env, regs, i); 17087 else if (base_type(regs[i].type) == PTR_TO_MEM) { 17088 const u32 mem_size = regs[i].mem_size; 17089 17090 mark_reg_known_zero(env, regs, i); 17091 regs[i].mem_size = mem_size; 17092 regs[i].id = ++env->id_gen; 17093 } 17094 } 17095 } else { 17096 /* 1st arg to a function */ 17097 regs[BPF_REG_1].type = PTR_TO_CTX; 17098 mark_reg_known_zero(env, regs, BPF_REG_1); 17099 ret = btf_check_subprog_arg_match(env, subprog, regs); 17100 if (ret == -EFAULT) 17101 /* unlikely verifier bug. abort. 17102 * ret == 0 and ret < 0 are sadly acceptable for 17103 * main() function due to backward compatibility. 17104 * Like socket filter program may be written as: 17105 * int bpf_prog(struct pt_regs *ctx) 17106 * and never dereference that ctx in the program. 17107 * 'struct pt_regs' is a type mismatch for socket 17108 * filter that should be using 'struct __sk_buff'. 17109 */ 17110 goto out; 17111 } 17112 17113 ret = do_check(env); 17114 out: 17115 /* check for NULL is necessary, since cur_state can be freed inside 17116 * do_check() under memory pressure. 17117 */ 17118 if (env->cur_state) { 17119 free_verifier_state(env->cur_state, true); 17120 env->cur_state = NULL; 17121 } 17122 while (!pop_stack(env, NULL, NULL, false)); 17123 if (!ret && pop_log) 17124 bpf_vlog_reset(&env->log, 0); 17125 free_states(env); 17126 return ret; 17127 } 17128 17129 /* Verify all global functions in a BPF program one by one based on their BTF. 17130 * All global functions must pass verification. Otherwise the whole program is rejected. 17131 * Consider: 17132 * int bar(int); 17133 * int foo(int f) 17134 * { 17135 * return bar(f); 17136 * } 17137 * int bar(int b) 17138 * { 17139 * ... 17140 * } 17141 * foo() will be verified first for R1=any_scalar_value. During verification it 17142 * will be assumed that bar() already verified successfully and call to bar() 17143 * from foo() will be checked for type match only. Later bar() will be verified 17144 * independently to check that it's safe for R1=any_scalar_value. 17145 */ 17146 static int do_check_subprogs(struct bpf_verifier_env *env) 17147 { 17148 struct bpf_prog_aux *aux = env->prog->aux; 17149 int i, ret; 17150 17151 if (!aux->func_info) 17152 return 0; 17153 17154 for (i = 1; i < env->subprog_cnt; i++) { 17155 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 17156 continue; 17157 env->insn_idx = env->subprog_info[i].start; 17158 WARN_ON_ONCE(env->insn_idx == 0); 17159 ret = do_check_common(env, i); 17160 if (ret) { 17161 return ret; 17162 } else if (env->log.level & BPF_LOG_LEVEL) { 17163 verbose(env, 17164 "Func#%d is safe for any args that match its prototype\n", 17165 i); 17166 } 17167 } 17168 return 0; 17169 } 17170 17171 static int do_check_main(struct bpf_verifier_env *env) 17172 { 17173 int ret; 17174 17175 env->insn_idx = 0; 17176 ret = do_check_common(env, 0); 17177 if (!ret) 17178 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 17179 return ret; 17180 } 17181 17182 17183 static void print_verification_stats(struct bpf_verifier_env *env) 17184 { 17185 int i; 17186 17187 if (env->log.level & BPF_LOG_STATS) { 17188 verbose(env, "verification time %lld usec\n", 17189 div_u64(env->verification_time, 1000)); 17190 verbose(env, "stack depth "); 17191 for (i = 0; i < env->subprog_cnt; i++) { 17192 u32 depth = env->subprog_info[i].stack_depth; 17193 17194 verbose(env, "%d", depth); 17195 if (i + 1 < env->subprog_cnt) 17196 verbose(env, "+"); 17197 } 17198 verbose(env, "\n"); 17199 } 17200 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 17201 "total_states %d peak_states %d mark_read %d\n", 17202 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 17203 env->max_states_per_insn, env->total_states, 17204 env->peak_states, env->longest_mark_read_walk); 17205 } 17206 17207 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 17208 { 17209 const struct btf_type *t, *func_proto; 17210 const struct bpf_struct_ops *st_ops; 17211 const struct btf_member *member; 17212 struct bpf_prog *prog = env->prog; 17213 u32 btf_id, member_idx; 17214 const char *mname; 17215 17216 if (!prog->gpl_compatible) { 17217 verbose(env, "struct ops programs must have a GPL compatible license\n"); 17218 return -EINVAL; 17219 } 17220 17221 btf_id = prog->aux->attach_btf_id; 17222 st_ops = bpf_struct_ops_find(btf_id); 17223 if (!st_ops) { 17224 verbose(env, "attach_btf_id %u is not a supported struct\n", 17225 btf_id); 17226 return -ENOTSUPP; 17227 } 17228 17229 t = st_ops->type; 17230 member_idx = prog->expected_attach_type; 17231 if (member_idx >= btf_type_vlen(t)) { 17232 verbose(env, "attach to invalid member idx %u of struct %s\n", 17233 member_idx, st_ops->name); 17234 return -EINVAL; 17235 } 17236 17237 member = &btf_type_member(t)[member_idx]; 17238 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 17239 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 17240 NULL); 17241 if (!func_proto) { 17242 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 17243 mname, member_idx, st_ops->name); 17244 return -EINVAL; 17245 } 17246 17247 if (st_ops->check_member) { 17248 int err = st_ops->check_member(t, member, prog); 17249 17250 if (err) { 17251 verbose(env, "attach to unsupported member %s of struct %s\n", 17252 mname, st_ops->name); 17253 return err; 17254 } 17255 } 17256 17257 prog->aux->attach_func_proto = func_proto; 17258 prog->aux->attach_func_name = mname; 17259 env->ops = st_ops->verifier_ops; 17260 17261 return 0; 17262 } 17263 #define SECURITY_PREFIX "security_" 17264 17265 static int check_attach_modify_return(unsigned long addr, const char *func_name) 17266 { 17267 if (within_error_injection_list(addr) || 17268 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 17269 return 0; 17270 17271 return -EINVAL; 17272 } 17273 17274 /* list of non-sleepable functions that are otherwise on 17275 * ALLOW_ERROR_INJECTION list 17276 */ 17277 BTF_SET_START(btf_non_sleepable_error_inject) 17278 /* Three functions below can be called from sleepable and non-sleepable context. 17279 * Assume non-sleepable from bpf safety point of view. 17280 */ 17281 BTF_ID(func, __filemap_add_folio) 17282 BTF_ID(func, should_fail_alloc_page) 17283 BTF_ID(func, should_failslab) 17284 BTF_SET_END(btf_non_sleepable_error_inject) 17285 17286 static int check_non_sleepable_error_inject(u32 btf_id) 17287 { 17288 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 17289 } 17290 17291 int bpf_check_attach_target(struct bpf_verifier_log *log, 17292 const struct bpf_prog *prog, 17293 const struct bpf_prog *tgt_prog, 17294 u32 btf_id, 17295 struct bpf_attach_target_info *tgt_info) 17296 { 17297 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 17298 const char prefix[] = "btf_trace_"; 17299 int ret = 0, subprog = -1, i; 17300 const struct btf_type *t; 17301 bool conservative = true; 17302 const char *tname; 17303 struct btf *btf; 17304 long addr = 0; 17305 17306 if (!btf_id) { 17307 bpf_log(log, "Tracing programs must provide btf_id\n"); 17308 return -EINVAL; 17309 } 17310 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 17311 if (!btf) { 17312 bpf_log(log, 17313 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 17314 return -EINVAL; 17315 } 17316 t = btf_type_by_id(btf, btf_id); 17317 if (!t) { 17318 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 17319 return -EINVAL; 17320 } 17321 tname = btf_name_by_offset(btf, t->name_off); 17322 if (!tname) { 17323 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 17324 return -EINVAL; 17325 } 17326 if (tgt_prog) { 17327 struct bpf_prog_aux *aux = tgt_prog->aux; 17328 17329 if (bpf_prog_is_dev_bound(prog->aux) && 17330 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 17331 bpf_log(log, "Target program bound device mismatch"); 17332 return -EINVAL; 17333 } 17334 17335 for (i = 0; i < aux->func_info_cnt; i++) 17336 if (aux->func_info[i].type_id == btf_id) { 17337 subprog = i; 17338 break; 17339 } 17340 if (subprog == -1) { 17341 bpf_log(log, "Subprog %s doesn't exist\n", tname); 17342 return -EINVAL; 17343 } 17344 conservative = aux->func_info_aux[subprog].unreliable; 17345 if (prog_extension) { 17346 if (conservative) { 17347 bpf_log(log, 17348 "Cannot replace static functions\n"); 17349 return -EINVAL; 17350 } 17351 if (!prog->jit_requested) { 17352 bpf_log(log, 17353 "Extension programs should be JITed\n"); 17354 return -EINVAL; 17355 } 17356 } 17357 if (!tgt_prog->jited) { 17358 bpf_log(log, "Can attach to only JITed progs\n"); 17359 return -EINVAL; 17360 } 17361 if (tgt_prog->type == prog->type) { 17362 /* Cannot fentry/fexit another fentry/fexit program. 17363 * Cannot attach program extension to another extension. 17364 * It's ok to attach fentry/fexit to extension program. 17365 */ 17366 bpf_log(log, "Cannot recursively attach\n"); 17367 return -EINVAL; 17368 } 17369 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 17370 prog_extension && 17371 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 17372 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 17373 /* Program extensions can extend all program types 17374 * except fentry/fexit. The reason is the following. 17375 * The fentry/fexit programs are used for performance 17376 * analysis, stats and can be attached to any program 17377 * type except themselves. When extension program is 17378 * replacing XDP function it is necessary to allow 17379 * performance analysis of all functions. Both original 17380 * XDP program and its program extension. Hence 17381 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 17382 * allowed. If extending of fentry/fexit was allowed it 17383 * would be possible to create long call chain 17384 * fentry->extension->fentry->extension beyond 17385 * reasonable stack size. Hence extending fentry is not 17386 * allowed. 17387 */ 17388 bpf_log(log, "Cannot extend fentry/fexit\n"); 17389 return -EINVAL; 17390 } 17391 } else { 17392 if (prog_extension) { 17393 bpf_log(log, "Cannot replace kernel functions\n"); 17394 return -EINVAL; 17395 } 17396 } 17397 17398 switch (prog->expected_attach_type) { 17399 case BPF_TRACE_RAW_TP: 17400 if (tgt_prog) { 17401 bpf_log(log, 17402 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 17403 return -EINVAL; 17404 } 17405 if (!btf_type_is_typedef(t)) { 17406 bpf_log(log, "attach_btf_id %u is not a typedef\n", 17407 btf_id); 17408 return -EINVAL; 17409 } 17410 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 17411 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 17412 btf_id, tname); 17413 return -EINVAL; 17414 } 17415 tname += sizeof(prefix) - 1; 17416 t = btf_type_by_id(btf, t->type); 17417 if (!btf_type_is_ptr(t)) 17418 /* should never happen in valid vmlinux build */ 17419 return -EINVAL; 17420 t = btf_type_by_id(btf, t->type); 17421 if (!btf_type_is_func_proto(t)) 17422 /* should never happen in valid vmlinux build */ 17423 return -EINVAL; 17424 17425 break; 17426 case BPF_TRACE_ITER: 17427 if (!btf_type_is_func(t)) { 17428 bpf_log(log, "attach_btf_id %u is not a function\n", 17429 btf_id); 17430 return -EINVAL; 17431 } 17432 t = btf_type_by_id(btf, t->type); 17433 if (!btf_type_is_func_proto(t)) 17434 return -EINVAL; 17435 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 17436 if (ret) 17437 return ret; 17438 break; 17439 default: 17440 if (!prog_extension) 17441 return -EINVAL; 17442 fallthrough; 17443 case BPF_MODIFY_RETURN: 17444 case BPF_LSM_MAC: 17445 case BPF_LSM_CGROUP: 17446 case BPF_TRACE_FENTRY: 17447 case BPF_TRACE_FEXIT: 17448 if (!btf_type_is_func(t)) { 17449 bpf_log(log, "attach_btf_id %u is not a function\n", 17450 btf_id); 17451 return -EINVAL; 17452 } 17453 if (prog_extension && 17454 btf_check_type_match(log, prog, btf, t)) 17455 return -EINVAL; 17456 t = btf_type_by_id(btf, t->type); 17457 if (!btf_type_is_func_proto(t)) 17458 return -EINVAL; 17459 17460 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 17461 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 17462 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 17463 return -EINVAL; 17464 17465 if (tgt_prog && conservative) 17466 t = NULL; 17467 17468 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 17469 if (ret < 0) 17470 return ret; 17471 17472 if (tgt_prog) { 17473 if (subprog == 0) 17474 addr = (long) tgt_prog->bpf_func; 17475 else 17476 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 17477 } else { 17478 addr = kallsyms_lookup_name(tname); 17479 if (!addr) { 17480 bpf_log(log, 17481 "The address of function %s cannot be found\n", 17482 tname); 17483 return -ENOENT; 17484 } 17485 } 17486 17487 if (prog->aux->sleepable) { 17488 ret = -EINVAL; 17489 switch (prog->type) { 17490 case BPF_PROG_TYPE_TRACING: 17491 17492 /* fentry/fexit/fmod_ret progs can be sleepable if they are 17493 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 17494 */ 17495 if (!check_non_sleepable_error_inject(btf_id) && 17496 within_error_injection_list(addr)) 17497 ret = 0; 17498 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 17499 * in the fmodret id set with the KF_SLEEPABLE flag. 17500 */ 17501 else { 17502 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id); 17503 17504 if (flags && (*flags & KF_SLEEPABLE)) 17505 ret = 0; 17506 } 17507 break; 17508 case BPF_PROG_TYPE_LSM: 17509 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 17510 * Only some of them are sleepable. 17511 */ 17512 if (bpf_lsm_is_sleepable_hook(btf_id)) 17513 ret = 0; 17514 break; 17515 default: 17516 break; 17517 } 17518 if (ret) { 17519 bpf_log(log, "%s is not sleepable\n", tname); 17520 return ret; 17521 } 17522 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 17523 if (tgt_prog) { 17524 bpf_log(log, "can't modify return codes of BPF programs\n"); 17525 return -EINVAL; 17526 } 17527 ret = -EINVAL; 17528 if (btf_kfunc_is_modify_return(btf, btf_id) || 17529 !check_attach_modify_return(addr, tname)) 17530 ret = 0; 17531 if (ret) { 17532 bpf_log(log, "%s() is not modifiable\n", tname); 17533 return ret; 17534 } 17535 } 17536 17537 break; 17538 } 17539 tgt_info->tgt_addr = addr; 17540 tgt_info->tgt_name = tname; 17541 tgt_info->tgt_type = t; 17542 return 0; 17543 } 17544 17545 BTF_SET_START(btf_id_deny) 17546 BTF_ID_UNUSED 17547 #ifdef CONFIG_SMP 17548 BTF_ID(func, migrate_disable) 17549 BTF_ID(func, migrate_enable) 17550 #endif 17551 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 17552 BTF_ID(func, rcu_read_unlock_strict) 17553 #endif 17554 BTF_SET_END(btf_id_deny) 17555 17556 static bool can_be_sleepable(struct bpf_prog *prog) 17557 { 17558 if (prog->type == BPF_PROG_TYPE_TRACING) { 17559 switch (prog->expected_attach_type) { 17560 case BPF_TRACE_FENTRY: 17561 case BPF_TRACE_FEXIT: 17562 case BPF_MODIFY_RETURN: 17563 case BPF_TRACE_ITER: 17564 return true; 17565 default: 17566 return false; 17567 } 17568 } 17569 return prog->type == BPF_PROG_TYPE_LSM || 17570 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 17571 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 17572 } 17573 17574 static int check_attach_btf_id(struct bpf_verifier_env *env) 17575 { 17576 struct bpf_prog *prog = env->prog; 17577 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 17578 struct bpf_attach_target_info tgt_info = {}; 17579 u32 btf_id = prog->aux->attach_btf_id; 17580 struct bpf_trampoline *tr; 17581 int ret; 17582 u64 key; 17583 17584 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 17585 if (prog->aux->sleepable) 17586 /* attach_btf_id checked to be zero already */ 17587 return 0; 17588 verbose(env, "Syscall programs can only be sleepable\n"); 17589 return -EINVAL; 17590 } 17591 17592 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 17593 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 17594 return -EINVAL; 17595 } 17596 17597 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 17598 return check_struct_ops_btf_id(env); 17599 17600 if (prog->type != BPF_PROG_TYPE_TRACING && 17601 prog->type != BPF_PROG_TYPE_LSM && 17602 prog->type != BPF_PROG_TYPE_EXT) 17603 return 0; 17604 17605 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 17606 if (ret) 17607 return ret; 17608 17609 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 17610 /* to make freplace equivalent to their targets, they need to 17611 * inherit env->ops and expected_attach_type for the rest of the 17612 * verification 17613 */ 17614 env->ops = bpf_verifier_ops[tgt_prog->type]; 17615 prog->expected_attach_type = tgt_prog->expected_attach_type; 17616 } 17617 17618 /* store info about the attachment target that will be used later */ 17619 prog->aux->attach_func_proto = tgt_info.tgt_type; 17620 prog->aux->attach_func_name = tgt_info.tgt_name; 17621 17622 if (tgt_prog) { 17623 prog->aux->saved_dst_prog_type = tgt_prog->type; 17624 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 17625 } 17626 17627 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 17628 prog->aux->attach_btf_trace = true; 17629 return 0; 17630 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 17631 if (!bpf_iter_prog_supported(prog)) 17632 return -EINVAL; 17633 return 0; 17634 } 17635 17636 if (prog->type == BPF_PROG_TYPE_LSM) { 17637 ret = bpf_lsm_verify_prog(&env->log, prog); 17638 if (ret < 0) 17639 return ret; 17640 } else if (prog->type == BPF_PROG_TYPE_TRACING && 17641 btf_id_set_contains(&btf_id_deny, btf_id)) { 17642 return -EINVAL; 17643 } 17644 17645 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 17646 tr = bpf_trampoline_get(key, &tgt_info); 17647 if (!tr) 17648 return -ENOMEM; 17649 17650 prog->aux->dst_trampoline = tr; 17651 return 0; 17652 } 17653 17654 struct btf *bpf_get_btf_vmlinux(void) 17655 { 17656 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 17657 mutex_lock(&bpf_verifier_lock); 17658 if (!btf_vmlinux) 17659 btf_vmlinux = btf_parse_vmlinux(); 17660 mutex_unlock(&bpf_verifier_lock); 17661 } 17662 return btf_vmlinux; 17663 } 17664 17665 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr) 17666 { 17667 u64 start_time = ktime_get_ns(); 17668 struct bpf_verifier_env *env; 17669 struct bpf_verifier_log *log; 17670 int i, len, ret = -EINVAL; 17671 bool is_priv; 17672 17673 /* no program is valid */ 17674 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 17675 return -EINVAL; 17676 17677 /* 'struct bpf_verifier_env' can be global, but since it's not small, 17678 * allocate/free it every time bpf_check() is called 17679 */ 17680 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 17681 if (!env) 17682 return -ENOMEM; 17683 log = &env->log; 17684 17685 len = (*prog)->len; 17686 env->insn_aux_data = 17687 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 17688 ret = -ENOMEM; 17689 if (!env->insn_aux_data) 17690 goto err_free_env; 17691 for (i = 0; i < len; i++) 17692 env->insn_aux_data[i].orig_idx = i; 17693 env->prog = *prog; 17694 env->ops = bpf_verifier_ops[env->prog->type]; 17695 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 17696 is_priv = bpf_capable(); 17697 17698 bpf_get_btf_vmlinux(); 17699 17700 /* grab the mutex to protect few globals used by verifier */ 17701 if (!is_priv) 17702 mutex_lock(&bpf_verifier_lock); 17703 17704 if (attr->log_level || attr->log_buf || attr->log_size) { 17705 /* user requested verbose verifier output 17706 * and supplied buffer to store the verification trace 17707 */ 17708 log->level = attr->log_level; 17709 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 17710 log->len_total = attr->log_size; 17711 17712 /* log attributes have to be sane */ 17713 if (!bpf_verifier_log_attr_valid(log)) { 17714 ret = -EINVAL; 17715 goto err_unlock; 17716 } 17717 } 17718 17719 mark_verifier_state_clean(env); 17720 17721 if (IS_ERR(btf_vmlinux)) { 17722 /* Either gcc or pahole or kernel are broken. */ 17723 verbose(env, "in-kernel BTF is malformed\n"); 17724 ret = PTR_ERR(btf_vmlinux); 17725 goto skip_full_check; 17726 } 17727 17728 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 17729 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 17730 env->strict_alignment = true; 17731 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 17732 env->strict_alignment = false; 17733 17734 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 17735 env->allow_uninit_stack = bpf_allow_uninit_stack(); 17736 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 17737 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 17738 env->bpf_capable = bpf_capable(); 17739 env->rcu_tag_supported = btf_vmlinux && 17740 btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0; 17741 17742 if (is_priv) 17743 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 17744 17745 env->explored_states = kvcalloc(state_htab_size(env), 17746 sizeof(struct bpf_verifier_state_list *), 17747 GFP_USER); 17748 ret = -ENOMEM; 17749 if (!env->explored_states) 17750 goto skip_full_check; 17751 17752 ret = add_subprog_and_kfunc(env); 17753 if (ret < 0) 17754 goto skip_full_check; 17755 17756 ret = check_subprogs(env); 17757 if (ret < 0) 17758 goto skip_full_check; 17759 17760 ret = check_btf_info(env, attr, uattr); 17761 if (ret < 0) 17762 goto skip_full_check; 17763 17764 ret = check_attach_btf_id(env); 17765 if (ret) 17766 goto skip_full_check; 17767 17768 ret = resolve_pseudo_ldimm64(env); 17769 if (ret < 0) 17770 goto skip_full_check; 17771 17772 if (bpf_prog_is_offloaded(env->prog->aux)) { 17773 ret = bpf_prog_offload_verifier_prep(env->prog); 17774 if (ret) 17775 goto skip_full_check; 17776 } 17777 17778 ret = check_cfg(env); 17779 if (ret < 0) 17780 goto skip_full_check; 17781 17782 ret = do_check_subprogs(env); 17783 ret = ret ?: do_check_main(env); 17784 17785 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 17786 ret = bpf_prog_offload_finalize(env); 17787 17788 skip_full_check: 17789 kvfree(env->explored_states); 17790 17791 if (ret == 0) 17792 ret = check_max_stack_depth(env); 17793 17794 /* instruction rewrites happen after this point */ 17795 if (ret == 0) 17796 ret = optimize_bpf_loop(env); 17797 17798 if (is_priv) { 17799 if (ret == 0) 17800 opt_hard_wire_dead_code_branches(env); 17801 if (ret == 0) 17802 ret = opt_remove_dead_code(env); 17803 if (ret == 0) 17804 ret = opt_remove_nops(env); 17805 } else { 17806 if (ret == 0) 17807 sanitize_dead_code(env); 17808 } 17809 17810 if (ret == 0) 17811 /* program is valid, convert *(u32*)(ctx + off) accesses */ 17812 ret = convert_ctx_accesses(env); 17813 17814 if (ret == 0) 17815 ret = do_misc_fixups(env); 17816 17817 /* do 32-bit optimization after insn patching has done so those patched 17818 * insns could be handled correctly. 17819 */ 17820 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 17821 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 17822 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 17823 : false; 17824 } 17825 17826 if (ret == 0) 17827 ret = fixup_call_args(env); 17828 17829 env->verification_time = ktime_get_ns() - start_time; 17830 print_verification_stats(env); 17831 env->prog->aux->verified_insns = env->insn_processed; 17832 17833 if (log->level && bpf_verifier_log_full(log)) 17834 ret = -ENOSPC; 17835 if (log->level && !log->ubuf) { 17836 ret = -EFAULT; 17837 goto err_release_maps; 17838 } 17839 17840 if (ret) 17841 goto err_release_maps; 17842 17843 if (env->used_map_cnt) { 17844 /* if program passed verifier, update used_maps in bpf_prog_info */ 17845 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 17846 sizeof(env->used_maps[0]), 17847 GFP_KERNEL); 17848 17849 if (!env->prog->aux->used_maps) { 17850 ret = -ENOMEM; 17851 goto err_release_maps; 17852 } 17853 17854 memcpy(env->prog->aux->used_maps, env->used_maps, 17855 sizeof(env->used_maps[0]) * env->used_map_cnt); 17856 env->prog->aux->used_map_cnt = env->used_map_cnt; 17857 } 17858 if (env->used_btf_cnt) { 17859 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 17860 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 17861 sizeof(env->used_btfs[0]), 17862 GFP_KERNEL); 17863 if (!env->prog->aux->used_btfs) { 17864 ret = -ENOMEM; 17865 goto err_release_maps; 17866 } 17867 17868 memcpy(env->prog->aux->used_btfs, env->used_btfs, 17869 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 17870 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 17871 } 17872 if (env->used_map_cnt || env->used_btf_cnt) { 17873 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 17874 * bpf_ld_imm64 instructions 17875 */ 17876 convert_pseudo_ld_imm64(env); 17877 } 17878 17879 adjust_btf_func(env); 17880 17881 err_release_maps: 17882 if (!env->prog->aux->used_maps) 17883 /* if we didn't copy map pointers into bpf_prog_info, release 17884 * them now. Otherwise free_used_maps() will release them. 17885 */ 17886 release_maps(env); 17887 if (!env->prog->aux->used_btfs) 17888 release_btfs(env); 17889 17890 /* extension progs temporarily inherit the attach_type of their targets 17891 for verification purposes, so set it back to zero before returning 17892 */ 17893 if (env->prog->type == BPF_PROG_TYPE_EXT) 17894 env->prog->expected_attach_type = 0; 17895 17896 *prog = env->prog; 17897 err_unlock: 17898 if (!is_priv) 17899 mutex_unlock(&bpf_verifier_lock); 17900 vfree(env->insn_aux_data); 17901 err_free_env: 17902 kfree(env); 17903 return ret; 17904 } 17905