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 194 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 195 { 196 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 197 } 198 199 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 200 { 201 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 202 } 203 204 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 205 const struct bpf_map *map, bool unpriv) 206 { 207 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 208 unpriv |= bpf_map_ptr_unpriv(aux); 209 aux->map_ptr_state = (unsigned long)map | 210 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 211 } 212 213 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 214 { 215 return aux->map_key_state & BPF_MAP_KEY_POISON; 216 } 217 218 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 219 { 220 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 221 } 222 223 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 224 { 225 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 226 } 227 228 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 229 { 230 bool poisoned = bpf_map_key_poisoned(aux); 231 232 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 233 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 234 } 235 236 static bool bpf_pseudo_call(const struct bpf_insn *insn) 237 { 238 return insn->code == (BPF_JMP | BPF_CALL) && 239 insn->src_reg == BPF_PSEUDO_CALL; 240 } 241 242 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 243 { 244 return insn->code == (BPF_JMP | BPF_CALL) && 245 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 246 } 247 248 struct bpf_call_arg_meta { 249 struct bpf_map *map_ptr; 250 bool raw_mode; 251 bool pkt_access; 252 u8 release_regno; 253 int regno; 254 int access_size; 255 int mem_size; 256 u64 msize_max_value; 257 int ref_obj_id; 258 int map_uid; 259 int func_id; 260 struct btf *btf; 261 u32 btf_id; 262 struct btf *ret_btf; 263 u32 ret_btf_id; 264 u32 subprogno; 265 struct btf_field *kptr_field; 266 u8 uninit_dynptr_regno; 267 }; 268 269 struct btf *btf_vmlinux; 270 271 static DEFINE_MUTEX(bpf_verifier_lock); 272 273 static const struct bpf_line_info * 274 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 275 { 276 const struct bpf_line_info *linfo; 277 const struct bpf_prog *prog; 278 u32 i, nr_linfo; 279 280 prog = env->prog; 281 nr_linfo = prog->aux->nr_linfo; 282 283 if (!nr_linfo || insn_off >= prog->len) 284 return NULL; 285 286 linfo = prog->aux->linfo; 287 for (i = 1; i < nr_linfo; i++) 288 if (insn_off < linfo[i].insn_off) 289 break; 290 291 return &linfo[i - 1]; 292 } 293 294 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, 295 va_list args) 296 { 297 unsigned int n; 298 299 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); 300 301 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, 302 "verifier log line truncated - local buffer too short\n"); 303 304 if (log->level == BPF_LOG_KERNEL) { 305 bool newline = n > 0 && log->kbuf[n - 1] == '\n'; 306 307 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n"); 308 return; 309 } 310 311 n = min(log->len_total - log->len_used - 1, n); 312 log->kbuf[n] = '\0'; 313 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) 314 log->len_used += n; 315 else 316 log->ubuf = NULL; 317 } 318 319 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos) 320 { 321 char zero = 0; 322 323 if (!bpf_verifier_log_needed(log)) 324 return; 325 326 log->len_used = new_pos; 327 if (put_user(zero, log->ubuf + new_pos)) 328 log->ubuf = NULL; 329 } 330 331 /* log_level controls verbosity level of eBPF verifier. 332 * bpf_verifier_log_write() is used to dump the verification trace to the log, 333 * so the user can figure out what's wrong with the program 334 */ 335 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 336 const char *fmt, ...) 337 { 338 va_list args; 339 340 if (!bpf_verifier_log_needed(&env->log)) 341 return; 342 343 va_start(args, fmt); 344 bpf_verifier_vlog(&env->log, fmt, args); 345 va_end(args); 346 } 347 EXPORT_SYMBOL_GPL(bpf_verifier_log_write); 348 349 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 350 { 351 struct bpf_verifier_env *env = private_data; 352 va_list args; 353 354 if (!bpf_verifier_log_needed(&env->log)) 355 return; 356 357 va_start(args, fmt); 358 bpf_verifier_vlog(&env->log, fmt, args); 359 va_end(args); 360 } 361 362 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log, 363 const char *fmt, ...) 364 { 365 va_list args; 366 367 if (!bpf_verifier_log_needed(log)) 368 return; 369 370 va_start(args, fmt); 371 bpf_verifier_vlog(log, fmt, args); 372 va_end(args); 373 } 374 EXPORT_SYMBOL_GPL(bpf_log); 375 376 static const char *ltrim(const char *s) 377 { 378 while (isspace(*s)) 379 s++; 380 381 return s; 382 } 383 384 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 385 u32 insn_off, 386 const char *prefix_fmt, ...) 387 { 388 const struct bpf_line_info *linfo; 389 390 if (!bpf_verifier_log_needed(&env->log)) 391 return; 392 393 linfo = find_linfo(env, insn_off); 394 if (!linfo || linfo == env->prev_linfo) 395 return; 396 397 if (prefix_fmt) { 398 va_list args; 399 400 va_start(args, prefix_fmt); 401 bpf_verifier_vlog(&env->log, prefix_fmt, args); 402 va_end(args); 403 } 404 405 verbose(env, "%s\n", 406 ltrim(btf_name_by_offset(env->prog->aux->btf, 407 linfo->line_off))); 408 409 env->prev_linfo = linfo; 410 } 411 412 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 413 struct bpf_reg_state *reg, 414 struct tnum *range, const char *ctx, 415 const char *reg_name) 416 { 417 char tn_buf[48]; 418 419 verbose(env, "At %s the register %s ", ctx, reg_name); 420 if (!tnum_is_unknown(reg->var_off)) { 421 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 422 verbose(env, "has value %s", tn_buf); 423 } else { 424 verbose(env, "has unknown scalar value"); 425 } 426 tnum_strn(tn_buf, sizeof(tn_buf), *range); 427 verbose(env, " should have been in %s\n", tn_buf); 428 } 429 430 static bool type_is_pkt_pointer(enum bpf_reg_type type) 431 { 432 type = base_type(type); 433 return type == PTR_TO_PACKET || 434 type == PTR_TO_PACKET_META; 435 } 436 437 static bool type_is_sk_pointer(enum bpf_reg_type type) 438 { 439 return type == PTR_TO_SOCKET || 440 type == PTR_TO_SOCK_COMMON || 441 type == PTR_TO_TCP_SOCK || 442 type == PTR_TO_XDP_SOCK; 443 } 444 445 static bool reg_type_not_null(enum bpf_reg_type type) 446 { 447 return type == PTR_TO_SOCKET || 448 type == PTR_TO_TCP_SOCK || 449 type == PTR_TO_MAP_VALUE || 450 type == PTR_TO_MAP_KEY || 451 type == PTR_TO_SOCK_COMMON; 452 } 453 454 static bool type_is_ptr_alloc_obj(u32 type) 455 { 456 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 457 } 458 459 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 460 { 461 struct btf_record *rec = NULL; 462 struct btf_struct_meta *meta; 463 464 if (reg->type == PTR_TO_MAP_VALUE) { 465 rec = reg->map_ptr->record; 466 } else if (type_is_ptr_alloc_obj(reg->type)) { 467 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 468 if (meta) 469 rec = meta->record; 470 } 471 return rec; 472 } 473 474 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 475 { 476 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 477 } 478 479 static bool type_is_rdonly_mem(u32 type) 480 { 481 return type & MEM_RDONLY; 482 } 483 484 static bool type_may_be_null(u32 type) 485 { 486 return type & PTR_MAYBE_NULL; 487 } 488 489 static bool is_acquire_function(enum bpf_func_id func_id, 490 const struct bpf_map *map) 491 { 492 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 493 494 if (func_id == BPF_FUNC_sk_lookup_tcp || 495 func_id == BPF_FUNC_sk_lookup_udp || 496 func_id == BPF_FUNC_skc_lookup_tcp || 497 func_id == BPF_FUNC_ringbuf_reserve || 498 func_id == BPF_FUNC_kptr_xchg) 499 return true; 500 501 if (func_id == BPF_FUNC_map_lookup_elem && 502 (map_type == BPF_MAP_TYPE_SOCKMAP || 503 map_type == BPF_MAP_TYPE_SOCKHASH)) 504 return true; 505 506 return false; 507 } 508 509 static bool is_ptr_cast_function(enum bpf_func_id func_id) 510 { 511 return func_id == BPF_FUNC_tcp_sock || 512 func_id == BPF_FUNC_sk_fullsock || 513 func_id == BPF_FUNC_skc_to_tcp_sock || 514 func_id == BPF_FUNC_skc_to_tcp6_sock || 515 func_id == BPF_FUNC_skc_to_udp6_sock || 516 func_id == BPF_FUNC_skc_to_mptcp_sock || 517 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 518 func_id == BPF_FUNC_skc_to_tcp_request_sock; 519 } 520 521 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 522 { 523 return func_id == BPF_FUNC_dynptr_data; 524 } 525 526 static bool is_callback_calling_function(enum bpf_func_id func_id) 527 { 528 return func_id == BPF_FUNC_for_each_map_elem || 529 func_id == BPF_FUNC_timer_set_callback || 530 func_id == BPF_FUNC_find_vma || 531 func_id == BPF_FUNC_loop || 532 func_id == BPF_FUNC_user_ringbuf_drain; 533 } 534 535 static bool is_storage_get_function(enum bpf_func_id func_id) 536 { 537 return func_id == BPF_FUNC_sk_storage_get || 538 func_id == BPF_FUNC_inode_storage_get || 539 func_id == BPF_FUNC_task_storage_get || 540 func_id == BPF_FUNC_cgrp_storage_get; 541 } 542 543 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 544 const struct bpf_map *map) 545 { 546 int ref_obj_uses = 0; 547 548 if (is_ptr_cast_function(func_id)) 549 ref_obj_uses++; 550 if (is_acquire_function(func_id, map)) 551 ref_obj_uses++; 552 if (is_dynptr_ref_function(func_id)) 553 ref_obj_uses++; 554 555 return ref_obj_uses > 1; 556 } 557 558 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 559 { 560 return BPF_CLASS(insn->code) == BPF_STX && 561 BPF_MODE(insn->code) == BPF_ATOMIC && 562 insn->imm == BPF_CMPXCHG; 563 } 564 565 /* string representation of 'enum bpf_reg_type' 566 * 567 * Note that reg_type_str() can not appear more than once in a single verbose() 568 * statement. 569 */ 570 static const char *reg_type_str(struct bpf_verifier_env *env, 571 enum bpf_reg_type type) 572 { 573 char postfix[16] = {0}, prefix[64] = {0}; 574 static const char * const str[] = { 575 [NOT_INIT] = "?", 576 [SCALAR_VALUE] = "scalar", 577 [PTR_TO_CTX] = "ctx", 578 [CONST_PTR_TO_MAP] = "map_ptr", 579 [PTR_TO_MAP_VALUE] = "map_value", 580 [PTR_TO_STACK] = "fp", 581 [PTR_TO_PACKET] = "pkt", 582 [PTR_TO_PACKET_META] = "pkt_meta", 583 [PTR_TO_PACKET_END] = "pkt_end", 584 [PTR_TO_FLOW_KEYS] = "flow_keys", 585 [PTR_TO_SOCKET] = "sock", 586 [PTR_TO_SOCK_COMMON] = "sock_common", 587 [PTR_TO_TCP_SOCK] = "tcp_sock", 588 [PTR_TO_TP_BUFFER] = "tp_buffer", 589 [PTR_TO_XDP_SOCK] = "xdp_sock", 590 [PTR_TO_BTF_ID] = "ptr_", 591 [PTR_TO_MEM] = "mem", 592 [PTR_TO_BUF] = "buf", 593 [PTR_TO_FUNC] = "func", 594 [PTR_TO_MAP_KEY] = "map_key", 595 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 596 }; 597 598 if (type & PTR_MAYBE_NULL) { 599 if (base_type(type) == PTR_TO_BTF_ID) 600 strncpy(postfix, "or_null_", 16); 601 else 602 strncpy(postfix, "_or_null", 16); 603 } 604 605 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 606 type & MEM_RDONLY ? "rdonly_" : "", 607 type & MEM_RINGBUF ? "ringbuf_" : "", 608 type & MEM_USER ? "user_" : "", 609 type & MEM_PERCPU ? "percpu_" : "", 610 type & MEM_RCU ? "rcu_" : "", 611 type & PTR_UNTRUSTED ? "untrusted_" : "", 612 type & PTR_TRUSTED ? "trusted_" : "" 613 ); 614 615 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s", 616 prefix, str[base_type(type)], postfix); 617 return env->type_str_buf; 618 } 619 620 static char slot_type_char[] = { 621 [STACK_INVALID] = '?', 622 [STACK_SPILL] = 'r', 623 [STACK_MISC] = 'm', 624 [STACK_ZERO] = '0', 625 [STACK_DYNPTR] = 'd', 626 }; 627 628 static void print_liveness(struct bpf_verifier_env *env, 629 enum bpf_reg_liveness live) 630 { 631 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 632 verbose(env, "_"); 633 if (live & REG_LIVE_READ) 634 verbose(env, "r"); 635 if (live & REG_LIVE_WRITTEN) 636 verbose(env, "w"); 637 if (live & REG_LIVE_DONE) 638 verbose(env, "D"); 639 } 640 641 static int get_spi(s32 off) 642 { 643 return (-off - 1) / BPF_REG_SIZE; 644 } 645 646 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 647 { 648 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 649 650 /* We need to check that slots between [spi - nr_slots + 1, spi] are 651 * within [0, allocated_stack). 652 * 653 * Please note that the spi grows downwards. For example, a dynptr 654 * takes the size of two stack slots; the first slot will be at 655 * spi and the second slot will be at spi - 1. 656 */ 657 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 658 } 659 660 static struct bpf_func_state *func(struct bpf_verifier_env *env, 661 const struct bpf_reg_state *reg) 662 { 663 struct bpf_verifier_state *cur = env->cur_state; 664 665 return cur->frame[reg->frameno]; 666 } 667 668 static const char *kernel_type_name(const struct btf* btf, u32 id) 669 { 670 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 671 } 672 673 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 674 { 675 env->scratched_regs |= 1U << regno; 676 } 677 678 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 679 { 680 env->scratched_stack_slots |= 1ULL << spi; 681 } 682 683 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 684 { 685 return (env->scratched_regs >> regno) & 1; 686 } 687 688 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 689 { 690 return (env->scratched_stack_slots >> regno) & 1; 691 } 692 693 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 694 { 695 return env->scratched_regs || env->scratched_stack_slots; 696 } 697 698 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 699 { 700 env->scratched_regs = 0U; 701 env->scratched_stack_slots = 0ULL; 702 } 703 704 /* Used for printing the entire verifier state. */ 705 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 706 { 707 env->scratched_regs = ~0U; 708 env->scratched_stack_slots = ~0ULL; 709 } 710 711 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 712 { 713 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 714 case DYNPTR_TYPE_LOCAL: 715 return BPF_DYNPTR_TYPE_LOCAL; 716 case DYNPTR_TYPE_RINGBUF: 717 return BPF_DYNPTR_TYPE_RINGBUF; 718 default: 719 return BPF_DYNPTR_TYPE_INVALID; 720 } 721 } 722 723 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 724 { 725 return type == BPF_DYNPTR_TYPE_RINGBUF; 726 } 727 728 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 729 enum bpf_dynptr_type type, 730 bool first_slot); 731 732 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 733 struct bpf_reg_state *reg); 734 735 static void mark_dynptr_stack_regs(struct bpf_reg_state *sreg1, 736 struct bpf_reg_state *sreg2, 737 enum bpf_dynptr_type type) 738 { 739 __mark_dynptr_reg(sreg1, type, true); 740 __mark_dynptr_reg(sreg2, type, false); 741 } 742 743 static void mark_dynptr_cb_reg(struct bpf_reg_state *reg, 744 enum bpf_dynptr_type type) 745 { 746 __mark_dynptr_reg(reg, type, true); 747 } 748 749 750 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 751 enum bpf_arg_type arg_type, int insn_idx) 752 { 753 struct bpf_func_state *state = func(env, reg); 754 enum bpf_dynptr_type type; 755 int spi, i, id; 756 757 spi = get_spi(reg->off); 758 759 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS)) 760 return -EINVAL; 761 762 for (i = 0; i < BPF_REG_SIZE; i++) { 763 state->stack[spi].slot_type[i] = STACK_DYNPTR; 764 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 765 } 766 767 type = arg_to_dynptr_type(arg_type); 768 if (type == BPF_DYNPTR_TYPE_INVALID) 769 return -EINVAL; 770 771 mark_dynptr_stack_regs(&state->stack[spi].spilled_ptr, 772 &state->stack[spi - 1].spilled_ptr, type); 773 774 if (dynptr_type_refcounted(type)) { 775 /* The id is used to track proper releasing */ 776 id = acquire_reference_state(env, insn_idx); 777 if (id < 0) 778 return id; 779 780 state->stack[spi].spilled_ptr.ref_obj_id = id; 781 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 782 } 783 784 return 0; 785 } 786 787 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 788 { 789 struct bpf_func_state *state = func(env, reg); 790 int spi, i; 791 792 spi = get_spi(reg->off); 793 794 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS)) 795 return -EINVAL; 796 797 for (i = 0; i < BPF_REG_SIZE; i++) { 798 state->stack[spi].slot_type[i] = STACK_INVALID; 799 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 800 } 801 802 /* Invalidate any slices associated with this dynptr */ 803 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) 804 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id)); 805 806 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 807 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 808 return 0; 809 } 810 811 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 812 { 813 struct bpf_func_state *state = func(env, reg); 814 int spi, i; 815 816 if (reg->type == CONST_PTR_TO_DYNPTR) 817 return false; 818 819 spi = get_spi(reg->off); 820 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS)) 821 return true; 822 823 for (i = 0; i < BPF_REG_SIZE; i++) { 824 if (state->stack[spi].slot_type[i] == STACK_DYNPTR || 825 state->stack[spi - 1].slot_type[i] == STACK_DYNPTR) 826 return false; 827 } 828 829 return true; 830 } 831 832 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 833 { 834 struct bpf_func_state *state = func(env, reg); 835 int spi; 836 int i; 837 838 /* This already represents first slot of initialized bpf_dynptr */ 839 if (reg->type == CONST_PTR_TO_DYNPTR) 840 return true; 841 842 spi = get_spi(reg->off); 843 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) || 844 !state->stack[spi].spilled_ptr.dynptr.first_slot) 845 return false; 846 847 for (i = 0; i < BPF_REG_SIZE; i++) { 848 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 849 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 850 return false; 851 } 852 853 return true; 854 } 855 856 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 857 enum bpf_arg_type arg_type) 858 { 859 struct bpf_func_state *state = func(env, reg); 860 enum bpf_dynptr_type dynptr_type; 861 int spi; 862 863 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 864 if (arg_type == ARG_PTR_TO_DYNPTR) 865 return true; 866 867 dynptr_type = arg_to_dynptr_type(arg_type); 868 if (reg->type == CONST_PTR_TO_DYNPTR) { 869 return reg->dynptr.type == dynptr_type; 870 } else { 871 spi = get_spi(reg->off); 872 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 873 } 874 } 875 876 /* The reg state of a pointer or a bounded scalar was saved when 877 * it was spilled to the stack. 878 */ 879 static bool is_spilled_reg(const struct bpf_stack_state *stack) 880 { 881 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 882 } 883 884 static void scrub_spilled_slot(u8 *stype) 885 { 886 if (*stype != STACK_INVALID) 887 *stype = STACK_MISC; 888 } 889 890 static void print_verifier_state(struct bpf_verifier_env *env, 891 const struct bpf_func_state *state, 892 bool print_all) 893 { 894 const struct bpf_reg_state *reg; 895 enum bpf_reg_type t; 896 int i; 897 898 if (state->frameno) 899 verbose(env, " frame%d:", state->frameno); 900 for (i = 0; i < MAX_BPF_REG; i++) { 901 reg = &state->regs[i]; 902 t = reg->type; 903 if (t == NOT_INIT) 904 continue; 905 if (!print_all && !reg_scratched(env, i)) 906 continue; 907 verbose(env, " R%d", i); 908 print_liveness(env, reg->live); 909 verbose(env, "="); 910 if (t == SCALAR_VALUE && reg->precise) 911 verbose(env, "P"); 912 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 913 tnum_is_const(reg->var_off)) { 914 /* reg->off should be 0 for SCALAR_VALUE */ 915 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 916 verbose(env, "%lld", reg->var_off.value + reg->off); 917 } else { 918 const char *sep = ""; 919 920 verbose(env, "%s", reg_type_str(env, t)); 921 if (base_type(t) == PTR_TO_BTF_ID) 922 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id)); 923 verbose(env, "("); 924 /* 925 * _a stands for append, was shortened to avoid multiline statements below. 926 * This macro is used to output a comma separated list of attributes. 927 */ 928 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 929 930 if (reg->id) 931 verbose_a("id=%d", reg->id); 932 if (reg->ref_obj_id) 933 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 934 if (t != SCALAR_VALUE) 935 verbose_a("off=%d", reg->off); 936 if (type_is_pkt_pointer(t)) 937 verbose_a("r=%d", reg->range); 938 else if (base_type(t) == CONST_PTR_TO_MAP || 939 base_type(t) == PTR_TO_MAP_KEY || 940 base_type(t) == PTR_TO_MAP_VALUE) 941 verbose_a("ks=%d,vs=%d", 942 reg->map_ptr->key_size, 943 reg->map_ptr->value_size); 944 if (tnum_is_const(reg->var_off)) { 945 /* Typically an immediate SCALAR_VALUE, but 946 * could be a pointer whose offset is too big 947 * for reg->off 948 */ 949 verbose_a("imm=%llx", reg->var_off.value); 950 } else { 951 if (reg->smin_value != reg->umin_value && 952 reg->smin_value != S64_MIN) 953 verbose_a("smin=%lld", (long long)reg->smin_value); 954 if (reg->smax_value != reg->umax_value && 955 reg->smax_value != S64_MAX) 956 verbose_a("smax=%lld", (long long)reg->smax_value); 957 if (reg->umin_value != 0) 958 verbose_a("umin=%llu", (unsigned long long)reg->umin_value); 959 if (reg->umax_value != U64_MAX) 960 verbose_a("umax=%llu", (unsigned long long)reg->umax_value); 961 if (!tnum_is_unknown(reg->var_off)) { 962 char tn_buf[48]; 963 964 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 965 verbose_a("var_off=%s", tn_buf); 966 } 967 if (reg->s32_min_value != reg->smin_value && 968 reg->s32_min_value != S32_MIN) 969 verbose_a("s32_min=%d", (int)(reg->s32_min_value)); 970 if (reg->s32_max_value != reg->smax_value && 971 reg->s32_max_value != S32_MAX) 972 verbose_a("s32_max=%d", (int)(reg->s32_max_value)); 973 if (reg->u32_min_value != reg->umin_value && 974 reg->u32_min_value != U32_MIN) 975 verbose_a("u32_min=%d", (int)(reg->u32_min_value)); 976 if (reg->u32_max_value != reg->umax_value && 977 reg->u32_max_value != U32_MAX) 978 verbose_a("u32_max=%d", (int)(reg->u32_max_value)); 979 } 980 #undef verbose_a 981 982 verbose(env, ")"); 983 } 984 } 985 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 986 char types_buf[BPF_REG_SIZE + 1]; 987 bool valid = false; 988 int j; 989 990 for (j = 0; j < BPF_REG_SIZE; j++) { 991 if (state->stack[i].slot_type[j] != STACK_INVALID) 992 valid = true; 993 types_buf[j] = slot_type_char[ 994 state->stack[i].slot_type[j]]; 995 } 996 types_buf[BPF_REG_SIZE] = 0; 997 if (!valid) 998 continue; 999 if (!print_all && !stack_slot_scratched(env, i)) 1000 continue; 1001 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1002 print_liveness(env, state->stack[i].spilled_ptr.live); 1003 if (is_spilled_reg(&state->stack[i])) { 1004 reg = &state->stack[i].spilled_ptr; 1005 t = reg->type; 1006 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1007 if (t == SCALAR_VALUE && reg->precise) 1008 verbose(env, "P"); 1009 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1010 verbose(env, "%lld", reg->var_off.value + reg->off); 1011 } else { 1012 verbose(env, "=%s", types_buf); 1013 } 1014 } 1015 if (state->acquired_refs && state->refs[0].id) { 1016 verbose(env, " refs=%d", state->refs[0].id); 1017 for (i = 1; i < state->acquired_refs; i++) 1018 if (state->refs[i].id) 1019 verbose(env, ",%d", state->refs[i].id); 1020 } 1021 if (state->in_callback_fn) 1022 verbose(env, " cb"); 1023 if (state->in_async_callback_fn) 1024 verbose(env, " async_cb"); 1025 verbose(env, "\n"); 1026 mark_verifier_state_clean(env); 1027 } 1028 1029 static inline u32 vlog_alignment(u32 pos) 1030 { 1031 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1032 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1033 } 1034 1035 static void print_insn_state(struct bpf_verifier_env *env, 1036 const struct bpf_func_state *state) 1037 { 1038 if (env->prev_log_len && env->prev_log_len == env->log.len_used) { 1039 /* remove new line character */ 1040 bpf_vlog_reset(&env->log, env->prev_log_len - 1); 1041 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' '); 1042 } else { 1043 verbose(env, "%d:", env->insn_idx); 1044 } 1045 print_verifier_state(env, state, false); 1046 } 1047 1048 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1049 * small to hold src. This is different from krealloc since we don't want to preserve 1050 * the contents of dst. 1051 * 1052 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1053 * not be allocated. 1054 */ 1055 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1056 { 1057 size_t alloc_bytes; 1058 void *orig = dst; 1059 size_t bytes; 1060 1061 if (ZERO_OR_NULL_PTR(src)) 1062 goto out; 1063 1064 if (unlikely(check_mul_overflow(n, size, &bytes))) 1065 return NULL; 1066 1067 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1068 dst = krealloc(orig, alloc_bytes, flags); 1069 if (!dst) { 1070 kfree(orig); 1071 return NULL; 1072 } 1073 1074 memcpy(dst, src, bytes); 1075 out: 1076 return dst ? dst : ZERO_SIZE_PTR; 1077 } 1078 1079 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1080 * small to hold new_n items. new items are zeroed out if the array grows. 1081 * 1082 * Contrary to krealloc_array, does not free arr if new_n is zero. 1083 */ 1084 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1085 { 1086 size_t alloc_size; 1087 void *new_arr; 1088 1089 if (!new_n || old_n == new_n) 1090 goto out; 1091 1092 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1093 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1094 if (!new_arr) { 1095 kfree(arr); 1096 return NULL; 1097 } 1098 arr = new_arr; 1099 1100 if (new_n > old_n) 1101 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1102 1103 out: 1104 return arr ? arr : ZERO_SIZE_PTR; 1105 } 1106 1107 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1108 { 1109 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1110 sizeof(struct bpf_reference_state), GFP_KERNEL); 1111 if (!dst->refs) 1112 return -ENOMEM; 1113 1114 dst->acquired_refs = src->acquired_refs; 1115 return 0; 1116 } 1117 1118 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1119 { 1120 size_t n = src->allocated_stack / BPF_REG_SIZE; 1121 1122 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1123 GFP_KERNEL); 1124 if (!dst->stack) 1125 return -ENOMEM; 1126 1127 dst->allocated_stack = src->allocated_stack; 1128 return 0; 1129 } 1130 1131 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1132 { 1133 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1134 sizeof(struct bpf_reference_state)); 1135 if (!state->refs) 1136 return -ENOMEM; 1137 1138 state->acquired_refs = n; 1139 return 0; 1140 } 1141 1142 static int grow_stack_state(struct bpf_func_state *state, int size) 1143 { 1144 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1145 1146 if (old_n >= n) 1147 return 0; 1148 1149 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1150 if (!state->stack) 1151 return -ENOMEM; 1152 1153 state->allocated_stack = size; 1154 return 0; 1155 } 1156 1157 /* Acquire a pointer id from the env and update the state->refs to include 1158 * this new pointer reference. 1159 * On success, returns a valid pointer id to associate with the register 1160 * On failure, returns a negative errno. 1161 */ 1162 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1163 { 1164 struct bpf_func_state *state = cur_func(env); 1165 int new_ofs = state->acquired_refs; 1166 int id, err; 1167 1168 err = resize_reference_state(state, state->acquired_refs + 1); 1169 if (err) 1170 return err; 1171 id = ++env->id_gen; 1172 state->refs[new_ofs].id = id; 1173 state->refs[new_ofs].insn_idx = insn_idx; 1174 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1175 1176 return id; 1177 } 1178 1179 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1180 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1181 { 1182 int i, last_idx; 1183 1184 last_idx = state->acquired_refs - 1; 1185 for (i = 0; i < state->acquired_refs; i++) { 1186 if (state->refs[i].id == ptr_id) { 1187 /* Cannot release caller references in callbacks */ 1188 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1189 return -EINVAL; 1190 if (last_idx && i != last_idx) 1191 memcpy(&state->refs[i], &state->refs[last_idx], 1192 sizeof(*state->refs)); 1193 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1194 state->acquired_refs--; 1195 return 0; 1196 } 1197 } 1198 return -EINVAL; 1199 } 1200 1201 static void free_func_state(struct bpf_func_state *state) 1202 { 1203 if (!state) 1204 return; 1205 kfree(state->refs); 1206 kfree(state->stack); 1207 kfree(state); 1208 } 1209 1210 static void clear_jmp_history(struct bpf_verifier_state *state) 1211 { 1212 kfree(state->jmp_history); 1213 state->jmp_history = NULL; 1214 state->jmp_history_cnt = 0; 1215 } 1216 1217 static void free_verifier_state(struct bpf_verifier_state *state, 1218 bool free_self) 1219 { 1220 int i; 1221 1222 for (i = 0; i <= state->curframe; i++) { 1223 free_func_state(state->frame[i]); 1224 state->frame[i] = NULL; 1225 } 1226 clear_jmp_history(state); 1227 if (free_self) 1228 kfree(state); 1229 } 1230 1231 /* copy verifier state from src to dst growing dst stack space 1232 * when necessary to accommodate larger src stack 1233 */ 1234 static int copy_func_state(struct bpf_func_state *dst, 1235 const struct bpf_func_state *src) 1236 { 1237 int err; 1238 1239 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1240 err = copy_reference_state(dst, src); 1241 if (err) 1242 return err; 1243 return copy_stack_state(dst, src); 1244 } 1245 1246 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1247 const struct bpf_verifier_state *src) 1248 { 1249 struct bpf_func_state *dst; 1250 int i, err; 1251 1252 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1253 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1254 GFP_USER); 1255 if (!dst_state->jmp_history) 1256 return -ENOMEM; 1257 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1258 1259 /* if dst has more stack frames then src frame, free them */ 1260 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1261 free_func_state(dst_state->frame[i]); 1262 dst_state->frame[i] = NULL; 1263 } 1264 dst_state->speculative = src->speculative; 1265 dst_state->active_rcu_lock = src->active_rcu_lock; 1266 dst_state->curframe = src->curframe; 1267 dst_state->active_lock.ptr = src->active_lock.ptr; 1268 dst_state->active_lock.id = src->active_lock.id; 1269 dst_state->branches = src->branches; 1270 dst_state->parent = src->parent; 1271 dst_state->first_insn_idx = src->first_insn_idx; 1272 dst_state->last_insn_idx = src->last_insn_idx; 1273 for (i = 0; i <= src->curframe; i++) { 1274 dst = dst_state->frame[i]; 1275 if (!dst) { 1276 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1277 if (!dst) 1278 return -ENOMEM; 1279 dst_state->frame[i] = dst; 1280 } 1281 err = copy_func_state(dst, src->frame[i]); 1282 if (err) 1283 return err; 1284 } 1285 return 0; 1286 } 1287 1288 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1289 { 1290 while (st) { 1291 u32 br = --st->branches; 1292 1293 /* WARN_ON(br > 1) technically makes sense here, 1294 * but see comment in push_stack(), hence: 1295 */ 1296 WARN_ONCE((int)br < 0, 1297 "BUG update_branch_counts:branches_to_explore=%d\n", 1298 br); 1299 if (br) 1300 break; 1301 st = st->parent; 1302 } 1303 } 1304 1305 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1306 int *insn_idx, bool pop_log) 1307 { 1308 struct bpf_verifier_state *cur = env->cur_state; 1309 struct bpf_verifier_stack_elem *elem, *head = env->head; 1310 int err; 1311 1312 if (env->head == NULL) 1313 return -ENOENT; 1314 1315 if (cur) { 1316 err = copy_verifier_state(cur, &head->st); 1317 if (err) 1318 return err; 1319 } 1320 if (pop_log) 1321 bpf_vlog_reset(&env->log, head->log_pos); 1322 if (insn_idx) 1323 *insn_idx = head->insn_idx; 1324 if (prev_insn_idx) 1325 *prev_insn_idx = head->prev_insn_idx; 1326 elem = head->next; 1327 free_verifier_state(&head->st, false); 1328 kfree(head); 1329 env->head = elem; 1330 env->stack_size--; 1331 return 0; 1332 } 1333 1334 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1335 int insn_idx, int prev_insn_idx, 1336 bool speculative) 1337 { 1338 struct bpf_verifier_state *cur = env->cur_state; 1339 struct bpf_verifier_stack_elem *elem; 1340 int err; 1341 1342 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1343 if (!elem) 1344 goto err; 1345 1346 elem->insn_idx = insn_idx; 1347 elem->prev_insn_idx = prev_insn_idx; 1348 elem->next = env->head; 1349 elem->log_pos = env->log.len_used; 1350 env->head = elem; 1351 env->stack_size++; 1352 err = copy_verifier_state(&elem->st, cur); 1353 if (err) 1354 goto err; 1355 elem->st.speculative |= speculative; 1356 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1357 verbose(env, "The sequence of %d jumps is too complex.\n", 1358 env->stack_size); 1359 goto err; 1360 } 1361 if (elem->st.parent) { 1362 ++elem->st.parent->branches; 1363 /* WARN_ON(branches > 2) technically makes sense here, 1364 * but 1365 * 1. speculative states will bump 'branches' for non-branch 1366 * instructions 1367 * 2. is_state_visited() heuristics may decide not to create 1368 * a new state for a sequence of branches and all such current 1369 * and cloned states will be pointing to a single parent state 1370 * which might have large 'branches' count. 1371 */ 1372 } 1373 return &elem->st; 1374 err: 1375 free_verifier_state(env->cur_state, true); 1376 env->cur_state = NULL; 1377 /* pop all elements and return */ 1378 while (!pop_stack(env, NULL, NULL, false)); 1379 return NULL; 1380 } 1381 1382 #define CALLER_SAVED_REGS 6 1383 static const int caller_saved[CALLER_SAVED_REGS] = { 1384 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1385 }; 1386 1387 /* This helper doesn't clear reg->id */ 1388 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1389 { 1390 reg->var_off = tnum_const(imm); 1391 reg->smin_value = (s64)imm; 1392 reg->smax_value = (s64)imm; 1393 reg->umin_value = imm; 1394 reg->umax_value = imm; 1395 1396 reg->s32_min_value = (s32)imm; 1397 reg->s32_max_value = (s32)imm; 1398 reg->u32_min_value = (u32)imm; 1399 reg->u32_max_value = (u32)imm; 1400 } 1401 1402 /* Mark the unknown part of a register (variable offset or scalar value) as 1403 * known to have the value @imm. 1404 */ 1405 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1406 { 1407 /* Clear id, off, and union(map_ptr, range) */ 1408 memset(((u8 *)reg) + sizeof(reg->type), 0, 1409 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1410 ___mark_reg_known(reg, imm); 1411 } 1412 1413 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1414 { 1415 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1416 reg->s32_min_value = (s32)imm; 1417 reg->s32_max_value = (s32)imm; 1418 reg->u32_min_value = (u32)imm; 1419 reg->u32_max_value = (u32)imm; 1420 } 1421 1422 /* Mark the 'variable offset' part of a register as zero. This should be 1423 * used only on registers holding a pointer type. 1424 */ 1425 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1426 { 1427 __mark_reg_known(reg, 0); 1428 } 1429 1430 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1431 { 1432 __mark_reg_known(reg, 0); 1433 reg->type = SCALAR_VALUE; 1434 } 1435 1436 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1437 struct bpf_reg_state *regs, u32 regno) 1438 { 1439 if (WARN_ON(regno >= MAX_BPF_REG)) { 1440 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1441 /* Something bad happened, let's kill all regs */ 1442 for (regno = 0; regno < MAX_BPF_REG; regno++) 1443 __mark_reg_not_init(env, regs + regno); 1444 return; 1445 } 1446 __mark_reg_known_zero(regs + regno); 1447 } 1448 1449 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1450 bool first_slot) 1451 { 1452 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1453 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1454 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1455 */ 1456 __mark_reg_known_zero(reg); 1457 reg->type = CONST_PTR_TO_DYNPTR; 1458 reg->dynptr.type = type; 1459 reg->dynptr.first_slot = first_slot; 1460 } 1461 1462 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1463 { 1464 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1465 const struct bpf_map *map = reg->map_ptr; 1466 1467 if (map->inner_map_meta) { 1468 reg->type = CONST_PTR_TO_MAP; 1469 reg->map_ptr = map->inner_map_meta; 1470 /* transfer reg's id which is unique for every map_lookup_elem 1471 * as UID of the inner map. 1472 */ 1473 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1474 reg->map_uid = reg->id; 1475 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1476 reg->type = PTR_TO_XDP_SOCK; 1477 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1478 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1479 reg->type = PTR_TO_SOCKET; 1480 } else { 1481 reg->type = PTR_TO_MAP_VALUE; 1482 } 1483 return; 1484 } 1485 1486 reg->type &= ~PTR_MAYBE_NULL; 1487 } 1488 1489 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1490 { 1491 return type_is_pkt_pointer(reg->type); 1492 } 1493 1494 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1495 { 1496 return reg_is_pkt_pointer(reg) || 1497 reg->type == PTR_TO_PACKET_END; 1498 } 1499 1500 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1501 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1502 enum bpf_reg_type which) 1503 { 1504 /* The register can already have a range from prior markings. 1505 * This is fine as long as it hasn't been advanced from its 1506 * origin. 1507 */ 1508 return reg->type == which && 1509 reg->id == 0 && 1510 reg->off == 0 && 1511 tnum_equals_const(reg->var_off, 0); 1512 } 1513 1514 /* Reset the min/max bounds of a register */ 1515 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1516 { 1517 reg->smin_value = S64_MIN; 1518 reg->smax_value = S64_MAX; 1519 reg->umin_value = 0; 1520 reg->umax_value = U64_MAX; 1521 1522 reg->s32_min_value = S32_MIN; 1523 reg->s32_max_value = S32_MAX; 1524 reg->u32_min_value = 0; 1525 reg->u32_max_value = U32_MAX; 1526 } 1527 1528 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1529 { 1530 reg->smin_value = S64_MIN; 1531 reg->smax_value = S64_MAX; 1532 reg->umin_value = 0; 1533 reg->umax_value = U64_MAX; 1534 } 1535 1536 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1537 { 1538 reg->s32_min_value = S32_MIN; 1539 reg->s32_max_value = S32_MAX; 1540 reg->u32_min_value = 0; 1541 reg->u32_max_value = U32_MAX; 1542 } 1543 1544 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1545 { 1546 struct tnum var32_off = tnum_subreg(reg->var_off); 1547 1548 /* min signed is max(sign bit) | min(other bits) */ 1549 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1550 var32_off.value | (var32_off.mask & S32_MIN)); 1551 /* max signed is min(sign bit) | max(other bits) */ 1552 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1553 var32_off.value | (var32_off.mask & S32_MAX)); 1554 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1555 reg->u32_max_value = min(reg->u32_max_value, 1556 (u32)(var32_off.value | var32_off.mask)); 1557 } 1558 1559 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1560 { 1561 /* min signed is max(sign bit) | min(other bits) */ 1562 reg->smin_value = max_t(s64, reg->smin_value, 1563 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1564 /* max signed is min(sign bit) | max(other bits) */ 1565 reg->smax_value = min_t(s64, reg->smax_value, 1566 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1567 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1568 reg->umax_value = min(reg->umax_value, 1569 reg->var_off.value | reg->var_off.mask); 1570 } 1571 1572 static void __update_reg_bounds(struct bpf_reg_state *reg) 1573 { 1574 __update_reg32_bounds(reg); 1575 __update_reg64_bounds(reg); 1576 } 1577 1578 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1579 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1580 { 1581 /* Learn sign from signed bounds. 1582 * If we cannot cross the sign boundary, then signed and unsigned bounds 1583 * are the same, so combine. This works even in the negative case, e.g. 1584 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1585 */ 1586 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 1587 reg->s32_min_value = reg->u32_min_value = 1588 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1589 reg->s32_max_value = reg->u32_max_value = 1590 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1591 return; 1592 } 1593 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1594 * boundary, so we must be careful. 1595 */ 1596 if ((s32)reg->u32_max_value >= 0) { 1597 /* Positive. We can't learn anything from the smin, but smax 1598 * is positive, hence safe. 1599 */ 1600 reg->s32_min_value = reg->u32_min_value; 1601 reg->s32_max_value = reg->u32_max_value = 1602 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1603 } else if ((s32)reg->u32_min_value < 0) { 1604 /* Negative. We can't learn anything from the smax, but smin 1605 * is negative, hence safe. 1606 */ 1607 reg->s32_min_value = reg->u32_min_value = 1608 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1609 reg->s32_max_value = reg->u32_max_value; 1610 } 1611 } 1612 1613 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 1614 { 1615 /* Learn sign from signed bounds. 1616 * If we cannot cross the sign boundary, then signed and unsigned bounds 1617 * are the same, so combine. This works even in the negative case, e.g. 1618 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1619 */ 1620 if (reg->smin_value >= 0 || reg->smax_value < 0) { 1621 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1622 reg->umin_value); 1623 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1624 reg->umax_value); 1625 return; 1626 } 1627 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1628 * boundary, so we must be careful. 1629 */ 1630 if ((s64)reg->umax_value >= 0) { 1631 /* Positive. We can't learn anything from the smin, but smax 1632 * is positive, hence safe. 1633 */ 1634 reg->smin_value = reg->umin_value; 1635 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1636 reg->umax_value); 1637 } else if ((s64)reg->umin_value < 0) { 1638 /* Negative. We can't learn anything from the smax, but smin 1639 * is negative, hence safe. 1640 */ 1641 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1642 reg->umin_value); 1643 reg->smax_value = reg->umax_value; 1644 } 1645 } 1646 1647 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 1648 { 1649 __reg32_deduce_bounds(reg); 1650 __reg64_deduce_bounds(reg); 1651 } 1652 1653 /* Attempts to improve var_off based on unsigned min/max information */ 1654 static void __reg_bound_offset(struct bpf_reg_state *reg) 1655 { 1656 struct tnum var64_off = tnum_intersect(reg->var_off, 1657 tnum_range(reg->umin_value, 1658 reg->umax_value)); 1659 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off), 1660 tnum_range(reg->u32_min_value, 1661 reg->u32_max_value)); 1662 1663 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 1664 } 1665 1666 static void reg_bounds_sync(struct bpf_reg_state *reg) 1667 { 1668 /* We might have learned new bounds from the var_off. */ 1669 __update_reg_bounds(reg); 1670 /* We might have learned something about the sign bit. */ 1671 __reg_deduce_bounds(reg); 1672 /* We might have learned some bits from the bounds. */ 1673 __reg_bound_offset(reg); 1674 /* Intersecting with the old var_off might have improved our bounds 1675 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1676 * then new var_off is (0; 0x7f...fc) which improves our umax. 1677 */ 1678 __update_reg_bounds(reg); 1679 } 1680 1681 static bool __reg32_bound_s64(s32 a) 1682 { 1683 return a >= 0 && a <= S32_MAX; 1684 } 1685 1686 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 1687 { 1688 reg->umin_value = reg->u32_min_value; 1689 reg->umax_value = reg->u32_max_value; 1690 1691 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 1692 * be positive otherwise set to worse case bounds and refine later 1693 * from tnum. 1694 */ 1695 if (__reg32_bound_s64(reg->s32_min_value) && 1696 __reg32_bound_s64(reg->s32_max_value)) { 1697 reg->smin_value = reg->s32_min_value; 1698 reg->smax_value = reg->s32_max_value; 1699 } else { 1700 reg->smin_value = 0; 1701 reg->smax_value = U32_MAX; 1702 } 1703 } 1704 1705 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 1706 { 1707 /* special case when 64-bit register has upper 32-bit register 1708 * zeroed. Typically happens after zext or <<32, >>32 sequence 1709 * allowing us to use 32-bit bounds directly, 1710 */ 1711 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 1712 __reg_assign_32_into_64(reg); 1713 } else { 1714 /* Otherwise the best we can do is push lower 32bit known and 1715 * unknown bits into register (var_off set from jmp logic) 1716 * then learn as much as possible from the 64-bit tnum 1717 * known and unknown bits. The previous smin/smax bounds are 1718 * invalid here because of jmp32 compare so mark them unknown 1719 * so they do not impact tnum bounds calculation. 1720 */ 1721 __mark_reg64_unbounded(reg); 1722 } 1723 reg_bounds_sync(reg); 1724 } 1725 1726 static bool __reg64_bound_s32(s64 a) 1727 { 1728 return a >= S32_MIN && a <= S32_MAX; 1729 } 1730 1731 static bool __reg64_bound_u32(u64 a) 1732 { 1733 return a >= U32_MIN && a <= U32_MAX; 1734 } 1735 1736 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 1737 { 1738 __mark_reg32_unbounded(reg); 1739 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 1740 reg->s32_min_value = (s32)reg->smin_value; 1741 reg->s32_max_value = (s32)reg->smax_value; 1742 } 1743 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 1744 reg->u32_min_value = (u32)reg->umin_value; 1745 reg->u32_max_value = (u32)reg->umax_value; 1746 } 1747 reg_bounds_sync(reg); 1748 } 1749 1750 /* Mark a register as having a completely unknown (scalar) value. */ 1751 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1752 struct bpf_reg_state *reg) 1753 { 1754 /* 1755 * Clear type, id, off, and union(map_ptr, range) and 1756 * padding between 'type' and union 1757 */ 1758 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 1759 reg->type = SCALAR_VALUE; 1760 reg->var_off = tnum_unknown; 1761 reg->frameno = 0; 1762 reg->precise = !env->bpf_capable; 1763 __mark_reg_unbounded(reg); 1764 } 1765 1766 static void mark_reg_unknown(struct bpf_verifier_env *env, 1767 struct bpf_reg_state *regs, u32 regno) 1768 { 1769 if (WARN_ON(regno >= MAX_BPF_REG)) { 1770 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 1771 /* Something bad happened, let's kill all regs except FP */ 1772 for (regno = 0; regno < BPF_REG_FP; regno++) 1773 __mark_reg_not_init(env, regs + regno); 1774 return; 1775 } 1776 __mark_reg_unknown(env, regs + regno); 1777 } 1778 1779 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1780 struct bpf_reg_state *reg) 1781 { 1782 __mark_reg_unknown(env, reg); 1783 reg->type = NOT_INIT; 1784 } 1785 1786 static void mark_reg_not_init(struct bpf_verifier_env *env, 1787 struct bpf_reg_state *regs, u32 regno) 1788 { 1789 if (WARN_ON(regno >= MAX_BPF_REG)) { 1790 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 1791 /* Something bad happened, let's kill all regs except FP */ 1792 for (regno = 0; regno < BPF_REG_FP; regno++) 1793 __mark_reg_not_init(env, regs + regno); 1794 return; 1795 } 1796 __mark_reg_not_init(env, regs + regno); 1797 } 1798 1799 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 1800 struct bpf_reg_state *regs, u32 regno, 1801 enum bpf_reg_type reg_type, 1802 struct btf *btf, u32 btf_id, 1803 enum bpf_type_flag flag) 1804 { 1805 if (reg_type == SCALAR_VALUE) { 1806 mark_reg_unknown(env, regs, regno); 1807 return; 1808 } 1809 mark_reg_known_zero(env, regs, regno); 1810 regs[regno].type = PTR_TO_BTF_ID | flag; 1811 regs[regno].btf = btf; 1812 regs[regno].btf_id = btf_id; 1813 } 1814 1815 #define DEF_NOT_SUBREG (0) 1816 static void init_reg_state(struct bpf_verifier_env *env, 1817 struct bpf_func_state *state) 1818 { 1819 struct bpf_reg_state *regs = state->regs; 1820 int i; 1821 1822 for (i = 0; i < MAX_BPF_REG; i++) { 1823 mark_reg_not_init(env, regs, i); 1824 regs[i].live = REG_LIVE_NONE; 1825 regs[i].parent = NULL; 1826 regs[i].subreg_def = DEF_NOT_SUBREG; 1827 } 1828 1829 /* frame pointer */ 1830 regs[BPF_REG_FP].type = PTR_TO_STACK; 1831 mark_reg_known_zero(env, regs, BPF_REG_FP); 1832 regs[BPF_REG_FP].frameno = state->frameno; 1833 } 1834 1835 #define BPF_MAIN_FUNC (-1) 1836 static void init_func_state(struct bpf_verifier_env *env, 1837 struct bpf_func_state *state, 1838 int callsite, int frameno, int subprogno) 1839 { 1840 state->callsite = callsite; 1841 state->frameno = frameno; 1842 state->subprogno = subprogno; 1843 state->callback_ret_range = tnum_range(0, 0); 1844 init_reg_state(env, state); 1845 mark_verifier_state_scratched(env); 1846 } 1847 1848 /* Similar to push_stack(), but for async callbacks */ 1849 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 1850 int insn_idx, int prev_insn_idx, 1851 int subprog) 1852 { 1853 struct bpf_verifier_stack_elem *elem; 1854 struct bpf_func_state *frame; 1855 1856 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1857 if (!elem) 1858 goto err; 1859 1860 elem->insn_idx = insn_idx; 1861 elem->prev_insn_idx = prev_insn_idx; 1862 elem->next = env->head; 1863 elem->log_pos = env->log.len_used; 1864 env->head = elem; 1865 env->stack_size++; 1866 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1867 verbose(env, 1868 "The sequence of %d jumps is too complex for async cb.\n", 1869 env->stack_size); 1870 goto err; 1871 } 1872 /* Unlike push_stack() do not copy_verifier_state(). 1873 * The caller state doesn't matter. 1874 * This is async callback. It starts in a fresh stack. 1875 * Initialize it similar to do_check_common(). 1876 */ 1877 elem->st.branches = 1; 1878 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 1879 if (!frame) 1880 goto err; 1881 init_func_state(env, frame, 1882 BPF_MAIN_FUNC /* callsite */, 1883 0 /* frameno within this callchain */, 1884 subprog /* subprog number within this prog */); 1885 elem->st.frame[0] = frame; 1886 return &elem->st; 1887 err: 1888 free_verifier_state(env->cur_state, true); 1889 env->cur_state = NULL; 1890 /* pop all elements and return */ 1891 while (!pop_stack(env, NULL, NULL, false)); 1892 return NULL; 1893 } 1894 1895 1896 enum reg_arg_type { 1897 SRC_OP, /* register is used as source operand */ 1898 DST_OP, /* register is used as destination operand */ 1899 DST_OP_NO_MARK /* same as above, check only, don't mark */ 1900 }; 1901 1902 static int cmp_subprogs(const void *a, const void *b) 1903 { 1904 return ((struct bpf_subprog_info *)a)->start - 1905 ((struct bpf_subprog_info *)b)->start; 1906 } 1907 1908 static int find_subprog(struct bpf_verifier_env *env, int off) 1909 { 1910 struct bpf_subprog_info *p; 1911 1912 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 1913 sizeof(env->subprog_info[0]), cmp_subprogs); 1914 if (!p) 1915 return -ENOENT; 1916 return p - env->subprog_info; 1917 1918 } 1919 1920 static int add_subprog(struct bpf_verifier_env *env, int off) 1921 { 1922 int insn_cnt = env->prog->len; 1923 int ret; 1924 1925 if (off >= insn_cnt || off < 0) { 1926 verbose(env, "call to invalid destination\n"); 1927 return -EINVAL; 1928 } 1929 ret = find_subprog(env, off); 1930 if (ret >= 0) 1931 return ret; 1932 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 1933 verbose(env, "too many subprograms\n"); 1934 return -E2BIG; 1935 } 1936 /* determine subprog starts. The end is one before the next starts */ 1937 env->subprog_info[env->subprog_cnt++].start = off; 1938 sort(env->subprog_info, env->subprog_cnt, 1939 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 1940 return env->subprog_cnt - 1; 1941 } 1942 1943 #define MAX_KFUNC_DESCS 256 1944 #define MAX_KFUNC_BTFS 256 1945 1946 struct bpf_kfunc_desc { 1947 struct btf_func_model func_model; 1948 u32 func_id; 1949 s32 imm; 1950 u16 offset; 1951 }; 1952 1953 struct bpf_kfunc_btf { 1954 struct btf *btf; 1955 struct module *module; 1956 u16 offset; 1957 }; 1958 1959 struct bpf_kfunc_desc_tab { 1960 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 1961 u32 nr_descs; 1962 }; 1963 1964 struct bpf_kfunc_btf_tab { 1965 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 1966 u32 nr_descs; 1967 }; 1968 1969 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 1970 { 1971 const struct bpf_kfunc_desc *d0 = a; 1972 const struct bpf_kfunc_desc *d1 = b; 1973 1974 /* func_id is not greater than BTF_MAX_TYPE */ 1975 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 1976 } 1977 1978 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 1979 { 1980 const struct bpf_kfunc_btf *d0 = a; 1981 const struct bpf_kfunc_btf *d1 = b; 1982 1983 return d0->offset - d1->offset; 1984 } 1985 1986 static const struct bpf_kfunc_desc * 1987 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 1988 { 1989 struct bpf_kfunc_desc desc = { 1990 .func_id = func_id, 1991 .offset = offset, 1992 }; 1993 struct bpf_kfunc_desc_tab *tab; 1994 1995 tab = prog->aux->kfunc_tab; 1996 return bsearch(&desc, tab->descs, tab->nr_descs, 1997 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 1998 } 1999 2000 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2001 s16 offset) 2002 { 2003 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2004 struct bpf_kfunc_btf_tab *tab; 2005 struct bpf_kfunc_btf *b; 2006 struct module *mod; 2007 struct btf *btf; 2008 int btf_fd; 2009 2010 tab = env->prog->aux->kfunc_btf_tab; 2011 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2012 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2013 if (!b) { 2014 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2015 verbose(env, "too many different module BTFs\n"); 2016 return ERR_PTR(-E2BIG); 2017 } 2018 2019 if (bpfptr_is_null(env->fd_array)) { 2020 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2021 return ERR_PTR(-EPROTO); 2022 } 2023 2024 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2025 offset * sizeof(btf_fd), 2026 sizeof(btf_fd))) 2027 return ERR_PTR(-EFAULT); 2028 2029 btf = btf_get_by_fd(btf_fd); 2030 if (IS_ERR(btf)) { 2031 verbose(env, "invalid module BTF fd specified\n"); 2032 return btf; 2033 } 2034 2035 if (!btf_is_module(btf)) { 2036 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2037 btf_put(btf); 2038 return ERR_PTR(-EINVAL); 2039 } 2040 2041 mod = btf_try_get_module(btf); 2042 if (!mod) { 2043 btf_put(btf); 2044 return ERR_PTR(-ENXIO); 2045 } 2046 2047 b = &tab->descs[tab->nr_descs++]; 2048 b->btf = btf; 2049 b->module = mod; 2050 b->offset = offset; 2051 2052 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2053 kfunc_btf_cmp_by_off, NULL); 2054 } 2055 return b->btf; 2056 } 2057 2058 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2059 { 2060 if (!tab) 2061 return; 2062 2063 while (tab->nr_descs--) { 2064 module_put(tab->descs[tab->nr_descs].module); 2065 btf_put(tab->descs[tab->nr_descs].btf); 2066 } 2067 kfree(tab); 2068 } 2069 2070 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2071 { 2072 if (offset) { 2073 if (offset < 0) { 2074 /* In the future, this can be allowed to increase limit 2075 * of fd index into fd_array, interpreted as u16. 2076 */ 2077 verbose(env, "negative offset disallowed for kernel module function call\n"); 2078 return ERR_PTR(-EINVAL); 2079 } 2080 2081 return __find_kfunc_desc_btf(env, offset); 2082 } 2083 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2084 } 2085 2086 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2087 { 2088 const struct btf_type *func, *func_proto; 2089 struct bpf_kfunc_btf_tab *btf_tab; 2090 struct bpf_kfunc_desc_tab *tab; 2091 struct bpf_prog_aux *prog_aux; 2092 struct bpf_kfunc_desc *desc; 2093 const char *func_name; 2094 struct btf *desc_btf; 2095 unsigned long call_imm; 2096 unsigned long addr; 2097 int err; 2098 2099 prog_aux = env->prog->aux; 2100 tab = prog_aux->kfunc_tab; 2101 btf_tab = prog_aux->kfunc_btf_tab; 2102 if (!tab) { 2103 if (!btf_vmlinux) { 2104 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2105 return -ENOTSUPP; 2106 } 2107 2108 if (!env->prog->jit_requested) { 2109 verbose(env, "JIT is required for calling kernel function\n"); 2110 return -ENOTSUPP; 2111 } 2112 2113 if (!bpf_jit_supports_kfunc_call()) { 2114 verbose(env, "JIT does not support calling kernel function\n"); 2115 return -ENOTSUPP; 2116 } 2117 2118 if (!env->prog->gpl_compatible) { 2119 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2120 return -EINVAL; 2121 } 2122 2123 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2124 if (!tab) 2125 return -ENOMEM; 2126 prog_aux->kfunc_tab = tab; 2127 } 2128 2129 /* func_id == 0 is always invalid, but instead of returning an error, be 2130 * conservative and wait until the code elimination pass before returning 2131 * error, so that invalid calls that get pruned out can be in BPF programs 2132 * loaded from userspace. It is also required that offset be untouched 2133 * for such calls. 2134 */ 2135 if (!func_id && !offset) 2136 return 0; 2137 2138 if (!btf_tab && offset) { 2139 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2140 if (!btf_tab) 2141 return -ENOMEM; 2142 prog_aux->kfunc_btf_tab = btf_tab; 2143 } 2144 2145 desc_btf = find_kfunc_desc_btf(env, offset); 2146 if (IS_ERR(desc_btf)) { 2147 verbose(env, "failed to find BTF for kernel function\n"); 2148 return PTR_ERR(desc_btf); 2149 } 2150 2151 if (find_kfunc_desc(env->prog, func_id, offset)) 2152 return 0; 2153 2154 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2155 verbose(env, "too many different kernel function calls\n"); 2156 return -E2BIG; 2157 } 2158 2159 func = btf_type_by_id(desc_btf, func_id); 2160 if (!func || !btf_type_is_func(func)) { 2161 verbose(env, "kernel btf_id %u is not a function\n", 2162 func_id); 2163 return -EINVAL; 2164 } 2165 func_proto = btf_type_by_id(desc_btf, func->type); 2166 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2167 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2168 func_id); 2169 return -EINVAL; 2170 } 2171 2172 func_name = btf_name_by_offset(desc_btf, func->name_off); 2173 addr = kallsyms_lookup_name(func_name); 2174 if (!addr) { 2175 verbose(env, "cannot find address for kernel function %s\n", 2176 func_name); 2177 return -EINVAL; 2178 } 2179 2180 call_imm = BPF_CALL_IMM(addr); 2181 /* Check whether or not the relative offset overflows desc->imm */ 2182 if ((unsigned long)(s32)call_imm != call_imm) { 2183 verbose(env, "address of kernel function %s is out of range\n", 2184 func_name); 2185 return -EINVAL; 2186 } 2187 2188 desc = &tab->descs[tab->nr_descs++]; 2189 desc->func_id = func_id; 2190 desc->imm = call_imm; 2191 desc->offset = offset; 2192 err = btf_distill_func_proto(&env->log, desc_btf, 2193 func_proto, func_name, 2194 &desc->func_model); 2195 if (!err) 2196 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2197 kfunc_desc_cmp_by_id_off, NULL); 2198 return err; 2199 } 2200 2201 static int kfunc_desc_cmp_by_imm(const void *a, const void *b) 2202 { 2203 const struct bpf_kfunc_desc *d0 = a; 2204 const struct bpf_kfunc_desc *d1 = b; 2205 2206 if (d0->imm > d1->imm) 2207 return 1; 2208 else if (d0->imm < d1->imm) 2209 return -1; 2210 return 0; 2211 } 2212 2213 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog) 2214 { 2215 struct bpf_kfunc_desc_tab *tab; 2216 2217 tab = prog->aux->kfunc_tab; 2218 if (!tab) 2219 return; 2220 2221 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2222 kfunc_desc_cmp_by_imm, NULL); 2223 } 2224 2225 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2226 { 2227 return !!prog->aux->kfunc_tab; 2228 } 2229 2230 const struct btf_func_model * 2231 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2232 const struct bpf_insn *insn) 2233 { 2234 const struct bpf_kfunc_desc desc = { 2235 .imm = insn->imm, 2236 }; 2237 const struct bpf_kfunc_desc *res; 2238 struct bpf_kfunc_desc_tab *tab; 2239 2240 tab = prog->aux->kfunc_tab; 2241 res = bsearch(&desc, tab->descs, tab->nr_descs, 2242 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm); 2243 2244 return res ? &res->func_model : NULL; 2245 } 2246 2247 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2248 { 2249 struct bpf_subprog_info *subprog = env->subprog_info; 2250 struct bpf_insn *insn = env->prog->insnsi; 2251 int i, ret, insn_cnt = env->prog->len; 2252 2253 /* Add entry function. */ 2254 ret = add_subprog(env, 0); 2255 if (ret) 2256 return ret; 2257 2258 for (i = 0; i < insn_cnt; i++, insn++) { 2259 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2260 !bpf_pseudo_kfunc_call(insn)) 2261 continue; 2262 2263 if (!env->bpf_capable) { 2264 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2265 return -EPERM; 2266 } 2267 2268 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2269 ret = add_subprog(env, i + insn->imm + 1); 2270 else 2271 ret = add_kfunc_call(env, insn->imm, insn->off); 2272 2273 if (ret < 0) 2274 return ret; 2275 } 2276 2277 /* Add a fake 'exit' subprog which could simplify subprog iteration 2278 * logic. 'subprog_cnt' should not be increased. 2279 */ 2280 subprog[env->subprog_cnt].start = insn_cnt; 2281 2282 if (env->log.level & BPF_LOG_LEVEL2) 2283 for (i = 0; i < env->subprog_cnt; i++) 2284 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2285 2286 return 0; 2287 } 2288 2289 static int check_subprogs(struct bpf_verifier_env *env) 2290 { 2291 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2292 struct bpf_subprog_info *subprog = env->subprog_info; 2293 struct bpf_insn *insn = env->prog->insnsi; 2294 int insn_cnt = env->prog->len; 2295 2296 /* now check that all jumps are within the same subprog */ 2297 subprog_start = subprog[cur_subprog].start; 2298 subprog_end = subprog[cur_subprog + 1].start; 2299 for (i = 0; i < insn_cnt; i++) { 2300 u8 code = insn[i].code; 2301 2302 if (code == (BPF_JMP | BPF_CALL) && 2303 insn[i].imm == BPF_FUNC_tail_call && 2304 insn[i].src_reg != BPF_PSEUDO_CALL) 2305 subprog[cur_subprog].has_tail_call = true; 2306 if (BPF_CLASS(code) == BPF_LD && 2307 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2308 subprog[cur_subprog].has_ld_abs = true; 2309 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2310 goto next; 2311 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2312 goto next; 2313 off = i + insn[i].off + 1; 2314 if (off < subprog_start || off >= subprog_end) { 2315 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2316 return -EINVAL; 2317 } 2318 next: 2319 if (i == subprog_end - 1) { 2320 /* to avoid fall-through from one subprog into another 2321 * the last insn of the subprog should be either exit 2322 * or unconditional jump back 2323 */ 2324 if (code != (BPF_JMP | BPF_EXIT) && 2325 code != (BPF_JMP | BPF_JA)) { 2326 verbose(env, "last insn is not an exit or jmp\n"); 2327 return -EINVAL; 2328 } 2329 subprog_start = subprog_end; 2330 cur_subprog++; 2331 if (cur_subprog < env->subprog_cnt) 2332 subprog_end = subprog[cur_subprog + 1].start; 2333 } 2334 } 2335 return 0; 2336 } 2337 2338 /* Parentage chain of this register (or stack slot) should take care of all 2339 * issues like callee-saved registers, stack slot allocation time, etc. 2340 */ 2341 static int mark_reg_read(struct bpf_verifier_env *env, 2342 const struct bpf_reg_state *state, 2343 struct bpf_reg_state *parent, u8 flag) 2344 { 2345 bool writes = parent == state->parent; /* Observe write marks */ 2346 int cnt = 0; 2347 2348 while (parent) { 2349 /* if read wasn't screened by an earlier write ... */ 2350 if (writes && state->live & REG_LIVE_WRITTEN) 2351 break; 2352 if (parent->live & REG_LIVE_DONE) { 2353 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2354 reg_type_str(env, parent->type), 2355 parent->var_off.value, parent->off); 2356 return -EFAULT; 2357 } 2358 /* The first condition is more likely to be true than the 2359 * second, checked it first. 2360 */ 2361 if ((parent->live & REG_LIVE_READ) == flag || 2362 parent->live & REG_LIVE_READ64) 2363 /* The parentage chain never changes and 2364 * this parent was already marked as LIVE_READ. 2365 * There is no need to keep walking the chain again and 2366 * keep re-marking all parents as LIVE_READ. 2367 * This case happens when the same register is read 2368 * multiple times without writes into it in-between. 2369 * Also, if parent has the stronger REG_LIVE_READ64 set, 2370 * then no need to set the weak REG_LIVE_READ32. 2371 */ 2372 break; 2373 /* ... then we depend on parent's value */ 2374 parent->live |= flag; 2375 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 2376 if (flag == REG_LIVE_READ64) 2377 parent->live &= ~REG_LIVE_READ32; 2378 state = parent; 2379 parent = state->parent; 2380 writes = true; 2381 cnt++; 2382 } 2383 2384 if (env->longest_mark_read_walk < cnt) 2385 env->longest_mark_read_walk = cnt; 2386 return 0; 2387 } 2388 2389 /* This function is supposed to be used by the following 32-bit optimization 2390 * code only. It returns TRUE if the source or destination register operates 2391 * on 64-bit, otherwise return FALSE. 2392 */ 2393 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 2394 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 2395 { 2396 u8 code, class, op; 2397 2398 code = insn->code; 2399 class = BPF_CLASS(code); 2400 op = BPF_OP(code); 2401 if (class == BPF_JMP) { 2402 /* BPF_EXIT for "main" will reach here. Return TRUE 2403 * conservatively. 2404 */ 2405 if (op == BPF_EXIT) 2406 return true; 2407 if (op == BPF_CALL) { 2408 /* BPF to BPF call will reach here because of marking 2409 * caller saved clobber with DST_OP_NO_MARK for which we 2410 * don't care the register def because they are anyway 2411 * marked as NOT_INIT already. 2412 */ 2413 if (insn->src_reg == BPF_PSEUDO_CALL) 2414 return false; 2415 /* Helper call will reach here because of arg type 2416 * check, conservatively return TRUE. 2417 */ 2418 if (t == SRC_OP) 2419 return true; 2420 2421 return false; 2422 } 2423 } 2424 2425 if (class == BPF_ALU64 || class == BPF_JMP || 2426 /* BPF_END always use BPF_ALU class. */ 2427 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 2428 return true; 2429 2430 if (class == BPF_ALU || class == BPF_JMP32) 2431 return false; 2432 2433 if (class == BPF_LDX) { 2434 if (t != SRC_OP) 2435 return BPF_SIZE(code) == BPF_DW; 2436 /* LDX source must be ptr. */ 2437 return true; 2438 } 2439 2440 if (class == BPF_STX) { 2441 /* BPF_STX (including atomic variants) has multiple source 2442 * operands, one of which is a ptr. Check whether the caller is 2443 * asking about it. 2444 */ 2445 if (t == SRC_OP && reg->type != SCALAR_VALUE) 2446 return true; 2447 return BPF_SIZE(code) == BPF_DW; 2448 } 2449 2450 if (class == BPF_LD) { 2451 u8 mode = BPF_MODE(code); 2452 2453 /* LD_IMM64 */ 2454 if (mode == BPF_IMM) 2455 return true; 2456 2457 /* Both LD_IND and LD_ABS return 32-bit data. */ 2458 if (t != SRC_OP) 2459 return false; 2460 2461 /* Implicit ctx ptr. */ 2462 if (regno == BPF_REG_6) 2463 return true; 2464 2465 /* Explicit source could be any width. */ 2466 return true; 2467 } 2468 2469 if (class == BPF_ST) 2470 /* The only source register for BPF_ST is a ptr. */ 2471 return true; 2472 2473 /* Conservatively return true at default. */ 2474 return true; 2475 } 2476 2477 /* Return the regno defined by the insn, or -1. */ 2478 static int insn_def_regno(const struct bpf_insn *insn) 2479 { 2480 switch (BPF_CLASS(insn->code)) { 2481 case BPF_JMP: 2482 case BPF_JMP32: 2483 case BPF_ST: 2484 return -1; 2485 case BPF_STX: 2486 if (BPF_MODE(insn->code) == BPF_ATOMIC && 2487 (insn->imm & BPF_FETCH)) { 2488 if (insn->imm == BPF_CMPXCHG) 2489 return BPF_REG_0; 2490 else 2491 return insn->src_reg; 2492 } else { 2493 return -1; 2494 } 2495 default: 2496 return insn->dst_reg; 2497 } 2498 } 2499 2500 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 2501 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 2502 { 2503 int dst_reg = insn_def_regno(insn); 2504 2505 if (dst_reg == -1) 2506 return false; 2507 2508 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 2509 } 2510 2511 static void mark_insn_zext(struct bpf_verifier_env *env, 2512 struct bpf_reg_state *reg) 2513 { 2514 s32 def_idx = reg->subreg_def; 2515 2516 if (def_idx == DEF_NOT_SUBREG) 2517 return; 2518 2519 env->insn_aux_data[def_idx - 1].zext_dst = true; 2520 /* The dst will be zero extended, so won't be sub-register anymore. */ 2521 reg->subreg_def = DEF_NOT_SUBREG; 2522 } 2523 2524 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 2525 enum reg_arg_type t) 2526 { 2527 struct bpf_verifier_state *vstate = env->cur_state; 2528 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2529 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 2530 struct bpf_reg_state *reg, *regs = state->regs; 2531 bool rw64; 2532 2533 if (regno >= MAX_BPF_REG) { 2534 verbose(env, "R%d is invalid\n", regno); 2535 return -EINVAL; 2536 } 2537 2538 mark_reg_scratched(env, regno); 2539 2540 reg = ®s[regno]; 2541 rw64 = is_reg64(env, insn, regno, reg, t); 2542 if (t == SRC_OP) { 2543 /* check whether register used as source operand can be read */ 2544 if (reg->type == NOT_INIT) { 2545 verbose(env, "R%d !read_ok\n", regno); 2546 return -EACCES; 2547 } 2548 /* We don't need to worry about FP liveness because it's read-only */ 2549 if (regno == BPF_REG_FP) 2550 return 0; 2551 2552 if (rw64) 2553 mark_insn_zext(env, reg); 2554 2555 return mark_reg_read(env, reg, reg->parent, 2556 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 2557 } else { 2558 /* check whether register used as dest operand can be written to */ 2559 if (regno == BPF_REG_FP) { 2560 verbose(env, "frame pointer is read only\n"); 2561 return -EACCES; 2562 } 2563 reg->live |= REG_LIVE_WRITTEN; 2564 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 2565 if (t == DST_OP) 2566 mark_reg_unknown(env, regs, regno); 2567 } 2568 return 0; 2569 } 2570 2571 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 2572 { 2573 env->insn_aux_data[idx].jmp_point = true; 2574 } 2575 2576 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 2577 { 2578 return env->insn_aux_data[insn_idx].jmp_point; 2579 } 2580 2581 /* for any branch, call, exit record the history of jmps in the given state */ 2582 static int push_jmp_history(struct bpf_verifier_env *env, 2583 struct bpf_verifier_state *cur) 2584 { 2585 u32 cnt = cur->jmp_history_cnt; 2586 struct bpf_idx_pair *p; 2587 size_t alloc_size; 2588 2589 if (!is_jmp_point(env, env->insn_idx)) 2590 return 0; 2591 2592 cnt++; 2593 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 2594 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 2595 if (!p) 2596 return -ENOMEM; 2597 p[cnt - 1].idx = env->insn_idx; 2598 p[cnt - 1].prev_idx = env->prev_insn_idx; 2599 cur->jmp_history = p; 2600 cur->jmp_history_cnt = cnt; 2601 return 0; 2602 } 2603 2604 /* Backtrack one insn at a time. If idx is not at the top of recorded 2605 * history then previous instruction came from straight line execution. 2606 */ 2607 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 2608 u32 *history) 2609 { 2610 u32 cnt = *history; 2611 2612 if (cnt && st->jmp_history[cnt - 1].idx == i) { 2613 i = st->jmp_history[cnt - 1].prev_idx; 2614 (*history)--; 2615 } else { 2616 i--; 2617 } 2618 return i; 2619 } 2620 2621 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 2622 { 2623 const struct btf_type *func; 2624 struct btf *desc_btf; 2625 2626 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 2627 return NULL; 2628 2629 desc_btf = find_kfunc_desc_btf(data, insn->off); 2630 if (IS_ERR(desc_btf)) 2631 return "<error>"; 2632 2633 func = btf_type_by_id(desc_btf, insn->imm); 2634 return btf_name_by_offset(desc_btf, func->name_off); 2635 } 2636 2637 /* For given verifier state backtrack_insn() is called from the last insn to 2638 * the first insn. Its purpose is to compute a bitmask of registers and 2639 * stack slots that needs precision in the parent verifier state. 2640 */ 2641 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 2642 u32 *reg_mask, u64 *stack_mask) 2643 { 2644 const struct bpf_insn_cbs cbs = { 2645 .cb_call = disasm_kfunc_name, 2646 .cb_print = verbose, 2647 .private_data = env, 2648 }; 2649 struct bpf_insn *insn = env->prog->insnsi + idx; 2650 u8 class = BPF_CLASS(insn->code); 2651 u8 opcode = BPF_OP(insn->code); 2652 u8 mode = BPF_MODE(insn->code); 2653 u32 dreg = 1u << insn->dst_reg; 2654 u32 sreg = 1u << insn->src_reg; 2655 u32 spi; 2656 2657 if (insn->code == 0) 2658 return 0; 2659 if (env->log.level & BPF_LOG_LEVEL2) { 2660 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask); 2661 verbose(env, "%d: ", idx); 2662 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 2663 } 2664 2665 if (class == BPF_ALU || class == BPF_ALU64) { 2666 if (!(*reg_mask & dreg)) 2667 return 0; 2668 if (opcode == BPF_MOV) { 2669 if (BPF_SRC(insn->code) == BPF_X) { 2670 /* dreg = sreg 2671 * dreg needs precision after this insn 2672 * sreg needs precision before this insn 2673 */ 2674 *reg_mask &= ~dreg; 2675 *reg_mask |= sreg; 2676 } else { 2677 /* dreg = K 2678 * dreg needs precision after this insn. 2679 * Corresponding register is already marked 2680 * as precise=true in this verifier state. 2681 * No further markings in parent are necessary 2682 */ 2683 *reg_mask &= ~dreg; 2684 } 2685 } else { 2686 if (BPF_SRC(insn->code) == BPF_X) { 2687 /* dreg += sreg 2688 * both dreg and sreg need precision 2689 * before this insn 2690 */ 2691 *reg_mask |= sreg; 2692 } /* else dreg += K 2693 * dreg still needs precision before this insn 2694 */ 2695 } 2696 } else if (class == BPF_LDX) { 2697 if (!(*reg_mask & dreg)) 2698 return 0; 2699 *reg_mask &= ~dreg; 2700 2701 /* scalars can only be spilled into stack w/o losing precision. 2702 * Load from any other memory can be zero extended. 2703 * The desire to keep that precision is already indicated 2704 * by 'precise' mark in corresponding register of this state. 2705 * No further tracking necessary. 2706 */ 2707 if (insn->src_reg != BPF_REG_FP) 2708 return 0; 2709 2710 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 2711 * that [fp - off] slot contains scalar that needs to be 2712 * tracked with precision 2713 */ 2714 spi = (-insn->off - 1) / BPF_REG_SIZE; 2715 if (spi >= 64) { 2716 verbose(env, "BUG spi %d\n", spi); 2717 WARN_ONCE(1, "verifier backtracking bug"); 2718 return -EFAULT; 2719 } 2720 *stack_mask |= 1ull << spi; 2721 } else if (class == BPF_STX || class == BPF_ST) { 2722 if (*reg_mask & dreg) 2723 /* stx & st shouldn't be using _scalar_ dst_reg 2724 * to access memory. It means backtracking 2725 * encountered a case of pointer subtraction. 2726 */ 2727 return -ENOTSUPP; 2728 /* scalars can only be spilled into stack */ 2729 if (insn->dst_reg != BPF_REG_FP) 2730 return 0; 2731 spi = (-insn->off - 1) / BPF_REG_SIZE; 2732 if (spi >= 64) { 2733 verbose(env, "BUG spi %d\n", spi); 2734 WARN_ONCE(1, "verifier backtracking bug"); 2735 return -EFAULT; 2736 } 2737 if (!(*stack_mask & (1ull << spi))) 2738 return 0; 2739 *stack_mask &= ~(1ull << spi); 2740 if (class == BPF_STX) 2741 *reg_mask |= sreg; 2742 } else if (class == BPF_JMP || class == BPF_JMP32) { 2743 if (opcode == BPF_CALL) { 2744 if (insn->src_reg == BPF_PSEUDO_CALL) 2745 return -ENOTSUPP; 2746 /* BPF helpers that invoke callback subprogs are 2747 * equivalent to BPF_PSEUDO_CALL above 2748 */ 2749 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm)) 2750 return -ENOTSUPP; 2751 /* kfunc with imm==0 is invalid and fixup_kfunc_call will 2752 * catch this error later. Make backtracking conservative 2753 * with ENOTSUPP. 2754 */ 2755 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && insn->imm == 0) 2756 return -ENOTSUPP; 2757 /* regular helper call sets R0 */ 2758 *reg_mask &= ~1; 2759 if (*reg_mask & 0x3f) { 2760 /* if backtracing was looking for registers R1-R5 2761 * they should have been found already. 2762 */ 2763 verbose(env, "BUG regs %x\n", *reg_mask); 2764 WARN_ONCE(1, "verifier backtracking bug"); 2765 return -EFAULT; 2766 } 2767 } else if (opcode == BPF_EXIT) { 2768 return -ENOTSUPP; 2769 } 2770 } else if (class == BPF_LD) { 2771 if (!(*reg_mask & dreg)) 2772 return 0; 2773 *reg_mask &= ~dreg; 2774 /* It's ld_imm64 or ld_abs or ld_ind. 2775 * For ld_imm64 no further tracking of precision 2776 * into parent is necessary 2777 */ 2778 if (mode == BPF_IND || mode == BPF_ABS) 2779 /* to be analyzed */ 2780 return -ENOTSUPP; 2781 } 2782 return 0; 2783 } 2784 2785 /* the scalar precision tracking algorithm: 2786 * . at the start all registers have precise=false. 2787 * . scalar ranges are tracked as normal through alu and jmp insns. 2788 * . once precise value of the scalar register is used in: 2789 * . ptr + scalar alu 2790 * . if (scalar cond K|scalar) 2791 * . helper_call(.., scalar, ...) where ARG_CONST is expected 2792 * backtrack through the verifier states and mark all registers and 2793 * stack slots with spilled constants that these scalar regisers 2794 * should be precise. 2795 * . during state pruning two registers (or spilled stack slots) 2796 * are equivalent if both are not precise. 2797 * 2798 * Note the verifier cannot simply walk register parentage chain, 2799 * since many different registers and stack slots could have been 2800 * used to compute single precise scalar. 2801 * 2802 * The approach of starting with precise=true for all registers and then 2803 * backtrack to mark a register as not precise when the verifier detects 2804 * that program doesn't care about specific value (e.g., when helper 2805 * takes register as ARG_ANYTHING parameter) is not safe. 2806 * 2807 * It's ok to walk single parentage chain of the verifier states. 2808 * It's possible that this backtracking will go all the way till 1st insn. 2809 * All other branches will be explored for needing precision later. 2810 * 2811 * The backtracking needs to deal with cases like: 2812 * 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) 2813 * r9 -= r8 2814 * r5 = r9 2815 * if r5 > 0x79f goto pc+7 2816 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 2817 * r5 += 1 2818 * ... 2819 * call bpf_perf_event_output#25 2820 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 2821 * 2822 * and this case: 2823 * r6 = 1 2824 * call foo // uses callee's r6 inside to compute r0 2825 * r0 += r6 2826 * if r0 == 0 goto 2827 * 2828 * to track above reg_mask/stack_mask needs to be independent for each frame. 2829 * 2830 * Also if parent's curframe > frame where backtracking started, 2831 * the verifier need to mark registers in both frames, otherwise callees 2832 * may incorrectly prune callers. This is similar to 2833 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 2834 * 2835 * For now backtracking falls back into conservative marking. 2836 */ 2837 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 2838 struct bpf_verifier_state *st) 2839 { 2840 struct bpf_func_state *func; 2841 struct bpf_reg_state *reg; 2842 int i, j; 2843 2844 /* big hammer: mark all scalars precise in this path. 2845 * pop_stack may still get !precise scalars. 2846 * We also skip current state and go straight to first parent state, 2847 * because precision markings in current non-checkpointed state are 2848 * not needed. See why in the comment in __mark_chain_precision below. 2849 */ 2850 for (st = st->parent; st; st = st->parent) { 2851 for (i = 0; i <= st->curframe; i++) { 2852 func = st->frame[i]; 2853 for (j = 0; j < BPF_REG_FP; j++) { 2854 reg = &func->regs[j]; 2855 if (reg->type != SCALAR_VALUE) 2856 continue; 2857 reg->precise = true; 2858 } 2859 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 2860 if (!is_spilled_reg(&func->stack[j])) 2861 continue; 2862 reg = &func->stack[j].spilled_ptr; 2863 if (reg->type != SCALAR_VALUE) 2864 continue; 2865 reg->precise = true; 2866 } 2867 } 2868 } 2869 } 2870 2871 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 2872 { 2873 struct bpf_func_state *func; 2874 struct bpf_reg_state *reg; 2875 int i, j; 2876 2877 for (i = 0; i <= st->curframe; i++) { 2878 func = st->frame[i]; 2879 for (j = 0; j < BPF_REG_FP; j++) { 2880 reg = &func->regs[j]; 2881 if (reg->type != SCALAR_VALUE) 2882 continue; 2883 reg->precise = false; 2884 } 2885 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 2886 if (!is_spilled_reg(&func->stack[j])) 2887 continue; 2888 reg = &func->stack[j].spilled_ptr; 2889 if (reg->type != SCALAR_VALUE) 2890 continue; 2891 reg->precise = false; 2892 } 2893 } 2894 } 2895 2896 /* 2897 * __mark_chain_precision() backtracks BPF program instruction sequence and 2898 * chain of verifier states making sure that register *regno* (if regno >= 0) 2899 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 2900 * SCALARS, as well as any other registers and slots that contribute to 2901 * a tracked state of given registers/stack slots, depending on specific BPF 2902 * assembly instructions (see backtrack_insns() for exact instruction handling 2903 * logic). This backtracking relies on recorded jmp_history and is able to 2904 * traverse entire chain of parent states. This process ends only when all the 2905 * necessary registers/slots and their transitive dependencies are marked as 2906 * precise. 2907 * 2908 * One important and subtle aspect is that precise marks *do not matter* in 2909 * the currently verified state (current state). It is important to understand 2910 * why this is the case. 2911 * 2912 * First, note that current state is the state that is not yet "checkpointed", 2913 * i.e., it is not yet put into env->explored_states, and it has no children 2914 * states as well. It's ephemeral, and can end up either a) being discarded if 2915 * compatible explored state is found at some point or BPF_EXIT instruction is 2916 * reached or b) checkpointed and put into env->explored_states, branching out 2917 * into one or more children states. 2918 * 2919 * In the former case, precise markings in current state are completely 2920 * ignored by state comparison code (see regsafe() for details). Only 2921 * checkpointed ("old") state precise markings are important, and if old 2922 * state's register/slot is precise, regsafe() assumes current state's 2923 * register/slot as precise and checks value ranges exactly and precisely. If 2924 * states turn out to be compatible, current state's necessary precise 2925 * markings and any required parent states' precise markings are enforced 2926 * after the fact with propagate_precision() logic, after the fact. But it's 2927 * important to realize that in this case, even after marking current state 2928 * registers/slots as precise, we immediately discard current state. So what 2929 * actually matters is any of the precise markings propagated into current 2930 * state's parent states, which are always checkpointed (due to b) case above). 2931 * As such, for scenario a) it doesn't matter if current state has precise 2932 * markings set or not. 2933 * 2934 * Now, for the scenario b), checkpointing and forking into child(ren) 2935 * state(s). Note that before current state gets to checkpointing step, any 2936 * processed instruction always assumes precise SCALAR register/slot 2937 * knowledge: if precise value or range is useful to prune jump branch, BPF 2938 * verifier takes this opportunity enthusiastically. Similarly, when 2939 * register's value is used to calculate offset or memory address, exact 2940 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 2941 * what we mentioned above about state comparison ignoring precise markings 2942 * during state comparison, BPF verifier ignores and also assumes precise 2943 * markings *at will* during instruction verification process. But as verifier 2944 * assumes precision, it also propagates any precision dependencies across 2945 * parent states, which are not yet finalized, so can be further restricted 2946 * based on new knowledge gained from restrictions enforced by their children 2947 * states. This is so that once those parent states are finalized, i.e., when 2948 * they have no more active children state, state comparison logic in 2949 * is_state_visited() would enforce strict and precise SCALAR ranges, if 2950 * required for correctness. 2951 * 2952 * To build a bit more intuition, note also that once a state is checkpointed, 2953 * the path we took to get to that state is not important. This is crucial 2954 * property for state pruning. When state is checkpointed and finalized at 2955 * some instruction index, it can be correctly and safely used to "short 2956 * circuit" any *compatible* state that reaches exactly the same instruction 2957 * index. I.e., if we jumped to that instruction from a completely different 2958 * code path than original finalized state was derived from, it doesn't 2959 * matter, current state can be discarded because from that instruction 2960 * forward having a compatible state will ensure we will safely reach the 2961 * exit. States describe preconditions for further exploration, but completely 2962 * forget the history of how we got here. 2963 * 2964 * This also means that even if we needed precise SCALAR range to get to 2965 * finalized state, but from that point forward *that same* SCALAR register is 2966 * never used in a precise context (i.e., it's precise value is not needed for 2967 * correctness), it's correct and safe to mark such register as "imprecise" 2968 * (i.e., precise marking set to false). This is what we rely on when we do 2969 * not set precise marking in current state. If no child state requires 2970 * precision for any given SCALAR register, it's safe to dictate that it can 2971 * be imprecise. If any child state does require this register to be precise, 2972 * we'll mark it precise later retroactively during precise markings 2973 * propagation from child state to parent states. 2974 * 2975 * Skipping precise marking setting in current state is a mild version of 2976 * relying on the above observation. But we can utilize this property even 2977 * more aggressively by proactively forgetting any precise marking in the 2978 * current state (which we inherited from the parent state), right before we 2979 * checkpoint it and branch off into new child state. This is done by 2980 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 2981 * finalized states which help in short circuiting more future states. 2982 */ 2983 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno, 2984 int spi) 2985 { 2986 struct bpf_verifier_state *st = env->cur_state; 2987 int first_idx = st->first_insn_idx; 2988 int last_idx = env->insn_idx; 2989 struct bpf_func_state *func; 2990 struct bpf_reg_state *reg; 2991 u32 reg_mask = regno >= 0 ? 1u << regno : 0; 2992 u64 stack_mask = spi >= 0 ? 1ull << spi : 0; 2993 bool skip_first = true; 2994 bool new_marks = false; 2995 int i, err; 2996 2997 if (!env->bpf_capable) 2998 return 0; 2999 3000 /* Do sanity checks against current state of register and/or stack 3001 * slot, but don't set precise flag in current state, as precision 3002 * tracking in the current state is unnecessary. 3003 */ 3004 func = st->frame[frame]; 3005 if (regno >= 0) { 3006 reg = &func->regs[regno]; 3007 if (reg->type != SCALAR_VALUE) { 3008 WARN_ONCE(1, "backtracing misuse"); 3009 return -EFAULT; 3010 } 3011 new_marks = true; 3012 } 3013 3014 while (spi >= 0) { 3015 if (!is_spilled_reg(&func->stack[spi])) { 3016 stack_mask = 0; 3017 break; 3018 } 3019 reg = &func->stack[spi].spilled_ptr; 3020 if (reg->type != SCALAR_VALUE) { 3021 stack_mask = 0; 3022 break; 3023 } 3024 new_marks = true; 3025 break; 3026 } 3027 3028 if (!new_marks) 3029 return 0; 3030 if (!reg_mask && !stack_mask) 3031 return 0; 3032 3033 for (;;) { 3034 DECLARE_BITMAP(mask, 64); 3035 u32 history = st->jmp_history_cnt; 3036 3037 if (env->log.level & BPF_LOG_LEVEL2) 3038 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx); 3039 3040 if (last_idx < 0) { 3041 /* we are at the entry into subprog, which 3042 * is expected for global funcs, but only if 3043 * requested precise registers are R1-R5 3044 * (which are global func's input arguments) 3045 */ 3046 if (st->curframe == 0 && 3047 st->frame[0]->subprogno > 0 && 3048 st->frame[0]->callsite == BPF_MAIN_FUNC && 3049 stack_mask == 0 && (reg_mask & ~0x3e) == 0) { 3050 bitmap_from_u64(mask, reg_mask); 3051 for_each_set_bit(i, mask, 32) { 3052 reg = &st->frame[0]->regs[i]; 3053 if (reg->type != SCALAR_VALUE) { 3054 reg_mask &= ~(1u << i); 3055 continue; 3056 } 3057 reg->precise = true; 3058 } 3059 return 0; 3060 } 3061 3062 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n", 3063 st->frame[0]->subprogno, reg_mask, stack_mask); 3064 WARN_ONCE(1, "verifier backtracking bug"); 3065 return -EFAULT; 3066 } 3067 3068 for (i = last_idx;;) { 3069 if (skip_first) { 3070 err = 0; 3071 skip_first = false; 3072 } else { 3073 err = backtrack_insn(env, i, ®_mask, &stack_mask); 3074 } 3075 if (err == -ENOTSUPP) { 3076 mark_all_scalars_precise(env, st); 3077 return 0; 3078 } else if (err) { 3079 return err; 3080 } 3081 if (!reg_mask && !stack_mask) 3082 /* Found assignment(s) into tracked register in this state. 3083 * Since this state is already marked, just return. 3084 * Nothing to be tracked further in the parent state. 3085 */ 3086 return 0; 3087 if (i == first_idx) 3088 break; 3089 i = get_prev_insn_idx(st, i, &history); 3090 if (i >= env->prog->len) { 3091 /* This can happen if backtracking reached insn 0 3092 * and there are still reg_mask or stack_mask 3093 * to backtrack. 3094 * It means the backtracking missed the spot where 3095 * particular register was initialized with a constant. 3096 */ 3097 verbose(env, "BUG backtracking idx %d\n", i); 3098 WARN_ONCE(1, "verifier backtracking bug"); 3099 return -EFAULT; 3100 } 3101 } 3102 st = st->parent; 3103 if (!st) 3104 break; 3105 3106 new_marks = false; 3107 func = st->frame[frame]; 3108 bitmap_from_u64(mask, reg_mask); 3109 for_each_set_bit(i, mask, 32) { 3110 reg = &func->regs[i]; 3111 if (reg->type != SCALAR_VALUE) { 3112 reg_mask &= ~(1u << i); 3113 continue; 3114 } 3115 if (!reg->precise) 3116 new_marks = true; 3117 reg->precise = true; 3118 } 3119 3120 bitmap_from_u64(mask, stack_mask); 3121 for_each_set_bit(i, mask, 64) { 3122 if (i >= func->allocated_stack / BPF_REG_SIZE) { 3123 /* the sequence of instructions: 3124 * 2: (bf) r3 = r10 3125 * 3: (7b) *(u64 *)(r3 -8) = r0 3126 * 4: (79) r4 = *(u64 *)(r10 -8) 3127 * doesn't contain jmps. It's backtracked 3128 * as a single block. 3129 * During backtracking insn 3 is not recognized as 3130 * stack access, so at the end of backtracking 3131 * stack slot fp-8 is still marked in stack_mask. 3132 * However the parent state may not have accessed 3133 * fp-8 and it's "unallocated" stack space. 3134 * In such case fallback to conservative. 3135 */ 3136 mark_all_scalars_precise(env, st); 3137 return 0; 3138 } 3139 3140 if (!is_spilled_reg(&func->stack[i])) { 3141 stack_mask &= ~(1ull << i); 3142 continue; 3143 } 3144 reg = &func->stack[i].spilled_ptr; 3145 if (reg->type != SCALAR_VALUE) { 3146 stack_mask &= ~(1ull << i); 3147 continue; 3148 } 3149 if (!reg->precise) 3150 new_marks = true; 3151 reg->precise = true; 3152 } 3153 if (env->log.level & BPF_LOG_LEVEL2) { 3154 verbose(env, "parent %s regs=%x stack=%llx marks:", 3155 new_marks ? "didn't have" : "already had", 3156 reg_mask, stack_mask); 3157 print_verifier_state(env, func, true); 3158 } 3159 3160 if (!reg_mask && !stack_mask) 3161 break; 3162 if (!new_marks) 3163 break; 3164 3165 last_idx = st->last_insn_idx; 3166 first_idx = st->first_insn_idx; 3167 } 3168 return 0; 3169 } 3170 3171 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3172 { 3173 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1); 3174 } 3175 3176 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno) 3177 { 3178 return __mark_chain_precision(env, frame, regno, -1); 3179 } 3180 3181 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi) 3182 { 3183 return __mark_chain_precision(env, frame, -1, spi); 3184 } 3185 3186 static bool is_spillable_regtype(enum bpf_reg_type type) 3187 { 3188 switch (base_type(type)) { 3189 case PTR_TO_MAP_VALUE: 3190 case PTR_TO_STACK: 3191 case PTR_TO_CTX: 3192 case PTR_TO_PACKET: 3193 case PTR_TO_PACKET_META: 3194 case PTR_TO_PACKET_END: 3195 case PTR_TO_FLOW_KEYS: 3196 case CONST_PTR_TO_MAP: 3197 case PTR_TO_SOCKET: 3198 case PTR_TO_SOCK_COMMON: 3199 case PTR_TO_TCP_SOCK: 3200 case PTR_TO_XDP_SOCK: 3201 case PTR_TO_BTF_ID: 3202 case PTR_TO_BUF: 3203 case PTR_TO_MEM: 3204 case PTR_TO_FUNC: 3205 case PTR_TO_MAP_KEY: 3206 return true; 3207 default: 3208 return false; 3209 } 3210 } 3211 3212 /* Does this register contain a constant zero? */ 3213 static bool register_is_null(struct bpf_reg_state *reg) 3214 { 3215 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 3216 } 3217 3218 static bool register_is_const(struct bpf_reg_state *reg) 3219 { 3220 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 3221 } 3222 3223 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 3224 { 3225 return tnum_is_unknown(reg->var_off) && 3226 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 3227 reg->umin_value == 0 && reg->umax_value == U64_MAX && 3228 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 3229 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 3230 } 3231 3232 static bool register_is_bounded(struct bpf_reg_state *reg) 3233 { 3234 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 3235 } 3236 3237 static bool __is_pointer_value(bool allow_ptr_leaks, 3238 const struct bpf_reg_state *reg) 3239 { 3240 if (allow_ptr_leaks) 3241 return false; 3242 3243 return reg->type != SCALAR_VALUE; 3244 } 3245 3246 static void save_register_state(struct bpf_func_state *state, 3247 int spi, struct bpf_reg_state *reg, 3248 int size) 3249 { 3250 int i; 3251 3252 state->stack[spi].spilled_ptr = *reg; 3253 if (size == BPF_REG_SIZE) 3254 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 3255 3256 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3257 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3258 3259 /* size < 8 bytes spill */ 3260 for (; i; i--) 3261 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 3262 } 3263 3264 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3265 * stack boundary and alignment are checked in check_mem_access() 3266 */ 3267 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3268 /* stack frame we're writing to */ 3269 struct bpf_func_state *state, 3270 int off, int size, int value_regno, 3271 int insn_idx) 3272 { 3273 struct bpf_func_state *cur; /* state of the current function */ 3274 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3275 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg; 3276 struct bpf_reg_state *reg = NULL; 3277 3278 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 3279 if (err) 3280 return err; 3281 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3282 * so it's aligned access and [off, off + size) are within stack limits 3283 */ 3284 if (!env->allow_ptr_leaks && 3285 state->stack[spi].slot_type[0] == STACK_SPILL && 3286 size != BPF_REG_SIZE) { 3287 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3288 return -EACCES; 3289 } 3290 3291 cur = env->cur_state->frame[env->cur_state->curframe]; 3292 if (value_regno >= 0) 3293 reg = &cur->regs[value_regno]; 3294 if (!env->bypass_spec_v4) { 3295 bool sanitize = reg && is_spillable_regtype(reg->type); 3296 3297 for (i = 0; i < size; i++) { 3298 u8 type = state->stack[spi].slot_type[i]; 3299 3300 if (type != STACK_MISC && type != STACK_ZERO) { 3301 sanitize = true; 3302 break; 3303 } 3304 } 3305 3306 if (sanitize) 3307 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 3308 } 3309 3310 mark_stack_slot_scratched(env, spi); 3311 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 3312 !register_is_null(reg) && env->bpf_capable) { 3313 if (dst_reg != BPF_REG_FP) { 3314 /* The backtracking logic can only recognize explicit 3315 * stack slot address like [fp - 8]. Other spill of 3316 * scalar via different register has to be conservative. 3317 * Backtrack from here and mark all registers as precise 3318 * that contributed into 'reg' being a constant. 3319 */ 3320 err = mark_chain_precision(env, value_regno); 3321 if (err) 3322 return err; 3323 } 3324 save_register_state(state, spi, reg, size); 3325 } else if (reg && is_spillable_regtype(reg->type)) { 3326 /* register containing pointer is being spilled into stack */ 3327 if (size != BPF_REG_SIZE) { 3328 verbose_linfo(env, insn_idx, "; "); 3329 verbose(env, "invalid size of register spill\n"); 3330 return -EACCES; 3331 } 3332 if (state != cur && reg->type == PTR_TO_STACK) { 3333 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3334 return -EINVAL; 3335 } 3336 save_register_state(state, spi, reg, size); 3337 } else { 3338 u8 type = STACK_MISC; 3339 3340 /* regular write of data into stack destroys any spilled ptr */ 3341 state->stack[spi].spilled_ptr.type = NOT_INIT; 3342 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */ 3343 if (is_spilled_reg(&state->stack[spi])) 3344 for (i = 0; i < BPF_REG_SIZE; i++) 3345 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3346 3347 /* only mark the slot as written if all 8 bytes were written 3348 * otherwise read propagation may incorrectly stop too soon 3349 * when stack slots are partially written. 3350 * This heuristic means that read propagation will be 3351 * conservative, since it will add reg_live_read marks 3352 * to stack slots all the way to first state when programs 3353 * writes+reads less than 8 bytes 3354 */ 3355 if (size == BPF_REG_SIZE) 3356 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 3357 3358 /* when we zero initialize stack slots mark them as such */ 3359 if (reg && register_is_null(reg)) { 3360 /* backtracking doesn't work for STACK_ZERO yet. */ 3361 err = mark_chain_precision(env, value_regno); 3362 if (err) 3363 return err; 3364 type = STACK_ZERO; 3365 } 3366 3367 /* Mark slots affected by this stack write. */ 3368 for (i = 0; i < size; i++) 3369 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 3370 type; 3371 } 3372 return 0; 3373 } 3374 3375 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 3376 * known to contain a variable offset. 3377 * This function checks whether the write is permitted and conservatively 3378 * tracks the effects of the write, considering that each stack slot in the 3379 * dynamic range is potentially written to. 3380 * 3381 * 'off' includes 'regno->off'. 3382 * 'value_regno' can be -1, meaning that an unknown value is being written to 3383 * the stack. 3384 * 3385 * Spilled pointers in range are not marked as written because we don't know 3386 * what's going to be actually written. This means that read propagation for 3387 * future reads cannot be terminated by this write. 3388 * 3389 * For privileged programs, uninitialized stack slots are considered 3390 * initialized by this write (even though we don't know exactly what offsets 3391 * are going to be written to). The idea is that we don't want the verifier to 3392 * reject future reads that access slots written to through variable offsets. 3393 */ 3394 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3395 /* func where register points to */ 3396 struct bpf_func_state *state, 3397 int ptr_regno, int off, int size, 3398 int value_regno, int insn_idx) 3399 { 3400 struct bpf_func_state *cur; /* state of the current function */ 3401 int min_off, max_off; 3402 int i, err; 3403 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 3404 bool writing_zero = false; 3405 /* set if the fact that we're writing a zero is used to let any 3406 * stack slots remain STACK_ZERO 3407 */ 3408 bool zero_used = false; 3409 3410 cur = env->cur_state->frame[env->cur_state->curframe]; 3411 ptr_reg = &cur->regs[ptr_regno]; 3412 min_off = ptr_reg->smin_value + off; 3413 max_off = ptr_reg->smax_value + off + size; 3414 if (value_regno >= 0) 3415 value_reg = &cur->regs[value_regno]; 3416 if (value_reg && register_is_null(value_reg)) 3417 writing_zero = true; 3418 3419 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 3420 if (err) 3421 return err; 3422 3423 3424 /* Variable offset writes destroy any spilled pointers in range. */ 3425 for (i = min_off; i < max_off; i++) { 3426 u8 new_type, *stype; 3427 int slot, spi; 3428 3429 slot = -i - 1; 3430 spi = slot / BPF_REG_SIZE; 3431 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3432 mark_stack_slot_scratched(env, spi); 3433 3434 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 3435 /* Reject the write if range we may write to has not 3436 * been initialized beforehand. If we didn't reject 3437 * here, the ptr status would be erased below (even 3438 * though not all slots are actually overwritten), 3439 * possibly opening the door to leaks. 3440 * 3441 * We do however catch STACK_INVALID case below, and 3442 * only allow reading possibly uninitialized memory 3443 * later for CAP_PERFMON, as the write may not happen to 3444 * that slot. 3445 */ 3446 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3447 insn_idx, i); 3448 return -EINVAL; 3449 } 3450 3451 /* Erase all spilled pointers. */ 3452 state->stack[spi].spilled_ptr.type = NOT_INIT; 3453 3454 /* Update the slot type. */ 3455 new_type = STACK_MISC; 3456 if (writing_zero && *stype == STACK_ZERO) { 3457 new_type = STACK_ZERO; 3458 zero_used = true; 3459 } 3460 /* If the slot is STACK_INVALID, we check whether it's OK to 3461 * pretend that it will be initialized by this write. The slot 3462 * might not actually be written to, and so if we mark it as 3463 * initialized future reads might leak uninitialized memory. 3464 * For privileged programs, we will accept such reads to slots 3465 * that may or may not be written because, if we're reject 3466 * them, the error would be too confusing. 3467 */ 3468 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 3469 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3470 insn_idx, i); 3471 return -EINVAL; 3472 } 3473 *stype = new_type; 3474 } 3475 if (zero_used) { 3476 /* backtracking doesn't work for STACK_ZERO yet. */ 3477 err = mark_chain_precision(env, value_regno); 3478 if (err) 3479 return err; 3480 } 3481 return 0; 3482 } 3483 3484 /* When register 'dst_regno' is assigned some values from stack[min_off, 3485 * max_off), we set the register's type according to the types of the 3486 * respective stack slots. If all the stack values are known to be zeros, then 3487 * so is the destination reg. Otherwise, the register is considered to be 3488 * SCALAR. This function does not deal with register filling; the caller must 3489 * ensure that all spilled registers in the stack range have been marked as 3490 * read. 3491 */ 3492 static void mark_reg_stack_read(struct bpf_verifier_env *env, 3493 /* func where src register points to */ 3494 struct bpf_func_state *ptr_state, 3495 int min_off, int max_off, int dst_regno) 3496 { 3497 struct bpf_verifier_state *vstate = env->cur_state; 3498 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3499 int i, slot, spi; 3500 u8 *stype; 3501 int zeros = 0; 3502 3503 for (i = min_off; i < max_off; i++) { 3504 slot = -i - 1; 3505 spi = slot / BPF_REG_SIZE; 3506 stype = ptr_state->stack[spi].slot_type; 3507 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 3508 break; 3509 zeros++; 3510 } 3511 if (zeros == max_off - min_off) { 3512 /* any access_size read into register is zero extended, 3513 * so the whole register == const_zero 3514 */ 3515 __mark_reg_const_zero(&state->regs[dst_regno]); 3516 /* backtracking doesn't support STACK_ZERO yet, 3517 * so mark it precise here, so that later 3518 * backtracking can stop here. 3519 * Backtracking may not need this if this register 3520 * doesn't participate in pointer adjustment. 3521 * Forward propagation of precise flag is not 3522 * necessary either. This mark is only to stop 3523 * backtracking. Any register that contributed 3524 * to const 0 was marked precise before spill. 3525 */ 3526 state->regs[dst_regno].precise = true; 3527 } else { 3528 /* have read misc data from the stack */ 3529 mark_reg_unknown(env, state->regs, dst_regno); 3530 } 3531 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3532 } 3533 3534 /* Read the stack at 'off' and put the results into the register indicated by 3535 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3536 * spilled reg. 3537 * 3538 * 'dst_regno' can be -1, meaning that the read value is not going to a 3539 * register. 3540 * 3541 * The access is assumed to be within the current stack bounds. 3542 */ 3543 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3544 /* func where src register points to */ 3545 struct bpf_func_state *reg_state, 3546 int off, int size, int dst_regno) 3547 { 3548 struct bpf_verifier_state *vstate = env->cur_state; 3549 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3550 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3551 struct bpf_reg_state *reg; 3552 u8 *stype, type; 3553 3554 stype = reg_state->stack[spi].slot_type; 3555 reg = ®_state->stack[spi].spilled_ptr; 3556 3557 if (is_spilled_reg(®_state->stack[spi])) { 3558 u8 spill_size = 1; 3559 3560 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3561 spill_size++; 3562 3563 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3564 if (reg->type != SCALAR_VALUE) { 3565 verbose_linfo(env, env->insn_idx, "; "); 3566 verbose(env, "invalid size of register fill\n"); 3567 return -EACCES; 3568 } 3569 3570 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3571 if (dst_regno < 0) 3572 return 0; 3573 3574 if (!(off % BPF_REG_SIZE) && size == spill_size) { 3575 /* The earlier check_reg_arg() has decided the 3576 * subreg_def for this insn. Save it first. 3577 */ 3578 s32 subreg_def = state->regs[dst_regno].subreg_def; 3579 3580 state->regs[dst_regno] = *reg; 3581 state->regs[dst_regno].subreg_def = subreg_def; 3582 } else { 3583 for (i = 0; i < size; i++) { 3584 type = stype[(slot - i) % BPF_REG_SIZE]; 3585 if (type == STACK_SPILL) 3586 continue; 3587 if (type == STACK_MISC) 3588 continue; 3589 verbose(env, "invalid read from stack off %d+%d size %d\n", 3590 off, i, size); 3591 return -EACCES; 3592 } 3593 mark_reg_unknown(env, state->regs, dst_regno); 3594 } 3595 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3596 return 0; 3597 } 3598 3599 if (dst_regno >= 0) { 3600 /* restore register state from stack */ 3601 state->regs[dst_regno] = *reg; 3602 /* mark reg as written since spilled pointer state likely 3603 * has its liveness marks cleared by is_state_visited() 3604 * which resets stack/reg liveness for state transitions 3605 */ 3606 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3607 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3608 /* If dst_regno==-1, the caller is asking us whether 3609 * it is acceptable to use this value as a SCALAR_VALUE 3610 * (e.g. for XADD). 3611 * We must not allow unprivileged callers to do that 3612 * with spilled pointers. 3613 */ 3614 verbose(env, "leaking pointer from stack off %d\n", 3615 off); 3616 return -EACCES; 3617 } 3618 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3619 } else { 3620 for (i = 0; i < size; i++) { 3621 type = stype[(slot - i) % BPF_REG_SIZE]; 3622 if (type == STACK_MISC) 3623 continue; 3624 if (type == STACK_ZERO) 3625 continue; 3626 verbose(env, "invalid read from stack off %d+%d size %d\n", 3627 off, i, size); 3628 return -EACCES; 3629 } 3630 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3631 if (dst_regno >= 0) 3632 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3633 } 3634 return 0; 3635 } 3636 3637 enum bpf_access_src { 3638 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3639 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3640 }; 3641 3642 static int check_stack_range_initialized(struct bpf_verifier_env *env, 3643 int regno, int off, int access_size, 3644 bool zero_size_allowed, 3645 enum bpf_access_src type, 3646 struct bpf_call_arg_meta *meta); 3647 3648 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3649 { 3650 return cur_regs(env) + regno; 3651 } 3652 3653 /* Read the stack at 'ptr_regno + off' and put the result into the register 3654 * 'dst_regno'. 3655 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 3656 * but not its variable offset. 3657 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3658 * 3659 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3660 * filling registers (i.e. reads of spilled register cannot be detected when 3661 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3662 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 3663 * offset; for a fixed offset check_stack_read_fixed_off should be used 3664 * instead. 3665 */ 3666 static int check_stack_read_var_off(struct bpf_verifier_env *env, 3667 int ptr_regno, int off, int size, int dst_regno) 3668 { 3669 /* The state of the source register. */ 3670 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3671 struct bpf_func_state *ptr_state = func(env, reg); 3672 int err; 3673 int min_off, max_off; 3674 3675 /* Note that we pass a NULL meta, so raw access will not be permitted. 3676 */ 3677 err = check_stack_range_initialized(env, ptr_regno, off, size, 3678 false, ACCESS_DIRECT, NULL); 3679 if (err) 3680 return err; 3681 3682 min_off = reg->smin_value + off; 3683 max_off = reg->smax_value + off; 3684 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 3685 return 0; 3686 } 3687 3688 /* check_stack_read dispatches to check_stack_read_fixed_off or 3689 * check_stack_read_var_off. 3690 * 3691 * The caller must ensure that the offset falls within the allocated stack 3692 * bounds. 3693 * 3694 * 'dst_regno' is a register which will receive the value from the stack. It 3695 * can be -1, meaning that the read value is not going to a register. 3696 */ 3697 static int check_stack_read(struct bpf_verifier_env *env, 3698 int ptr_regno, int off, int size, 3699 int dst_regno) 3700 { 3701 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3702 struct bpf_func_state *state = func(env, reg); 3703 int err; 3704 /* Some accesses are only permitted with a static offset. */ 3705 bool var_off = !tnum_is_const(reg->var_off); 3706 3707 /* The offset is required to be static when reads don't go to a 3708 * register, in order to not leak pointers (see 3709 * check_stack_read_fixed_off). 3710 */ 3711 if (dst_regno < 0 && var_off) { 3712 char tn_buf[48]; 3713 3714 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3715 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 3716 tn_buf, off, size); 3717 return -EACCES; 3718 } 3719 /* Variable offset is prohibited for unprivileged mode for simplicity 3720 * since it requires corresponding support in Spectre masking for stack 3721 * ALU. See also retrieve_ptr_limit(). 3722 */ 3723 if (!env->bypass_spec_v1 && var_off) { 3724 char tn_buf[48]; 3725 3726 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3727 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 3728 ptr_regno, tn_buf); 3729 return -EACCES; 3730 } 3731 3732 if (!var_off) { 3733 off += reg->var_off.value; 3734 err = check_stack_read_fixed_off(env, state, off, size, 3735 dst_regno); 3736 } else { 3737 /* Variable offset stack reads need more conservative handling 3738 * than fixed offset ones. Note that dst_regno >= 0 on this 3739 * branch. 3740 */ 3741 err = check_stack_read_var_off(env, ptr_regno, off, size, 3742 dst_regno); 3743 } 3744 return err; 3745 } 3746 3747 3748 /* check_stack_write dispatches to check_stack_write_fixed_off or 3749 * check_stack_write_var_off. 3750 * 3751 * 'ptr_regno' is the register used as a pointer into the stack. 3752 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 3753 * 'value_regno' is the register whose value we're writing to the stack. It can 3754 * be -1, meaning that we're not writing from a register. 3755 * 3756 * The caller must ensure that the offset falls within the maximum stack size. 3757 */ 3758 static int check_stack_write(struct bpf_verifier_env *env, 3759 int ptr_regno, int off, int size, 3760 int value_regno, int insn_idx) 3761 { 3762 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3763 struct bpf_func_state *state = func(env, reg); 3764 int err; 3765 3766 if (tnum_is_const(reg->var_off)) { 3767 off += reg->var_off.value; 3768 err = check_stack_write_fixed_off(env, state, off, size, 3769 value_regno, insn_idx); 3770 } else { 3771 /* Variable offset stack reads need more conservative handling 3772 * than fixed offset ones. 3773 */ 3774 err = check_stack_write_var_off(env, state, 3775 ptr_regno, off, size, 3776 value_regno, insn_idx); 3777 } 3778 return err; 3779 } 3780 3781 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 3782 int off, int size, enum bpf_access_type type) 3783 { 3784 struct bpf_reg_state *regs = cur_regs(env); 3785 struct bpf_map *map = regs[regno].map_ptr; 3786 u32 cap = bpf_map_flags_to_cap(map); 3787 3788 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 3789 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 3790 map->value_size, off, size); 3791 return -EACCES; 3792 } 3793 3794 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 3795 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 3796 map->value_size, off, size); 3797 return -EACCES; 3798 } 3799 3800 return 0; 3801 } 3802 3803 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 3804 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 3805 int off, int size, u32 mem_size, 3806 bool zero_size_allowed) 3807 { 3808 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 3809 struct bpf_reg_state *reg; 3810 3811 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 3812 return 0; 3813 3814 reg = &cur_regs(env)[regno]; 3815 switch (reg->type) { 3816 case PTR_TO_MAP_KEY: 3817 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 3818 mem_size, off, size); 3819 break; 3820 case PTR_TO_MAP_VALUE: 3821 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 3822 mem_size, off, size); 3823 break; 3824 case PTR_TO_PACKET: 3825 case PTR_TO_PACKET_META: 3826 case PTR_TO_PACKET_END: 3827 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 3828 off, size, regno, reg->id, off, mem_size); 3829 break; 3830 case PTR_TO_MEM: 3831 default: 3832 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 3833 mem_size, off, size); 3834 } 3835 3836 return -EACCES; 3837 } 3838 3839 /* check read/write into a memory region with possible variable offset */ 3840 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 3841 int off, int size, u32 mem_size, 3842 bool zero_size_allowed) 3843 { 3844 struct bpf_verifier_state *vstate = env->cur_state; 3845 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3846 struct bpf_reg_state *reg = &state->regs[regno]; 3847 int err; 3848 3849 /* We may have adjusted the register pointing to memory region, so we 3850 * need to try adding each of min_value and max_value to off 3851 * to make sure our theoretical access will be safe. 3852 * 3853 * The minimum value is only important with signed 3854 * comparisons where we can't assume the floor of a 3855 * value is 0. If we are using signed variables for our 3856 * index'es we need to make sure that whatever we use 3857 * will have a set floor within our range. 3858 */ 3859 if (reg->smin_value < 0 && 3860 (reg->smin_value == S64_MIN || 3861 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 3862 reg->smin_value + off < 0)) { 3863 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3864 regno); 3865 return -EACCES; 3866 } 3867 err = __check_mem_access(env, regno, reg->smin_value + off, size, 3868 mem_size, zero_size_allowed); 3869 if (err) { 3870 verbose(env, "R%d min value is outside of the allowed memory range\n", 3871 regno); 3872 return err; 3873 } 3874 3875 /* If we haven't set a max value then we need to bail since we can't be 3876 * sure we won't do bad things. 3877 * If reg->umax_value + off could overflow, treat that as unbounded too. 3878 */ 3879 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 3880 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 3881 regno); 3882 return -EACCES; 3883 } 3884 err = __check_mem_access(env, regno, reg->umax_value + off, size, 3885 mem_size, zero_size_allowed); 3886 if (err) { 3887 verbose(env, "R%d max value is outside of the allowed memory range\n", 3888 regno); 3889 return err; 3890 } 3891 3892 return 0; 3893 } 3894 3895 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 3896 const struct bpf_reg_state *reg, int regno, 3897 bool fixed_off_ok) 3898 { 3899 /* Access to this pointer-typed register or passing it to a helper 3900 * is only allowed in its original, unmodified form. 3901 */ 3902 3903 if (reg->off < 0) { 3904 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 3905 reg_type_str(env, reg->type), regno, reg->off); 3906 return -EACCES; 3907 } 3908 3909 if (!fixed_off_ok && reg->off) { 3910 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 3911 reg_type_str(env, reg->type), regno, reg->off); 3912 return -EACCES; 3913 } 3914 3915 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3916 char tn_buf[48]; 3917 3918 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3919 verbose(env, "variable %s access var_off=%s disallowed\n", 3920 reg_type_str(env, reg->type), tn_buf); 3921 return -EACCES; 3922 } 3923 3924 return 0; 3925 } 3926 3927 int check_ptr_off_reg(struct bpf_verifier_env *env, 3928 const struct bpf_reg_state *reg, int regno) 3929 { 3930 return __check_ptr_off_reg(env, reg, regno, false); 3931 } 3932 3933 static int map_kptr_match_type(struct bpf_verifier_env *env, 3934 struct btf_field *kptr_field, 3935 struct bpf_reg_state *reg, u32 regno) 3936 { 3937 const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 3938 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED; 3939 const char *reg_name = ""; 3940 3941 /* Only unreferenced case accepts untrusted pointers */ 3942 if (kptr_field->type == BPF_KPTR_UNREF) 3943 perm_flags |= PTR_UNTRUSTED; 3944 3945 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 3946 goto bad_type; 3947 3948 if (!btf_is_kernel(reg->btf)) { 3949 verbose(env, "R%d must point to kernel BTF\n", regno); 3950 return -EINVAL; 3951 } 3952 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 3953 reg_name = kernel_type_name(reg->btf, reg->btf_id); 3954 3955 /* For ref_ptr case, release function check should ensure we get one 3956 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 3957 * normal store of unreferenced kptr, we must ensure var_off is zero. 3958 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 3959 * reg->off and reg->ref_obj_id are not needed here. 3960 */ 3961 if (__check_ptr_off_reg(env, reg, regno, true)) 3962 return -EACCES; 3963 3964 /* A full type match is needed, as BTF can be vmlinux or module BTF, and 3965 * we also need to take into account the reg->off. 3966 * 3967 * We want to support cases like: 3968 * 3969 * struct foo { 3970 * struct bar br; 3971 * struct baz bz; 3972 * }; 3973 * 3974 * struct foo *v; 3975 * v = func(); // PTR_TO_BTF_ID 3976 * val->foo = v; // reg->off is zero, btf and btf_id match type 3977 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 3978 * // first member type of struct after comparison fails 3979 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 3980 * // to match type 3981 * 3982 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 3983 * is zero. We must also ensure that btf_struct_ids_match does not walk 3984 * the struct to match type against first member of struct, i.e. reject 3985 * second case from above. Hence, when type is BPF_KPTR_REF, we set 3986 * strict mode to true for type match. 3987 */ 3988 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 3989 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 3990 kptr_field->type == BPF_KPTR_REF)) 3991 goto bad_type; 3992 return 0; 3993 bad_type: 3994 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 3995 reg_type_str(env, reg->type), reg_name); 3996 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 3997 if (kptr_field->type == BPF_KPTR_UNREF) 3998 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 3999 targ_name); 4000 else 4001 verbose(env, "\n"); 4002 return -EINVAL; 4003 } 4004 4005 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 4006 int value_regno, int insn_idx, 4007 struct btf_field *kptr_field) 4008 { 4009 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4010 int class = BPF_CLASS(insn->code); 4011 struct bpf_reg_state *val_reg; 4012 4013 /* Things we already checked for in check_map_access and caller: 4014 * - Reject cases where variable offset may touch kptr 4015 * - size of access (must be BPF_DW) 4016 * - tnum_is_const(reg->var_off) 4017 * - kptr_field->offset == off + reg->var_off.value 4018 */ 4019 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4020 if (BPF_MODE(insn->code) != BPF_MEM) { 4021 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4022 return -EACCES; 4023 } 4024 4025 /* We only allow loading referenced kptr, since it will be marked as 4026 * untrusted, similar to unreferenced kptr. 4027 */ 4028 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) { 4029 verbose(env, "store to referenced kptr disallowed\n"); 4030 return -EACCES; 4031 } 4032 4033 if (class == BPF_LDX) { 4034 val_reg = reg_state(env, value_regno); 4035 /* We can simply mark the value_regno receiving the pointer 4036 * value from map as PTR_TO_BTF_ID, with the correct type. 4037 */ 4038 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 4039 kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED); 4040 /* For mark_ptr_or_null_reg */ 4041 val_reg->id = ++env->id_gen; 4042 } else if (class == BPF_STX) { 4043 val_reg = reg_state(env, value_regno); 4044 if (!register_is_null(val_reg) && 4045 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4046 return -EACCES; 4047 } else if (class == BPF_ST) { 4048 if (insn->imm) { 4049 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4050 kptr_field->offset); 4051 return -EACCES; 4052 } 4053 } else { 4054 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4055 return -EACCES; 4056 } 4057 return 0; 4058 } 4059 4060 /* check read/write into a map element with possible variable offset */ 4061 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 4062 int off, int size, bool zero_size_allowed, 4063 enum bpf_access_src src) 4064 { 4065 struct bpf_verifier_state *vstate = env->cur_state; 4066 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4067 struct bpf_reg_state *reg = &state->regs[regno]; 4068 struct bpf_map *map = reg->map_ptr; 4069 struct btf_record *rec; 4070 int err, i; 4071 4072 err = check_mem_region_access(env, regno, off, size, map->value_size, 4073 zero_size_allowed); 4074 if (err) 4075 return err; 4076 4077 if (IS_ERR_OR_NULL(map->record)) 4078 return 0; 4079 rec = map->record; 4080 for (i = 0; i < rec->cnt; i++) { 4081 struct btf_field *field = &rec->fields[i]; 4082 u32 p = field->offset; 4083 4084 /* If any part of a field can be touched by load/store, reject 4085 * this program. To check that [x1, x2) overlaps with [y1, y2), 4086 * it is sufficient to check x1 < y2 && y1 < x2. 4087 */ 4088 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 4089 p < reg->umax_value + off + size) { 4090 switch (field->type) { 4091 case BPF_KPTR_UNREF: 4092 case BPF_KPTR_REF: 4093 if (src != ACCESS_DIRECT) { 4094 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 4095 return -EACCES; 4096 } 4097 if (!tnum_is_const(reg->var_off)) { 4098 verbose(env, "kptr access cannot have variable offset\n"); 4099 return -EACCES; 4100 } 4101 if (p != off + reg->var_off.value) { 4102 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 4103 p, off + reg->var_off.value); 4104 return -EACCES; 4105 } 4106 if (size != bpf_size_to_bytes(BPF_DW)) { 4107 verbose(env, "kptr access size must be BPF_DW\n"); 4108 return -EACCES; 4109 } 4110 break; 4111 default: 4112 verbose(env, "%s cannot be accessed directly by load/store\n", 4113 btf_field_type_name(field->type)); 4114 return -EACCES; 4115 } 4116 } 4117 } 4118 return 0; 4119 } 4120 4121 #define MAX_PACKET_OFF 0xffff 4122 4123 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4124 const struct bpf_call_arg_meta *meta, 4125 enum bpf_access_type t) 4126 { 4127 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4128 4129 switch (prog_type) { 4130 /* Program types only with direct read access go here! */ 4131 case BPF_PROG_TYPE_LWT_IN: 4132 case BPF_PROG_TYPE_LWT_OUT: 4133 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4134 case BPF_PROG_TYPE_SK_REUSEPORT: 4135 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4136 case BPF_PROG_TYPE_CGROUP_SKB: 4137 if (t == BPF_WRITE) 4138 return false; 4139 fallthrough; 4140 4141 /* Program types with direct read + write access go here! */ 4142 case BPF_PROG_TYPE_SCHED_CLS: 4143 case BPF_PROG_TYPE_SCHED_ACT: 4144 case BPF_PROG_TYPE_XDP: 4145 case BPF_PROG_TYPE_LWT_XMIT: 4146 case BPF_PROG_TYPE_SK_SKB: 4147 case BPF_PROG_TYPE_SK_MSG: 4148 if (meta) 4149 return meta->pkt_access; 4150 4151 env->seen_direct_write = true; 4152 return true; 4153 4154 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4155 if (t == BPF_WRITE) 4156 env->seen_direct_write = true; 4157 4158 return true; 4159 4160 default: 4161 return false; 4162 } 4163 } 4164 4165 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 4166 int size, bool zero_size_allowed) 4167 { 4168 struct bpf_reg_state *regs = cur_regs(env); 4169 struct bpf_reg_state *reg = ®s[regno]; 4170 int err; 4171 4172 /* We may have added a variable offset to the packet pointer; but any 4173 * reg->range we have comes after that. We are only checking the fixed 4174 * offset. 4175 */ 4176 4177 /* We don't allow negative numbers, because we aren't tracking enough 4178 * detail to prove they're safe. 4179 */ 4180 if (reg->smin_value < 0) { 4181 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4182 regno); 4183 return -EACCES; 4184 } 4185 4186 err = reg->range < 0 ? -EINVAL : 4187 __check_mem_access(env, regno, off, size, reg->range, 4188 zero_size_allowed); 4189 if (err) { 4190 verbose(env, "R%d offset is outside of the packet\n", regno); 4191 return err; 4192 } 4193 4194 /* __check_mem_access has made sure "off + size - 1" is within u16. 4195 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 4196 * otherwise find_good_pkt_pointers would have refused to set range info 4197 * that __check_mem_access would have rejected this pkt access. 4198 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 4199 */ 4200 env->prog->aux->max_pkt_offset = 4201 max_t(u32, env->prog->aux->max_pkt_offset, 4202 off + reg->umax_value + size - 1); 4203 4204 return err; 4205 } 4206 4207 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4208 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4209 enum bpf_access_type t, enum bpf_reg_type *reg_type, 4210 struct btf **btf, u32 *btf_id) 4211 { 4212 struct bpf_insn_access_aux info = { 4213 .reg_type = *reg_type, 4214 .log = &env->log, 4215 }; 4216 4217 if (env->ops->is_valid_access && 4218 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 4219 /* A non zero info.ctx_field_size indicates that this field is a 4220 * candidate for later verifier transformation to load the whole 4221 * field and then apply a mask when accessed with a narrower 4222 * access than actual ctx access size. A zero info.ctx_field_size 4223 * will only allow for whole field access and rejects any other 4224 * type of narrower access. 4225 */ 4226 *reg_type = info.reg_type; 4227 4228 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 4229 *btf = info.btf; 4230 *btf_id = info.btf_id; 4231 } else { 4232 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 4233 } 4234 /* remember the offset of last byte accessed in ctx */ 4235 if (env->prog->aux->max_ctx_offset < off + size) 4236 env->prog->aux->max_ctx_offset = off + size; 4237 return 0; 4238 } 4239 4240 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4241 return -EACCES; 4242 } 4243 4244 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 4245 int size) 4246 { 4247 if (size < 0 || off < 0 || 4248 (u64)off + size > sizeof(struct bpf_flow_keys)) { 4249 verbose(env, "invalid access to flow keys off=%d size=%d\n", 4250 off, size); 4251 return -EACCES; 4252 } 4253 return 0; 4254 } 4255 4256 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 4257 u32 regno, int off, int size, 4258 enum bpf_access_type t) 4259 { 4260 struct bpf_reg_state *regs = cur_regs(env); 4261 struct bpf_reg_state *reg = ®s[regno]; 4262 struct bpf_insn_access_aux info = {}; 4263 bool valid; 4264 4265 if (reg->smin_value < 0) { 4266 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4267 regno); 4268 return -EACCES; 4269 } 4270 4271 switch (reg->type) { 4272 case PTR_TO_SOCK_COMMON: 4273 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 4274 break; 4275 case PTR_TO_SOCKET: 4276 valid = bpf_sock_is_valid_access(off, size, t, &info); 4277 break; 4278 case PTR_TO_TCP_SOCK: 4279 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 4280 break; 4281 case PTR_TO_XDP_SOCK: 4282 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 4283 break; 4284 default: 4285 valid = false; 4286 } 4287 4288 4289 if (valid) { 4290 env->insn_aux_data[insn_idx].ctx_field_size = 4291 info.ctx_field_size; 4292 return 0; 4293 } 4294 4295 verbose(env, "R%d invalid %s access off=%d size=%d\n", 4296 regno, reg_type_str(env, reg->type), off, size); 4297 4298 return -EACCES; 4299 } 4300 4301 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 4302 { 4303 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 4304 } 4305 4306 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 4307 { 4308 const struct bpf_reg_state *reg = reg_state(env, regno); 4309 4310 return reg->type == PTR_TO_CTX; 4311 } 4312 4313 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 4314 { 4315 const struct bpf_reg_state *reg = reg_state(env, regno); 4316 4317 return type_is_sk_pointer(reg->type); 4318 } 4319 4320 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 4321 { 4322 const struct bpf_reg_state *reg = reg_state(env, regno); 4323 4324 return type_is_pkt_pointer(reg->type); 4325 } 4326 4327 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 4328 { 4329 const struct bpf_reg_state *reg = reg_state(env, regno); 4330 4331 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 4332 return reg->type == PTR_TO_FLOW_KEYS; 4333 } 4334 4335 static bool is_trusted_reg(const struct bpf_reg_state *reg) 4336 { 4337 /* A referenced register is always trusted. */ 4338 if (reg->ref_obj_id) 4339 return true; 4340 4341 /* If a register is not referenced, it is trusted if it has the 4342 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 4343 * other type modifiers may be safe, but we elect to take an opt-in 4344 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 4345 * not. 4346 * 4347 * Eventually, we should make PTR_TRUSTED the single source of truth 4348 * for whether a register is trusted. 4349 */ 4350 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 4351 !bpf_type_has_unsafe_modifiers(reg->type); 4352 } 4353 4354 static bool is_rcu_reg(const struct bpf_reg_state *reg) 4355 { 4356 return reg->type & MEM_RCU; 4357 } 4358 4359 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 4360 const struct bpf_reg_state *reg, 4361 int off, int size, bool strict) 4362 { 4363 struct tnum reg_off; 4364 int ip_align; 4365 4366 /* Byte size accesses are always allowed. */ 4367 if (!strict || size == 1) 4368 return 0; 4369 4370 /* For platforms that do not have a Kconfig enabling 4371 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 4372 * NET_IP_ALIGN is universally set to '2'. And on platforms 4373 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 4374 * to this code only in strict mode where we want to emulate 4375 * the NET_IP_ALIGN==2 checking. Therefore use an 4376 * unconditional IP align value of '2'. 4377 */ 4378 ip_align = 2; 4379 4380 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 4381 if (!tnum_is_aligned(reg_off, size)) { 4382 char tn_buf[48]; 4383 4384 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4385 verbose(env, 4386 "misaligned packet access off %d+%s+%d+%d size %d\n", 4387 ip_align, tn_buf, reg->off, off, size); 4388 return -EACCES; 4389 } 4390 4391 return 0; 4392 } 4393 4394 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 4395 const struct bpf_reg_state *reg, 4396 const char *pointer_desc, 4397 int off, int size, bool strict) 4398 { 4399 struct tnum reg_off; 4400 4401 /* Byte size accesses are always allowed. */ 4402 if (!strict || size == 1) 4403 return 0; 4404 4405 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 4406 if (!tnum_is_aligned(reg_off, size)) { 4407 char tn_buf[48]; 4408 4409 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4410 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 4411 pointer_desc, tn_buf, reg->off, off, size); 4412 return -EACCES; 4413 } 4414 4415 return 0; 4416 } 4417 4418 static int check_ptr_alignment(struct bpf_verifier_env *env, 4419 const struct bpf_reg_state *reg, int off, 4420 int size, bool strict_alignment_once) 4421 { 4422 bool strict = env->strict_alignment || strict_alignment_once; 4423 const char *pointer_desc = ""; 4424 4425 switch (reg->type) { 4426 case PTR_TO_PACKET: 4427 case PTR_TO_PACKET_META: 4428 /* Special case, because of NET_IP_ALIGN. Given metadata sits 4429 * right in front, treat it the very same way. 4430 */ 4431 return check_pkt_ptr_alignment(env, reg, off, size, strict); 4432 case PTR_TO_FLOW_KEYS: 4433 pointer_desc = "flow keys "; 4434 break; 4435 case PTR_TO_MAP_KEY: 4436 pointer_desc = "key "; 4437 break; 4438 case PTR_TO_MAP_VALUE: 4439 pointer_desc = "value "; 4440 break; 4441 case PTR_TO_CTX: 4442 pointer_desc = "context "; 4443 break; 4444 case PTR_TO_STACK: 4445 pointer_desc = "stack "; 4446 /* The stack spill tracking logic in check_stack_write_fixed_off() 4447 * and check_stack_read_fixed_off() relies on stack accesses being 4448 * aligned. 4449 */ 4450 strict = true; 4451 break; 4452 case PTR_TO_SOCKET: 4453 pointer_desc = "sock "; 4454 break; 4455 case PTR_TO_SOCK_COMMON: 4456 pointer_desc = "sock_common "; 4457 break; 4458 case PTR_TO_TCP_SOCK: 4459 pointer_desc = "tcp_sock "; 4460 break; 4461 case PTR_TO_XDP_SOCK: 4462 pointer_desc = "xdp_sock "; 4463 break; 4464 default: 4465 break; 4466 } 4467 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 4468 strict); 4469 } 4470 4471 static int update_stack_depth(struct bpf_verifier_env *env, 4472 const struct bpf_func_state *func, 4473 int off) 4474 { 4475 u16 stack = env->subprog_info[func->subprogno].stack_depth; 4476 4477 if (stack >= -off) 4478 return 0; 4479 4480 /* update known max for given subprogram */ 4481 env->subprog_info[func->subprogno].stack_depth = -off; 4482 return 0; 4483 } 4484 4485 /* starting from main bpf function walk all instructions of the function 4486 * and recursively walk all callees that given function can call. 4487 * Ignore jump and exit insns. 4488 * Since recursion is prevented by check_cfg() this algorithm 4489 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 4490 */ 4491 static int check_max_stack_depth(struct bpf_verifier_env *env) 4492 { 4493 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 4494 struct bpf_subprog_info *subprog = env->subprog_info; 4495 struct bpf_insn *insn = env->prog->insnsi; 4496 bool tail_call_reachable = false; 4497 int ret_insn[MAX_CALL_FRAMES]; 4498 int ret_prog[MAX_CALL_FRAMES]; 4499 int j; 4500 4501 process_func: 4502 /* protect against potential stack overflow that might happen when 4503 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 4504 * depth for such case down to 256 so that the worst case scenario 4505 * would result in 8k stack size (32 which is tailcall limit * 256 = 4506 * 8k). 4507 * 4508 * To get the idea what might happen, see an example: 4509 * func1 -> sub rsp, 128 4510 * subfunc1 -> sub rsp, 256 4511 * tailcall1 -> add rsp, 256 4512 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 4513 * subfunc2 -> sub rsp, 64 4514 * subfunc22 -> sub rsp, 128 4515 * tailcall2 -> add rsp, 128 4516 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 4517 * 4518 * tailcall will unwind the current stack frame but it will not get rid 4519 * of caller's stack as shown on the example above. 4520 */ 4521 if (idx && subprog[idx].has_tail_call && depth >= 256) { 4522 verbose(env, 4523 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 4524 depth); 4525 return -EACCES; 4526 } 4527 /* round up to 32-bytes, since this is granularity 4528 * of interpreter stack size 4529 */ 4530 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 4531 if (depth > MAX_BPF_STACK) { 4532 verbose(env, "combined stack size of %d calls is %d. Too large\n", 4533 frame + 1, depth); 4534 return -EACCES; 4535 } 4536 continue_func: 4537 subprog_end = subprog[idx + 1].start; 4538 for (; i < subprog_end; i++) { 4539 int next_insn; 4540 4541 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 4542 continue; 4543 /* remember insn and function to return to */ 4544 ret_insn[frame] = i + 1; 4545 ret_prog[frame] = idx; 4546 4547 /* find the callee */ 4548 next_insn = i + insn[i].imm + 1; 4549 idx = find_subprog(env, next_insn); 4550 if (idx < 0) { 4551 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 4552 next_insn); 4553 return -EFAULT; 4554 } 4555 if (subprog[idx].is_async_cb) { 4556 if (subprog[idx].has_tail_call) { 4557 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 4558 return -EFAULT; 4559 } 4560 /* async callbacks don't increase bpf prog stack size */ 4561 continue; 4562 } 4563 i = next_insn; 4564 4565 if (subprog[idx].has_tail_call) 4566 tail_call_reachable = true; 4567 4568 frame++; 4569 if (frame >= MAX_CALL_FRAMES) { 4570 verbose(env, "the call stack of %d frames is too deep !\n", 4571 frame); 4572 return -E2BIG; 4573 } 4574 goto process_func; 4575 } 4576 /* if tail call got detected across bpf2bpf calls then mark each of the 4577 * currently present subprog frames as tail call reachable subprogs; 4578 * this info will be utilized by JIT so that we will be preserving the 4579 * tail call counter throughout bpf2bpf calls combined with tailcalls 4580 */ 4581 if (tail_call_reachable) 4582 for (j = 0; j < frame; j++) 4583 subprog[ret_prog[j]].tail_call_reachable = true; 4584 if (subprog[0].tail_call_reachable) 4585 env->prog->aux->tail_call_reachable = true; 4586 4587 /* end of for() loop means the last insn of the 'subprog' 4588 * was reached. Doesn't matter whether it was JA or EXIT 4589 */ 4590 if (frame == 0) 4591 return 0; 4592 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 4593 frame--; 4594 i = ret_insn[frame]; 4595 idx = ret_prog[frame]; 4596 goto continue_func; 4597 } 4598 4599 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 4600 static int get_callee_stack_depth(struct bpf_verifier_env *env, 4601 const struct bpf_insn *insn, int idx) 4602 { 4603 int start = idx + insn->imm + 1, subprog; 4604 4605 subprog = find_subprog(env, start); 4606 if (subprog < 0) { 4607 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 4608 start); 4609 return -EFAULT; 4610 } 4611 return env->subprog_info[subprog].stack_depth; 4612 } 4613 #endif 4614 4615 static int __check_buffer_access(struct bpf_verifier_env *env, 4616 const char *buf_info, 4617 const struct bpf_reg_state *reg, 4618 int regno, int off, int size) 4619 { 4620 if (off < 0) { 4621 verbose(env, 4622 "R%d invalid %s buffer access: off=%d, size=%d\n", 4623 regno, buf_info, off, size); 4624 return -EACCES; 4625 } 4626 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4627 char tn_buf[48]; 4628 4629 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4630 verbose(env, 4631 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 4632 regno, off, tn_buf); 4633 return -EACCES; 4634 } 4635 4636 return 0; 4637 } 4638 4639 static int check_tp_buffer_access(struct bpf_verifier_env *env, 4640 const struct bpf_reg_state *reg, 4641 int regno, int off, int size) 4642 { 4643 int err; 4644 4645 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 4646 if (err) 4647 return err; 4648 4649 if (off + size > env->prog->aux->max_tp_access) 4650 env->prog->aux->max_tp_access = off + size; 4651 4652 return 0; 4653 } 4654 4655 static int check_buffer_access(struct bpf_verifier_env *env, 4656 const struct bpf_reg_state *reg, 4657 int regno, int off, int size, 4658 bool zero_size_allowed, 4659 u32 *max_access) 4660 { 4661 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 4662 int err; 4663 4664 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 4665 if (err) 4666 return err; 4667 4668 if (off + size > *max_access) 4669 *max_access = off + size; 4670 4671 return 0; 4672 } 4673 4674 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 4675 static void zext_32_to_64(struct bpf_reg_state *reg) 4676 { 4677 reg->var_off = tnum_subreg(reg->var_off); 4678 __reg_assign_32_into_64(reg); 4679 } 4680 4681 /* truncate register to smaller size (in bytes) 4682 * must be called with size < BPF_REG_SIZE 4683 */ 4684 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 4685 { 4686 u64 mask; 4687 4688 /* clear high bits in bit representation */ 4689 reg->var_off = tnum_cast(reg->var_off, size); 4690 4691 /* fix arithmetic bounds */ 4692 mask = ((u64)1 << (size * 8)) - 1; 4693 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 4694 reg->umin_value &= mask; 4695 reg->umax_value &= mask; 4696 } else { 4697 reg->umin_value = 0; 4698 reg->umax_value = mask; 4699 } 4700 reg->smin_value = reg->umin_value; 4701 reg->smax_value = reg->umax_value; 4702 4703 /* If size is smaller than 32bit register the 32bit register 4704 * values are also truncated so we push 64-bit bounds into 4705 * 32-bit bounds. Above were truncated < 32-bits already. 4706 */ 4707 if (size >= 4) 4708 return; 4709 __reg_combine_64_into_32(reg); 4710 } 4711 4712 static bool bpf_map_is_rdonly(const struct bpf_map *map) 4713 { 4714 /* A map is considered read-only if the following condition are true: 4715 * 4716 * 1) BPF program side cannot change any of the map content. The 4717 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 4718 * and was set at map creation time. 4719 * 2) The map value(s) have been initialized from user space by a 4720 * loader and then "frozen", such that no new map update/delete 4721 * operations from syscall side are possible for the rest of 4722 * the map's lifetime from that point onwards. 4723 * 3) Any parallel/pending map update/delete operations from syscall 4724 * side have been completed. Only after that point, it's safe to 4725 * assume that map value(s) are immutable. 4726 */ 4727 return (map->map_flags & BPF_F_RDONLY_PROG) && 4728 READ_ONCE(map->frozen) && 4729 !bpf_map_write_active(map); 4730 } 4731 4732 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 4733 { 4734 void *ptr; 4735 u64 addr; 4736 int err; 4737 4738 err = map->ops->map_direct_value_addr(map, &addr, off); 4739 if (err) 4740 return err; 4741 ptr = (void *)(long)addr + off; 4742 4743 switch (size) { 4744 case sizeof(u8): 4745 *val = (u64)*(u8 *)ptr; 4746 break; 4747 case sizeof(u16): 4748 *val = (u64)*(u16 *)ptr; 4749 break; 4750 case sizeof(u32): 4751 *val = (u64)*(u32 *)ptr; 4752 break; 4753 case sizeof(u64): 4754 *val = *(u64 *)ptr; 4755 break; 4756 default: 4757 return -EINVAL; 4758 } 4759 return 0; 4760 } 4761 4762 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 4763 struct bpf_reg_state *regs, 4764 int regno, int off, int size, 4765 enum bpf_access_type atype, 4766 int value_regno) 4767 { 4768 struct bpf_reg_state *reg = regs + regno; 4769 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 4770 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 4771 enum bpf_type_flag flag = 0; 4772 u32 btf_id; 4773 int ret; 4774 4775 if (!env->allow_ptr_leaks) { 4776 verbose(env, 4777 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 4778 tname); 4779 return -EPERM; 4780 } 4781 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 4782 verbose(env, 4783 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 4784 tname); 4785 return -EINVAL; 4786 } 4787 if (off < 0) { 4788 verbose(env, 4789 "R%d is ptr_%s invalid negative access: off=%d\n", 4790 regno, tname, off); 4791 return -EACCES; 4792 } 4793 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4794 char tn_buf[48]; 4795 4796 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4797 verbose(env, 4798 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 4799 regno, tname, off, tn_buf); 4800 return -EACCES; 4801 } 4802 4803 if (reg->type & MEM_USER) { 4804 verbose(env, 4805 "R%d is ptr_%s access user memory: off=%d\n", 4806 regno, tname, off); 4807 return -EACCES; 4808 } 4809 4810 if (reg->type & MEM_PERCPU) { 4811 verbose(env, 4812 "R%d is ptr_%s access percpu memory: off=%d\n", 4813 regno, tname, off); 4814 return -EACCES; 4815 } 4816 4817 if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) { 4818 if (!btf_is_kernel(reg->btf)) { 4819 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 4820 return -EFAULT; 4821 } 4822 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag); 4823 } else { 4824 /* Writes are permitted with default btf_struct_access for 4825 * program allocated objects (which always have ref_obj_id > 0), 4826 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 4827 */ 4828 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 4829 verbose(env, "only read is supported\n"); 4830 return -EACCES; 4831 } 4832 4833 if (type_is_alloc(reg->type) && !reg->ref_obj_id) { 4834 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 4835 return -EFAULT; 4836 } 4837 4838 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag); 4839 } 4840 4841 if (ret < 0) 4842 return ret; 4843 4844 /* If this is an untrusted pointer, all pointers formed by walking it 4845 * also inherit the untrusted flag. 4846 */ 4847 if (type_flag(reg->type) & PTR_UNTRUSTED) 4848 flag |= PTR_UNTRUSTED; 4849 4850 /* By default any pointer obtained from walking a trusted pointer is 4851 * no longer trusted except the rcu case below. 4852 */ 4853 flag &= ~PTR_TRUSTED; 4854 4855 if (flag & MEM_RCU) { 4856 /* Mark value register as MEM_RCU only if it is protected by 4857 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU 4858 * itself can already indicate trustedness inside the rcu 4859 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since 4860 * it could be null in some cases. 4861 */ 4862 if (!env->cur_state->active_rcu_lock || 4863 !(is_trusted_reg(reg) || is_rcu_reg(reg))) 4864 flag &= ~MEM_RCU; 4865 else 4866 flag |= PTR_MAYBE_NULL; 4867 } else if (reg->type & MEM_RCU) { 4868 /* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged 4869 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively. 4870 */ 4871 flag |= PTR_UNTRUSTED; 4872 } 4873 4874 if (atype == BPF_READ && value_regno >= 0) 4875 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 4876 4877 return 0; 4878 } 4879 4880 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 4881 struct bpf_reg_state *regs, 4882 int regno, int off, int size, 4883 enum bpf_access_type atype, 4884 int value_regno) 4885 { 4886 struct bpf_reg_state *reg = regs + regno; 4887 struct bpf_map *map = reg->map_ptr; 4888 struct bpf_reg_state map_reg; 4889 enum bpf_type_flag flag = 0; 4890 const struct btf_type *t; 4891 const char *tname; 4892 u32 btf_id; 4893 int ret; 4894 4895 if (!btf_vmlinux) { 4896 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 4897 return -ENOTSUPP; 4898 } 4899 4900 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 4901 verbose(env, "map_ptr access not supported for map type %d\n", 4902 map->map_type); 4903 return -ENOTSUPP; 4904 } 4905 4906 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 4907 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 4908 4909 if (!env->allow_ptr_leaks) { 4910 verbose(env, 4911 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 4912 tname); 4913 return -EPERM; 4914 } 4915 4916 if (off < 0) { 4917 verbose(env, "R%d is %s invalid negative access: off=%d\n", 4918 regno, tname, off); 4919 return -EACCES; 4920 } 4921 4922 if (atype != BPF_READ) { 4923 verbose(env, "only read from %s is supported\n", tname); 4924 return -EACCES; 4925 } 4926 4927 /* Simulate access to a PTR_TO_BTF_ID */ 4928 memset(&map_reg, 0, sizeof(map_reg)); 4929 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 4930 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag); 4931 if (ret < 0) 4932 return ret; 4933 4934 if (value_regno >= 0) 4935 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 4936 4937 return 0; 4938 } 4939 4940 /* Check that the stack access at the given offset is within bounds. The 4941 * maximum valid offset is -1. 4942 * 4943 * The minimum valid offset is -MAX_BPF_STACK for writes, and 4944 * -state->allocated_stack for reads. 4945 */ 4946 static int check_stack_slot_within_bounds(int off, 4947 struct bpf_func_state *state, 4948 enum bpf_access_type t) 4949 { 4950 int min_valid_off; 4951 4952 if (t == BPF_WRITE) 4953 min_valid_off = -MAX_BPF_STACK; 4954 else 4955 min_valid_off = -state->allocated_stack; 4956 4957 if (off < min_valid_off || off > -1) 4958 return -EACCES; 4959 return 0; 4960 } 4961 4962 /* Check that the stack access at 'regno + off' falls within the maximum stack 4963 * bounds. 4964 * 4965 * 'off' includes `regno->offset`, but not its dynamic part (if any). 4966 */ 4967 static int check_stack_access_within_bounds( 4968 struct bpf_verifier_env *env, 4969 int regno, int off, int access_size, 4970 enum bpf_access_src src, enum bpf_access_type type) 4971 { 4972 struct bpf_reg_state *regs = cur_regs(env); 4973 struct bpf_reg_state *reg = regs + regno; 4974 struct bpf_func_state *state = func(env, reg); 4975 int min_off, max_off; 4976 int err; 4977 char *err_extra; 4978 4979 if (src == ACCESS_HELPER) 4980 /* We don't know if helpers are reading or writing (or both). */ 4981 err_extra = " indirect access to"; 4982 else if (type == BPF_READ) 4983 err_extra = " read from"; 4984 else 4985 err_extra = " write to"; 4986 4987 if (tnum_is_const(reg->var_off)) { 4988 min_off = reg->var_off.value + off; 4989 if (access_size > 0) 4990 max_off = min_off + access_size - 1; 4991 else 4992 max_off = min_off; 4993 } else { 4994 if (reg->smax_value >= BPF_MAX_VAR_OFF || 4995 reg->smin_value <= -BPF_MAX_VAR_OFF) { 4996 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 4997 err_extra, regno); 4998 return -EACCES; 4999 } 5000 min_off = reg->smin_value + off; 5001 if (access_size > 0) 5002 max_off = reg->smax_value + off + access_size - 1; 5003 else 5004 max_off = min_off; 5005 } 5006 5007 err = check_stack_slot_within_bounds(min_off, state, type); 5008 if (!err) 5009 err = check_stack_slot_within_bounds(max_off, state, type); 5010 5011 if (err) { 5012 if (tnum_is_const(reg->var_off)) { 5013 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 5014 err_extra, regno, off, access_size); 5015 } else { 5016 char tn_buf[48]; 5017 5018 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5019 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 5020 err_extra, regno, tn_buf, access_size); 5021 } 5022 } 5023 return err; 5024 } 5025 5026 /* check whether memory at (regno + off) is accessible for t = (read | write) 5027 * if t==write, value_regno is a register which value is stored into memory 5028 * if t==read, value_regno is a register which will receive the value from memory 5029 * if t==write && value_regno==-1, some unknown value is stored into memory 5030 * if t==read && value_regno==-1, don't care what we read from memory 5031 */ 5032 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 5033 int off, int bpf_size, enum bpf_access_type t, 5034 int value_regno, bool strict_alignment_once) 5035 { 5036 struct bpf_reg_state *regs = cur_regs(env); 5037 struct bpf_reg_state *reg = regs + regno; 5038 struct bpf_func_state *state; 5039 int size, err = 0; 5040 5041 size = bpf_size_to_bytes(bpf_size); 5042 if (size < 0) 5043 return size; 5044 5045 /* alignment checks will add in reg->off themselves */ 5046 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 5047 if (err) 5048 return err; 5049 5050 /* for access checks, reg->off is just part of off */ 5051 off += reg->off; 5052 5053 if (reg->type == PTR_TO_MAP_KEY) { 5054 if (t == BPF_WRITE) { 5055 verbose(env, "write to change key R%d not allowed\n", regno); 5056 return -EACCES; 5057 } 5058 5059 err = check_mem_region_access(env, regno, off, size, 5060 reg->map_ptr->key_size, false); 5061 if (err) 5062 return err; 5063 if (value_regno >= 0) 5064 mark_reg_unknown(env, regs, value_regno); 5065 } else if (reg->type == PTR_TO_MAP_VALUE) { 5066 struct btf_field *kptr_field = NULL; 5067 5068 if (t == BPF_WRITE && value_regno >= 0 && 5069 is_pointer_value(env, value_regno)) { 5070 verbose(env, "R%d leaks addr into map\n", value_regno); 5071 return -EACCES; 5072 } 5073 err = check_map_access_type(env, regno, off, size, t); 5074 if (err) 5075 return err; 5076 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 5077 if (err) 5078 return err; 5079 if (tnum_is_const(reg->var_off)) 5080 kptr_field = btf_record_find(reg->map_ptr->record, 5081 off + reg->var_off.value, BPF_KPTR); 5082 if (kptr_field) { 5083 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 5084 } else if (t == BPF_READ && value_regno >= 0) { 5085 struct bpf_map *map = reg->map_ptr; 5086 5087 /* if map is read-only, track its contents as scalars */ 5088 if (tnum_is_const(reg->var_off) && 5089 bpf_map_is_rdonly(map) && 5090 map->ops->map_direct_value_addr) { 5091 int map_off = off + reg->var_off.value; 5092 u64 val = 0; 5093 5094 err = bpf_map_direct_read(map, map_off, size, 5095 &val); 5096 if (err) 5097 return err; 5098 5099 regs[value_regno].type = SCALAR_VALUE; 5100 __mark_reg_known(®s[value_regno], val); 5101 } else { 5102 mark_reg_unknown(env, regs, value_regno); 5103 } 5104 } 5105 } else if (base_type(reg->type) == PTR_TO_MEM) { 5106 bool rdonly_mem = type_is_rdonly_mem(reg->type); 5107 5108 if (type_may_be_null(reg->type)) { 5109 verbose(env, "R%d invalid mem access '%s'\n", regno, 5110 reg_type_str(env, reg->type)); 5111 return -EACCES; 5112 } 5113 5114 if (t == BPF_WRITE && rdonly_mem) { 5115 verbose(env, "R%d cannot write into %s\n", 5116 regno, reg_type_str(env, reg->type)); 5117 return -EACCES; 5118 } 5119 5120 if (t == BPF_WRITE && value_regno >= 0 && 5121 is_pointer_value(env, value_regno)) { 5122 verbose(env, "R%d leaks addr into mem\n", value_regno); 5123 return -EACCES; 5124 } 5125 5126 err = check_mem_region_access(env, regno, off, size, 5127 reg->mem_size, false); 5128 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 5129 mark_reg_unknown(env, regs, value_regno); 5130 } else if (reg->type == PTR_TO_CTX) { 5131 enum bpf_reg_type reg_type = SCALAR_VALUE; 5132 struct btf *btf = NULL; 5133 u32 btf_id = 0; 5134 5135 if (t == BPF_WRITE && value_regno >= 0 && 5136 is_pointer_value(env, value_regno)) { 5137 verbose(env, "R%d leaks addr into ctx\n", value_regno); 5138 return -EACCES; 5139 } 5140 5141 err = check_ptr_off_reg(env, reg, regno); 5142 if (err < 0) 5143 return err; 5144 5145 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 5146 &btf_id); 5147 if (err) 5148 verbose_linfo(env, insn_idx, "; "); 5149 if (!err && t == BPF_READ && value_regno >= 0) { 5150 /* ctx access returns either a scalar, or a 5151 * PTR_TO_PACKET[_META,_END]. In the latter 5152 * case, we know the offset is zero. 5153 */ 5154 if (reg_type == SCALAR_VALUE) { 5155 mark_reg_unknown(env, regs, value_regno); 5156 } else { 5157 mark_reg_known_zero(env, regs, 5158 value_regno); 5159 if (type_may_be_null(reg_type)) 5160 regs[value_regno].id = ++env->id_gen; 5161 /* A load of ctx field could have different 5162 * actual load size with the one encoded in the 5163 * insn. When the dst is PTR, it is for sure not 5164 * a sub-register. 5165 */ 5166 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 5167 if (base_type(reg_type) == PTR_TO_BTF_ID) { 5168 regs[value_regno].btf = btf; 5169 regs[value_regno].btf_id = btf_id; 5170 } 5171 } 5172 regs[value_regno].type = reg_type; 5173 } 5174 5175 } else if (reg->type == PTR_TO_STACK) { 5176 /* Basic bounds checks. */ 5177 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 5178 if (err) 5179 return err; 5180 5181 state = func(env, reg); 5182 err = update_stack_depth(env, state, off); 5183 if (err) 5184 return err; 5185 5186 if (t == BPF_READ) 5187 err = check_stack_read(env, regno, off, size, 5188 value_regno); 5189 else 5190 err = check_stack_write(env, regno, off, size, 5191 value_regno, insn_idx); 5192 } else if (reg_is_pkt_pointer(reg)) { 5193 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 5194 verbose(env, "cannot write into packet\n"); 5195 return -EACCES; 5196 } 5197 if (t == BPF_WRITE && value_regno >= 0 && 5198 is_pointer_value(env, value_regno)) { 5199 verbose(env, "R%d leaks addr into packet\n", 5200 value_regno); 5201 return -EACCES; 5202 } 5203 err = check_packet_access(env, regno, off, size, false); 5204 if (!err && t == BPF_READ && value_regno >= 0) 5205 mark_reg_unknown(env, regs, value_regno); 5206 } else if (reg->type == PTR_TO_FLOW_KEYS) { 5207 if (t == BPF_WRITE && value_regno >= 0 && 5208 is_pointer_value(env, value_regno)) { 5209 verbose(env, "R%d leaks addr into flow keys\n", 5210 value_regno); 5211 return -EACCES; 5212 } 5213 5214 err = check_flow_keys_access(env, off, size); 5215 if (!err && t == BPF_READ && value_regno >= 0) 5216 mark_reg_unknown(env, regs, value_regno); 5217 } else if (type_is_sk_pointer(reg->type)) { 5218 if (t == BPF_WRITE) { 5219 verbose(env, "R%d cannot write into %s\n", 5220 regno, reg_type_str(env, reg->type)); 5221 return -EACCES; 5222 } 5223 err = check_sock_access(env, insn_idx, regno, off, size, t); 5224 if (!err && value_regno >= 0) 5225 mark_reg_unknown(env, regs, value_regno); 5226 } else if (reg->type == PTR_TO_TP_BUFFER) { 5227 err = check_tp_buffer_access(env, reg, regno, off, size); 5228 if (!err && t == BPF_READ && value_regno >= 0) 5229 mark_reg_unknown(env, regs, value_regno); 5230 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 5231 !type_may_be_null(reg->type)) { 5232 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 5233 value_regno); 5234 } else if (reg->type == CONST_PTR_TO_MAP) { 5235 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 5236 value_regno); 5237 } else if (base_type(reg->type) == PTR_TO_BUF) { 5238 bool rdonly_mem = type_is_rdonly_mem(reg->type); 5239 u32 *max_access; 5240 5241 if (rdonly_mem) { 5242 if (t == BPF_WRITE) { 5243 verbose(env, "R%d cannot write into %s\n", 5244 regno, reg_type_str(env, reg->type)); 5245 return -EACCES; 5246 } 5247 max_access = &env->prog->aux->max_rdonly_access; 5248 } else { 5249 max_access = &env->prog->aux->max_rdwr_access; 5250 } 5251 5252 err = check_buffer_access(env, reg, regno, off, size, false, 5253 max_access); 5254 5255 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 5256 mark_reg_unknown(env, regs, value_regno); 5257 } else { 5258 verbose(env, "R%d invalid mem access '%s'\n", regno, 5259 reg_type_str(env, reg->type)); 5260 return -EACCES; 5261 } 5262 5263 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 5264 regs[value_regno].type == SCALAR_VALUE) { 5265 /* b/h/w load zero-extends, mark upper bits as known 0 */ 5266 coerce_reg_to_size(®s[value_regno], size); 5267 } 5268 return err; 5269 } 5270 5271 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 5272 { 5273 int load_reg; 5274 int err; 5275 5276 switch (insn->imm) { 5277 case BPF_ADD: 5278 case BPF_ADD | BPF_FETCH: 5279 case BPF_AND: 5280 case BPF_AND | BPF_FETCH: 5281 case BPF_OR: 5282 case BPF_OR | BPF_FETCH: 5283 case BPF_XOR: 5284 case BPF_XOR | BPF_FETCH: 5285 case BPF_XCHG: 5286 case BPF_CMPXCHG: 5287 break; 5288 default: 5289 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 5290 return -EINVAL; 5291 } 5292 5293 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 5294 verbose(env, "invalid atomic operand size\n"); 5295 return -EINVAL; 5296 } 5297 5298 /* check src1 operand */ 5299 err = check_reg_arg(env, insn->src_reg, SRC_OP); 5300 if (err) 5301 return err; 5302 5303 /* check src2 operand */ 5304 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 5305 if (err) 5306 return err; 5307 5308 if (insn->imm == BPF_CMPXCHG) { 5309 /* Check comparison of R0 with memory location */ 5310 const u32 aux_reg = BPF_REG_0; 5311 5312 err = check_reg_arg(env, aux_reg, SRC_OP); 5313 if (err) 5314 return err; 5315 5316 if (is_pointer_value(env, aux_reg)) { 5317 verbose(env, "R%d leaks addr into mem\n", aux_reg); 5318 return -EACCES; 5319 } 5320 } 5321 5322 if (is_pointer_value(env, insn->src_reg)) { 5323 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 5324 return -EACCES; 5325 } 5326 5327 if (is_ctx_reg(env, insn->dst_reg) || 5328 is_pkt_reg(env, insn->dst_reg) || 5329 is_flow_key_reg(env, insn->dst_reg) || 5330 is_sk_reg(env, insn->dst_reg)) { 5331 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 5332 insn->dst_reg, 5333 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 5334 return -EACCES; 5335 } 5336 5337 if (insn->imm & BPF_FETCH) { 5338 if (insn->imm == BPF_CMPXCHG) 5339 load_reg = BPF_REG_0; 5340 else 5341 load_reg = insn->src_reg; 5342 5343 /* check and record load of old value */ 5344 err = check_reg_arg(env, load_reg, DST_OP); 5345 if (err) 5346 return err; 5347 } else { 5348 /* This instruction accesses a memory location but doesn't 5349 * actually load it into a register. 5350 */ 5351 load_reg = -1; 5352 } 5353 5354 /* Check whether we can read the memory, with second call for fetch 5355 * case to simulate the register fill. 5356 */ 5357 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5358 BPF_SIZE(insn->code), BPF_READ, -1, true); 5359 if (!err && load_reg >= 0) 5360 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5361 BPF_SIZE(insn->code), BPF_READ, load_reg, 5362 true); 5363 if (err) 5364 return err; 5365 5366 /* Check whether we can write into the same memory. */ 5367 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5368 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 5369 if (err) 5370 return err; 5371 5372 return 0; 5373 } 5374 5375 /* When register 'regno' is used to read the stack (either directly or through 5376 * a helper function) make sure that it's within stack boundary and, depending 5377 * on the access type, that all elements of the stack are initialized. 5378 * 5379 * 'off' includes 'regno->off', but not its dynamic part (if any). 5380 * 5381 * All registers that have been spilled on the stack in the slots within the 5382 * read offsets are marked as read. 5383 */ 5384 static int check_stack_range_initialized( 5385 struct bpf_verifier_env *env, int regno, int off, 5386 int access_size, bool zero_size_allowed, 5387 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 5388 { 5389 struct bpf_reg_state *reg = reg_state(env, regno); 5390 struct bpf_func_state *state = func(env, reg); 5391 int err, min_off, max_off, i, j, slot, spi; 5392 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 5393 enum bpf_access_type bounds_check_type; 5394 /* Some accesses can write anything into the stack, others are 5395 * read-only. 5396 */ 5397 bool clobber = false; 5398 5399 if (access_size == 0 && !zero_size_allowed) { 5400 verbose(env, "invalid zero-sized read\n"); 5401 return -EACCES; 5402 } 5403 5404 if (type == ACCESS_HELPER) { 5405 /* The bounds checks for writes are more permissive than for 5406 * reads. However, if raw_mode is not set, we'll do extra 5407 * checks below. 5408 */ 5409 bounds_check_type = BPF_WRITE; 5410 clobber = true; 5411 } else { 5412 bounds_check_type = BPF_READ; 5413 } 5414 err = check_stack_access_within_bounds(env, regno, off, access_size, 5415 type, bounds_check_type); 5416 if (err) 5417 return err; 5418 5419 5420 if (tnum_is_const(reg->var_off)) { 5421 min_off = max_off = reg->var_off.value + off; 5422 } else { 5423 /* Variable offset is prohibited for unprivileged mode for 5424 * simplicity since it requires corresponding support in 5425 * Spectre masking for stack ALU. 5426 * See also retrieve_ptr_limit(). 5427 */ 5428 if (!env->bypass_spec_v1) { 5429 char tn_buf[48]; 5430 5431 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5432 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 5433 regno, err_extra, tn_buf); 5434 return -EACCES; 5435 } 5436 /* Only initialized buffer on stack is allowed to be accessed 5437 * with variable offset. With uninitialized buffer it's hard to 5438 * guarantee that whole memory is marked as initialized on 5439 * helper return since specific bounds are unknown what may 5440 * cause uninitialized stack leaking. 5441 */ 5442 if (meta && meta->raw_mode) 5443 meta = NULL; 5444 5445 min_off = reg->smin_value + off; 5446 max_off = reg->smax_value + off; 5447 } 5448 5449 if (meta && meta->raw_mode) { 5450 meta->access_size = access_size; 5451 meta->regno = regno; 5452 return 0; 5453 } 5454 5455 for (i = min_off; i < max_off + access_size; i++) { 5456 u8 *stype; 5457 5458 slot = -i - 1; 5459 spi = slot / BPF_REG_SIZE; 5460 if (state->allocated_stack <= slot) 5461 goto err; 5462 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 5463 if (*stype == STACK_MISC) 5464 goto mark; 5465 if (*stype == STACK_ZERO) { 5466 if (clobber) { 5467 /* helper can write anything into the stack */ 5468 *stype = STACK_MISC; 5469 } 5470 goto mark; 5471 } 5472 5473 if (is_spilled_reg(&state->stack[spi]) && 5474 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 5475 env->allow_ptr_leaks)) { 5476 if (clobber) { 5477 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 5478 for (j = 0; j < BPF_REG_SIZE; j++) 5479 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 5480 } 5481 goto mark; 5482 } 5483 5484 err: 5485 if (tnum_is_const(reg->var_off)) { 5486 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 5487 err_extra, regno, min_off, i - min_off, access_size); 5488 } else { 5489 char tn_buf[48]; 5490 5491 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5492 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 5493 err_extra, regno, tn_buf, i - min_off, access_size); 5494 } 5495 return -EACCES; 5496 mark: 5497 /* reading any byte out of 8-byte 'spill_slot' will cause 5498 * the whole slot to be marked as 'read' 5499 */ 5500 mark_reg_read(env, &state->stack[spi].spilled_ptr, 5501 state->stack[spi].spilled_ptr.parent, 5502 REG_LIVE_READ64); 5503 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 5504 * be sure that whether stack slot is written to or not. Hence, 5505 * we must still conservatively propagate reads upwards even if 5506 * helper may write to the entire memory range. 5507 */ 5508 } 5509 return update_stack_depth(env, state, min_off); 5510 } 5511 5512 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 5513 int access_size, bool zero_size_allowed, 5514 struct bpf_call_arg_meta *meta) 5515 { 5516 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5517 u32 *max_access; 5518 5519 switch (base_type(reg->type)) { 5520 case PTR_TO_PACKET: 5521 case PTR_TO_PACKET_META: 5522 return check_packet_access(env, regno, reg->off, access_size, 5523 zero_size_allowed); 5524 case PTR_TO_MAP_KEY: 5525 if (meta && meta->raw_mode) { 5526 verbose(env, "R%d cannot write into %s\n", regno, 5527 reg_type_str(env, reg->type)); 5528 return -EACCES; 5529 } 5530 return check_mem_region_access(env, regno, reg->off, access_size, 5531 reg->map_ptr->key_size, false); 5532 case PTR_TO_MAP_VALUE: 5533 if (check_map_access_type(env, regno, reg->off, access_size, 5534 meta && meta->raw_mode ? BPF_WRITE : 5535 BPF_READ)) 5536 return -EACCES; 5537 return check_map_access(env, regno, reg->off, access_size, 5538 zero_size_allowed, ACCESS_HELPER); 5539 case PTR_TO_MEM: 5540 if (type_is_rdonly_mem(reg->type)) { 5541 if (meta && meta->raw_mode) { 5542 verbose(env, "R%d cannot write into %s\n", regno, 5543 reg_type_str(env, reg->type)); 5544 return -EACCES; 5545 } 5546 } 5547 return check_mem_region_access(env, regno, reg->off, 5548 access_size, reg->mem_size, 5549 zero_size_allowed); 5550 case PTR_TO_BUF: 5551 if (type_is_rdonly_mem(reg->type)) { 5552 if (meta && meta->raw_mode) { 5553 verbose(env, "R%d cannot write into %s\n", regno, 5554 reg_type_str(env, reg->type)); 5555 return -EACCES; 5556 } 5557 5558 max_access = &env->prog->aux->max_rdonly_access; 5559 } else { 5560 max_access = &env->prog->aux->max_rdwr_access; 5561 } 5562 return check_buffer_access(env, reg, regno, reg->off, 5563 access_size, zero_size_allowed, 5564 max_access); 5565 case PTR_TO_STACK: 5566 return check_stack_range_initialized( 5567 env, 5568 regno, reg->off, access_size, 5569 zero_size_allowed, ACCESS_HELPER, meta); 5570 case PTR_TO_CTX: 5571 /* in case the function doesn't know how to access the context, 5572 * (because we are in a program of type SYSCALL for example), we 5573 * can not statically check its size. 5574 * Dynamically check it now. 5575 */ 5576 if (!env->ops->convert_ctx_access) { 5577 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 5578 int offset = access_size - 1; 5579 5580 /* Allow zero-byte read from PTR_TO_CTX */ 5581 if (access_size == 0) 5582 return zero_size_allowed ? 0 : -EACCES; 5583 5584 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 5585 atype, -1, false); 5586 } 5587 5588 fallthrough; 5589 default: /* scalar_value or invalid ptr */ 5590 /* Allow zero-byte read from NULL, regardless of pointer type */ 5591 if (zero_size_allowed && access_size == 0 && 5592 register_is_null(reg)) 5593 return 0; 5594 5595 verbose(env, "R%d type=%s ", regno, 5596 reg_type_str(env, reg->type)); 5597 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 5598 return -EACCES; 5599 } 5600 } 5601 5602 static int check_mem_size_reg(struct bpf_verifier_env *env, 5603 struct bpf_reg_state *reg, u32 regno, 5604 bool zero_size_allowed, 5605 struct bpf_call_arg_meta *meta) 5606 { 5607 int err; 5608 5609 /* This is used to refine r0 return value bounds for helpers 5610 * that enforce this value as an upper bound on return values. 5611 * See do_refine_retval_range() for helpers that can refine 5612 * the return value. C type of helper is u32 so we pull register 5613 * bound from umax_value however, if negative verifier errors 5614 * out. Only upper bounds can be learned because retval is an 5615 * int type and negative retvals are allowed. 5616 */ 5617 meta->msize_max_value = reg->umax_value; 5618 5619 /* The register is SCALAR_VALUE; the access check 5620 * happens using its boundaries. 5621 */ 5622 if (!tnum_is_const(reg->var_off)) 5623 /* For unprivileged variable accesses, disable raw 5624 * mode so that the program is required to 5625 * initialize all the memory that the helper could 5626 * just partially fill up. 5627 */ 5628 meta = NULL; 5629 5630 if (reg->smin_value < 0) { 5631 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 5632 regno); 5633 return -EACCES; 5634 } 5635 5636 if (reg->umin_value == 0) { 5637 err = check_helper_mem_access(env, regno - 1, 0, 5638 zero_size_allowed, 5639 meta); 5640 if (err) 5641 return err; 5642 } 5643 5644 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 5645 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 5646 regno); 5647 return -EACCES; 5648 } 5649 err = check_helper_mem_access(env, regno - 1, 5650 reg->umax_value, 5651 zero_size_allowed, meta); 5652 if (!err) 5653 err = mark_chain_precision(env, regno); 5654 return err; 5655 } 5656 5657 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5658 u32 regno, u32 mem_size) 5659 { 5660 bool may_be_null = type_may_be_null(reg->type); 5661 struct bpf_reg_state saved_reg; 5662 struct bpf_call_arg_meta meta; 5663 int err; 5664 5665 if (register_is_null(reg)) 5666 return 0; 5667 5668 memset(&meta, 0, sizeof(meta)); 5669 /* Assuming that the register contains a value check if the memory 5670 * access is safe. Temporarily save and restore the register's state as 5671 * the conversion shouldn't be visible to a caller. 5672 */ 5673 if (may_be_null) { 5674 saved_reg = *reg; 5675 mark_ptr_not_null_reg(reg); 5676 } 5677 5678 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 5679 /* Check access for BPF_WRITE */ 5680 meta.raw_mode = true; 5681 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 5682 5683 if (may_be_null) 5684 *reg = saved_reg; 5685 5686 return err; 5687 } 5688 5689 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5690 u32 regno) 5691 { 5692 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 5693 bool may_be_null = type_may_be_null(mem_reg->type); 5694 struct bpf_reg_state saved_reg; 5695 struct bpf_call_arg_meta meta; 5696 int err; 5697 5698 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 5699 5700 memset(&meta, 0, sizeof(meta)); 5701 5702 if (may_be_null) { 5703 saved_reg = *mem_reg; 5704 mark_ptr_not_null_reg(mem_reg); 5705 } 5706 5707 err = check_mem_size_reg(env, reg, regno, true, &meta); 5708 /* Check access for BPF_WRITE */ 5709 meta.raw_mode = true; 5710 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 5711 5712 if (may_be_null) 5713 *mem_reg = saved_reg; 5714 return err; 5715 } 5716 5717 /* Implementation details: 5718 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 5719 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 5720 * Two bpf_map_lookups (even with the same key) will have different reg->id. 5721 * Two separate bpf_obj_new will also have different reg->id. 5722 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 5723 * clears reg->id after value_or_null->value transition, since the verifier only 5724 * cares about the range of access to valid map value pointer and doesn't care 5725 * about actual address of the map element. 5726 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 5727 * reg->id > 0 after value_or_null->value transition. By doing so 5728 * two bpf_map_lookups will be considered two different pointers that 5729 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 5730 * returned from bpf_obj_new. 5731 * The verifier allows taking only one bpf_spin_lock at a time to avoid 5732 * dead-locks. 5733 * Since only one bpf_spin_lock is allowed the checks are simpler than 5734 * reg_is_refcounted() logic. The verifier needs to remember only 5735 * one spin_lock instead of array of acquired_refs. 5736 * cur_state->active_lock remembers which map value element or allocated 5737 * object got locked and clears it after bpf_spin_unlock. 5738 */ 5739 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 5740 bool is_lock) 5741 { 5742 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5743 struct bpf_verifier_state *cur = env->cur_state; 5744 bool is_const = tnum_is_const(reg->var_off); 5745 u64 val = reg->var_off.value; 5746 struct bpf_map *map = NULL; 5747 struct btf *btf = NULL; 5748 struct btf_record *rec; 5749 5750 if (!is_const) { 5751 verbose(env, 5752 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 5753 regno); 5754 return -EINVAL; 5755 } 5756 if (reg->type == PTR_TO_MAP_VALUE) { 5757 map = reg->map_ptr; 5758 if (!map->btf) { 5759 verbose(env, 5760 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 5761 map->name); 5762 return -EINVAL; 5763 } 5764 } else { 5765 btf = reg->btf; 5766 } 5767 5768 rec = reg_btf_record(reg); 5769 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 5770 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 5771 map ? map->name : "kptr"); 5772 return -EINVAL; 5773 } 5774 if (rec->spin_lock_off != val + reg->off) { 5775 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 5776 val + reg->off, rec->spin_lock_off); 5777 return -EINVAL; 5778 } 5779 if (is_lock) { 5780 if (cur->active_lock.ptr) { 5781 verbose(env, 5782 "Locking two bpf_spin_locks are not allowed\n"); 5783 return -EINVAL; 5784 } 5785 if (map) 5786 cur->active_lock.ptr = map; 5787 else 5788 cur->active_lock.ptr = btf; 5789 cur->active_lock.id = reg->id; 5790 } else { 5791 struct bpf_func_state *fstate = cur_func(env); 5792 void *ptr; 5793 int i; 5794 5795 if (map) 5796 ptr = map; 5797 else 5798 ptr = btf; 5799 5800 if (!cur->active_lock.ptr) { 5801 verbose(env, "bpf_spin_unlock without taking a lock\n"); 5802 return -EINVAL; 5803 } 5804 if (cur->active_lock.ptr != ptr || 5805 cur->active_lock.id != reg->id) { 5806 verbose(env, "bpf_spin_unlock of different lock\n"); 5807 return -EINVAL; 5808 } 5809 cur->active_lock.ptr = NULL; 5810 cur->active_lock.id = 0; 5811 5812 for (i = fstate->acquired_refs - 1; i >= 0; i--) { 5813 int err; 5814 5815 /* Complain on error because this reference state cannot 5816 * be freed before this point, as bpf_spin_lock critical 5817 * section does not allow functions that release the 5818 * allocated object immediately. 5819 */ 5820 if (!fstate->refs[i].release_on_unlock) 5821 continue; 5822 err = release_reference(env, fstate->refs[i].id); 5823 if (err) { 5824 verbose(env, "failed to release release_on_unlock reference"); 5825 return err; 5826 } 5827 } 5828 } 5829 return 0; 5830 } 5831 5832 static int process_timer_func(struct bpf_verifier_env *env, int regno, 5833 struct bpf_call_arg_meta *meta) 5834 { 5835 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5836 bool is_const = tnum_is_const(reg->var_off); 5837 struct bpf_map *map = reg->map_ptr; 5838 u64 val = reg->var_off.value; 5839 5840 if (!is_const) { 5841 verbose(env, 5842 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 5843 regno); 5844 return -EINVAL; 5845 } 5846 if (!map->btf) { 5847 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 5848 map->name); 5849 return -EINVAL; 5850 } 5851 if (!btf_record_has_field(map->record, BPF_TIMER)) { 5852 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 5853 return -EINVAL; 5854 } 5855 if (map->record->timer_off != val + reg->off) { 5856 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 5857 val + reg->off, map->record->timer_off); 5858 return -EINVAL; 5859 } 5860 if (meta->map_ptr) { 5861 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 5862 return -EFAULT; 5863 } 5864 meta->map_uid = reg->map_uid; 5865 meta->map_ptr = map; 5866 return 0; 5867 } 5868 5869 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 5870 struct bpf_call_arg_meta *meta) 5871 { 5872 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5873 struct bpf_map *map_ptr = reg->map_ptr; 5874 struct btf_field *kptr_field; 5875 u32 kptr_off; 5876 5877 if (!tnum_is_const(reg->var_off)) { 5878 verbose(env, 5879 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 5880 regno); 5881 return -EINVAL; 5882 } 5883 if (!map_ptr->btf) { 5884 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 5885 map_ptr->name); 5886 return -EINVAL; 5887 } 5888 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 5889 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 5890 return -EINVAL; 5891 } 5892 5893 meta->map_ptr = map_ptr; 5894 kptr_off = reg->off + reg->var_off.value; 5895 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 5896 if (!kptr_field) { 5897 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 5898 return -EACCES; 5899 } 5900 if (kptr_field->type != BPF_KPTR_REF) { 5901 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 5902 return -EACCES; 5903 } 5904 meta->kptr_field = kptr_field; 5905 return 0; 5906 } 5907 5908 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 5909 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 5910 * 5911 * In both cases we deal with the first 8 bytes, but need to mark the next 8 5912 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 5913 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 5914 * 5915 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 5916 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 5917 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 5918 * mutate the view of the dynptr and also possibly destroy it. In the latter 5919 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 5920 * memory that dynptr points to. 5921 * 5922 * The verifier will keep track both levels of mutation (bpf_dynptr's in 5923 * reg->type and the memory's in reg->dynptr.type), but there is no support for 5924 * readonly dynptr view yet, hence only the first case is tracked and checked. 5925 * 5926 * This is consistent with how C applies the const modifier to a struct object, 5927 * where the pointer itself inside bpf_dynptr becomes const but not what it 5928 * points to. 5929 * 5930 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 5931 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 5932 */ 5933 int process_dynptr_func(struct bpf_verifier_env *env, int regno, 5934 enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) 5935 { 5936 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5937 5938 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 5939 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 5940 */ 5941 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 5942 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 5943 return -EFAULT; 5944 } 5945 /* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 5946 * check_func_arg_reg_off's logic. We only need to check offset 5947 * alignment for PTR_TO_STACK. 5948 */ 5949 if (reg->type == PTR_TO_STACK && (reg->off % BPF_REG_SIZE)) { 5950 verbose(env, "cannot pass in dynptr at an offset=%d\n", reg->off); 5951 return -EINVAL; 5952 } 5953 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 5954 * constructing a mutable bpf_dynptr object. 5955 * 5956 * Currently, this is only possible with PTR_TO_STACK 5957 * pointing to a region of at least 16 bytes which doesn't 5958 * contain an existing bpf_dynptr. 5959 * 5960 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 5961 * mutated or destroyed. However, the memory it points to 5962 * may be mutated. 5963 * 5964 * None - Points to a initialized dynptr that can be mutated and 5965 * destroyed, including mutation of the memory it points 5966 * to. 5967 */ 5968 if (arg_type & MEM_UNINIT) { 5969 if (!is_dynptr_reg_valid_uninit(env, reg)) { 5970 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 5971 return -EINVAL; 5972 } 5973 5974 /* We only support one dynptr being uninitialized at the moment, 5975 * which is sufficient for the helper functions we have right now. 5976 */ 5977 if (meta->uninit_dynptr_regno) { 5978 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n"); 5979 return -EFAULT; 5980 } 5981 5982 meta->uninit_dynptr_regno = regno; 5983 } else /* MEM_RDONLY and None case from above */ { 5984 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 5985 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 5986 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 5987 return -EINVAL; 5988 } 5989 5990 if (!is_dynptr_reg_valid_init(env, reg)) { 5991 verbose(env, 5992 "Expected an initialized dynptr as arg #%d\n", 5993 regno); 5994 return -EINVAL; 5995 } 5996 5997 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 5998 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 5999 const char *err_extra = ""; 6000 6001 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 6002 case DYNPTR_TYPE_LOCAL: 6003 err_extra = "local"; 6004 break; 6005 case DYNPTR_TYPE_RINGBUF: 6006 err_extra = "ringbuf"; 6007 break; 6008 default: 6009 err_extra = "<unknown>"; 6010 break; 6011 } 6012 verbose(env, 6013 "Expected a dynptr of type %s as arg #%d\n", 6014 err_extra, regno); 6015 return -EINVAL; 6016 } 6017 } 6018 return 0; 6019 } 6020 6021 static bool arg_type_is_mem_size(enum bpf_arg_type type) 6022 { 6023 return type == ARG_CONST_SIZE || 6024 type == ARG_CONST_SIZE_OR_ZERO; 6025 } 6026 6027 static bool arg_type_is_release(enum bpf_arg_type type) 6028 { 6029 return type & OBJ_RELEASE; 6030 } 6031 6032 static bool arg_type_is_dynptr(enum bpf_arg_type type) 6033 { 6034 return base_type(type) == ARG_PTR_TO_DYNPTR; 6035 } 6036 6037 static int int_ptr_type_to_size(enum bpf_arg_type type) 6038 { 6039 if (type == ARG_PTR_TO_INT) 6040 return sizeof(u32); 6041 else if (type == ARG_PTR_TO_LONG) 6042 return sizeof(u64); 6043 6044 return -EINVAL; 6045 } 6046 6047 static int resolve_map_arg_type(struct bpf_verifier_env *env, 6048 const struct bpf_call_arg_meta *meta, 6049 enum bpf_arg_type *arg_type) 6050 { 6051 if (!meta->map_ptr) { 6052 /* kernel subsystem misconfigured verifier */ 6053 verbose(env, "invalid map_ptr to access map->type\n"); 6054 return -EACCES; 6055 } 6056 6057 switch (meta->map_ptr->map_type) { 6058 case BPF_MAP_TYPE_SOCKMAP: 6059 case BPF_MAP_TYPE_SOCKHASH: 6060 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 6061 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 6062 } else { 6063 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 6064 return -EINVAL; 6065 } 6066 break; 6067 case BPF_MAP_TYPE_BLOOM_FILTER: 6068 if (meta->func_id == BPF_FUNC_map_peek_elem) 6069 *arg_type = ARG_PTR_TO_MAP_VALUE; 6070 break; 6071 default: 6072 break; 6073 } 6074 return 0; 6075 } 6076 6077 struct bpf_reg_types { 6078 const enum bpf_reg_type types[10]; 6079 u32 *btf_id; 6080 }; 6081 6082 static const struct bpf_reg_types sock_types = { 6083 .types = { 6084 PTR_TO_SOCK_COMMON, 6085 PTR_TO_SOCKET, 6086 PTR_TO_TCP_SOCK, 6087 PTR_TO_XDP_SOCK, 6088 }, 6089 }; 6090 6091 #ifdef CONFIG_NET 6092 static const struct bpf_reg_types btf_id_sock_common_types = { 6093 .types = { 6094 PTR_TO_SOCK_COMMON, 6095 PTR_TO_SOCKET, 6096 PTR_TO_TCP_SOCK, 6097 PTR_TO_XDP_SOCK, 6098 PTR_TO_BTF_ID, 6099 PTR_TO_BTF_ID | PTR_TRUSTED, 6100 }, 6101 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 6102 }; 6103 #endif 6104 6105 static const struct bpf_reg_types mem_types = { 6106 .types = { 6107 PTR_TO_STACK, 6108 PTR_TO_PACKET, 6109 PTR_TO_PACKET_META, 6110 PTR_TO_MAP_KEY, 6111 PTR_TO_MAP_VALUE, 6112 PTR_TO_MEM, 6113 PTR_TO_MEM | MEM_RINGBUF, 6114 PTR_TO_BUF, 6115 }, 6116 }; 6117 6118 static const struct bpf_reg_types int_ptr_types = { 6119 .types = { 6120 PTR_TO_STACK, 6121 PTR_TO_PACKET, 6122 PTR_TO_PACKET_META, 6123 PTR_TO_MAP_KEY, 6124 PTR_TO_MAP_VALUE, 6125 }, 6126 }; 6127 6128 static const struct bpf_reg_types spin_lock_types = { 6129 .types = { 6130 PTR_TO_MAP_VALUE, 6131 PTR_TO_BTF_ID | MEM_ALLOC, 6132 } 6133 }; 6134 6135 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 6136 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 6137 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 6138 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 6139 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 6140 static const struct bpf_reg_types btf_ptr_types = { 6141 .types = { 6142 PTR_TO_BTF_ID, 6143 PTR_TO_BTF_ID | PTR_TRUSTED, 6144 PTR_TO_BTF_ID | MEM_RCU, 6145 }, 6146 }; 6147 static const struct bpf_reg_types percpu_btf_ptr_types = { 6148 .types = { 6149 PTR_TO_BTF_ID | MEM_PERCPU, 6150 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 6151 } 6152 }; 6153 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 6154 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 6155 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 6156 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 6157 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 6158 static const struct bpf_reg_types dynptr_types = { 6159 .types = { 6160 PTR_TO_STACK, 6161 CONST_PTR_TO_DYNPTR, 6162 } 6163 }; 6164 6165 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 6166 [ARG_PTR_TO_MAP_KEY] = &mem_types, 6167 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 6168 [ARG_CONST_SIZE] = &scalar_types, 6169 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 6170 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 6171 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 6172 [ARG_PTR_TO_CTX] = &context_types, 6173 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 6174 #ifdef CONFIG_NET 6175 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 6176 #endif 6177 [ARG_PTR_TO_SOCKET] = &fullsock_types, 6178 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 6179 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 6180 [ARG_PTR_TO_MEM] = &mem_types, 6181 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 6182 [ARG_PTR_TO_INT] = &int_ptr_types, 6183 [ARG_PTR_TO_LONG] = &int_ptr_types, 6184 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 6185 [ARG_PTR_TO_FUNC] = &func_ptr_types, 6186 [ARG_PTR_TO_STACK] = &stack_ptr_types, 6187 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 6188 [ARG_PTR_TO_TIMER] = &timer_types, 6189 [ARG_PTR_TO_KPTR] = &kptr_types, 6190 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 6191 }; 6192 6193 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 6194 enum bpf_arg_type arg_type, 6195 const u32 *arg_btf_id, 6196 struct bpf_call_arg_meta *meta) 6197 { 6198 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6199 enum bpf_reg_type expected, type = reg->type; 6200 const struct bpf_reg_types *compatible; 6201 int i, j; 6202 6203 compatible = compatible_reg_types[base_type(arg_type)]; 6204 if (!compatible) { 6205 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 6206 return -EFAULT; 6207 } 6208 6209 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 6210 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 6211 * 6212 * Same for MAYBE_NULL: 6213 * 6214 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 6215 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 6216 * 6217 * Therefore we fold these flags depending on the arg_type before comparison. 6218 */ 6219 if (arg_type & MEM_RDONLY) 6220 type &= ~MEM_RDONLY; 6221 if (arg_type & PTR_MAYBE_NULL) 6222 type &= ~PTR_MAYBE_NULL; 6223 6224 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 6225 expected = compatible->types[i]; 6226 if (expected == NOT_INIT) 6227 break; 6228 6229 if (type == expected) 6230 goto found; 6231 } 6232 6233 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 6234 for (j = 0; j + 1 < i; j++) 6235 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 6236 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 6237 return -EACCES; 6238 6239 found: 6240 if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) { 6241 /* For bpf_sk_release, it needs to match against first member 6242 * 'struct sock_common', hence make an exception for it. This 6243 * allows bpf_sk_release to work for multiple socket types. 6244 */ 6245 bool strict_type_match = arg_type_is_release(arg_type) && 6246 meta->func_id != BPF_FUNC_sk_release; 6247 6248 if (!arg_btf_id) { 6249 if (!compatible->btf_id) { 6250 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 6251 return -EFAULT; 6252 } 6253 arg_btf_id = compatible->btf_id; 6254 } 6255 6256 if (meta->func_id == BPF_FUNC_kptr_xchg) { 6257 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 6258 return -EACCES; 6259 } else { 6260 if (arg_btf_id == BPF_PTR_POISON) { 6261 verbose(env, "verifier internal error:"); 6262 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 6263 regno); 6264 return -EACCES; 6265 } 6266 6267 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 6268 btf_vmlinux, *arg_btf_id, 6269 strict_type_match)) { 6270 verbose(env, "R%d is of type %s but %s is expected\n", 6271 regno, kernel_type_name(reg->btf, reg->btf_id), 6272 kernel_type_name(btf_vmlinux, *arg_btf_id)); 6273 return -EACCES; 6274 } 6275 } 6276 } else if (type_is_alloc(reg->type)) { 6277 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) { 6278 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 6279 return -EFAULT; 6280 } 6281 } 6282 6283 return 0; 6284 } 6285 6286 int check_func_arg_reg_off(struct bpf_verifier_env *env, 6287 const struct bpf_reg_state *reg, int regno, 6288 enum bpf_arg_type arg_type) 6289 { 6290 u32 type = reg->type; 6291 6292 /* When referenced register is passed to release function, its fixed 6293 * offset must be 0. 6294 * 6295 * We will check arg_type_is_release reg has ref_obj_id when storing 6296 * meta->release_regno. 6297 */ 6298 if (arg_type_is_release(arg_type)) { 6299 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 6300 * may not directly point to the object being released, but to 6301 * dynptr pointing to such object, which might be at some offset 6302 * on the stack. In that case, we simply to fallback to the 6303 * default handling. 6304 */ 6305 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 6306 return 0; 6307 /* Doing check_ptr_off_reg check for the offset will catch this 6308 * because fixed_off_ok is false, but checking here allows us 6309 * to give the user a better error message. 6310 */ 6311 if (reg->off) { 6312 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 6313 regno); 6314 return -EINVAL; 6315 } 6316 return __check_ptr_off_reg(env, reg, regno, false); 6317 } 6318 6319 switch (type) { 6320 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 6321 case PTR_TO_STACK: 6322 case PTR_TO_PACKET: 6323 case PTR_TO_PACKET_META: 6324 case PTR_TO_MAP_KEY: 6325 case PTR_TO_MAP_VALUE: 6326 case PTR_TO_MEM: 6327 case PTR_TO_MEM | MEM_RDONLY: 6328 case PTR_TO_MEM | MEM_RINGBUF: 6329 case PTR_TO_BUF: 6330 case PTR_TO_BUF | MEM_RDONLY: 6331 case SCALAR_VALUE: 6332 return 0; 6333 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 6334 * fixed offset. 6335 */ 6336 case PTR_TO_BTF_ID: 6337 case PTR_TO_BTF_ID | MEM_ALLOC: 6338 case PTR_TO_BTF_ID | PTR_TRUSTED: 6339 case PTR_TO_BTF_ID | MEM_RCU: 6340 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED: 6341 /* When referenced PTR_TO_BTF_ID is passed to release function, 6342 * its fixed offset must be 0. In the other cases, fixed offset 6343 * can be non-zero. This was already checked above. So pass 6344 * fixed_off_ok as true to allow fixed offset for all other 6345 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 6346 * still need to do checks instead of returning. 6347 */ 6348 return __check_ptr_off_reg(env, reg, regno, true); 6349 default: 6350 return __check_ptr_off_reg(env, reg, regno, false); 6351 } 6352 } 6353 6354 static u32 dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 6355 { 6356 struct bpf_func_state *state = func(env, reg); 6357 int spi; 6358 6359 if (reg->type == CONST_PTR_TO_DYNPTR) 6360 return reg->ref_obj_id; 6361 6362 spi = get_spi(reg->off); 6363 return state->stack[spi].spilled_ptr.ref_obj_id; 6364 } 6365 6366 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 6367 struct bpf_call_arg_meta *meta, 6368 const struct bpf_func_proto *fn) 6369 { 6370 u32 regno = BPF_REG_1 + arg; 6371 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6372 enum bpf_arg_type arg_type = fn->arg_type[arg]; 6373 enum bpf_reg_type type = reg->type; 6374 u32 *arg_btf_id = NULL; 6375 int err = 0; 6376 6377 if (arg_type == ARG_DONTCARE) 6378 return 0; 6379 6380 err = check_reg_arg(env, regno, SRC_OP); 6381 if (err) 6382 return err; 6383 6384 if (arg_type == ARG_ANYTHING) { 6385 if (is_pointer_value(env, regno)) { 6386 verbose(env, "R%d leaks addr into helper function\n", 6387 regno); 6388 return -EACCES; 6389 } 6390 return 0; 6391 } 6392 6393 if (type_is_pkt_pointer(type) && 6394 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 6395 verbose(env, "helper access to the packet is not allowed\n"); 6396 return -EACCES; 6397 } 6398 6399 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 6400 err = resolve_map_arg_type(env, meta, &arg_type); 6401 if (err) 6402 return err; 6403 } 6404 6405 if (register_is_null(reg) && type_may_be_null(arg_type)) 6406 /* A NULL register has a SCALAR_VALUE type, so skip 6407 * type checking. 6408 */ 6409 goto skip_type_check; 6410 6411 /* arg_btf_id and arg_size are in a union. */ 6412 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 6413 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 6414 arg_btf_id = fn->arg_btf_id[arg]; 6415 6416 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 6417 if (err) 6418 return err; 6419 6420 err = check_func_arg_reg_off(env, reg, regno, arg_type); 6421 if (err) 6422 return err; 6423 6424 skip_type_check: 6425 if (arg_type_is_release(arg_type)) { 6426 if (arg_type_is_dynptr(arg_type)) { 6427 struct bpf_func_state *state = func(env, reg); 6428 int spi; 6429 6430 /* Only dynptr created on stack can be released, thus 6431 * the get_spi and stack state checks for spilled_ptr 6432 * should only be done before process_dynptr_func for 6433 * PTR_TO_STACK. 6434 */ 6435 if (reg->type == PTR_TO_STACK) { 6436 spi = get_spi(reg->off); 6437 if (!is_spi_bounds_valid(state, spi, BPF_DYNPTR_NR_SLOTS) || 6438 !state->stack[spi].spilled_ptr.ref_obj_id) { 6439 verbose(env, "arg %d is an unacquired reference\n", regno); 6440 return -EINVAL; 6441 } 6442 } else { 6443 verbose(env, "cannot release unowned const bpf_dynptr\n"); 6444 return -EINVAL; 6445 } 6446 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 6447 verbose(env, "R%d must be referenced when passed to release function\n", 6448 regno); 6449 return -EINVAL; 6450 } 6451 if (meta->release_regno) { 6452 verbose(env, "verifier internal error: more than one release argument\n"); 6453 return -EFAULT; 6454 } 6455 meta->release_regno = regno; 6456 } 6457 6458 if (reg->ref_obj_id) { 6459 if (meta->ref_obj_id) { 6460 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 6461 regno, reg->ref_obj_id, 6462 meta->ref_obj_id); 6463 return -EFAULT; 6464 } 6465 meta->ref_obj_id = reg->ref_obj_id; 6466 } 6467 6468 switch (base_type(arg_type)) { 6469 case ARG_CONST_MAP_PTR: 6470 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 6471 if (meta->map_ptr) { 6472 /* Use map_uid (which is unique id of inner map) to reject: 6473 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 6474 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 6475 * if (inner_map1 && inner_map2) { 6476 * timer = bpf_map_lookup_elem(inner_map1); 6477 * if (timer) 6478 * // mismatch would have been allowed 6479 * bpf_timer_init(timer, inner_map2); 6480 * } 6481 * 6482 * Comparing map_ptr is enough to distinguish normal and outer maps. 6483 */ 6484 if (meta->map_ptr != reg->map_ptr || 6485 meta->map_uid != reg->map_uid) { 6486 verbose(env, 6487 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 6488 meta->map_uid, reg->map_uid); 6489 return -EINVAL; 6490 } 6491 } 6492 meta->map_ptr = reg->map_ptr; 6493 meta->map_uid = reg->map_uid; 6494 break; 6495 case ARG_PTR_TO_MAP_KEY: 6496 /* bpf_map_xxx(..., map_ptr, ..., key) call: 6497 * check that [key, key + map->key_size) are within 6498 * stack limits and initialized 6499 */ 6500 if (!meta->map_ptr) { 6501 /* in function declaration map_ptr must come before 6502 * map_key, so that it's verified and known before 6503 * we have to check map_key here. Otherwise it means 6504 * that kernel subsystem misconfigured verifier 6505 */ 6506 verbose(env, "invalid map_ptr to access map->key\n"); 6507 return -EACCES; 6508 } 6509 err = check_helper_mem_access(env, regno, 6510 meta->map_ptr->key_size, false, 6511 NULL); 6512 break; 6513 case ARG_PTR_TO_MAP_VALUE: 6514 if (type_may_be_null(arg_type) && register_is_null(reg)) 6515 return 0; 6516 6517 /* bpf_map_xxx(..., map_ptr, ..., value) call: 6518 * check [value, value + map->value_size) validity 6519 */ 6520 if (!meta->map_ptr) { 6521 /* kernel subsystem misconfigured verifier */ 6522 verbose(env, "invalid map_ptr to access map->value\n"); 6523 return -EACCES; 6524 } 6525 meta->raw_mode = arg_type & MEM_UNINIT; 6526 err = check_helper_mem_access(env, regno, 6527 meta->map_ptr->value_size, false, 6528 meta); 6529 break; 6530 case ARG_PTR_TO_PERCPU_BTF_ID: 6531 if (!reg->btf_id) { 6532 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 6533 return -EACCES; 6534 } 6535 meta->ret_btf = reg->btf; 6536 meta->ret_btf_id = reg->btf_id; 6537 break; 6538 case ARG_PTR_TO_SPIN_LOCK: 6539 if (meta->func_id == BPF_FUNC_spin_lock) { 6540 err = process_spin_lock(env, regno, true); 6541 if (err) 6542 return err; 6543 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 6544 err = process_spin_lock(env, regno, false); 6545 if (err) 6546 return err; 6547 } else { 6548 verbose(env, "verifier internal error\n"); 6549 return -EFAULT; 6550 } 6551 break; 6552 case ARG_PTR_TO_TIMER: 6553 err = process_timer_func(env, regno, meta); 6554 if (err) 6555 return err; 6556 break; 6557 case ARG_PTR_TO_FUNC: 6558 meta->subprogno = reg->subprogno; 6559 break; 6560 case ARG_PTR_TO_MEM: 6561 /* The access to this pointer is only checked when we hit the 6562 * next is_mem_size argument below. 6563 */ 6564 meta->raw_mode = arg_type & MEM_UNINIT; 6565 if (arg_type & MEM_FIXED_SIZE) { 6566 err = check_helper_mem_access(env, regno, 6567 fn->arg_size[arg], false, 6568 meta); 6569 } 6570 break; 6571 case ARG_CONST_SIZE: 6572 err = check_mem_size_reg(env, reg, regno, false, meta); 6573 break; 6574 case ARG_CONST_SIZE_OR_ZERO: 6575 err = check_mem_size_reg(env, reg, regno, true, meta); 6576 break; 6577 case ARG_PTR_TO_DYNPTR: 6578 err = process_dynptr_func(env, regno, arg_type, meta); 6579 if (err) 6580 return err; 6581 break; 6582 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 6583 if (!tnum_is_const(reg->var_off)) { 6584 verbose(env, "R%d is not a known constant'\n", 6585 regno); 6586 return -EACCES; 6587 } 6588 meta->mem_size = reg->var_off.value; 6589 err = mark_chain_precision(env, regno); 6590 if (err) 6591 return err; 6592 break; 6593 case ARG_PTR_TO_INT: 6594 case ARG_PTR_TO_LONG: 6595 { 6596 int size = int_ptr_type_to_size(arg_type); 6597 6598 err = check_helper_mem_access(env, regno, size, false, meta); 6599 if (err) 6600 return err; 6601 err = check_ptr_alignment(env, reg, 0, size, true); 6602 break; 6603 } 6604 case ARG_PTR_TO_CONST_STR: 6605 { 6606 struct bpf_map *map = reg->map_ptr; 6607 int map_off; 6608 u64 map_addr; 6609 char *str_ptr; 6610 6611 if (!bpf_map_is_rdonly(map)) { 6612 verbose(env, "R%d does not point to a readonly map'\n", regno); 6613 return -EACCES; 6614 } 6615 6616 if (!tnum_is_const(reg->var_off)) { 6617 verbose(env, "R%d is not a constant address'\n", regno); 6618 return -EACCES; 6619 } 6620 6621 if (!map->ops->map_direct_value_addr) { 6622 verbose(env, "no direct value access support for this map type\n"); 6623 return -EACCES; 6624 } 6625 6626 err = check_map_access(env, regno, reg->off, 6627 map->value_size - reg->off, false, 6628 ACCESS_HELPER); 6629 if (err) 6630 return err; 6631 6632 map_off = reg->off + reg->var_off.value; 6633 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 6634 if (err) { 6635 verbose(env, "direct value access on string failed\n"); 6636 return err; 6637 } 6638 6639 str_ptr = (char *)(long)(map_addr); 6640 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 6641 verbose(env, "string is not zero-terminated\n"); 6642 return -EINVAL; 6643 } 6644 break; 6645 } 6646 case ARG_PTR_TO_KPTR: 6647 err = process_kptr_func(env, regno, meta); 6648 if (err) 6649 return err; 6650 break; 6651 } 6652 6653 return err; 6654 } 6655 6656 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 6657 { 6658 enum bpf_attach_type eatype = env->prog->expected_attach_type; 6659 enum bpf_prog_type type = resolve_prog_type(env->prog); 6660 6661 if (func_id != BPF_FUNC_map_update_elem) 6662 return false; 6663 6664 /* It's not possible to get access to a locked struct sock in these 6665 * contexts, so updating is safe. 6666 */ 6667 switch (type) { 6668 case BPF_PROG_TYPE_TRACING: 6669 if (eatype == BPF_TRACE_ITER) 6670 return true; 6671 break; 6672 case BPF_PROG_TYPE_SOCKET_FILTER: 6673 case BPF_PROG_TYPE_SCHED_CLS: 6674 case BPF_PROG_TYPE_SCHED_ACT: 6675 case BPF_PROG_TYPE_XDP: 6676 case BPF_PROG_TYPE_SK_REUSEPORT: 6677 case BPF_PROG_TYPE_FLOW_DISSECTOR: 6678 case BPF_PROG_TYPE_SK_LOOKUP: 6679 return true; 6680 default: 6681 break; 6682 } 6683 6684 verbose(env, "cannot update sockmap in this context\n"); 6685 return false; 6686 } 6687 6688 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 6689 { 6690 return env->prog->jit_requested && 6691 bpf_jit_supports_subprog_tailcalls(); 6692 } 6693 6694 static int check_map_func_compatibility(struct bpf_verifier_env *env, 6695 struct bpf_map *map, int func_id) 6696 { 6697 if (!map) 6698 return 0; 6699 6700 /* We need a two way check, first is from map perspective ... */ 6701 switch (map->map_type) { 6702 case BPF_MAP_TYPE_PROG_ARRAY: 6703 if (func_id != BPF_FUNC_tail_call) 6704 goto error; 6705 break; 6706 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 6707 if (func_id != BPF_FUNC_perf_event_read && 6708 func_id != BPF_FUNC_perf_event_output && 6709 func_id != BPF_FUNC_skb_output && 6710 func_id != BPF_FUNC_perf_event_read_value && 6711 func_id != BPF_FUNC_xdp_output) 6712 goto error; 6713 break; 6714 case BPF_MAP_TYPE_RINGBUF: 6715 if (func_id != BPF_FUNC_ringbuf_output && 6716 func_id != BPF_FUNC_ringbuf_reserve && 6717 func_id != BPF_FUNC_ringbuf_query && 6718 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 6719 func_id != BPF_FUNC_ringbuf_submit_dynptr && 6720 func_id != BPF_FUNC_ringbuf_discard_dynptr) 6721 goto error; 6722 break; 6723 case BPF_MAP_TYPE_USER_RINGBUF: 6724 if (func_id != BPF_FUNC_user_ringbuf_drain) 6725 goto error; 6726 break; 6727 case BPF_MAP_TYPE_STACK_TRACE: 6728 if (func_id != BPF_FUNC_get_stackid) 6729 goto error; 6730 break; 6731 case BPF_MAP_TYPE_CGROUP_ARRAY: 6732 if (func_id != BPF_FUNC_skb_under_cgroup && 6733 func_id != BPF_FUNC_current_task_under_cgroup) 6734 goto error; 6735 break; 6736 case BPF_MAP_TYPE_CGROUP_STORAGE: 6737 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 6738 if (func_id != BPF_FUNC_get_local_storage) 6739 goto error; 6740 break; 6741 case BPF_MAP_TYPE_DEVMAP: 6742 case BPF_MAP_TYPE_DEVMAP_HASH: 6743 if (func_id != BPF_FUNC_redirect_map && 6744 func_id != BPF_FUNC_map_lookup_elem) 6745 goto error; 6746 break; 6747 /* Restrict bpf side of cpumap and xskmap, open when use-cases 6748 * appear. 6749 */ 6750 case BPF_MAP_TYPE_CPUMAP: 6751 if (func_id != BPF_FUNC_redirect_map) 6752 goto error; 6753 break; 6754 case BPF_MAP_TYPE_XSKMAP: 6755 if (func_id != BPF_FUNC_redirect_map && 6756 func_id != BPF_FUNC_map_lookup_elem) 6757 goto error; 6758 break; 6759 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 6760 case BPF_MAP_TYPE_HASH_OF_MAPS: 6761 if (func_id != BPF_FUNC_map_lookup_elem) 6762 goto error; 6763 break; 6764 case BPF_MAP_TYPE_SOCKMAP: 6765 if (func_id != BPF_FUNC_sk_redirect_map && 6766 func_id != BPF_FUNC_sock_map_update && 6767 func_id != BPF_FUNC_map_delete_elem && 6768 func_id != BPF_FUNC_msg_redirect_map && 6769 func_id != BPF_FUNC_sk_select_reuseport && 6770 func_id != BPF_FUNC_map_lookup_elem && 6771 !may_update_sockmap(env, func_id)) 6772 goto error; 6773 break; 6774 case BPF_MAP_TYPE_SOCKHASH: 6775 if (func_id != BPF_FUNC_sk_redirect_hash && 6776 func_id != BPF_FUNC_sock_hash_update && 6777 func_id != BPF_FUNC_map_delete_elem && 6778 func_id != BPF_FUNC_msg_redirect_hash && 6779 func_id != BPF_FUNC_sk_select_reuseport && 6780 func_id != BPF_FUNC_map_lookup_elem && 6781 !may_update_sockmap(env, func_id)) 6782 goto error; 6783 break; 6784 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 6785 if (func_id != BPF_FUNC_sk_select_reuseport) 6786 goto error; 6787 break; 6788 case BPF_MAP_TYPE_QUEUE: 6789 case BPF_MAP_TYPE_STACK: 6790 if (func_id != BPF_FUNC_map_peek_elem && 6791 func_id != BPF_FUNC_map_pop_elem && 6792 func_id != BPF_FUNC_map_push_elem) 6793 goto error; 6794 break; 6795 case BPF_MAP_TYPE_SK_STORAGE: 6796 if (func_id != BPF_FUNC_sk_storage_get && 6797 func_id != BPF_FUNC_sk_storage_delete) 6798 goto error; 6799 break; 6800 case BPF_MAP_TYPE_INODE_STORAGE: 6801 if (func_id != BPF_FUNC_inode_storage_get && 6802 func_id != BPF_FUNC_inode_storage_delete) 6803 goto error; 6804 break; 6805 case BPF_MAP_TYPE_TASK_STORAGE: 6806 if (func_id != BPF_FUNC_task_storage_get && 6807 func_id != BPF_FUNC_task_storage_delete) 6808 goto error; 6809 break; 6810 case BPF_MAP_TYPE_CGRP_STORAGE: 6811 if (func_id != BPF_FUNC_cgrp_storage_get && 6812 func_id != BPF_FUNC_cgrp_storage_delete) 6813 goto error; 6814 break; 6815 case BPF_MAP_TYPE_BLOOM_FILTER: 6816 if (func_id != BPF_FUNC_map_peek_elem && 6817 func_id != BPF_FUNC_map_push_elem) 6818 goto error; 6819 break; 6820 default: 6821 break; 6822 } 6823 6824 /* ... and second from the function itself. */ 6825 switch (func_id) { 6826 case BPF_FUNC_tail_call: 6827 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 6828 goto error; 6829 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 6830 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 6831 return -EINVAL; 6832 } 6833 break; 6834 case BPF_FUNC_perf_event_read: 6835 case BPF_FUNC_perf_event_output: 6836 case BPF_FUNC_perf_event_read_value: 6837 case BPF_FUNC_skb_output: 6838 case BPF_FUNC_xdp_output: 6839 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 6840 goto error; 6841 break; 6842 case BPF_FUNC_ringbuf_output: 6843 case BPF_FUNC_ringbuf_reserve: 6844 case BPF_FUNC_ringbuf_query: 6845 case BPF_FUNC_ringbuf_reserve_dynptr: 6846 case BPF_FUNC_ringbuf_submit_dynptr: 6847 case BPF_FUNC_ringbuf_discard_dynptr: 6848 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 6849 goto error; 6850 break; 6851 case BPF_FUNC_user_ringbuf_drain: 6852 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 6853 goto error; 6854 break; 6855 case BPF_FUNC_get_stackid: 6856 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 6857 goto error; 6858 break; 6859 case BPF_FUNC_current_task_under_cgroup: 6860 case BPF_FUNC_skb_under_cgroup: 6861 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 6862 goto error; 6863 break; 6864 case BPF_FUNC_redirect_map: 6865 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 6866 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 6867 map->map_type != BPF_MAP_TYPE_CPUMAP && 6868 map->map_type != BPF_MAP_TYPE_XSKMAP) 6869 goto error; 6870 break; 6871 case BPF_FUNC_sk_redirect_map: 6872 case BPF_FUNC_msg_redirect_map: 6873 case BPF_FUNC_sock_map_update: 6874 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 6875 goto error; 6876 break; 6877 case BPF_FUNC_sk_redirect_hash: 6878 case BPF_FUNC_msg_redirect_hash: 6879 case BPF_FUNC_sock_hash_update: 6880 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 6881 goto error; 6882 break; 6883 case BPF_FUNC_get_local_storage: 6884 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 6885 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 6886 goto error; 6887 break; 6888 case BPF_FUNC_sk_select_reuseport: 6889 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 6890 map->map_type != BPF_MAP_TYPE_SOCKMAP && 6891 map->map_type != BPF_MAP_TYPE_SOCKHASH) 6892 goto error; 6893 break; 6894 case BPF_FUNC_map_pop_elem: 6895 if (map->map_type != BPF_MAP_TYPE_QUEUE && 6896 map->map_type != BPF_MAP_TYPE_STACK) 6897 goto error; 6898 break; 6899 case BPF_FUNC_map_peek_elem: 6900 case BPF_FUNC_map_push_elem: 6901 if (map->map_type != BPF_MAP_TYPE_QUEUE && 6902 map->map_type != BPF_MAP_TYPE_STACK && 6903 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 6904 goto error; 6905 break; 6906 case BPF_FUNC_map_lookup_percpu_elem: 6907 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 6908 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 6909 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 6910 goto error; 6911 break; 6912 case BPF_FUNC_sk_storage_get: 6913 case BPF_FUNC_sk_storage_delete: 6914 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 6915 goto error; 6916 break; 6917 case BPF_FUNC_inode_storage_get: 6918 case BPF_FUNC_inode_storage_delete: 6919 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 6920 goto error; 6921 break; 6922 case BPF_FUNC_task_storage_get: 6923 case BPF_FUNC_task_storage_delete: 6924 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 6925 goto error; 6926 break; 6927 case BPF_FUNC_cgrp_storage_get: 6928 case BPF_FUNC_cgrp_storage_delete: 6929 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 6930 goto error; 6931 break; 6932 default: 6933 break; 6934 } 6935 6936 return 0; 6937 error: 6938 verbose(env, "cannot pass map_type %d into func %s#%d\n", 6939 map->map_type, func_id_name(func_id), func_id); 6940 return -EINVAL; 6941 } 6942 6943 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 6944 { 6945 int count = 0; 6946 6947 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 6948 count++; 6949 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 6950 count++; 6951 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 6952 count++; 6953 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 6954 count++; 6955 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 6956 count++; 6957 6958 /* We only support one arg being in raw mode at the moment, 6959 * which is sufficient for the helper functions we have 6960 * right now. 6961 */ 6962 return count <= 1; 6963 } 6964 6965 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 6966 { 6967 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 6968 bool has_size = fn->arg_size[arg] != 0; 6969 bool is_next_size = false; 6970 6971 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 6972 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 6973 6974 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 6975 return is_next_size; 6976 6977 return has_size == is_next_size || is_next_size == is_fixed; 6978 } 6979 6980 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 6981 { 6982 /* bpf_xxx(..., buf, len) call will access 'len' 6983 * bytes from memory 'buf'. Both arg types need 6984 * to be paired, so make sure there's no buggy 6985 * helper function specification. 6986 */ 6987 if (arg_type_is_mem_size(fn->arg1_type) || 6988 check_args_pair_invalid(fn, 0) || 6989 check_args_pair_invalid(fn, 1) || 6990 check_args_pair_invalid(fn, 2) || 6991 check_args_pair_invalid(fn, 3) || 6992 check_args_pair_invalid(fn, 4)) 6993 return false; 6994 6995 return true; 6996 } 6997 6998 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 6999 { 7000 int i; 7001 7002 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 7003 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 7004 return !!fn->arg_btf_id[i]; 7005 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 7006 return fn->arg_btf_id[i] == BPF_PTR_POISON; 7007 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 7008 /* arg_btf_id and arg_size are in a union. */ 7009 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 7010 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 7011 return false; 7012 } 7013 7014 return true; 7015 } 7016 7017 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 7018 { 7019 return check_raw_mode_ok(fn) && 7020 check_arg_pair_ok(fn) && 7021 check_btf_id_ok(fn) ? 0 : -EINVAL; 7022 } 7023 7024 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 7025 * are now invalid, so turn them into unknown SCALAR_VALUE. 7026 */ 7027 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 7028 { 7029 struct bpf_func_state *state; 7030 struct bpf_reg_state *reg; 7031 7032 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 7033 if (reg_is_pkt_pointer_any(reg)) 7034 __mark_reg_unknown(env, reg); 7035 })); 7036 } 7037 7038 enum { 7039 AT_PKT_END = -1, 7040 BEYOND_PKT_END = -2, 7041 }; 7042 7043 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 7044 { 7045 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7046 struct bpf_reg_state *reg = &state->regs[regn]; 7047 7048 if (reg->type != PTR_TO_PACKET) 7049 /* PTR_TO_PACKET_META is not supported yet */ 7050 return; 7051 7052 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 7053 * How far beyond pkt_end it goes is unknown. 7054 * if (!range_open) it's the case of pkt >= pkt_end 7055 * if (range_open) it's the case of pkt > pkt_end 7056 * hence this pointer is at least 1 byte bigger than pkt_end 7057 */ 7058 if (range_open) 7059 reg->range = BEYOND_PKT_END; 7060 else 7061 reg->range = AT_PKT_END; 7062 } 7063 7064 /* The pointer with the specified id has released its reference to kernel 7065 * resources. Identify all copies of the same pointer and clear the reference. 7066 */ 7067 static int release_reference(struct bpf_verifier_env *env, 7068 int ref_obj_id) 7069 { 7070 struct bpf_func_state *state; 7071 struct bpf_reg_state *reg; 7072 int err; 7073 7074 err = release_reference_state(cur_func(env), ref_obj_id); 7075 if (err) 7076 return err; 7077 7078 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 7079 if (reg->ref_obj_id == ref_obj_id) { 7080 if (!env->allow_ptr_leaks) 7081 __mark_reg_not_init(env, reg); 7082 else 7083 __mark_reg_unknown(env, reg); 7084 } 7085 })); 7086 7087 return 0; 7088 } 7089 7090 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 7091 struct bpf_reg_state *regs) 7092 { 7093 int i; 7094 7095 /* after the call registers r0 - r5 were scratched */ 7096 for (i = 0; i < CALLER_SAVED_REGS; i++) { 7097 mark_reg_not_init(env, regs, caller_saved[i]); 7098 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 7099 } 7100 } 7101 7102 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 7103 struct bpf_func_state *caller, 7104 struct bpf_func_state *callee, 7105 int insn_idx); 7106 7107 static int set_callee_state(struct bpf_verifier_env *env, 7108 struct bpf_func_state *caller, 7109 struct bpf_func_state *callee, int insn_idx); 7110 7111 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7112 int *insn_idx, int subprog, 7113 set_callee_state_fn set_callee_state_cb) 7114 { 7115 struct bpf_verifier_state *state = env->cur_state; 7116 struct bpf_func_info_aux *func_info_aux; 7117 struct bpf_func_state *caller, *callee; 7118 int err; 7119 bool is_global = false; 7120 7121 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 7122 verbose(env, "the call stack of %d frames is too deep\n", 7123 state->curframe + 2); 7124 return -E2BIG; 7125 } 7126 7127 caller = state->frame[state->curframe]; 7128 if (state->frame[state->curframe + 1]) { 7129 verbose(env, "verifier bug. Frame %d already allocated\n", 7130 state->curframe + 1); 7131 return -EFAULT; 7132 } 7133 7134 func_info_aux = env->prog->aux->func_info_aux; 7135 if (func_info_aux) 7136 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 7137 err = btf_check_subprog_call(env, subprog, caller->regs); 7138 if (err == -EFAULT) 7139 return err; 7140 if (is_global) { 7141 if (err) { 7142 verbose(env, "Caller passes invalid args into func#%d\n", 7143 subprog); 7144 return err; 7145 } else { 7146 if (env->log.level & BPF_LOG_LEVEL) 7147 verbose(env, 7148 "Func#%d is global and valid. Skipping.\n", 7149 subprog); 7150 clear_caller_saved_regs(env, caller->regs); 7151 7152 /* All global functions return a 64-bit SCALAR_VALUE */ 7153 mark_reg_unknown(env, caller->regs, BPF_REG_0); 7154 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 7155 7156 /* continue with next insn after call */ 7157 return 0; 7158 } 7159 } 7160 7161 /* set_callee_state is used for direct subprog calls, but we are 7162 * interested in validating only BPF helpers that can call subprogs as 7163 * callbacks 7164 */ 7165 if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) { 7166 verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n", 7167 func_id_name(insn->imm), insn->imm); 7168 return -EFAULT; 7169 } 7170 7171 if (insn->code == (BPF_JMP | BPF_CALL) && 7172 insn->src_reg == 0 && 7173 insn->imm == BPF_FUNC_timer_set_callback) { 7174 struct bpf_verifier_state *async_cb; 7175 7176 /* there is no real recursion here. timer callbacks are async */ 7177 env->subprog_info[subprog].is_async_cb = true; 7178 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 7179 *insn_idx, subprog); 7180 if (!async_cb) 7181 return -EFAULT; 7182 callee = async_cb->frame[0]; 7183 callee->async_entry_cnt = caller->async_entry_cnt + 1; 7184 7185 /* Convert bpf_timer_set_callback() args into timer callback args */ 7186 err = set_callee_state_cb(env, caller, callee, *insn_idx); 7187 if (err) 7188 return err; 7189 7190 clear_caller_saved_regs(env, caller->regs); 7191 mark_reg_unknown(env, caller->regs, BPF_REG_0); 7192 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 7193 /* continue with next insn after call */ 7194 return 0; 7195 } 7196 7197 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 7198 if (!callee) 7199 return -ENOMEM; 7200 state->frame[state->curframe + 1] = callee; 7201 7202 /* callee cannot access r0, r6 - r9 for reading and has to write 7203 * into its own stack before reading from it. 7204 * callee can read/write into caller's stack 7205 */ 7206 init_func_state(env, callee, 7207 /* remember the callsite, it will be used by bpf_exit */ 7208 *insn_idx /* callsite */, 7209 state->curframe + 1 /* frameno within this callchain */, 7210 subprog /* subprog number within this prog */); 7211 7212 /* Transfer references to the callee */ 7213 err = copy_reference_state(callee, caller); 7214 if (err) 7215 goto err_out; 7216 7217 err = set_callee_state_cb(env, caller, callee, *insn_idx); 7218 if (err) 7219 goto err_out; 7220 7221 clear_caller_saved_regs(env, caller->regs); 7222 7223 /* only increment it after check_reg_arg() finished */ 7224 state->curframe++; 7225 7226 /* and go analyze first insn of the callee */ 7227 *insn_idx = env->subprog_info[subprog].start - 1; 7228 7229 if (env->log.level & BPF_LOG_LEVEL) { 7230 verbose(env, "caller:\n"); 7231 print_verifier_state(env, caller, true); 7232 verbose(env, "callee:\n"); 7233 print_verifier_state(env, callee, true); 7234 } 7235 return 0; 7236 7237 err_out: 7238 free_func_state(callee); 7239 state->frame[state->curframe + 1] = NULL; 7240 return err; 7241 } 7242 7243 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 7244 struct bpf_func_state *caller, 7245 struct bpf_func_state *callee) 7246 { 7247 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 7248 * void *callback_ctx, u64 flags); 7249 * callback_fn(struct bpf_map *map, void *key, void *value, 7250 * void *callback_ctx); 7251 */ 7252 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 7253 7254 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 7255 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7256 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 7257 7258 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 7259 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 7260 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 7261 7262 /* pointer to stack or null */ 7263 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 7264 7265 /* unused */ 7266 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7267 return 0; 7268 } 7269 7270 static int set_callee_state(struct bpf_verifier_env *env, 7271 struct bpf_func_state *caller, 7272 struct bpf_func_state *callee, int insn_idx) 7273 { 7274 int i; 7275 7276 /* copy r1 - r5 args that callee can access. The copy includes parent 7277 * pointers, which connects us up to the liveness chain 7278 */ 7279 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 7280 callee->regs[i] = caller->regs[i]; 7281 return 0; 7282 } 7283 7284 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7285 int *insn_idx) 7286 { 7287 int subprog, target_insn; 7288 7289 target_insn = *insn_idx + insn->imm + 1; 7290 subprog = find_subprog(env, target_insn); 7291 if (subprog < 0) { 7292 verbose(env, "verifier bug. No program starts at insn %d\n", 7293 target_insn); 7294 return -EFAULT; 7295 } 7296 7297 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 7298 } 7299 7300 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 7301 struct bpf_func_state *caller, 7302 struct bpf_func_state *callee, 7303 int insn_idx) 7304 { 7305 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 7306 struct bpf_map *map; 7307 int err; 7308 7309 if (bpf_map_ptr_poisoned(insn_aux)) { 7310 verbose(env, "tail_call abusing map_ptr\n"); 7311 return -EINVAL; 7312 } 7313 7314 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 7315 if (!map->ops->map_set_for_each_callback_args || 7316 !map->ops->map_for_each_callback) { 7317 verbose(env, "callback function not allowed for map\n"); 7318 return -ENOTSUPP; 7319 } 7320 7321 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 7322 if (err) 7323 return err; 7324 7325 callee->in_callback_fn = true; 7326 callee->callback_ret_range = tnum_range(0, 1); 7327 return 0; 7328 } 7329 7330 static int set_loop_callback_state(struct bpf_verifier_env *env, 7331 struct bpf_func_state *caller, 7332 struct bpf_func_state *callee, 7333 int insn_idx) 7334 { 7335 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 7336 * u64 flags); 7337 * callback_fn(u32 index, void *callback_ctx); 7338 */ 7339 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 7340 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 7341 7342 /* unused */ 7343 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 7344 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7345 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7346 7347 callee->in_callback_fn = true; 7348 callee->callback_ret_range = tnum_range(0, 1); 7349 return 0; 7350 } 7351 7352 static int set_timer_callback_state(struct bpf_verifier_env *env, 7353 struct bpf_func_state *caller, 7354 struct bpf_func_state *callee, 7355 int insn_idx) 7356 { 7357 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 7358 7359 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 7360 * callback_fn(struct bpf_map *map, void *key, void *value); 7361 */ 7362 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 7363 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 7364 callee->regs[BPF_REG_1].map_ptr = map_ptr; 7365 7366 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 7367 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7368 callee->regs[BPF_REG_2].map_ptr = map_ptr; 7369 7370 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 7371 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 7372 callee->regs[BPF_REG_3].map_ptr = map_ptr; 7373 7374 /* unused */ 7375 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7376 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7377 callee->in_async_callback_fn = true; 7378 callee->callback_ret_range = tnum_range(0, 1); 7379 return 0; 7380 } 7381 7382 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 7383 struct bpf_func_state *caller, 7384 struct bpf_func_state *callee, 7385 int insn_idx) 7386 { 7387 /* bpf_find_vma(struct task_struct *task, u64 addr, 7388 * void *callback_fn, void *callback_ctx, u64 flags) 7389 * (callback_fn)(struct task_struct *task, 7390 * struct vm_area_struct *vma, void *callback_ctx); 7391 */ 7392 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 7393 7394 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 7395 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7396 callee->regs[BPF_REG_2].btf = btf_vmlinux; 7397 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 7398 7399 /* pointer to stack or null */ 7400 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 7401 7402 /* unused */ 7403 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7404 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7405 callee->in_callback_fn = true; 7406 callee->callback_ret_range = tnum_range(0, 1); 7407 return 0; 7408 } 7409 7410 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 7411 struct bpf_func_state *caller, 7412 struct bpf_func_state *callee, 7413 int insn_idx) 7414 { 7415 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 7416 * callback_ctx, u64 flags); 7417 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 7418 */ 7419 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 7420 mark_dynptr_cb_reg(&callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 7421 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 7422 7423 /* unused */ 7424 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 7425 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7426 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7427 7428 callee->in_callback_fn = true; 7429 callee->callback_ret_range = tnum_range(0, 1); 7430 return 0; 7431 } 7432 7433 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 7434 { 7435 struct bpf_verifier_state *state = env->cur_state; 7436 struct bpf_func_state *caller, *callee; 7437 struct bpf_reg_state *r0; 7438 int err; 7439 7440 callee = state->frame[state->curframe]; 7441 r0 = &callee->regs[BPF_REG_0]; 7442 if (r0->type == PTR_TO_STACK) { 7443 /* technically it's ok to return caller's stack pointer 7444 * (or caller's caller's pointer) back to the caller, 7445 * since these pointers are valid. Only current stack 7446 * pointer will be invalid as soon as function exits, 7447 * but let's be conservative 7448 */ 7449 verbose(env, "cannot return stack pointer to the caller\n"); 7450 return -EINVAL; 7451 } 7452 7453 caller = state->frame[state->curframe - 1]; 7454 if (callee->in_callback_fn) { 7455 /* enforce R0 return value range [0, 1]. */ 7456 struct tnum range = callee->callback_ret_range; 7457 7458 if (r0->type != SCALAR_VALUE) { 7459 verbose(env, "R0 not a scalar value\n"); 7460 return -EACCES; 7461 } 7462 if (!tnum_in(range, r0->var_off)) { 7463 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 7464 return -EINVAL; 7465 } 7466 } else { 7467 /* return to the caller whatever r0 had in the callee */ 7468 caller->regs[BPF_REG_0] = *r0; 7469 } 7470 7471 /* callback_fn frame should have released its own additions to parent's 7472 * reference state at this point, or check_reference_leak would 7473 * complain, hence it must be the same as the caller. There is no need 7474 * to copy it back. 7475 */ 7476 if (!callee->in_callback_fn) { 7477 /* Transfer references to the caller */ 7478 err = copy_reference_state(caller, callee); 7479 if (err) 7480 return err; 7481 } 7482 7483 *insn_idx = callee->callsite + 1; 7484 if (env->log.level & BPF_LOG_LEVEL) { 7485 verbose(env, "returning from callee:\n"); 7486 print_verifier_state(env, callee, true); 7487 verbose(env, "to caller at %d:\n", *insn_idx); 7488 print_verifier_state(env, caller, true); 7489 } 7490 /* clear everything in the callee */ 7491 free_func_state(callee); 7492 state->frame[state->curframe--] = NULL; 7493 return 0; 7494 } 7495 7496 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 7497 int func_id, 7498 struct bpf_call_arg_meta *meta) 7499 { 7500 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 7501 7502 if (ret_type != RET_INTEGER || 7503 (func_id != BPF_FUNC_get_stack && 7504 func_id != BPF_FUNC_get_task_stack && 7505 func_id != BPF_FUNC_probe_read_str && 7506 func_id != BPF_FUNC_probe_read_kernel_str && 7507 func_id != BPF_FUNC_probe_read_user_str)) 7508 return; 7509 7510 ret_reg->smax_value = meta->msize_max_value; 7511 ret_reg->s32_max_value = meta->msize_max_value; 7512 ret_reg->smin_value = -MAX_ERRNO; 7513 ret_reg->s32_min_value = -MAX_ERRNO; 7514 reg_bounds_sync(ret_reg); 7515 } 7516 7517 static int 7518 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 7519 int func_id, int insn_idx) 7520 { 7521 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 7522 struct bpf_map *map = meta->map_ptr; 7523 7524 if (func_id != BPF_FUNC_tail_call && 7525 func_id != BPF_FUNC_map_lookup_elem && 7526 func_id != BPF_FUNC_map_update_elem && 7527 func_id != BPF_FUNC_map_delete_elem && 7528 func_id != BPF_FUNC_map_push_elem && 7529 func_id != BPF_FUNC_map_pop_elem && 7530 func_id != BPF_FUNC_map_peek_elem && 7531 func_id != BPF_FUNC_for_each_map_elem && 7532 func_id != BPF_FUNC_redirect_map && 7533 func_id != BPF_FUNC_map_lookup_percpu_elem) 7534 return 0; 7535 7536 if (map == NULL) { 7537 verbose(env, "kernel subsystem misconfigured verifier\n"); 7538 return -EINVAL; 7539 } 7540 7541 /* In case of read-only, some additional restrictions 7542 * need to be applied in order to prevent altering the 7543 * state of the map from program side. 7544 */ 7545 if ((map->map_flags & BPF_F_RDONLY_PROG) && 7546 (func_id == BPF_FUNC_map_delete_elem || 7547 func_id == BPF_FUNC_map_update_elem || 7548 func_id == BPF_FUNC_map_push_elem || 7549 func_id == BPF_FUNC_map_pop_elem)) { 7550 verbose(env, "write into map forbidden\n"); 7551 return -EACCES; 7552 } 7553 7554 if (!BPF_MAP_PTR(aux->map_ptr_state)) 7555 bpf_map_ptr_store(aux, meta->map_ptr, 7556 !meta->map_ptr->bypass_spec_v1); 7557 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 7558 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 7559 !meta->map_ptr->bypass_spec_v1); 7560 return 0; 7561 } 7562 7563 static int 7564 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 7565 int func_id, int insn_idx) 7566 { 7567 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 7568 struct bpf_reg_state *regs = cur_regs(env), *reg; 7569 struct bpf_map *map = meta->map_ptr; 7570 u64 val, max; 7571 int err; 7572 7573 if (func_id != BPF_FUNC_tail_call) 7574 return 0; 7575 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 7576 verbose(env, "kernel subsystem misconfigured verifier\n"); 7577 return -EINVAL; 7578 } 7579 7580 reg = ®s[BPF_REG_3]; 7581 val = reg->var_off.value; 7582 max = map->max_entries; 7583 7584 if (!(register_is_const(reg) && val < max)) { 7585 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 7586 return 0; 7587 } 7588 7589 err = mark_chain_precision(env, BPF_REG_3); 7590 if (err) 7591 return err; 7592 if (bpf_map_key_unseen(aux)) 7593 bpf_map_key_store(aux, val); 7594 else if (!bpf_map_key_poisoned(aux) && 7595 bpf_map_key_immediate(aux) != val) 7596 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 7597 return 0; 7598 } 7599 7600 static int check_reference_leak(struct bpf_verifier_env *env) 7601 { 7602 struct bpf_func_state *state = cur_func(env); 7603 bool refs_lingering = false; 7604 int i; 7605 7606 if (state->frameno && !state->in_callback_fn) 7607 return 0; 7608 7609 for (i = 0; i < state->acquired_refs; i++) { 7610 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 7611 continue; 7612 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 7613 state->refs[i].id, state->refs[i].insn_idx); 7614 refs_lingering = true; 7615 } 7616 return refs_lingering ? -EINVAL : 0; 7617 } 7618 7619 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 7620 struct bpf_reg_state *regs) 7621 { 7622 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 7623 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 7624 struct bpf_map *fmt_map = fmt_reg->map_ptr; 7625 int err, fmt_map_off, num_args; 7626 u64 fmt_addr; 7627 char *fmt; 7628 7629 /* data must be an array of u64 */ 7630 if (data_len_reg->var_off.value % 8) 7631 return -EINVAL; 7632 num_args = data_len_reg->var_off.value / 8; 7633 7634 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 7635 * and map_direct_value_addr is set. 7636 */ 7637 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 7638 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 7639 fmt_map_off); 7640 if (err) { 7641 verbose(env, "verifier bug\n"); 7642 return -EFAULT; 7643 } 7644 fmt = (char *)(long)fmt_addr + fmt_map_off; 7645 7646 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 7647 * can focus on validating the format specifiers. 7648 */ 7649 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args); 7650 if (err < 0) 7651 verbose(env, "Invalid format string\n"); 7652 7653 return err; 7654 } 7655 7656 static int check_get_func_ip(struct bpf_verifier_env *env) 7657 { 7658 enum bpf_prog_type type = resolve_prog_type(env->prog); 7659 int func_id = BPF_FUNC_get_func_ip; 7660 7661 if (type == BPF_PROG_TYPE_TRACING) { 7662 if (!bpf_prog_has_trampoline(env->prog)) { 7663 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 7664 func_id_name(func_id), func_id); 7665 return -ENOTSUPP; 7666 } 7667 return 0; 7668 } else if (type == BPF_PROG_TYPE_KPROBE) { 7669 return 0; 7670 } 7671 7672 verbose(env, "func %s#%d not supported for program type %d\n", 7673 func_id_name(func_id), func_id, type); 7674 return -ENOTSUPP; 7675 } 7676 7677 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 7678 { 7679 return &env->insn_aux_data[env->insn_idx]; 7680 } 7681 7682 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 7683 { 7684 struct bpf_reg_state *regs = cur_regs(env); 7685 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 7686 bool reg_is_null = register_is_null(reg); 7687 7688 if (reg_is_null) 7689 mark_chain_precision(env, BPF_REG_4); 7690 7691 return reg_is_null; 7692 } 7693 7694 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 7695 { 7696 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 7697 7698 if (!state->initialized) { 7699 state->initialized = 1; 7700 state->fit_for_inline = loop_flag_is_zero(env); 7701 state->callback_subprogno = subprogno; 7702 return; 7703 } 7704 7705 if (!state->fit_for_inline) 7706 return; 7707 7708 state->fit_for_inline = (loop_flag_is_zero(env) && 7709 state->callback_subprogno == subprogno); 7710 } 7711 7712 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7713 int *insn_idx_p) 7714 { 7715 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 7716 const struct bpf_func_proto *fn = NULL; 7717 enum bpf_return_type ret_type; 7718 enum bpf_type_flag ret_flag; 7719 struct bpf_reg_state *regs; 7720 struct bpf_call_arg_meta meta; 7721 int insn_idx = *insn_idx_p; 7722 bool changes_data; 7723 int i, err, func_id; 7724 7725 /* find function prototype */ 7726 func_id = insn->imm; 7727 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 7728 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 7729 func_id); 7730 return -EINVAL; 7731 } 7732 7733 if (env->ops->get_func_proto) 7734 fn = env->ops->get_func_proto(func_id, env->prog); 7735 if (!fn) { 7736 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 7737 func_id); 7738 return -EINVAL; 7739 } 7740 7741 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 7742 if (!env->prog->gpl_compatible && fn->gpl_only) { 7743 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 7744 return -EINVAL; 7745 } 7746 7747 if (fn->allowed && !fn->allowed(env->prog)) { 7748 verbose(env, "helper call is not allowed in probe\n"); 7749 return -EINVAL; 7750 } 7751 7752 if (!env->prog->aux->sleepable && fn->might_sleep) { 7753 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 7754 return -EINVAL; 7755 } 7756 7757 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 7758 changes_data = bpf_helper_changes_pkt_data(fn->func); 7759 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 7760 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 7761 func_id_name(func_id), func_id); 7762 return -EINVAL; 7763 } 7764 7765 memset(&meta, 0, sizeof(meta)); 7766 meta.pkt_access = fn->pkt_access; 7767 7768 err = check_func_proto(fn, func_id); 7769 if (err) { 7770 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 7771 func_id_name(func_id), func_id); 7772 return err; 7773 } 7774 7775 if (env->cur_state->active_rcu_lock) { 7776 if (fn->might_sleep) { 7777 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 7778 func_id_name(func_id), func_id); 7779 return -EINVAL; 7780 } 7781 7782 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 7783 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 7784 } 7785 7786 meta.func_id = func_id; 7787 /* check args */ 7788 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 7789 err = check_func_arg(env, i, &meta, fn); 7790 if (err) 7791 return err; 7792 } 7793 7794 err = record_func_map(env, &meta, func_id, insn_idx); 7795 if (err) 7796 return err; 7797 7798 err = record_func_key(env, &meta, func_id, insn_idx); 7799 if (err) 7800 return err; 7801 7802 /* Mark slots with STACK_MISC in case of raw mode, stack offset 7803 * is inferred from register state. 7804 */ 7805 for (i = 0; i < meta.access_size; i++) { 7806 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 7807 BPF_WRITE, -1, false); 7808 if (err) 7809 return err; 7810 } 7811 7812 regs = cur_regs(env); 7813 7814 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 7815 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr 7816 * is safe to do directly. 7817 */ 7818 if (meta.uninit_dynptr_regno) { 7819 if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) { 7820 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n"); 7821 return -EFAULT; 7822 } 7823 /* we write BPF_DW bits (8 bytes) at a time */ 7824 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 7825 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno, 7826 i, BPF_DW, BPF_WRITE, -1, false); 7827 if (err) 7828 return err; 7829 } 7830 7831 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno], 7832 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1], 7833 insn_idx); 7834 if (err) 7835 return err; 7836 } 7837 7838 if (meta.release_regno) { 7839 err = -EINVAL; 7840 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 7841 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 7842 * is safe to do directly. 7843 */ 7844 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 7845 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 7846 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 7847 return -EFAULT; 7848 } 7849 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 7850 } else if (meta.ref_obj_id) { 7851 err = release_reference(env, meta.ref_obj_id); 7852 } else if (register_is_null(®s[meta.release_regno])) { 7853 /* meta.ref_obj_id can only be 0 if register that is meant to be 7854 * released is NULL, which must be > R0. 7855 */ 7856 err = 0; 7857 } 7858 if (err) { 7859 verbose(env, "func %s#%d reference has not been acquired before\n", 7860 func_id_name(func_id), func_id); 7861 return err; 7862 } 7863 } 7864 7865 switch (func_id) { 7866 case BPF_FUNC_tail_call: 7867 err = check_reference_leak(env); 7868 if (err) { 7869 verbose(env, "tail_call would lead to reference leak\n"); 7870 return err; 7871 } 7872 break; 7873 case BPF_FUNC_get_local_storage: 7874 /* check that flags argument in get_local_storage(map, flags) is 0, 7875 * this is required because get_local_storage() can't return an error. 7876 */ 7877 if (!register_is_null(®s[BPF_REG_2])) { 7878 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 7879 return -EINVAL; 7880 } 7881 break; 7882 case BPF_FUNC_for_each_map_elem: 7883 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 7884 set_map_elem_callback_state); 7885 break; 7886 case BPF_FUNC_timer_set_callback: 7887 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 7888 set_timer_callback_state); 7889 break; 7890 case BPF_FUNC_find_vma: 7891 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 7892 set_find_vma_callback_state); 7893 break; 7894 case BPF_FUNC_snprintf: 7895 err = check_bpf_snprintf_call(env, regs); 7896 break; 7897 case BPF_FUNC_loop: 7898 update_loop_inline_state(env, meta.subprogno); 7899 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 7900 set_loop_callback_state); 7901 break; 7902 case BPF_FUNC_dynptr_from_mem: 7903 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 7904 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 7905 reg_type_str(env, regs[BPF_REG_1].type)); 7906 return -EACCES; 7907 } 7908 break; 7909 case BPF_FUNC_set_retval: 7910 if (prog_type == BPF_PROG_TYPE_LSM && 7911 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 7912 if (!env->prog->aux->attach_func_proto->type) { 7913 /* Make sure programs that attach to void 7914 * hooks don't try to modify return value. 7915 */ 7916 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 7917 return -EINVAL; 7918 } 7919 } 7920 break; 7921 case BPF_FUNC_dynptr_data: 7922 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 7923 if (arg_type_is_dynptr(fn->arg_type[i])) { 7924 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i]; 7925 7926 if (meta.ref_obj_id) { 7927 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 7928 return -EFAULT; 7929 } 7930 7931 meta.ref_obj_id = dynptr_ref_obj_id(env, reg); 7932 break; 7933 } 7934 } 7935 if (i == MAX_BPF_FUNC_REG_ARGS) { 7936 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n"); 7937 return -EFAULT; 7938 } 7939 break; 7940 case BPF_FUNC_user_ringbuf_drain: 7941 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 7942 set_user_ringbuf_callback_state); 7943 break; 7944 } 7945 7946 if (err) 7947 return err; 7948 7949 /* reset caller saved regs */ 7950 for (i = 0; i < CALLER_SAVED_REGS; i++) { 7951 mark_reg_not_init(env, regs, caller_saved[i]); 7952 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 7953 } 7954 7955 /* helper call returns 64-bit value. */ 7956 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 7957 7958 /* update return register (already marked as written above) */ 7959 ret_type = fn->ret_type; 7960 ret_flag = type_flag(ret_type); 7961 7962 switch (base_type(ret_type)) { 7963 case RET_INTEGER: 7964 /* sets type to SCALAR_VALUE */ 7965 mark_reg_unknown(env, regs, BPF_REG_0); 7966 break; 7967 case RET_VOID: 7968 regs[BPF_REG_0].type = NOT_INIT; 7969 break; 7970 case RET_PTR_TO_MAP_VALUE: 7971 /* There is no offset yet applied, variable or fixed */ 7972 mark_reg_known_zero(env, regs, BPF_REG_0); 7973 /* remember map_ptr, so that check_map_access() 7974 * can check 'value_size' boundary of memory access 7975 * to map element returned from bpf_map_lookup_elem() 7976 */ 7977 if (meta.map_ptr == NULL) { 7978 verbose(env, 7979 "kernel subsystem misconfigured verifier\n"); 7980 return -EINVAL; 7981 } 7982 regs[BPF_REG_0].map_ptr = meta.map_ptr; 7983 regs[BPF_REG_0].map_uid = meta.map_uid; 7984 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 7985 if (!type_may_be_null(ret_type) && 7986 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 7987 regs[BPF_REG_0].id = ++env->id_gen; 7988 } 7989 break; 7990 case RET_PTR_TO_SOCKET: 7991 mark_reg_known_zero(env, regs, BPF_REG_0); 7992 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 7993 break; 7994 case RET_PTR_TO_SOCK_COMMON: 7995 mark_reg_known_zero(env, regs, BPF_REG_0); 7996 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 7997 break; 7998 case RET_PTR_TO_TCP_SOCK: 7999 mark_reg_known_zero(env, regs, BPF_REG_0); 8000 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 8001 break; 8002 case RET_PTR_TO_MEM: 8003 mark_reg_known_zero(env, regs, BPF_REG_0); 8004 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 8005 regs[BPF_REG_0].mem_size = meta.mem_size; 8006 break; 8007 case RET_PTR_TO_MEM_OR_BTF_ID: 8008 { 8009 const struct btf_type *t; 8010 8011 mark_reg_known_zero(env, regs, BPF_REG_0); 8012 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 8013 if (!btf_type_is_struct(t)) { 8014 u32 tsize; 8015 const struct btf_type *ret; 8016 const char *tname; 8017 8018 /* resolve the type size of ksym. */ 8019 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 8020 if (IS_ERR(ret)) { 8021 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 8022 verbose(env, "unable to resolve the size of type '%s': %ld\n", 8023 tname, PTR_ERR(ret)); 8024 return -EINVAL; 8025 } 8026 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 8027 regs[BPF_REG_0].mem_size = tsize; 8028 } else { 8029 /* MEM_RDONLY may be carried from ret_flag, but it 8030 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 8031 * it will confuse the check of PTR_TO_BTF_ID in 8032 * check_mem_access(). 8033 */ 8034 ret_flag &= ~MEM_RDONLY; 8035 8036 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 8037 regs[BPF_REG_0].btf = meta.ret_btf; 8038 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 8039 } 8040 break; 8041 } 8042 case RET_PTR_TO_BTF_ID: 8043 { 8044 struct btf *ret_btf; 8045 int ret_btf_id; 8046 8047 mark_reg_known_zero(env, regs, BPF_REG_0); 8048 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 8049 if (func_id == BPF_FUNC_kptr_xchg) { 8050 ret_btf = meta.kptr_field->kptr.btf; 8051 ret_btf_id = meta.kptr_field->kptr.btf_id; 8052 } else { 8053 if (fn->ret_btf_id == BPF_PTR_POISON) { 8054 verbose(env, "verifier internal error:"); 8055 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 8056 func_id_name(func_id)); 8057 return -EINVAL; 8058 } 8059 ret_btf = btf_vmlinux; 8060 ret_btf_id = *fn->ret_btf_id; 8061 } 8062 if (ret_btf_id == 0) { 8063 verbose(env, "invalid return type %u of func %s#%d\n", 8064 base_type(ret_type), func_id_name(func_id), 8065 func_id); 8066 return -EINVAL; 8067 } 8068 regs[BPF_REG_0].btf = ret_btf; 8069 regs[BPF_REG_0].btf_id = ret_btf_id; 8070 break; 8071 } 8072 default: 8073 verbose(env, "unknown return type %u of func %s#%d\n", 8074 base_type(ret_type), func_id_name(func_id), func_id); 8075 return -EINVAL; 8076 } 8077 8078 if (type_may_be_null(regs[BPF_REG_0].type)) 8079 regs[BPF_REG_0].id = ++env->id_gen; 8080 8081 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 8082 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 8083 func_id_name(func_id), func_id); 8084 return -EFAULT; 8085 } 8086 8087 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 8088 /* For release_reference() */ 8089 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 8090 } else if (is_acquire_function(func_id, meta.map_ptr)) { 8091 int id = acquire_reference_state(env, insn_idx); 8092 8093 if (id < 0) 8094 return id; 8095 /* For mark_ptr_or_null_reg() */ 8096 regs[BPF_REG_0].id = id; 8097 /* For release_reference() */ 8098 regs[BPF_REG_0].ref_obj_id = id; 8099 } 8100 8101 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 8102 8103 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 8104 if (err) 8105 return err; 8106 8107 if ((func_id == BPF_FUNC_get_stack || 8108 func_id == BPF_FUNC_get_task_stack) && 8109 !env->prog->has_callchain_buf) { 8110 const char *err_str; 8111 8112 #ifdef CONFIG_PERF_EVENTS 8113 err = get_callchain_buffers(sysctl_perf_event_max_stack); 8114 err_str = "cannot get callchain buffer for func %s#%d\n"; 8115 #else 8116 err = -ENOTSUPP; 8117 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 8118 #endif 8119 if (err) { 8120 verbose(env, err_str, func_id_name(func_id), func_id); 8121 return err; 8122 } 8123 8124 env->prog->has_callchain_buf = true; 8125 } 8126 8127 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 8128 env->prog->call_get_stack = true; 8129 8130 if (func_id == BPF_FUNC_get_func_ip) { 8131 if (check_get_func_ip(env)) 8132 return -ENOTSUPP; 8133 env->prog->call_get_func_ip = true; 8134 } 8135 8136 if (changes_data) 8137 clear_all_pkt_pointers(env); 8138 return 0; 8139 } 8140 8141 /* mark_btf_func_reg_size() is used when the reg size is determined by 8142 * the BTF func_proto's return value size and argument. 8143 */ 8144 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 8145 size_t reg_size) 8146 { 8147 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 8148 8149 if (regno == BPF_REG_0) { 8150 /* Function return value */ 8151 reg->live |= REG_LIVE_WRITTEN; 8152 reg->subreg_def = reg_size == sizeof(u64) ? 8153 DEF_NOT_SUBREG : env->insn_idx + 1; 8154 } else { 8155 /* Function argument */ 8156 if (reg_size == sizeof(u64)) { 8157 mark_insn_zext(env, reg); 8158 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 8159 } else { 8160 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 8161 } 8162 } 8163 } 8164 8165 struct bpf_kfunc_call_arg_meta { 8166 /* In parameters */ 8167 struct btf *btf; 8168 u32 func_id; 8169 u32 kfunc_flags; 8170 const struct btf_type *func_proto; 8171 const char *func_name; 8172 /* Out parameters */ 8173 u32 ref_obj_id; 8174 u8 release_regno; 8175 bool r0_rdonly; 8176 u32 ret_btf_id; 8177 u64 r0_size; 8178 struct { 8179 u64 value; 8180 bool found; 8181 } arg_constant; 8182 struct { 8183 struct btf *btf; 8184 u32 btf_id; 8185 } arg_obj_drop; 8186 struct { 8187 struct btf_field *field; 8188 } arg_list_head; 8189 }; 8190 8191 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 8192 { 8193 return meta->kfunc_flags & KF_ACQUIRE; 8194 } 8195 8196 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 8197 { 8198 return meta->kfunc_flags & KF_RET_NULL; 8199 } 8200 8201 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 8202 { 8203 return meta->kfunc_flags & KF_RELEASE; 8204 } 8205 8206 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 8207 { 8208 return meta->kfunc_flags & KF_TRUSTED_ARGS; 8209 } 8210 8211 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 8212 { 8213 return meta->kfunc_flags & KF_SLEEPABLE; 8214 } 8215 8216 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 8217 { 8218 return meta->kfunc_flags & KF_DESTRUCTIVE; 8219 } 8220 8221 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 8222 { 8223 return meta->kfunc_flags & KF_RCU; 8224 } 8225 8226 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg) 8227 { 8228 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET); 8229 } 8230 8231 static bool __kfunc_param_match_suffix(const struct btf *btf, 8232 const struct btf_param *arg, 8233 const char *suffix) 8234 { 8235 int suffix_len = strlen(suffix), len; 8236 const char *param_name; 8237 8238 /* In the future, this can be ported to use BTF tagging */ 8239 param_name = btf_name_by_offset(btf, arg->name_off); 8240 if (str_is_empty(param_name)) 8241 return false; 8242 len = strlen(param_name); 8243 if (len < suffix_len) 8244 return false; 8245 param_name += len - suffix_len; 8246 return !strncmp(param_name, suffix, suffix_len); 8247 } 8248 8249 static bool is_kfunc_arg_mem_size(const struct btf *btf, 8250 const struct btf_param *arg, 8251 const struct bpf_reg_state *reg) 8252 { 8253 const struct btf_type *t; 8254 8255 t = btf_type_skip_modifiers(btf, arg->type, NULL); 8256 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 8257 return false; 8258 8259 return __kfunc_param_match_suffix(btf, arg, "__sz"); 8260 } 8261 8262 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 8263 { 8264 return __kfunc_param_match_suffix(btf, arg, "__k"); 8265 } 8266 8267 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 8268 { 8269 return __kfunc_param_match_suffix(btf, arg, "__ign"); 8270 } 8271 8272 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 8273 { 8274 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 8275 } 8276 8277 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 8278 const struct btf_param *arg, 8279 const char *name) 8280 { 8281 int len, target_len = strlen(name); 8282 const char *param_name; 8283 8284 param_name = btf_name_by_offset(btf, arg->name_off); 8285 if (str_is_empty(param_name)) 8286 return false; 8287 len = strlen(param_name); 8288 if (len != target_len) 8289 return false; 8290 if (strcmp(param_name, name)) 8291 return false; 8292 8293 return true; 8294 } 8295 8296 enum { 8297 KF_ARG_DYNPTR_ID, 8298 KF_ARG_LIST_HEAD_ID, 8299 KF_ARG_LIST_NODE_ID, 8300 }; 8301 8302 BTF_ID_LIST(kf_arg_btf_ids) 8303 BTF_ID(struct, bpf_dynptr_kern) 8304 BTF_ID(struct, bpf_list_head) 8305 BTF_ID(struct, bpf_list_node) 8306 8307 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 8308 const struct btf_param *arg, int type) 8309 { 8310 const struct btf_type *t; 8311 u32 res_id; 8312 8313 t = btf_type_skip_modifiers(btf, arg->type, NULL); 8314 if (!t) 8315 return false; 8316 if (!btf_type_is_ptr(t)) 8317 return false; 8318 t = btf_type_skip_modifiers(btf, t->type, &res_id); 8319 if (!t) 8320 return false; 8321 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 8322 } 8323 8324 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 8325 { 8326 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 8327 } 8328 8329 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 8330 { 8331 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 8332 } 8333 8334 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 8335 { 8336 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 8337 } 8338 8339 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 8340 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 8341 const struct btf *btf, 8342 const struct btf_type *t, int rec) 8343 { 8344 const struct btf_type *member_type; 8345 const struct btf_member *member; 8346 u32 i; 8347 8348 if (!btf_type_is_struct(t)) 8349 return false; 8350 8351 for_each_member(i, t, member) { 8352 const struct btf_array *array; 8353 8354 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 8355 if (btf_type_is_struct(member_type)) { 8356 if (rec >= 3) { 8357 verbose(env, "max struct nesting depth exceeded\n"); 8358 return false; 8359 } 8360 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 8361 return false; 8362 continue; 8363 } 8364 if (btf_type_is_array(member_type)) { 8365 array = btf_array(member_type); 8366 if (!array->nelems) 8367 return false; 8368 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 8369 if (!btf_type_is_scalar(member_type)) 8370 return false; 8371 continue; 8372 } 8373 if (!btf_type_is_scalar(member_type)) 8374 return false; 8375 } 8376 return true; 8377 } 8378 8379 8380 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 8381 #ifdef CONFIG_NET 8382 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 8383 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8384 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 8385 #endif 8386 }; 8387 8388 enum kfunc_ptr_arg_type { 8389 KF_ARG_PTR_TO_CTX, 8390 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 8391 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */ 8392 KF_ARG_PTR_TO_DYNPTR, 8393 KF_ARG_PTR_TO_LIST_HEAD, 8394 KF_ARG_PTR_TO_LIST_NODE, 8395 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 8396 KF_ARG_PTR_TO_MEM, 8397 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 8398 }; 8399 8400 enum special_kfunc_type { 8401 KF_bpf_obj_new_impl, 8402 KF_bpf_obj_drop_impl, 8403 KF_bpf_list_push_front, 8404 KF_bpf_list_push_back, 8405 KF_bpf_list_pop_front, 8406 KF_bpf_list_pop_back, 8407 KF_bpf_cast_to_kern_ctx, 8408 KF_bpf_rdonly_cast, 8409 KF_bpf_rcu_read_lock, 8410 KF_bpf_rcu_read_unlock, 8411 }; 8412 8413 BTF_SET_START(special_kfunc_set) 8414 BTF_ID(func, bpf_obj_new_impl) 8415 BTF_ID(func, bpf_obj_drop_impl) 8416 BTF_ID(func, bpf_list_push_front) 8417 BTF_ID(func, bpf_list_push_back) 8418 BTF_ID(func, bpf_list_pop_front) 8419 BTF_ID(func, bpf_list_pop_back) 8420 BTF_ID(func, bpf_cast_to_kern_ctx) 8421 BTF_ID(func, bpf_rdonly_cast) 8422 BTF_SET_END(special_kfunc_set) 8423 8424 BTF_ID_LIST(special_kfunc_list) 8425 BTF_ID(func, bpf_obj_new_impl) 8426 BTF_ID(func, bpf_obj_drop_impl) 8427 BTF_ID(func, bpf_list_push_front) 8428 BTF_ID(func, bpf_list_push_back) 8429 BTF_ID(func, bpf_list_pop_front) 8430 BTF_ID(func, bpf_list_pop_back) 8431 BTF_ID(func, bpf_cast_to_kern_ctx) 8432 BTF_ID(func, bpf_rdonly_cast) 8433 BTF_ID(func, bpf_rcu_read_lock) 8434 BTF_ID(func, bpf_rcu_read_unlock) 8435 8436 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 8437 { 8438 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 8439 } 8440 8441 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 8442 { 8443 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 8444 } 8445 8446 static enum kfunc_ptr_arg_type 8447 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 8448 struct bpf_kfunc_call_arg_meta *meta, 8449 const struct btf_type *t, const struct btf_type *ref_t, 8450 const char *ref_tname, const struct btf_param *args, 8451 int argno, int nargs) 8452 { 8453 u32 regno = argno + 1; 8454 struct bpf_reg_state *regs = cur_regs(env); 8455 struct bpf_reg_state *reg = ®s[regno]; 8456 bool arg_mem_size = false; 8457 8458 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 8459 return KF_ARG_PTR_TO_CTX; 8460 8461 /* In this function, we verify the kfunc's BTF as per the argument type, 8462 * leaving the rest of the verification with respect to the register 8463 * type to our caller. When a set of conditions hold in the BTF type of 8464 * arguments, we resolve it to a known kfunc_ptr_arg_type. 8465 */ 8466 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 8467 return KF_ARG_PTR_TO_CTX; 8468 8469 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 8470 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 8471 8472 if (is_kfunc_arg_kptr_get(meta, argno)) { 8473 if (!btf_type_is_ptr(ref_t)) { 8474 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n"); 8475 return -EINVAL; 8476 } 8477 ref_t = btf_type_by_id(meta->btf, ref_t->type); 8478 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off); 8479 if (!btf_type_is_struct(ref_t)) { 8480 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n", 8481 meta->func_name, btf_type_str(ref_t), ref_tname); 8482 return -EINVAL; 8483 } 8484 return KF_ARG_PTR_TO_KPTR; 8485 } 8486 8487 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 8488 return KF_ARG_PTR_TO_DYNPTR; 8489 8490 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 8491 return KF_ARG_PTR_TO_LIST_HEAD; 8492 8493 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 8494 return KF_ARG_PTR_TO_LIST_NODE; 8495 8496 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 8497 if (!btf_type_is_struct(ref_t)) { 8498 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 8499 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 8500 return -EINVAL; 8501 } 8502 return KF_ARG_PTR_TO_BTF_ID; 8503 } 8504 8505 if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])) 8506 arg_mem_size = true; 8507 8508 /* This is the catch all argument type of register types supported by 8509 * check_helper_mem_access. However, we only allow when argument type is 8510 * pointer to scalar, or struct composed (recursively) of scalars. When 8511 * arg_mem_size is true, the pointer can be void *. 8512 */ 8513 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 8514 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 8515 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 8516 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 8517 return -EINVAL; 8518 } 8519 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 8520 } 8521 8522 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 8523 struct bpf_reg_state *reg, 8524 const struct btf_type *ref_t, 8525 const char *ref_tname, u32 ref_id, 8526 struct bpf_kfunc_call_arg_meta *meta, 8527 int argno) 8528 { 8529 const struct btf_type *reg_ref_t; 8530 bool strict_type_match = false; 8531 const struct btf *reg_btf; 8532 const char *reg_ref_tname; 8533 u32 reg_ref_id; 8534 8535 if (base_type(reg->type) == PTR_TO_BTF_ID) { 8536 reg_btf = reg->btf; 8537 reg_ref_id = reg->btf_id; 8538 } else { 8539 reg_btf = btf_vmlinux; 8540 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 8541 } 8542 8543 if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id)) 8544 strict_type_match = true; 8545 8546 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 8547 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 8548 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 8549 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 8550 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 8551 btf_type_str(reg_ref_t), reg_ref_tname); 8552 return -EINVAL; 8553 } 8554 return 0; 8555 } 8556 8557 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env, 8558 struct bpf_reg_state *reg, 8559 const struct btf_type *ref_t, 8560 const char *ref_tname, 8561 struct bpf_kfunc_call_arg_meta *meta, 8562 int argno) 8563 { 8564 struct btf_field *kptr_field; 8565 8566 /* check_func_arg_reg_off allows var_off for 8567 * PTR_TO_MAP_VALUE, but we need fixed offset to find 8568 * off_desc. 8569 */ 8570 if (!tnum_is_const(reg->var_off)) { 8571 verbose(env, "arg#0 must have constant offset\n"); 8572 return -EINVAL; 8573 } 8574 8575 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR); 8576 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) { 8577 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n", 8578 reg->off + reg->var_off.value); 8579 return -EINVAL; 8580 } 8581 8582 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf, 8583 kptr_field->kptr.btf_id, true)) { 8584 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n", 8585 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 8586 return -EINVAL; 8587 } 8588 return 0; 8589 } 8590 8591 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id) 8592 { 8593 struct bpf_func_state *state = cur_func(env); 8594 struct bpf_reg_state *reg; 8595 int i; 8596 8597 /* bpf_spin_lock only allows calling list_push and list_pop, no BPF 8598 * subprogs, no global functions. This means that the references would 8599 * not be released inside the critical section but they may be added to 8600 * the reference state, and the acquired_refs are never copied out for a 8601 * different frame as BPF to BPF calls don't work in bpf_spin_lock 8602 * critical sections. 8603 */ 8604 if (!ref_obj_id) { 8605 verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n"); 8606 return -EFAULT; 8607 } 8608 for (i = 0; i < state->acquired_refs; i++) { 8609 if (state->refs[i].id == ref_obj_id) { 8610 if (state->refs[i].release_on_unlock) { 8611 verbose(env, "verifier internal error: expected false release_on_unlock"); 8612 return -EFAULT; 8613 } 8614 state->refs[i].release_on_unlock = true; 8615 /* Now mark everyone sharing same ref_obj_id as untrusted */ 8616 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8617 if (reg->ref_obj_id == ref_obj_id) 8618 reg->type |= PTR_UNTRUSTED; 8619 })); 8620 return 0; 8621 } 8622 } 8623 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 8624 return -EFAULT; 8625 } 8626 8627 /* Implementation details: 8628 * 8629 * Each register points to some region of memory, which we define as an 8630 * allocation. Each allocation may embed a bpf_spin_lock which protects any 8631 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 8632 * allocation. The lock and the data it protects are colocated in the same 8633 * memory region. 8634 * 8635 * Hence, everytime a register holds a pointer value pointing to such 8636 * allocation, the verifier preserves a unique reg->id for it. 8637 * 8638 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 8639 * bpf_spin_lock is called. 8640 * 8641 * To enable this, lock state in the verifier captures two values: 8642 * active_lock.ptr = Register's type specific pointer 8643 * active_lock.id = A unique ID for each register pointer value 8644 * 8645 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 8646 * supported register types. 8647 * 8648 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 8649 * allocated objects is the reg->btf pointer. 8650 * 8651 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 8652 * can establish the provenance of the map value statically for each distinct 8653 * lookup into such maps. They always contain a single map value hence unique 8654 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 8655 * 8656 * So, in case of global variables, they use array maps with max_entries = 1, 8657 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 8658 * into the same map value as max_entries is 1, as described above). 8659 * 8660 * In case of inner map lookups, the inner map pointer has same map_ptr as the 8661 * outer map pointer (in verifier context), but each lookup into an inner map 8662 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 8663 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 8664 * will get different reg->id assigned to each lookup, hence different 8665 * active_lock.id. 8666 * 8667 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 8668 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 8669 * returned from bpf_obj_new. Each allocation receives a new reg->id. 8670 */ 8671 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8672 { 8673 void *ptr; 8674 u32 id; 8675 8676 switch ((int)reg->type) { 8677 case PTR_TO_MAP_VALUE: 8678 ptr = reg->map_ptr; 8679 break; 8680 case PTR_TO_BTF_ID | MEM_ALLOC: 8681 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED: 8682 ptr = reg->btf; 8683 break; 8684 default: 8685 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 8686 return -EFAULT; 8687 } 8688 id = reg->id; 8689 8690 if (!env->cur_state->active_lock.ptr) 8691 return -EINVAL; 8692 if (env->cur_state->active_lock.ptr != ptr || 8693 env->cur_state->active_lock.id != id) { 8694 verbose(env, "held lock and object are not in the same allocation\n"); 8695 return -EINVAL; 8696 } 8697 return 0; 8698 } 8699 8700 static bool is_bpf_list_api_kfunc(u32 btf_id) 8701 { 8702 return btf_id == special_kfunc_list[KF_bpf_list_push_front] || 8703 btf_id == special_kfunc_list[KF_bpf_list_push_back] || 8704 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 8705 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 8706 } 8707 8708 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 8709 struct bpf_reg_state *reg, u32 regno, 8710 struct bpf_kfunc_call_arg_meta *meta) 8711 { 8712 struct btf_field *field; 8713 struct btf_record *rec; 8714 u32 list_head_off; 8715 8716 if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) { 8717 verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n"); 8718 return -EFAULT; 8719 } 8720 8721 if (!tnum_is_const(reg->var_off)) { 8722 verbose(env, 8723 "R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n", 8724 regno); 8725 return -EINVAL; 8726 } 8727 8728 rec = reg_btf_record(reg); 8729 list_head_off = reg->off + reg->var_off.value; 8730 field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD); 8731 if (!field) { 8732 verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off); 8733 return -EINVAL; 8734 } 8735 8736 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 8737 if (check_reg_allocation_locked(env, reg)) { 8738 verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n", 8739 rec->spin_lock_off); 8740 return -EINVAL; 8741 } 8742 8743 if (meta->arg_list_head.field) { 8744 verbose(env, "verifier internal error: repeating bpf_list_head arg\n"); 8745 return -EFAULT; 8746 } 8747 meta->arg_list_head.field = field; 8748 return 0; 8749 } 8750 8751 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 8752 struct bpf_reg_state *reg, u32 regno, 8753 struct bpf_kfunc_call_arg_meta *meta) 8754 { 8755 const struct btf_type *et, *t; 8756 struct btf_field *field; 8757 struct btf_record *rec; 8758 u32 list_node_off; 8759 8760 if (meta->btf != btf_vmlinux || 8761 (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] && 8762 meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) { 8763 verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n"); 8764 return -EFAULT; 8765 } 8766 8767 if (!tnum_is_const(reg->var_off)) { 8768 verbose(env, 8769 "R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n", 8770 regno); 8771 return -EINVAL; 8772 } 8773 8774 rec = reg_btf_record(reg); 8775 list_node_off = reg->off + reg->var_off.value; 8776 field = btf_record_find(rec, list_node_off, BPF_LIST_NODE); 8777 if (!field || field->offset != list_node_off) { 8778 verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off); 8779 return -EINVAL; 8780 } 8781 8782 field = meta->arg_list_head.field; 8783 8784 et = btf_type_by_id(field->list_head.btf, field->list_head.value_btf_id); 8785 t = btf_type_by_id(reg->btf, reg->btf_id); 8786 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->list_head.btf, 8787 field->list_head.value_btf_id, true)) { 8788 verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d " 8789 "in struct %s, but arg is at offset=%d in struct %s\n", 8790 field->list_head.node_offset, btf_name_by_offset(field->list_head.btf, et->name_off), 8791 list_node_off, btf_name_by_offset(reg->btf, t->name_off)); 8792 return -EINVAL; 8793 } 8794 8795 if (list_node_off != field->list_head.node_offset) { 8796 verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n", 8797 list_node_off, field->list_head.node_offset, 8798 btf_name_by_offset(field->list_head.btf, et->name_off)); 8799 return -EINVAL; 8800 } 8801 /* Set arg#1 for expiration after unlock */ 8802 return ref_set_release_on_unlock(env, reg->ref_obj_id); 8803 } 8804 8805 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta) 8806 { 8807 const char *func_name = meta->func_name, *ref_tname; 8808 const struct btf *btf = meta->btf; 8809 const struct btf_param *args; 8810 u32 i, nargs; 8811 int ret; 8812 8813 args = (const struct btf_param *)(meta->func_proto + 1); 8814 nargs = btf_type_vlen(meta->func_proto); 8815 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 8816 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 8817 MAX_BPF_FUNC_REG_ARGS); 8818 return -EINVAL; 8819 } 8820 8821 /* Check that BTF function arguments match actual types that the 8822 * verifier sees. 8823 */ 8824 for (i = 0; i < nargs; i++) { 8825 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 8826 const struct btf_type *t, *ref_t, *resolve_ret; 8827 enum bpf_arg_type arg_type = ARG_DONTCARE; 8828 u32 regno = i + 1, ref_id, type_size; 8829 bool is_ret_buf_sz = false; 8830 int kf_arg_type; 8831 8832 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 8833 8834 if (is_kfunc_arg_ignore(btf, &args[i])) 8835 continue; 8836 8837 if (btf_type_is_scalar(t)) { 8838 if (reg->type != SCALAR_VALUE) { 8839 verbose(env, "R%d is not a scalar\n", regno); 8840 return -EINVAL; 8841 } 8842 8843 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 8844 if (meta->arg_constant.found) { 8845 verbose(env, "verifier internal error: only one constant argument permitted\n"); 8846 return -EFAULT; 8847 } 8848 if (!tnum_is_const(reg->var_off)) { 8849 verbose(env, "R%d must be a known constant\n", regno); 8850 return -EINVAL; 8851 } 8852 ret = mark_chain_precision(env, regno); 8853 if (ret < 0) 8854 return ret; 8855 meta->arg_constant.found = true; 8856 meta->arg_constant.value = reg->var_off.value; 8857 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 8858 meta->r0_rdonly = true; 8859 is_ret_buf_sz = true; 8860 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 8861 is_ret_buf_sz = true; 8862 } 8863 8864 if (is_ret_buf_sz) { 8865 if (meta->r0_size) { 8866 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 8867 return -EINVAL; 8868 } 8869 8870 if (!tnum_is_const(reg->var_off)) { 8871 verbose(env, "R%d is not a const\n", regno); 8872 return -EINVAL; 8873 } 8874 8875 meta->r0_size = reg->var_off.value; 8876 ret = mark_chain_precision(env, regno); 8877 if (ret) 8878 return ret; 8879 } 8880 continue; 8881 } 8882 8883 if (!btf_type_is_ptr(t)) { 8884 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 8885 return -EINVAL; 8886 } 8887 8888 if (reg->ref_obj_id) { 8889 if (is_kfunc_release(meta) && meta->ref_obj_id) { 8890 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 8891 regno, reg->ref_obj_id, 8892 meta->ref_obj_id); 8893 return -EFAULT; 8894 } 8895 meta->ref_obj_id = reg->ref_obj_id; 8896 if (is_kfunc_release(meta)) 8897 meta->release_regno = regno; 8898 } 8899 8900 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 8901 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 8902 8903 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 8904 if (kf_arg_type < 0) 8905 return kf_arg_type; 8906 8907 switch (kf_arg_type) { 8908 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 8909 case KF_ARG_PTR_TO_BTF_ID: 8910 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 8911 break; 8912 8913 if (!is_trusted_reg(reg)) { 8914 if (!is_kfunc_rcu(meta)) { 8915 verbose(env, "R%d must be referenced or trusted\n", regno); 8916 return -EINVAL; 8917 } 8918 if (!is_rcu_reg(reg)) { 8919 verbose(env, "R%d must be a rcu pointer\n", regno); 8920 return -EINVAL; 8921 } 8922 } 8923 8924 fallthrough; 8925 case KF_ARG_PTR_TO_CTX: 8926 /* Trusted arguments have the same offset checks as release arguments */ 8927 arg_type |= OBJ_RELEASE; 8928 break; 8929 case KF_ARG_PTR_TO_KPTR: 8930 case KF_ARG_PTR_TO_DYNPTR: 8931 case KF_ARG_PTR_TO_LIST_HEAD: 8932 case KF_ARG_PTR_TO_LIST_NODE: 8933 case KF_ARG_PTR_TO_MEM: 8934 case KF_ARG_PTR_TO_MEM_SIZE: 8935 /* Trusted by default */ 8936 break; 8937 default: 8938 WARN_ON_ONCE(1); 8939 return -EFAULT; 8940 } 8941 8942 if (is_kfunc_release(meta) && reg->ref_obj_id) 8943 arg_type |= OBJ_RELEASE; 8944 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 8945 if (ret < 0) 8946 return ret; 8947 8948 switch (kf_arg_type) { 8949 case KF_ARG_PTR_TO_CTX: 8950 if (reg->type != PTR_TO_CTX) { 8951 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 8952 return -EINVAL; 8953 } 8954 8955 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 8956 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 8957 if (ret < 0) 8958 return -EINVAL; 8959 meta->ret_btf_id = ret; 8960 } 8961 break; 8962 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 8963 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 8964 verbose(env, "arg#%d expected pointer to allocated object\n", i); 8965 return -EINVAL; 8966 } 8967 if (!reg->ref_obj_id) { 8968 verbose(env, "allocated object must be referenced\n"); 8969 return -EINVAL; 8970 } 8971 if (meta->btf == btf_vmlinux && 8972 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 8973 meta->arg_obj_drop.btf = reg->btf; 8974 meta->arg_obj_drop.btf_id = reg->btf_id; 8975 } 8976 break; 8977 case KF_ARG_PTR_TO_KPTR: 8978 if (reg->type != PTR_TO_MAP_VALUE) { 8979 verbose(env, "arg#0 expected pointer to map value\n"); 8980 return -EINVAL; 8981 } 8982 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i); 8983 if (ret < 0) 8984 return ret; 8985 break; 8986 case KF_ARG_PTR_TO_DYNPTR: 8987 if (reg->type != PTR_TO_STACK && 8988 reg->type != CONST_PTR_TO_DYNPTR) { 8989 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 8990 return -EINVAL; 8991 } 8992 8993 ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL); 8994 if (ret < 0) 8995 return ret; 8996 break; 8997 case KF_ARG_PTR_TO_LIST_HEAD: 8998 if (reg->type != PTR_TO_MAP_VALUE && 8999 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9000 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 9001 return -EINVAL; 9002 } 9003 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 9004 verbose(env, "allocated object must be referenced\n"); 9005 return -EINVAL; 9006 } 9007 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 9008 if (ret < 0) 9009 return ret; 9010 break; 9011 case KF_ARG_PTR_TO_LIST_NODE: 9012 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9013 verbose(env, "arg#%d expected pointer to allocated object\n", i); 9014 return -EINVAL; 9015 } 9016 if (!reg->ref_obj_id) { 9017 verbose(env, "allocated object must be referenced\n"); 9018 return -EINVAL; 9019 } 9020 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 9021 if (ret < 0) 9022 return ret; 9023 break; 9024 case KF_ARG_PTR_TO_BTF_ID: 9025 /* Only base_type is checked, further checks are done here */ 9026 if ((base_type(reg->type) != PTR_TO_BTF_ID || 9027 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 9028 !reg2btf_ids[base_type(reg->type)]) { 9029 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 9030 verbose(env, "expected %s or socket\n", 9031 reg_type_str(env, base_type(reg->type) | 9032 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 9033 return -EINVAL; 9034 } 9035 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 9036 if (ret < 0) 9037 return ret; 9038 break; 9039 case KF_ARG_PTR_TO_MEM: 9040 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 9041 if (IS_ERR(resolve_ret)) { 9042 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 9043 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 9044 return -EINVAL; 9045 } 9046 ret = check_mem_reg(env, reg, regno, type_size); 9047 if (ret < 0) 9048 return ret; 9049 break; 9050 case KF_ARG_PTR_TO_MEM_SIZE: 9051 ret = check_kfunc_mem_size_reg(env, ®s[regno + 1], regno + 1); 9052 if (ret < 0) { 9053 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 9054 return ret; 9055 } 9056 /* Skip next '__sz' argument */ 9057 i++; 9058 break; 9059 } 9060 } 9061 9062 if (is_kfunc_release(meta) && !meta->release_regno) { 9063 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 9064 func_name); 9065 return -EINVAL; 9066 } 9067 9068 return 0; 9069 } 9070 9071 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9072 int *insn_idx_p) 9073 { 9074 const struct btf_type *t, *func, *func_proto, *ptr_type; 9075 struct bpf_reg_state *regs = cur_regs(env); 9076 const char *func_name, *ptr_type_name; 9077 bool sleepable, rcu_lock, rcu_unlock; 9078 struct bpf_kfunc_call_arg_meta meta; 9079 u32 i, nargs, func_id, ptr_type_id; 9080 int err, insn_idx = *insn_idx_p; 9081 const struct btf_param *args; 9082 const struct btf_type *ret_t; 9083 struct btf *desc_btf; 9084 u32 *kfunc_flags; 9085 9086 /* skip for now, but return error when we find this in fixup_kfunc_call */ 9087 if (!insn->imm) 9088 return 0; 9089 9090 desc_btf = find_kfunc_desc_btf(env, insn->off); 9091 if (IS_ERR(desc_btf)) 9092 return PTR_ERR(desc_btf); 9093 9094 func_id = insn->imm; 9095 func = btf_type_by_id(desc_btf, func_id); 9096 func_name = btf_name_by_offset(desc_btf, func->name_off); 9097 func_proto = btf_type_by_id(desc_btf, func->type); 9098 9099 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id); 9100 if (!kfunc_flags) { 9101 verbose(env, "calling kernel function %s is not allowed\n", 9102 func_name); 9103 return -EACCES; 9104 } 9105 9106 /* Prepare kfunc call metadata */ 9107 memset(&meta, 0, sizeof(meta)); 9108 meta.btf = desc_btf; 9109 meta.func_id = func_id; 9110 meta.kfunc_flags = *kfunc_flags; 9111 meta.func_proto = func_proto; 9112 meta.func_name = func_name; 9113 9114 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 9115 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 9116 return -EACCES; 9117 } 9118 9119 sleepable = is_kfunc_sleepable(&meta); 9120 if (sleepable && !env->prog->aux->sleepable) { 9121 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 9122 return -EACCES; 9123 } 9124 9125 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 9126 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 9127 if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) { 9128 verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name); 9129 return -EACCES; 9130 } 9131 9132 if (env->cur_state->active_rcu_lock) { 9133 struct bpf_func_state *state; 9134 struct bpf_reg_state *reg; 9135 9136 if (rcu_lock) { 9137 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 9138 return -EINVAL; 9139 } else if (rcu_unlock) { 9140 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9141 if (reg->type & MEM_RCU) { 9142 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 9143 reg->type |= PTR_UNTRUSTED; 9144 } 9145 })); 9146 env->cur_state->active_rcu_lock = false; 9147 } else if (sleepable) { 9148 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 9149 return -EACCES; 9150 } 9151 } else if (rcu_lock) { 9152 env->cur_state->active_rcu_lock = true; 9153 } else if (rcu_unlock) { 9154 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 9155 return -EINVAL; 9156 } 9157 9158 /* Check the arguments */ 9159 err = check_kfunc_args(env, &meta); 9160 if (err < 0) 9161 return err; 9162 /* In case of release function, we get register number of refcounted 9163 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 9164 */ 9165 if (meta.release_regno) { 9166 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 9167 if (err) { 9168 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 9169 func_name, func_id); 9170 return err; 9171 } 9172 } 9173 9174 for (i = 0; i < CALLER_SAVED_REGS; i++) 9175 mark_reg_not_init(env, regs, caller_saved[i]); 9176 9177 /* Check return type */ 9178 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL); 9179 9180 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 9181 /* Only exception is bpf_obj_new_impl */ 9182 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) { 9183 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 9184 return -EINVAL; 9185 } 9186 } 9187 9188 if (btf_type_is_scalar(t)) { 9189 mark_reg_unknown(env, regs, BPF_REG_0); 9190 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 9191 } else if (btf_type_is_ptr(t)) { 9192 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 9193 9194 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 9195 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 9196 struct btf *ret_btf; 9197 u32 ret_btf_id; 9198 9199 if (unlikely(!bpf_global_ma_set)) 9200 return -ENOMEM; 9201 9202 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 9203 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 9204 return -EINVAL; 9205 } 9206 9207 ret_btf = env->prog->aux->btf; 9208 ret_btf_id = meta.arg_constant.value; 9209 9210 /* This may be NULL due to user not supplying a BTF */ 9211 if (!ret_btf) { 9212 verbose(env, "bpf_obj_new requires prog BTF\n"); 9213 return -EINVAL; 9214 } 9215 9216 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 9217 if (!ret_t || !__btf_type_is_struct(ret_t)) { 9218 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 9219 return -EINVAL; 9220 } 9221 9222 mark_reg_known_zero(env, regs, BPF_REG_0); 9223 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 9224 regs[BPF_REG_0].btf = ret_btf; 9225 regs[BPF_REG_0].btf_id = ret_btf_id; 9226 9227 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size; 9228 env->insn_aux_data[insn_idx].kptr_struct_meta = 9229 btf_find_struct_meta(ret_btf, ret_btf_id); 9230 } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 9231 env->insn_aux_data[insn_idx].kptr_struct_meta = 9232 btf_find_struct_meta(meta.arg_obj_drop.btf, 9233 meta.arg_obj_drop.btf_id); 9234 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 9235 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 9236 struct btf_field *field = meta.arg_list_head.field; 9237 9238 mark_reg_known_zero(env, regs, BPF_REG_0); 9239 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 9240 regs[BPF_REG_0].btf = field->list_head.btf; 9241 regs[BPF_REG_0].btf_id = field->list_head.value_btf_id; 9242 regs[BPF_REG_0].off = field->list_head.node_offset; 9243 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 9244 mark_reg_known_zero(env, regs, BPF_REG_0); 9245 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 9246 regs[BPF_REG_0].btf = desc_btf; 9247 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 9248 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 9249 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 9250 if (!ret_t || !btf_type_is_struct(ret_t)) { 9251 verbose(env, 9252 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 9253 return -EINVAL; 9254 } 9255 9256 mark_reg_known_zero(env, regs, BPF_REG_0); 9257 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 9258 regs[BPF_REG_0].btf = desc_btf; 9259 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 9260 } else { 9261 verbose(env, "kernel function %s unhandled dynamic return type\n", 9262 meta.func_name); 9263 return -EFAULT; 9264 } 9265 } else if (!__btf_type_is_struct(ptr_type)) { 9266 if (!meta.r0_size) { 9267 ptr_type_name = btf_name_by_offset(desc_btf, 9268 ptr_type->name_off); 9269 verbose(env, 9270 "kernel function %s returns pointer type %s %s is not supported\n", 9271 func_name, 9272 btf_type_str(ptr_type), 9273 ptr_type_name); 9274 return -EINVAL; 9275 } 9276 9277 mark_reg_known_zero(env, regs, BPF_REG_0); 9278 regs[BPF_REG_0].type = PTR_TO_MEM; 9279 regs[BPF_REG_0].mem_size = meta.r0_size; 9280 9281 if (meta.r0_rdonly) 9282 regs[BPF_REG_0].type |= MEM_RDONLY; 9283 9284 /* Ensures we don't access the memory after a release_reference() */ 9285 if (meta.ref_obj_id) 9286 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 9287 } else { 9288 mark_reg_known_zero(env, regs, BPF_REG_0); 9289 regs[BPF_REG_0].btf = desc_btf; 9290 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 9291 regs[BPF_REG_0].btf_id = ptr_type_id; 9292 } 9293 9294 if (is_kfunc_ret_null(&meta)) { 9295 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 9296 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 9297 regs[BPF_REG_0].id = ++env->id_gen; 9298 } 9299 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 9300 if (is_kfunc_acquire(&meta)) { 9301 int id = acquire_reference_state(env, insn_idx); 9302 9303 if (id < 0) 9304 return id; 9305 if (is_kfunc_ret_null(&meta)) 9306 regs[BPF_REG_0].id = id; 9307 regs[BPF_REG_0].ref_obj_id = id; 9308 } 9309 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 9310 regs[BPF_REG_0].id = ++env->id_gen; 9311 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */ 9312 9313 nargs = btf_type_vlen(func_proto); 9314 args = (const struct btf_param *)(func_proto + 1); 9315 for (i = 0; i < nargs; i++) { 9316 u32 regno = i + 1; 9317 9318 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 9319 if (btf_type_is_ptr(t)) 9320 mark_btf_func_reg_size(env, regno, sizeof(void *)); 9321 else 9322 /* scalar. ensured by btf_check_kfunc_arg_match() */ 9323 mark_btf_func_reg_size(env, regno, t->size); 9324 } 9325 9326 return 0; 9327 } 9328 9329 static bool signed_add_overflows(s64 a, s64 b) 9330 { 9331 /* Do the add in u64, where overflow is well-defined */ 9332 s64 res = (s64)((u64)a + (u64)b); 9333 9334 if (b < 0) 9335 return res > a; 9336 return res < a; 9337 } 9338 9339 static bool signed_add32_overflows(s32 a, s32 b) 9340 { 9341 /* Do the add in u32, where overflow is well-defined */ 9342 s32 res = (s32)((u32)a + (u32)b); 9343 9344 if (b < 0) 9345 return res > a; 9346 return res < a; 9347 } 9348 9349 static bool signed_sub_overflows(s64 a, s64 b) 9350 { 9351 /* Do the sub in u64, where overflow is well-defined */ 9352 s64 res = (s64)((u64)a - (u64)b); 9353 9354 if (b < 0) 9355 return res < a; 9356 return res > a; 9357 } 9358 9359 static bool signed_sub32_overflows(s32 a, s32 b) 9360 { 9361 /* Do the sub in u32, where overflow is well-defined */ 9362 s32 res = (s32)((u32)a - (u32)b); 9363 9364 if (b < 0) 9365 return res < a; 9366 return res > a; 9367 } 9368 9369 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 9370 const struct bpf_reg_state *reg, 9371 enum bpf_reg_type type) 9372 { 9373 bool known = tnum_is_const(reg->var_off); 9374 s64 val = reg->var_off.value; 9375 s64 smin = reg->smin_value; 9376 9377 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 9378 verbose(env, "math between %s pointer and %lld is not allowed\n", 9379 reg_type_str(env, type), val); 9380 return false; 9381 } 9382 9383 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 9384 verbose(env, "%s pointer offset %d is not allowed\n", 9385 reg_type_str(env, type), reg->off); 9386 return false; 9387 } 9388 9389 if (smin == S64_MIN) { 9390 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 9391 reg_type_str(env, type)); 9392 return false; 9393 } 9394 9395 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 9396 verbose(env, "value %lld makes %s pointer be out of bounds\n", 9397 smin, reg_type_str(env, type)); 9398 return false; 9399 } 9400 9401 return true; 9402 } 9403 9404 enum { 9405 REASON_BOUNDS = -1, 9406 REASON_TYPE = -2, 9407 REASON_PATHS = -3, 9408 REASON_LIMIT = -4, 9409 REASON_STACK = -5, 9410 }; 9411 9412 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 9413 u32 *alu_limit, bool mask_to_left) 9414 { 9415 u32 max = 0, ptr_limit = 0; 9416 9417 switch (ptr_reg->type) { 9418 case PTR_TO_STACK: 9419 /* Offset 0 is out-of-bounds, but acceptable start for the 9420 * left direction, see BPF_REG_FP. Also, unknown scalar 9421 * offset where we would need to deal with min/max bounds is 9422 * currently prohibited for unprivileged. 9423 */ 9424 max = MAX_BPF_STACK + mask_to_left; 9425 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 9426 break; 9427 case PTR_TO_MAP_VALUE: 9428 max = ptr_reg->map_ptr->value_size; 9429 ptr_limit = (mask_to_left ? 9430 ptr_reg->smin_value : 9431 ptr_reg->umax_value) + ptr_reg->off; 9432 break; 9433 default: 9434 return REASON_TYPE; 9435 } 9436 9437 if (ptr_limit >= max) 9438 return REASON_LIMIT; 9439 *alu_limit = ptr_limit; 9440 return 0; 9441 } 9442 9443 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 9444 const struct bpf_insn *insn) 9445 { 9446 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 9447 } 9448 9449 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 9450 u32 alu_state, u32 alu_limit) 9451 { 9452 /* If we arrived here from different branches with different 9453 * state or limits to sanitize, then this won't work. 9454 */ 9455 if (aux->alu_state && 9456 (aux->alu_state != alu_state || 9457 aux->alu_limit != alu_limit)) 9458 return REASON_PATHS; 9459 9460 /* Corresponding fixup done in do_misc_fixups(). */ 9461 aux->alu_state = alu_state; 9462 aux->alu_limit = alu_limit; 9463 return 0; 9464 } 9465 9466 static int sanitize_val_alu(struct bpf_verifier_env *env, 9467 struct bpf_insn *insn) 9468 { 9469 struct bpf_insn_aux_data *aux = cur_aux(env); 9470 9471 if (can_skip_alu_sanitation(env, insn)) 9472 return 0; 9473 9474 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 9475 } 9476 9477 static bool sanitize_needed(u8 opcode) 9478 { 9479 return opcode == BPF_ADD || opcode == BPF_SUB; 9480 } 9481 9482 struct bpf_sanitize_info { 9483 struct bpf_insn_aux_data aux; 9484 bool mask_to_left; 9485 }; 9486 9487 static struct bpf_verifier_state * 9488 sanitize_speculative_path(struct bpf_verifier_env *env, 9489 const struct bpf_insn *insn, 9490 u32 next_idx, u32 curr_idx) 9491 { 9492 struct bpf_verifier_state *branch; 9493 struct bpf_reg_state *regs; 9494 9495 branch = push_stack(env, next_idx, curr_idx, true); 9496 if (branch && insn) { 9497 regs = branch->frame[branch->curframe]->regs; 9498 if (BPF_SRC(insn->code) == BPF_K) { 9499 mark_reg_unknown(env, regs, insn->dst_reg); 9500 } else if (BPF_SRC(insn->code) == BPF_X) { 9501 mark_reg_unknown(env, regs, insn->dst_reg); 9502 mark_reg_unknown(env, regs, insn->src_reg); 9503 } 9504 } 9505 return branch; 9506 } 9507 9508 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 9509 struct bpf_insn *insn, 9510 const struct bpf_reg_state *ptr_reg, 9511 const struct bpf_reg_state *off_reg, 9512 struct bpf_reg_state *dst_reg, 9513 struct bpf_sanitize_info *info, 9514 const bool commit_window) 9515 { 9516 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 9517 struct bpf_verifier_state *vstate = env->cur_state; 9518 bool off_is_imm = tnum_is_const(off_reg->var_off); 9519 bool off_is_neg = off_reg->smin_value < 0; 9520 bool ptr_is_dst_reg = ptr_reg == dst_reg; 9521 u8 opcode = BPF_OP(insn->code); 9522 u32 alu_state, alu_limit; 9523 struct bpf_reg_state tmp; 9524 bool ret; 9525 int err; 9526 9527 if (can_skip_alu_sanitation(env, insn)) 9528 return 0; 9529 9530 /* We already marked aux for masking from non-speculative 9531 * paths, thus we got here in the first place. We only care 9532 * to explore bad access from here. 9533 */ 9534 if (vstate->speculative) 9535 goto do_sim; 9536 9537 if (!commit_window) { 9538 if (!tnum_is_const(off_reg->var_off) && 9539 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 9540 return REASON_BOUNDS; 9541 9542 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 9543 (opcode == BPF_SUB && !off_is_neg); 9544 } 9545 9546 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 9547 if (err < 0) 9548 return err; 9549 9550 if (commit_window) { 9551 /* In commit phase we narrow the masking window based on 9552 * the observed pointer move after the simulated operation. 9553 */ 9554 alu_state = info->aux.alu_state; 9555 alu_limit = abs(info->aux.alu_limit - alu_limit); 9556 } else { 9557 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 9558 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 9559 alu_state |= ptr_is_dst_reg ? 9560 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 9561 9562 /* Limit pruning on unknown scalars to enable deep search for 9563 * potential masking differences from other program paths. 9564 */ 9565 if (!off_is_imm) 9566 env->explore_alu_limits = true; 9567 } 9568 9569 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 9570 if (err < 0) 9571 return err; 9572 do_sim: 9573 /* If we're in commit phase, we're done here given we already 9574 * pushed the truncated dst_reg into the speculative verification 9575 * stack. 9576 * 9577 * Also, when register is a known constant, we rewrite register-based 9578 * operation to immediate-based, and thus do not need masking (and as 9579 * a consequence, do not need to simulate the zero-truncation either). 9580 */ 9581 if (commit_window || off_is_imm) 9582 return 0; 9583 9584 /* Simulate and find potential out-of-bounds access under 9585 * speculative execution from truncation as a result of 9586 * masking when off was not within expected range. If off 9587 * sits in dst, then we temporarily need to move ptr there 9588 * to simulate dst (== 0) +/-= ptr. Needed, for example, 9589 * for cases where we use K-based arithmetic in one direction 9590 * and truncated reg-based in the other in order to explore 9591 * bad access. 9592 */ 9593 if (!ptr_is_dst_reg) { 9594 tmp = *dst_reg; 9595 *dst_reg = *ptr_reg; 9596 } 9597 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 9598 env->insn_idx); 9599 if (!ptr_is_dst_reg && ret) 9600 *dst_reg = tmp; 9601 return !ret ? REASON_STACK : 0; 9602 } 9603 9604 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 9605 { 9606 struct bpf_verifier_state *vstate = env->cur_state; 9607 9608 /* If we simulate paths under speculation, we don't update the 9609 * insn as 'seen' such that when we verify unreachable paths in 9610 * the non-speculative domain, sanitize_dead_code() can still 9611 * rewrite/sanitize them. 9612 */ 9613 if (!vstate->speculative) 9614 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 9615 } 9616 9617 static int sanitize_err(struct bpf_verifier_env *env, 9618 const struct bpf_insn *insn, int reason, 9619 const struct bpf_reg_state *off_reg, 9620 const struct bpf_reg_state *dst_reg) 9621 { 9622 static const char *err = "pointer arithmetic with it prohibited for !root"; 9623 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 9624 u32 dst = insn->dst_reg, src = insn->src_reg; 9625 9626 switch (reason) { 9627 case REASON_BOUNDS: 9628 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 9629 off_reg == dst_reg ? dst : src, err); 9630 break; 9631 case REASON_TYPE: 9632 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 9633 off_reg == dst_reg ? src : dst, err); 9634 break; 9635 case REASON_PATHS: 9636 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 9637 dst, op, err); 9638 break; 9639 case REASON_LIMIT: 9640 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 9641 dst, op, err); 9642 break; 9643 case REASON_STACK: 9644 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 9645 dst, err); 9646 break; 9647 default: 9648 verbose(env, "verifier internal error: unknown reason (%d)\n", 9649 reason); 9650 break; 9651 } 9652 9653 return -EACCES; 9654 } 9655 9656 /* check that stack access falls within stack limits and that 'reg' doesn't 9657 * have a variable offset. 9658 * 9659 * Variable offset is prohibited for unprivileged mode for simplicity since it 9660 * requires corresponding support in Spectre masking for stack ALU. See also 9661 * retrieve_ptr_limit(). 9662 * 9663 * 9664 * 'off' includes 'reg->off'. 9665 */ 9666 static int check_stack_access_for_ptr_arithmetic( 9667 struct bpf_verifier_env *env, 9668 int regno, 9669 const struct bpf_reg_state *reg, 9670 int off) 9671 { 9672 if (!tnum_is_const(reg->var_off)) { 9673 char tn_buf[48]; 9674 9675 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 9676 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 9677 regno, tn_buf, off); 9678 return -EACCES; 9679 } 9680 9681 if (off >= 0 || off < -MAX_BPF_STACK) { 9682 verbose(env, "R%d stack pointer arithmetic goes out of range, " 9683 "prohibited for !root; off=%d\n", regno, off); 9684 return -EACCES; 9685 } 9686 9687 return 0; 9688 } 9689 9690 static int sanitize_check_bounds(struct bpf_verifier_env *env, 9691 const struct bpf_insn *insn, 9692 const struct bpf_reg_state *dst_reg) 9693 { 9694 u32 dst = insn->dst_reg; 9695 9696 /* For unprivileged we require that resulting offset must be in bounds 9697 * in order to be able to sanitize access later on. 9698 */ 9699 if (env->bypass_spec_v1) 9700 return 0; 9701 9702 switch (dst_reg->type) { 9703 case PTR_TO_STACK: 9704 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 9705 dst_reg->off + dst_reg->var_off.value)) 9706 return -EACCES; 9707 break; 9708 case PTR_TO_MAP_VALUE: 9709 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 9710 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 9711 "prohibited for !root\n", dst); 9712 return -EACCES; 9713 } 9714 break; 9715 default: 9716 break; 9717 } 9718 9719 return 0; 9720 } 9721 9722 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 9723 * Caller should also handle BPF_MOV case separately. 9724 * If we return -EACCES, caller may want to try again treating pointer as a 9725 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 9726 */ 9727 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 9728 struct bpf_insn *insn, 9729 const struct bpf_reg_state *ptr_reg, 9730 const struct bpf_reg_state *off_reg) 9731 { 9732 struct bpf_verifier_state *vstate = env->cur_state; 9733 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9734 struct bpf_reg_state *regs = state->regs, *dst_reg; 9735 bool known = tnum_is_const(off_reg->var_off); 9736 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 9737 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 9738 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 9739 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 9740 struct bpf_sanitize_info info = {}; 9741 u8 opcode = BPF_OP(insn->code); 9742 u32 dst = insn->dst_reg; 9743 int ret; 9744 9745 dst_reg = ®s[dst]; 9746 9747 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 9748 smin_val > smax_val || umin_val > umax_val) { 9749 /* Taint dst register if offset had invalid bounds derived from 9750 * e.g. dead branches. 9751 */ 9752 __mark_reg_unknown(env, dst_reg); 9753 return 0; 9754 } 9755 9756 if (BPF_CLASS(insn->code) != BPF_ALU64) { 9757 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 9758 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 9759 __mark_reg_unknown(env, dst_reg); 9760 return 0; 9761 } 9762 9763 verbose(env, 9764 "R%d 32-bit pointer arithmetic prohibited\n", 9765 dst); 9766 return -EACCES; 9767 } 9768 9769 if (ptr_reg->type & PTR_MAYBE_NULL) { 9770 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 9771 dst, reg_type_str(env, ptr_reg->type)); 9772 return -EACCES; 9773 } 9774 9775 switch (base_type(ptr_reg->type)) { 9776 case CONST_PTR_TO_MAP: 9777 /* smin_val represents the known value */ 9778 if (known && smin_val == 0 && opcode == BPF_ADD) 9779 break; 9780 fallthrough; 9781 case PTR_TO_PACKET_END: 9782 case PTR_TO_SOCKET: 9783 case PTR_TO_SOCK_COMMON: 9784 case PTR_TO_TCP_SOCK: 9785 case PTR_TO_XDP_SOCK: 9786 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 9787 dst, reg_type_str(env, ptr_reg->type)); 9788 return -EACCES; 9789 default: 9790 break; 9791 } 9792 9793 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 9794 * The id may be overwritten later if we create a new variable offset. 9795 */ 9796 dst_reg->type = ptr_reg->type; 9797 dst_reg->id = ptr_reg->id; 9798 9799 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 9800 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 9801 return -EINVAL; 9802 9803 /* pointer types do not carry 32-bit bounds at the moment. */ 9804 __mark_reg32_unbounded(dst_reg); 9805 9806 if (sanitize_needed(opcode)) { 9807 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 9808 &info, false); 9809 if (ret < 0) 9810 return sanitize_err(env, insn, ret, off_reg, dst_reg); 9811 } 9812 9813 switch (opcode) { 9814 case BPF_ADD: 9815 /* We can take a fixed offset as long as it doesn't overflow 9816 * the s32 'off' field 9817 */ 9818 if (known && (ptr_reg->off + smin_val == 9819 (s64)(s32)(ptr_reg->off + smin_val))) { 9820 /* pointer += K. Accumulate it into fixed offset */ 9821 dst_reg->smin_value = smin_ptr; 9822 dst_reg->smax_value = smax_ptr; 9823 dst_reg->umin_value = umin_ptr; 9824 dst_reg->umax_value = umax_ptr; 9825 dst_reg->var_off = ptr_reg->var_off; 9826 dst_reg->off = ptr_reg->off + smin_val; 9827 dst_reg->raw = ptr_reg->raw; 9828 break; 9829 } 9830 /* A new variable offset is created. Note that off_reg->off 9831 * == 0, since it's a scalar. 9832 * dst_reg gets the pointer type and since some positive 9833 * integer value was added to the pointer, give it a new 'id' 9834 * if it's a PTR_TO_PACKET. 9835 * this creates a new 'base' pointer, off_reg (variable) gets 9836 * added into the variable offset, and we copy the fixed offset 9837 * from ptr_reg. 9838 */ 9839 if (signed_add_overflows(smin_ptr, smin_val) || 9840 signed_add_overflows(smax_ptr, smax_val)) { 9841 dst_reg->smin_value = S64_MIN; 9842 dst_reg->smax_value = S64_MAX; 9843 } else { 9844 dst_reg->smin_value = smin_ptr + smin_val; 9845 dst_reg->smax_value = smax_ptr + smax_val; 9846 } 9847 if (umin_ptr + umin_val < umin_ptr || 9848 umax_ptr + umax_val < umax_ptr) { 9849 dst_reg->umin_value = 0; 9850 dst_reg->umax_value = U64_MAX; 9851 } else { 9852 dst_reg->umin_value = umin_ptr + umin_val; 9853 dst_reg->umax_value = umax_ptr + umax_val; 9854 } 9855 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 9856 dst_reg->off = ptr_reg->off; 9857 dst_reg->raw = ptr_reg->raw; 9858 if (reg_is_pkt_pointer(ptr_reg)) { 9859 dst_reg->id = ++env->id_gen; 9860 /* something was added to pkt_ptr, set range to zero */ 9861 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 9862 } 9863 break; 9864 case BPF_SUB: 9865 if (dst_reg == off_reg) { 9866 /* scalar -= pointer. Creates an unknown scalar */ 9867 verbose(env, "R%d tried to subtract pointer from scalar\n", 9868 dst); 9869 return -EACCES; 9870 } 9871 /* We don't allow subtraction from FP, because (according to 9872 * test_verifier.c test "invalid fp arithmetic", JITs might not 9873 * be able to deal with it. 9874 */ 9875 if (ptr_reg->type == PTR_TO_STACK) { 9876 verbose(env, "R%d subtraction from stack pointer prohibited\n", 9877 dst); 9878 return -EACCES; 9879 } 9880 if (known && (ptr_reg->off - smin_val == 9881 (s64)(s32)(ptr_reg->off - smin_val))) { 9882 /* pointer -= K. Subtract it from fixed offset */ 9883 dst_reg->smin_value = smin_ptr; 9884 dst_reg->smax_value = smax_ptr; 9885 dst_reg->umin_value = umin_ptr; 9886 dst_reg->umax_value = umax_ptr; 9887 dst_reg->var_off = ptr_reg->var_off; 9888 dst_reg->id = ptr_reg->id; 9889 dst_reg->off = ptr_reg->off - smin_val; 9890 dst_reg->raw = ptr_reg->raw; 9891 break; 9892 } 9893 /* A new variable offset is created. If the subtrahend is known 9894 * nonnegative, then any reg->range we had before is still good. 9895 */ 9896 if (signed_sub_overflows(smin_ptr, smax_val) || 9897 signed_sub_overflows(smax_ptr, smin_val)) { 9898 /* Overflow possible, we know nothing */ 9899 dst_reg->smin_value = S64_MIN; 9900 dst_reg->smax_value = S64_MAX; 9901 } else { 9902 dst_reg->smin_value = smin_ptr - smax_val; 9903 dst_reg->smax_value = smax_ptr - smin_val; 9904 } 9905 if (umin_ptr < umax_val) { 9906 /* Overflow possible, we know nothing */ 9907 dst_reg->umin_value = 0; 9908 dst_reg->umax_value = U64_MAX; 9909 } else { 9910 /* Cannot overflow (as long as bounds are consistent) */ 9911 dst_reg->umin_value = umin_ptr - umax_val; 9912 dst_reg->umax_value = umax_ptr - umin_val; 9913 } 9914 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 9915 dst_reg->off = ptr_reg->off; 9916 dst_reg->raw = ptr_reg->raw; 9917 if (reg_is_pkt_pointer(ptr_reg)) { 9918 dst_reg->id = ++env->id_gen; 9919 /* something was added to pkt_ptr, set range to zero */ 9920 if (smin_val < 0) 9921 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 9922 } 9923 break; 9924 case BPF_AND: 9925 case BPF_OR: 9926 case BPF_XOR: 9927 /* bitwise ops on pointers are troublesome, prohibit. */ 9928 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 9929 dst, bpf_alu_string[opcode >> 4]); 9930 return -EACCES; 9931 default: 9932 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 9933 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 9934 dst, bpf_alu_string[opcode >> 4]); 9935 return -EACCES; 9936 } 9937 9938 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 9939 return -EINVAL; 9940 reg_bounds_sync(dst_reg); 9941 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 9942 return -EACCES; 9943 if (sanitize_needed(opcode)) { 9944 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 9945 &info, true); 9946 if (ret < 0) 9947 return sanitize_err(env, insn, ret, off_reg, dst_reg); 9948 } 9949 9950 return 0; 9951 } 9952 9953 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 9954 struct bpf_reg_state *src_reg) 9955 { 9956 s32 smin_val = src_reg->s32_min_value; 9957 s32 smax_val = src_reg->s32_max_value; 9958 u32 umin_val = src_reg->u32_min_value; 9959 u32 umax_val = src_reg->u32_max_value; 9960 9961 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 9962 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 9963 dst_reg->s32_min_value = S32_MIN; 9964 dst_reg->s32_max_value = S32_MAX; 9965 } else { 9966 dst_reg->s32_min_value += smin_val; 9967 dst_reg->s32_max_value += smax_val; 9968 } 9969 if (dst_reg->u32_min_value + umin_val < umin_val || 9970 dst_reg->u32_max_value + umax_val < umax_val) { 9971 dst_reg->u32_min_value = 0; 9972 dst_reg->u32_max_value = U32_MAX; 9973 } else { 9974 dst_reg->u32_min_value += umin_val; 9975 dst_reg->u32_max_value += umax_val; 9976 } 9977 } 9978 9979 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 9980 struct bpf_reg_state *src_reg) 9981 { 9982 s64 smin_val = src_reg->smin_value; 9983 s64 smax_val = src_reg->smax_value; 9984 u64 umin_val = src_reg->umin_value; 9985 u64 umax_val = src_reg->umax_value; 9986 9987 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 9988 signed_add_overflows(dst_reg->smax_value, smax_val)) { 9989 dst_reg->smin_value = S64_MIN; 9990 dst_reg->smax_value = S64_MAX; 9991 } else { 9992 dst_reg->smin_value += smin_val; 9993 dst_reg->smax_value += smax_val; 9994 } 9995 if (dst_reg->umin_value + umin_val < umin_val || 9996 dst_reg->umax_value + umax_val < umax_val) { 9997 dst_reg->umin_value = 0; 9998 dst_reg->umax_value = U64_MAX; 9999 } else { 10000 dst_reg->umin_value += umin_val; 10001 dst_reg->umax_value += umax_val; 10002 } 10003 } 10004 10005 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 10006 struct bpf_reg_state *src_reg) 10007 { 10008 s32 smin_val = src_reg->s32_min_value; 10009 s32 smax_val = src_reg->s32_max_value; 10010 u32 umin_val = src_reg->u32_min_value; 10011 u32 umax_val = src_reg->u32_max_value; 10012 10013 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 10014 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 10015 /* Overflow possible, we know nothing */ 10016 dst_reg->s32_min_value = S32_MIN; 10017 dst_reg->s32_max_value = S32_MAX; 10018 } else { 10019 dst_reg->s32_min_value -= smax_val; 10020 dst_reg->s32_max_value -= smin_val; 10021 } 10022 if (dst_reg->u32_min_value < umax_val) { 10023 /* Overflow possible, we know nothing */ 10024 dst_reg->u32_min_value = 0; 10025 dst_reg->u32_max_value = U32_MAX; 10026 } else { 10027 /* Cannot overflow (as long as bounds are consistent) */ 10028 dst_reg->u32_min_value -= umax_val; 10029 dst_reg->u32_max_value -= umin_val; 10030 } 10031 } 10032 10033 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 10034 struct bpf_reg_state *src_reg) 10035 { 10036 s64 smin_val = src_reg->smin_value; 10037 s64 smax_val = src_reg->smax_value; 10038 u64 umin_val = src_reg->umin_value; 10039 u64 umax_val = src_reg->umax_value; 10040 10041 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 10042 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 10043 /* Overflow possible, we know nothing */ 10044 dst_reg->smin_value = S64_MIN; 10045 dst_reg->smax_value = S64_MAX; 10046 } else { 10047 dst_reg->smin_value -= smax_val; 10048 dst_reg->smax_value -= smin_val; 10049 } 10050 if (dst_reg->umin_value < umax_val) { 10051 /* Overflow possible, we know nothing */ 10052 dst_reg->umin_value = 0; 10053 dst_reg->umax_value = U64_MAX; 10054 } else { 10055 /* Cannot overflow (as long as bounds are consistent) */ 10056 dst_reg->umin_value -= umax_val; 10057 dst_reg->umax_value -= umin_val; 10058 } 10059 } 10060 10061 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 10062 struct bpf_reg_state *src_reg) 10063 { 10064 s32 smin_val = src_reg->s32_min_value; 10065 u32 umin_val = src_reg->u32_min_value; 10066 u32 umax_val = src_reg->u32_max_value; 10067 10068 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 10069 /* Ain't nobody got time to multiply that sign */ 10070 __mark_reg32_unbounded(dst_reg); 10071 return; 10072 } 10073 /* Both values are positive, so we can work with unsigned and 10074 * copy the result to signed (unless it exceeds S32_MAX). 10075 */ 10076 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 10077 /* Potential overflow, we know nothing */ 10078 __mark_reg32_unbounded(dst_reg); 10079 return; 10080 } 10081 dst_reg->u32_min_value *= umin_val; 10082 dst_reg->u32_max_value *= umax_val; 10083 if (dst_reg->u32_max_value > S32_MAX) { 10084 /* Overflow possible, we know nothing */ 10085 dst_reg->s32_min_value = S32_MIN; 10086 dst_reg->s32_max_value = S32_MAX; 10087 } else { 10088 dst_reg->s32_min_value = dst_reg->u32_min_value; 10089 dst_reg->s32_max_value = dst_reg->u32_max_value; 10090 } 10091 } 10092 10093 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 10094 struct bpf_reg_state *src_reg) 10095 { 10096 s64 smin_val = src_reg->smin_value; 10097 u64 umin_val = src_reg->umin_value; 10098 u64 umax_val = src_reg->umax_value; 10099 10100 if (smin_val < 0 || dst_reg->smin_value < 0) { 10101 /* Ain't nobody got time to multiply that sign */ 10102 __mark_reg64_unbounded(dst_reg); 10103 return; 10104 } 10105 /* Both values are positive, so we can work with unsigned and 10106 * copy the result to signed (unless it exceeds S64_MAX). 10107 */ 10108 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 10109 /* Potential overflow, we know nothing */ 10110 __mark_reg64_unbounded(dst_reg); 10111 return; 10112 } 10113 dst_reg->umin_value *= umin_val; 10114 dst_reg->umax_value *= umax_val; 10115 if (dst_reg->umax_value > S64_MAX) { 10116 /* Overflow possible, we know nothing */ 10117 dst_reg->smin_value = S64_MIN; 10118 dst_reg->smax_value = S64_MAX; 10119 } else { 10120 dst_reg->smin_value = dst_reg->umin_value; 10121 dst_reg->smax_value = dst_reg->umax_value; 10122 } 10123 } 10124 10125 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 10126 struct bpf_reg_state *src_reg) 10127 { 10128 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10129 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10130 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10131 s32 smin_val = src_reg->s32_min_value; 10132 u32 umax_val = src_reg->u32_max_value; 10133 10134 if (src_known && dst_known) { 10135 __mark_reg32_known(dst_reg, var32_off.value); 10136 return; 10137 } 10138 10139 /* We get our minimum from the var_off, since that's inherently 10140 * bitwise. Our maximum is the minimum of the operands' maxima. 10141 */ 10142 dst_reg->u32_min_value = var32_off.value; 10143 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 10144 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 10145 /* Lose signed bounds when ANDing negative numbers, 10146 * ain't nobody got time for that. 10147 */ 10148 dst_reg->s32_min_value = S32_MIN; 10149 dst_reg->s32_max_value = S32_MAX; 10150 } else { 10151 /* ANDing two positives gives a positive, so safe to 10152 * cast result into s64. 10153 */ 10154 dst_reg->s32_min_value = dst_reg->u32_min_value; 10155 dst_reg->s32_max_value = dst_reg->u32_max_value; 10156 } 10157 } 10158 10159 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 10160 struct bpf_reg_state *src_reg) 10161 { 10162 bool src_known = tnum_is_const(src_reg->var_off); 10163 bool dst_known = tnum_is_const(dst_reg->var_off); 10164 s64 smin_val = src_reg->smin_value; 10165 u64 umax_val = src_reg->umax_value; 10166 10167 if (src_known && dst_known) { 10168 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10169 return; 10170 } 10171 10172 /* We get our minimum from the var_off, since that's inherently 10173 * bitwise. Our maximum is the minimum of the operands' maxima. 10174 */ 10175 dst_reg->umin_value = dst_reg->var_off.value; 10176 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 10177 if (dst_reg->smin_value < 0 || smin_val < 0) { 10178 /* Lose signed bounds when ANDing negative numbers, 10179 * ain't nobody got time for that. 10180 */ 10181 dst_reg->smin_value = S64_MIN; 10182 dst_reg->smax_value = S64_MAX; 10183 } else { 10184 /* ANDing two positives gives a positive, so safe to 10185 * cast result into s64. 10186 */ 10187 dst_reg->smin_value = dst_reg->umin_value; 10188 dst_reg->smax_value = dst_reg->umax_value; 10189 } 10190 /* We may learn something more from the var_off */ 10191 __update_reg_bounds(dst_reg); 10192 } 10193 10194 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 10195 struct bpf_reg_state *src_reg) 10196 { 10197 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10198 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10199 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10200 s32 smin_val = src_reg->s32_min_value; 10201 u32 umin_val = src_reg->u32_min_value; 10202 10203 if (src_known && dst_known) { 10204 __mark_reg32_known(dst_reg, var32_off.value); 10205 return; 10206 } 10207 10208 /* We get our maximum from the var_off, and our minimum is the 10209 * maximum of the operands' minima 10210 */ 10211 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 10212 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 10213 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 10214 /* Lose signed bounds when ORing negative numbers, 10215 * ain't nobody got time for that. 10216 */ 10217 dst_reg->s32_min_value = S32_MIN; 10218 dst_reg->s32_max_value = S32_MAX; 10219 } else { 10220 /* ORing two positives gives a positive, so safe to 10221 * cast result into s64. 10222 */ 10223 dst_reg->s32_min_value = dst_reg->u32_min_value; 10224 dst_reg->s32_max_value = dst_reg->u32_max_value; 10225 } 10226 } 10227 10228 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 10229 struct bpf_reg_state *src_reg) 10230 { 10231 bool src_known = tnum_is_const(src_reg->var_off); 10232 bool dst_known = tnum_is_const(dst_reg->var_off); 10233 s64 smin_val = src_reg->smin_value; 10234 u64 umin_val = src_reg->umin_value; 10235 10236 if (src_known && dst_known) { 10237 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10238 return; 10239 } 10240 10241 /* We get our maximum from the var_off, and our minimum is the 10242 * maximum of the operands' minima 10243 */ 10244 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 10245 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 10246 if (dst_reg->smin_value < 0 || smin_val < 0) { 10247 /* Lose signed bounds when ORing negative numbers, 10248 * ain't nobody got time for that. 10249 */ 10250 dst_reg->smin_value = S64_MIN; 10251 dst_reg->smax_value = S64_MAX; 10252 } else { 10253 /* ORing two positives gives a positive, so safe to 10254 * cast result into s64. 10255 */ 10256 dst_reg->smin_value = dst_reg->umin_value; 10257 dst_reg->smax_value = dst_reg->umax_value; 10258 } 10259 /* We may learn something more from the var_off */ 10260 __update_reg_bounds(dst_reg); 10261 } 10262 10263 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 10264 struct bpf_reg_state *src_reg) 10265 { 10266 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10267 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10268 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10269 s32 smin_val = src_reg->s32_min_value; 10270 10271 if (src_known && dst_known) { 10272 __mark_reg32_known(dst_reg, var32_off.value); 10273 return; 10274 } 10275 10276 /* We get both minimum and maximum from the var32_off. */ 10277 dst_reg->u32_min_value = var32_off.value; 10278 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 10279 10280 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 10281 /* XORing two positive sign numbers gives a positive, 10282 * so safe to cast u32 result into s32. 10283 */ 10284 dst_reg->s32_min_value = dst_reg->u32_min_value; 10285 dst_reg->s32_max_value = dst_reg->u32_max_value; 10286 } else { 10287 dst_reg->s32_min_value = S32_MIN; 10288 dst_reg->s32_max_value = S32_MAX; 10289 } 10290 } 10291 10292 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 10293 struct bpf_reg_state *src_reg) 10294 { 10295 bool src_known = tnum_is_const(src_reg->var_off); 10296 bool dst_known = tnum_is_const(dst_reg->var_off); 10297 s64 smin_val = src_reg->smin_value; 10298 10299 if (src_known && dst_known) { 10300 /* dst_reg->var_off.value has been updated earlier */ 10301 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10302 return; 10303 } 10304 10305 /* We get both minimum and maximum from the var_off. */ 10306 dst_reg->umin_value = dst_reg->var_off.value; 10307 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 10308 10309 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 10310 /* XORing two positive sign numbers gives a positive, 10311 * so safe to cast u64 result into s64. 10312 */ 10313 dst_reg->smin_value = dst_reg->umin_value; 10314 dst_reg->smax_value = dst_reg->umax_value; 10315 } else { 10316 dst_reg->smin_value = S64_MIN; 10317 dst_reg->smax_value = S64_MAX; 10318 } 10319 10320 __update_reg_bounds(dst_reg); 10321 } 10322 10323 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 10324 u64 umin_val, u64 umax_val) 10325 { 10326 /* We lose all sign bit information (except what we can pick 10327 * up from var_off) 10328 */ 10329 dst_reg->s32_min_value = S32_MIN; 10330 dst_reg->s32_max_value = S32_MAX; 10331 /* If we might shift our top bit out, then we know nothing */ 10332 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 10333 dst_reg->u32_min_value = 0; 10334 dst_reg->u32_max_value = U32_MAX; 10335 } else { 10336 dst_reg->u32_min_value <<= umin_val; 10337 dst_reg->u32_max_value <<= umax_val; 10338 } 10339 } 10340 10341 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 10342 struct bpf_reg_state *src_reg) 10343 { 10344 u32 umax_val = src_reg->u32_max_value; 10345 u32 umin_val = src_reg->u32_min_value; 10346 /* u32 alu operation will zext upper bits */ 10347 struct tnum subreg = tnum_subreg(dst_reg->var_off); 10348 10349 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 10350 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 10351 /* Not required but being careful mark reg64 bounds as unknown so 10352 * that we are forced to pick them up from tnum and zext later and 10353 * if some path skips this step we are still safe. 10354 */ 10355 __mark_reg64_unbounded(dst_reg); 10356 __update_reg32_bounds(dst_reg); 10357 } 10358 10359 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 10360 u64 umin_val, u64 umax_val) 10361 { 10362 /* Special case <<32 because it is a common compiler pattern to sign 10363 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 10364 * positive we know this shift will also be positive so we can track 10365 * bounds correctly. Otherwise we lose all sign bit information except 10366 * what we can pick up from var_off. Perhaps we can generalize this 10367 * later to shifts of any length. 10368 */ 10369 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 10370 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 10371 else 10372 dst_reg->smax_value = S64_MAX; 10373 10374 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 10375 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 10376 else 10377 dst_reg->smin_value = S64_MIN; 10378 10379 /* If we might shift our top bit out, then we know nothing */ 10380 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 10381 dst_reg->umin_value = 0; 10382 dst_reg->umax_value = U64_MAX; 10383 } else { 10384 dst_reg->umin_value <<= umin_val; 10385 dst_reg->umax_value <<= umax_val; 10386 } 10387 } 10388 10389 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 10390 struct bpf_reg_state *src_reg) 10391 { 10392 u64 umax_val = src_reg->umax_value; 10393 u64 umin_val = src_reg->umin_value; 10394 10395 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 10396 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 10397 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 10398 10399 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 10400 /* We may learn something more from the var_off */ 10401 __update_reg_bounds(dst_reg); 10402 } 10403 10404 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 10405 struct bpf_reg_state *src_reg) 10406 { 10407 struct tnum subreg = tnum_subreg(dst_reg->var_off); 10408 u32 umax_val = src_reg->u32_max_value; 10409 u32 umin_val = src_reg->u32_min_value; 10410 10411 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 10412 * be negative, then either: 10413 * 1) src_reg might be zero, so the sign bit of the result is 10414 * unknown, so we lose our signed bounds 10415 * 2) it's known negative, thus the unsigned bounds capture the 10416 * signed bounds 10417 * 3) the signed bounds cross zero, so they tell us nothing 10418 * about the result 10419 * If the value in dst_reg is known nonnegative, then again the 10420 * unsigned bounds capture the signed bounds. 10421 * Thus, in all cases it suffices to blow away our signed bounds 10422 * and rely on inferring new ones from the unsigned bounds and 10423 * var_off of the result. 10424 */ 10425 dst_reg->s32_min_value = S32_MIN; 10426 dst_reg->s32_max_value = S32_MAX; 10427 10428 dst_reg->var_off = tnum_rshift(subreg, umin_val); 10429 dst_reg->u32_min_value >>= umax_val; 10430 dst_reg->u32_max_value >>= umin_val; 10431 10432 __mark_reg64_unbounded(dst_reg); 10433 __update_reg32_bounds(dst_reg); 10434 } 10435 10436 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 10437 struct bpf_reg_state *src_reg) 10438 { 10439 u64 umax_val = src_reg->umax_value; 10440 u64 umin_val = src_reg->umin_value; 10441 10442 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 10443 * be negative, then either: 10444 * 1) src_reg might be zero, so the sign bit of the result is 10445 * unknown, so we lose our signed bounds 10446 * 2) it's known negative, thus the unsigned bounds capture the 10447 * signed bounds 10448 * 3) the signed bounds cross zero, so they tell us nothing 10449 * about the result 10450 * If the value in dst_reg is known nonnegative, then again the 10451 * unsigned bounds capture the signed bounds. 10452 * Thus, in all cases it suffices to blow away our signed bounds 10453 * and rely on inferring new ones from the unsigned bounds and 10454 * var_off of the result. 10455 */ 10456 dst_reg->smin_value = S64_MIN; 10457 dst_reg->smax_value = S64_MAX; 10458 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 10459 dst_reg->umin_value >>= umax_val; 10460 dst_reg->umax_value >>= umin_val; 10461 10462 /* Its not easy to operate on alu32 bounds here because it depends 10463 * on bits being shifted in. Take easy way out and mark unbounded 10464 * so we can recalculate later from tnum. 10465 */ 10466 __mark_reg32_unbounded(dst_reg); 10467 __update_reg_bounds(dst_reg); 10468 } 10469 10470 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 10471 struct bpf_reg_state *src_reg) 10472 { 10473 u64 umin_val = src_reg->u32_min_value; 10474 10475 /* Upon reaching here, src_known is true and 10476 * umax_val is equal to umin_val. 10477 */ 10478 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 10479 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 10480 10481 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 10482 10483 /* blow away the dst_reg umin_value/umax_value and rely on 10484 * dst_reg var_off to refine the result. 10485 */ 10486 dst_reg->u32_min_value = 0; 10487 dst_reg->u32_max_value = U32_MAX; 10488 10489 __mark_reg64_unbounded(dst_reg); 10490 __update_reg32_bounds(dst_reg); 10491 } 10492 10493 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 10494 struct bpf_reg_state *src_reg) 10495 { 10496 u64 umin_val = src_reg->umin_value; 10497 10498 /* Upon reaching here, src_known is true and umax_val is equal 10499 * to umin_val. 10500 */ 10501 dst_reg->smin_value >>= umin_val; 10502 dst_reg->smax_value >>= umin_val; 10503 10504 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 10505 10506 /* blow away the dst_reg umin_value/umax_value and rely on 10507 * dst_reg var_off to refine the result. 10508 */ 10509 dst_reg->umin_value = 0; 10510 dst_reg->umax_value = U64_MAX; 10511 10512 /* Its not easy to operate on alu32 bounds here because it depends 10513 * on bits being shifted in from upper 32-bits. Take easy way out 10514 * and mark unbounded so we can recalculate later from tnum. 10515 */ 10516 __mark_reg32_unbounded(dst_reg); 10517 __update_reg_bounds(dst_reg); 10518 } 10519 10520 /* WARNING: This function does calculations on 64-bit values, but the actual 10521 * execution may occur on 32-bit values. Therefore, things like bitshifts 10522 * need extra checks in the 32-bit case. 10523 */ 10524 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 10525 struct bpf_insn *insn, 10526 struct bpf_reg_state *dst_reg, 10527 struct bpf_reg_state src_reg) 10528 { 10529 struct bpf_reg_state *regs = cur_regs(env); 10530 u8 opcode = BPF_OP(insn->code); 10531 bool src_known; 10532 s64 smin_val, smax_val; 10533 u64 umin_val, umax_val; 10534 s32 s32_min_val, s32_max_val; 10535 u32 u32_min_val, u32_max_val; 10536 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 10537 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 10538 int ret; 10539 10540 smin_val = src_reg.smin_value; 10541 smax_val = src_reg.smax_value; 10542 umin_val = src_reg.umin_value; 10543 umax_val = src_reg.umax_value; 10544 10545 s32_min_val = src_reg.s32_min_value; 10546 s32_max_val = src_reg.s32_max_value; 10547 u32_min_val = src_reg.u32_min_value; 10548 u32_max_val = src_reg.u32_max_value; 10549 10550 if (alu32) { 10551 src_known = tnum_subreg_is_const(src_reg.var_off); 10552 if ((src_known && 10553 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 10554 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 10555 /* Taint dst register if offset had invalid bounds 10556 * derived from e.g. dead branches. 10557 */ 10558 __mark_reg_unknown(env, dst_reg); 10559 return 0; 10560 } 10561 } else { 10562 src_known = tnum_is_const(src_reg.var_off); 10563 if ((src_known && 10564 (smin_val != smax_val || umin_val != umax_val)) || 10565 smin_val > smax_val || umin_val > umax_val) { 10566 /* Taint dst register if offset had invalid bounds 10567 * derived from e.g. dead branches. 10568 */ 10569 __mark_reg_unknown(env, dst_reg); 10570 return 0; 10571 } 10572 } 10573 10574 if (!src_known && 10575 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 10576 __mark_reg_unknown(env, dst_reg); 10577 return 0; 10578 } 10579 10580 if (sanitize_needed(opcode)) { 10581 ret = sanitize_val_alu(env, insn); 10582 if (ret < 0) 10583 return sanitize_err(env, insn, ret, NULL, NULL); 10584 } 10585 10586 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 10587 * There are two classes of instructions: The first class we track both 10588 * alu32 and alu64 sign/unsigned bounds independently this provides the 10589 * greatest amount of precision when alu operations are mixed with jmp32 10590 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 10591 * and BPF_OR. This is possible because these ops have fairly easy to 10592 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 10593 * See alu32 verifier tests for examples. The second class of 10594 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 10595 * with regards to tracking sign/unsigned bounds because the bits may 10596 * cross subreg boundaries in the alu64 case. When this happens we mark 10597 * the reg unbounded in the subreg bound space and use the resulting 10598 * tnum to calculate an approximation of the sign/unsigned bounds. 10599 */ 10600 switch (opcode) { 10601 case BPF_ADD: 10602 scalar32_min_max_add(dst_reg, &src_reg); 10603 scalar_min_max_add(dst_reg, &src_reg); 10604 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 10605 break; 10606 case BPF_SUB: 10607 scalar32_min_max_sub(dst_reg, &src_reg); 10608 scalar_min_max_sub(dst_reg, &src_reg); 10609 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 10610 break; 10611 case BPF_MUL: 10612 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 10613 scalar32_min_max_mul(dst_reg, &src_reg); 10614 scalar_min_max_mul(dst_reg, &src_reg); 10615 break; 10616 case BPF_AND: 10617 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 10618 scalar32_min_max_and(dst_reg, &src_reg); 10619 scalar_min_max_and(dst_reg, &src_reg); 10620 break; 10621 case BPF_OR: 10622 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 10623 scalar32_min_max_or(dst_reg, &src_reg); 10624 scalar_min_max_or(dst_reg, &src_reg); 10625 break; 10626 case BPF_XOR: 10627 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 10628 scalar32_min_max_xor(dst_reg, &src_reg); 10629 scalar_min_max_xor(dst_reg, &src_reg); 10630 break; 10631 case BPF_LSH: 10632 if (umax_val >= insn_bitness) { 10633 /* Shifts greater than 31 or 63 are undefined. 10634 * This includes shifts by a negative number. 10635 */ 10636 mark_reg_unknown(env, regs, insn->dst_reg); 10637 break; 10638 } 10639 if (alu32) 10640 scalar32_min_max_lsh(dst_reg, &src_reg); 10641 else 10642 scalar_min_max_lsh(dst_reg, &src_reg); 10643 break; 10644 case BPF_RSH: 10645 if (umax_val >= insn_bitness) { 10646 /* Shifts greater than 31 or 63 are undefined. 10647 * This includes shifts by a negative number. 10648 */ 10649 mark_reg_unknown(env, regs, insn->dst_reg); 10650 break; 10651 } 10652 if (alu32) 10653 scalar32_min_max_rsh(dst_reg, &src_reg); 10654 else 10655 scalar_min_max_rsh(dst_reg, &src_reg); 10656 break; 10657 case BPF_ARSH: 10658 if (umax_val >= insn_bitness) { 10659 /* Shifts greater than 31 or 63 are undefined. 10660 * This includes shifts by a negative number. 10661 */ 10662 mark_reg_unknown(env, regs, insn->dst_reg); 10663 break; 10664 } 10665 if (alu32) 10666 scalar32_min_max_arsh(dst_reg, &src_reg); 10667 else 10668 scalar_min_max_arsh(dst_reg, &src_reg); 10669 break; 10670 default: 10671 mark_reg_unknown(env, regs, insn->dst_reg); 10672 break; 10673 } 10674 10675 /* ALU32 ops are zero extended into 64bit register */ 10676 if (alu32) 10677 zext_32_to_64(dst_reg); 10678 reg_bounds_sync(dst_reg); 10679 return 0; 10680 } 10681 10682 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 10683 * and var_off. 10684 */ 10685 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 10686 struct bpf_insn *insn) 10687 { 10688 struct bpf_verifier_state *vstate = env->cur_state; 10689 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 10690 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 10691 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 10692 u8 opcode = BPF_OP(insn->code); 10693 int err; 10694 10695 dst_reg = ®s[insn->dst_reg]; 10696 src_reg = NULL; 10697 if (dst_reg->type != SCALAR_VALUE) 10698 ptr_reg = dst_reg; 10699 else 10700 /* Make sure ID is cleared otherwise dst_reg min/max could be 10701 * incorrectly propagated into other registers by find_equal_scalars() 10702 */ 10703 dst_reg->id = 0; 10704 if (BPF_SRC(insn->code) == BPF_X) { 10705 src_reg = ®s[insn->src_reg]; 10706 if (src_reg->type != SCALAR_VALUE) { 10707 if (dst_reg->type != SCALAR_VALUE) { 10708 /* Combining two pointers by any ALU op yields 10709 * an arbitrary scalar. Disallow all math except 10710 * pointer subtraction 10711 */ 10712 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 10713 mark_reg_unknown(env, regs, insn->dst_reg); 10714 return 0; 10715 } 10716 verbose(env, "R%d pointer %s pointer prohibited\n", 10717 insn->dst_reg, 10718 bpf_alu_string[opcode >> 4]); 10719 return -EACCES; 10720 } else { 10721 /* scalar += pointer 10722 * This is legal, but we have to reverse our 10723 * src/dest handling in computing the range 10724 */ 10725 err = mark_chain_precision(env, insn->dst_reg); 10726 if (err) 10727 return err; 10728 return adjust_ptr_min_max_vals(env, insn, 10729 src_reg, dst_reg); 10730 } 10731 } else if (ptr_reg) { 10732 /* pointer += scalar */ 10733 err = mark_chain_precision(env, insn->src_reg); 10734 if (err) 10735 return err; 10736 return adjust_ptr_min_max_vals(env, insn, 10737 dst_reg, src_reg); 10738 } else if (dst_reg->precise) { 10739 /* if dst_reg is precise, src_reg should be precise as well */ 10740 err = mark_chain_precision(env, insn->src_reg); 10741 if (err) 10742 return err; 10743 } 10744 } else { 10745 /* Pretend the src is a reg with a known value, since we only 10746 * need to be able to read from this state. 10747 */ 10748 off_reg.type = SCALAR_VALUE; 10749 __mark_reg_known(&off_reg, insn->imm); 10750 src_reg = &off_reg; 10751 if (ptr_reg) /* pointer += K */ 10752 return adjust_ptr_min_max_vals(env, insn, 10753 ptr_reg, src_reg); 10754 } 10755 10756 /* Got here implies adding two SCALAR_VALUEs */ 10757 if (WARN_ON_ONCE(ptr_reg)) { 10758 print_verifier_state(env, state, true); 10759 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 10760 return -EINVAL; 10761 } 10762 if (WARN_ON(!src_reg)) { 10763 print_verifier_state(env, state, true); 10764 verbose(env, "verifier internal error: no src_reg\n"); 10765 return -EINVAL; 10766 } 10767 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 10768 } 10769 10770 /* check validity of 32-bit and 64-bit arithmetic operations */ 10771 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 10772 { 10773 struct bpf_reg_state *regs = cur_regs(env); 10774 u8 opcode = BPF_OP(insn->code); 10775 int err; 10776 10777 if (opcode == BPF_END || opcode == BPF_NEG) { 10778 if (opcode == BPF_NEG) { 10779 if (BPF_SRC(insn->code) != BPF_K || 10780 insn->src_reg != BPF_REG_0 || 10781 insn->off != 0 || insn->imm != 0) { 10782 verbose(env, "BPF_NEG uses reserved fields\n"); 10783 return -EINVAL; 10784 } 10785 } else { 10786 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 10787 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 10788 BPF_CLASS(insn->code) == BPF_ALU64) { 10789 verbose(env, "BPF_END uses reserved fields\n"); 10790 return -EINVAL; 10791 } 10792 } 10793 10794 /* check src operand */ 10795 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 10796 if (err) 10797 return err; 10798 10799 if (is_pointer_value(env, insn->dst_reg)) { 10800 verbose(env, "R%d pointer arithmetic prohibited\n", 10801 insn->dst_reg); 10802 return -EACCES; 10803 } 10804 10805 /* check dest operand */ 10806 err = check_reg_arg(env, insn->dst_reg, DST_OP); 10807 if (err) 10808 return err; 10809 10810 } else if (opcode == BPF_MOV) { 10811 10812 if (BPF_SRC(insn->code) == BPF_X) { 10813 if (insn->imm != 0 || insn->off != 0) { 10814 verbose(env, "BPF_MOV uses reserved fields\n"); 10815 return -EINVAL; 10816 } 10817 10818 /* check src operand */ 10819 err = check_reg_arg(env, insn->src_reg, SRC_OP); 10820 if (err) 10821 return err; 10822 } else { 10823 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 10824 verbose(env, "BPF_MOV uses reserved fields\n"); 10825 return -EINVAL; 10826 } 10827 } 10828 10829 /* check dest operand, mark as required later */ 10830 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 10831 if (err) 10832 return err; 10833 10834 if (BPF_SRC(insn->code) == BPF_X) { 10835 struct bpf_reg_state *src_reg = regs + insn->src_reg; 10836 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 10837 10838 if (BPF_CLASS(insn->code) == BPF_ALU64) { 10839 /* case: R1 = R2 10840 * copy register state to dest reg 10841 */ 10842 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 10843 /* Assign src and dst registers the same ID 10844 * that will be used by find_equal_scalars() 10845 * to propagate min/max range. 10846 */ 10847 src_reg->id = ++env->id_gen; 10848 *dst_reg = *src_reg; 10849 dst_reg->live |= REG_LIVE_WRITTEN; 10850 dst_reg->subreg_def = DEF_NOT_SUBREG; 10851 } else { 10852 /* R1 = (u32) R2 */ 10853 if (is_pointer_value(env, insn->src_reg)) { 10854 verbose(env, 10855 "R%d partial copy of pointer\n", 10856 insn->src_reg); 10857 return -EACCES; 10858 } else if (src_reg->type == SCALAR_VALUE) { 10859 *dst_reg = *src_reg; 10860 /* Make sure ID is cleared otherwise 10861 * dst_reg min/max could be incorrectly 10862 * propagated into src_reg by find_equal_scalars() 10863 */ 10864 dst_reg->id = 0; 10865 dst_reg->live |= REG_LIVE_WRITTEN; 10866 dst_reg->subreg_def = env->insn_idx + 1; 10867 } else { 10868 mark_reg_unknown(env, regs, 10869 insn->dst_reg); 10870 } 10871 zext_32_to_64(dst_reg); 10872 reg_bounds_sync(dst_reg); 10873 } 10874 } else { 10875 /* case: R = imm 10876 * remember the value we stored into this reg 10877 */ 10878 /* clear any state __mark_reg_known doesn't set */ 10879 mark_reg_unknown(env, regs, insn->dst_reg); 10880 regs[insn->dst_reg].type = SCALAR_VALUE; 10881 if (BPF_CLASS(insn->code) == BPF_ALU64) { 10882 __mark_reg_known(regs + insn->dst_reg, 10883 insn->imm); 10884 } else { 10885 __mark_reg_known(regs + insn->dst_reg, 10886 (u32)insn->imm); 10887 } 10888 } 10889 10890 } else if (opcode > BPF_END) { 10891 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 10892 return -EINVAL; 10893 10894 } else { /* all other ALU ops: and, sub, xor, add, ... */ 10895 10896 if (BPF_SRC(insn->code) == BPF_X) { 10897 if (insn->imm != 0 || insn->off != 0) { 10898 verbose(env, "BPF_ALU uses reserved fields\n"); 10899 return -EINVAL; 10900 } 10901 /* check src1 operand */ 10902 err = check_reg_arg(env, insn->src_reg, SRC_OP); 10903 if (err) 10904 return err; 10905 } else { 10906 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 10907 verbose(env, "BPF_ALU uses reserved fields\n"); 10908 return -EINVAL; 10909 } 10910 } 10911 10912 /* check src2 operand */ 10913 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 10914 if (err) 10915 return err; 10916 10917 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 10918 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 10919 verbose(env, "div by zero\n"); 10920 return -EINVAL; 10921 } 10922 10923 if ((opcode == BPF_LSH || opcode == BPF_RSH || 10924 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 10925 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 10926 10927 if (insn->imm < 0 || insn->imm >= size) { 10928 verbose(env, "invalid shift %d\n", insn->imm); 10929 return -EINVAL; 10930 } 10931 } 10932 10933 /* check dest operand */ 10934 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 10935 if (err) 10936 return err; 10937 10938 return adjust_reg_min_max_vals(env, insn); 10939 } 10940 10941 return 0; 10942 } 10943 10944 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 10945 struct bpf_reg_state *dst_reg, 10946 enum bpf_reg_type type, 10947 bool range_right_open) 10948 { 10949 struct bpf_func_state *state; 10950 struct bpf_reg_state *reg; 10951 int new_range; 10952 10953 if (dst_reg->off < 0 || 10954 (dst_reg->off == 0 && range_right_open)) 10955 /* This doesn't give us any range */ 10956 return; 10957 10958 if (dst_reg->umax_value > MAX_PACKET_OFF || 10959 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 10960 /* Risk of overflow. For instance, ptr + (1<<63) may be less 10961 * than pkt_end, but that's because it's also less than pkt. 10962 */ 10963 return; 10964 10965 new_range = dst_reg->off; 10966 if (range_right_open) 10967 new_range++; 10968 10969 /* Examples for register markings: 10970 * 10971 * pkt_data in dst register: 10972 * 10973 * r2 = r3; 10974 * r2 += 8; 10975 * if (r2 > pkt_end) goto <handle exception> 10976 * <access okay> 10977 * 10978 * r2 = r3; 10979 * r2 += 8; 10980 * if (r2 < pkt_end) goto <access okay> 10981 * <handle exception> 10982 * 10983 * Where: 10984 * r2 == dst_reg, pkt_end == src_reg 10985 * r2=pkt(id=n,off=8,r=0) 10986 * r3=pkt(id=n,off=0,r=0) 10987 * 10988 * pkt_data in src register: 10989 * 10990 * r2 = r3; 10991 * r2 += 8; 10992 * if (pkt_end >= r2) goto <access okay> 10993 * <handle exception> 10994 * 10995 * r2 = r3; 10996 * r2 += 8; 10997 * if (pkt_end <= r2) goto <handle exception> 10998 * <access okay> 10999 * 11000 * Where: 11001 * pkt_end == dst_reg, r2 == src_reg 11002 * r2=pkt(id=n,off=8,r=0) 11003 * r3=pkt(id=n,off=0,r=0) 11004 * 11005 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 11006 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 11007 * and [r3, r3 + 8-1) respectively is safe to access depending on 11008 * the check. 11009 */ 11010 11011 /* If our ids match, then we must have the same max_value. And we 11012 * don't care about the other reg's fixed offset, since if it's too big 11013 * the range won't allow anything. 11014 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 11015 */ 11016 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 11017 if (reg->type == type && reg->id == dst_reg->id) 11018 /* keep the maximum range already checked */ 11019 reg->range = max(reg->range, new_range); 11020 })); 11021 } 11022 11023 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 11024 { 11025 struct tnum subreg = tnum_subreg(reg->var_off); 11026 s32 sval = (s32)val; 11027 11028 switch (opcode) { 11029 case BPF_JEQ: 11030 if (tnum_is_const(subreg)) 11031 return !!tnum_equals_const(subreg, val); 11032 break; 11033 case BPF_JNE: 11034 if (tnum_is_const(subreg)) 11035 return !tnum_equals_const(subreg, val); 11036 break; 11037 case BPF_JSET: 11038 if ((~subreg.mask & subreg.value) & val) 11039 return 1; 11040 if (!((subreg.mask | subreg.value) & val)) 11041 return 0; 11042 break; 11043 case BPF_JGT: 11044 if (reg->u32_min_value > val) 11045 return 1; 11046 else if (reg->u32_max_value <= val) 11047 return 0; 11048 break; 11049 case BPF_JSGT: 11050 if (reg->s32_min_value > sval) 11051 return 1; 11052 else if (reg->s32_max_value <= sval) 11053 return 0; 11054 break; 11055 case BPF_JLT: 11056 if (reg->u32_max_value < val) 11057 return 1; 11058 else if (reg->u32_min_value >= val) 11059 return 0; 11060 break; 11061 case BPF_JSLT: 11062 if (reg->s32_max_value < sval) 11063 return 1; 11064 else if (reg->s32_min_value >= sval) 11065 return 0; 11066 break; 11067 case BPF_JGE: 11068 if (reg->u32_min_value >= val) 11069 return 1; 11070 else if (reg->u32_max_value < val) 11071 return 0; 11072 break; 11073 case BPF_JSGE: 11074 if (reg->s32_min_value >= sval) 11075 return 1; 11076 else if (reg->s32_max_value < sval) 11077 return 0; 11078 break; 11079 case BPF_JLE: 11080 if (reg->u32_max_value <= val) 11081 return 1; 11082 else if (reg->u32_min_value > val) 11083 return 0; 11084 break; 11085 case BPF_JSLE: 11086 if (reg->s32_max_value <= sval) 11087 return 1; 11088 else if (reg->s32_min_value > sval) 11089 return 0; 11090 break; 11091 } 11092 11093 return -1; 11094 } 11095 11096 11097 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 11098 { 11099 s64 sval = (s64)val; 11100 11101 switch (opcode) { 11102 case BPF_JEQ: 11103 if (tnum_is_const(reg->var_off)) 11104 return !!tnum_equals_const(reg->var_off, val); 11105 break; 11106 case BPF_JNE: 11107 if (tnum_is_const(reg->var_off)) 11108 return !tnum_equals_const(reg->var_off, val); 11109 break; 11110 case BPF_JSET: 11111 if ((~reg->var_off.mask & reg->var_off.value) & val) 11112 return 1; 11113 if (!((reg->var_off.mask | reg->var_off.value) & val)) 11114 return 0; 11115 break; 11116 case BPF_JGT: 11117 if (reg->umin_value > val) 11118 return 1; 11119 else if (reg->umax_value <= val) 11120 return 0; 11121 break; 11122 case BPF_JSGT: 11123 if (reg->smin_value > sval) 11124 return 1; 11125 else if (reg->smax_value <= sval) 11126 return 0; 11127 break; 11128 case BPF_JLT: 11129 if (reg->umax_value < val) 11130 return 1; 11131 else if (reg->umin_value >= val) 11132 return 0; 11133 break; 11134 case BPF_JSLT: 11135 if (reg->smax_value < sval) 11136 return 1; 11137 else if (reg->smin_value >= sval) 11138 return 0; 11139 break; 11140 case BPF_JGE: 11141 if (reg->umin_value >= val) 11142 return 1; 11143 else if (reg->umax_value < val) 11144 return 0; 11145 break; 11146 case BPF_JSGE: 11147 if (reg->smin_value >= sval) 11148 return 1; 11149 else if (reg->smax_value < sval) 11150 return 0; 11151 break; 11152 case BPF_JLE: 11153 if (reg->umax_value <= val) 11154 return 1; 11155 else if (reg->umin_value > val) 11156 return 0; 11157 break; 11158 case BPF_JSLE: 11159 if (reg->smax_value <= sval) 11160 return 1; 11161 else if (reg->smin_value > sval) 11162 return 0; 11163 break; 11164 } 11165 11166 return -1; 11167 } 11168 11169 /* compute branch direction of the expression "if (reg opcode val) goto target;" 11170 * and return: 11171 * 1 - branch will be taken and "goto target" will be executed 11172 * 0 - branch will not be taken and fall-through to next insn 11173 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 11174 * range [0,10] 11175 */ 11176 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 11177 bool is_jmp32) 11178 { 11179 if (__is_pointer_value(false, reg)) { 11180 if (!reg_type_not_null(reg->type)) 11181 return -1; 11182 11183 /* If pointer is valid tests against zero will fail so we can 11184 * use this to direct branch taken. 11185 */ 11186 if (val != 0) 11187 return -1; 11188 11189 switch (opcode) { 11190 case BPF_JEQ: 11191 return 0; 11192 case BPF_JNE: 11193 return 1; 11194 default: 11195 return -1; 11196 } 11197 } 11198 11199 if (is_jmp32) 11200 return is_branch32_taken(reg, val, opcode); 11201 return is_branch64_taken(reg, val, opcode); 11202 } 11203 11204 static int flip_opcode(u32 opcode) 11205 { 11206 /* How can we transform "a <op> b" into "b <op> a"? */ 11207 static const u8 opcode_flip[16] = { 11208 /* these stay the same */ 11209 [BPF_JEQ >> 4] = BPF_JEQ, 11210 [BPF_JNE >> 4] = BPF_JNE, 11211 [BPF_JSET >> 4] = BPF_JSET, 11212 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 11213 [BPF_JGE >> 4] = BPF_JLE, 11214 [BPF_JGT >> 4] = BPF_JLT, 11215 [BPF_JLE >> 4] = BPF_JGE, 11216 [BPF_JLT >> 4] = BPF_JGT, 11217 [BPF_JSGE >> 4] = BPF_JSLE, 11218 [BPF_JSGT >> 4] = BPF_JSLT, 11219 [BPF_JSLE >> 4] = BPF_JSGE, 11220 [BPF_JSLT >> 4] = BPF_JSGT 11221 }; 11222 return opcode_flip[opcode >> 4]; 11223 } 11224 11225 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 11226 struct bpf_reg_state *src_reg, 11227 u8 opcode) 11228 { 11229 struct bpf_reg_state *pkt; 11230 11231 if (src_reg->type == PTR_TO_PACKET_END) { 11232 pkt = dst_reg; 11233 } else if (dst_reg->type == PTR_TO_PACKET_END) { 11234 pkt = src_reg; 11235 opcode = flip_opcode(opcode); 11236 } else { 11237 return -1; 11238 } 11239 11240 if (pkt->range >= 0) 11241 return -1; 11242 11243 switch (opcode) { 11244 case BPF_JLE: 11245 /* pkt <= pkt_end */ 11246 fallthrough; 11247 case BPF_JGT: 11248 /* pkt > pkt_end */ 11249 if (pkt->range == BEYOND_PKT_END) 11250 /* pkt has at last one extra byte beyond pkt_end */ 11251 return opcode == BPF_JGT; 11252 break; 11253 case BPF_JLT: 11254 /* pkt < pkt_end */ 11255 fallthrough; 11256 case BPF_JGE: 11257 /* pkt >= pkt_end */ 11258 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 11259 return opcode == BPF_JGE; 11260 break; 11261 } 11262 return -1; 11263 } 11264 11265 /* Adjusts the register min/max values in the case that the dst_reg is the 11266 * variable register that we are working on, and src_reg is a constant or we're 11267 * simply doing a BPF_K check. 11268 * In JEQ/JNE cases we also adjust the var_off values. 11269 */ 11270 static void reg_set_min_max(struct bpf_reg_state *true_reg, 11271 struct bpf_reg_state *false_reg, 11272 u64 val, u32 val32, 11273 u8 opcode, bool is_jmp32) 11274 { 11275 struct tnum false_32off = tnum_subreg(false_reg->var_off); 11276 struct tnum false_64off = false_reg->var_off; 11277 struct tnum true_32off = tnum_subreg(true_reg->var_off); 11278 struct tnum true_64off = true_reg->var_off; 11279 s64 sval = (s64)val; 11280 s32 sval32 = (s32)val32; 11281 11282 /* If the dst_reg is a pointer, we can't learn anything about its 11283 * variable offset from the compare (unless src_reg were a pointer into 11284 * the same object, but we don't bother with that. 11285 * Since false_reg and true_reg have the same type by construction, we 11286 * only need to check one of them for pointerness. 11287 */ 11288 if (__is_pointer_value(false, false_reg)) 11289 return; 11290 11291 switch (opcode) { 11292 /* JEQ/JNE comparison doesn't change the register equivalence. 11293 * 11294 * r1 = r2; 11295 * if (r1 == 42) goto label; 11296 * ... 11297 * label: // here both r1 and r2 are known to be 42. 11298 * 11299 * Hence when marking register as known preserve it's ID. 11300 */ 11301 case BPF_JEQ: 11302 if (is_jmp32) { 11303 __mark_reg32_known(true_reg, val32); 11304 true_32off = tnum_subreg(true_reg->var_off); 11305 } else { 11306 ___mark_reg_known(true_reg, val); 11307 true_64off = true_reg->var_off; 11308 } 11309 break; 11310 case BPF_JNE: 11311 if (is_jmp32) { 11312 __mark_reg32_known(false_reg, val32); 11313 false_32off = tnum_subreg(false_reg->var_off); 11314 } else { 11315 ___mark_reg_known(false_reg, val); 11316 false_64off = false_reg->var_off; 11317 } 11318 break; 11319 case BPF_JSET: 11320 if (is_jmp32) { 11321 false_32off = tnum_and(false_32off, tnum_const(~val32)); 11322 if (is_power_of_2(val32)) 11323 true_32off = tnum_or(true_32off, 11324 tnum_const(val32)); 11325 } else { 11326 false_64off = tnum_and(false_64off, tnum_const(~val)); 11327 if (is_power_of_2(val)) 11328 true_64off = tnum_or(true_64off, 11329 tnum_const(val)); 11330 } 11331 break; 11332 case BPF_JGE: 11333 case BPF_JGT: 11334 { 11335 if (is_jmp32) { 11336 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 11337 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 11338 11339 false_reg->u32_max_value = min(false_reg->u32_max_value, 11340 false_umax); 11341 true_reg->u32_min_value = max(true_reg->u32_min_value, 11342 true_umin); 11343 } else { 11344 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 11345 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 11346 11347 false_reg->umax_value = min(false_reg->umax_value, false_umax); 11348 true_reg->umin_value = max(true_reg->umin_value, true_umin); 11349 } 11350 break; 11351 } 11352 case BPF_JSGE: 11353 case BPF_JSGT: 11354 { 11355 if (is_jmp32) { 11356 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 11357 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 11358 11359 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 11360 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 11361 } else { 11362 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 11363 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 11364 11365 false_reg->smax_value = min(false_reg->smax_value, false_smax); 11366 true_reg->smin_value = max(true_reg->smin_value, true_smin); 11367 } 11368 break; 11369 } 11370 case BPF_JLE: 11371 case BPF_JLT: 11372 { 11373 if (is_jmp32) { 11374 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 11375 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 11376 11377 false_reg->u32_min_value = max(false_reg->u32_min_value, 11378 false_umin); 11379 true_reg->u32_max_value = min(true_reg->u32_max_value, 11380 true_umax); 11381 } else { 11382 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 11383 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 11384 11385 false_reg->umin_value = max(false_reg->umin_value, false_umin); 11386 true_reg->umax_value = min(true_reg->umax_value, true_umax); 11387 } 11388 break; 11389 } 11390 case BPF_JSLE: 11391 case BPF_JSLT: 11392 { 11393 if (is_jmp32) { 11394 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 11395 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 11396 11397 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 11398 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 11399 } else { 11400 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 11401 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 11402 11403 false_reg->smin_value = max(false_reg->smin_value, false_smin); 11404 true_reg->smax_value = min(true_reg->smax_value, true_smax); 11405 } 11406 break; 11407 } 11408 default: 11409 return; 11410 } 11411 11412 if (is_jmp32) { 11413 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 11414 tnum_subreg(false_32off)); 11415 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 11416 tnum_subreg(true_32off)); 11417 __reg_combine_32_into_64(false_reg); 11418 __reg_combine_32_into_64(true_reg); 11419 } else { 11420 false_reg->var_off = false_64off; 11421 true_reg->var_off = true_64off; 11422 __reg_combine_64_into_32(false_reg); 11423 __reg_combine_64_into_32(true_reg); 11424 } 11425 } 11426 11427 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 11428 * the variable reg. 11429 */ 11430 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 11431 struct bpf_reg_state *false_reg, 11432 u64 val, u32 val32, 11433 u8 opcode, bool is_jmp32) 11434 { 11435 opcode = flip_opcode(opcode); 11436 /* This uses zero as "not present in table"; luckily the zero opcode, 11437 * BPF_JA, can't get here. 11438 */ 11439 if (opcode) 11440 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 11441 } 11442 11443 /* Regs are known to be equal, so intersect their min/max/var_off */ 11444 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 11445 struct bpf_reg_state *dst_reg) 11446 { 11447 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 11448 dst_reg->umin_value); 11449 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 11450 dst_reg->umax_value); 11451 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 11452 dst_reg->smin_value); 11453 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 11454 dst_reg->smax_value); 11455 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 11456 dst_reg->var_off); 11457 reg_bounds_sync(src_reg); 11458 reg_bounds_sync(dst_reg); 11459 } 11460 11461 static void reg_combine_min_max(struct bpf_reg_state *true_src, 11462 struct bpf_reg_state *true_dst, 11463 struct bpf_reg_state *false_src, 11464 struct bpf_reg_state *false_dst, 11465 u8 opcode) 11466 { 11467 switch (opcode) { 11468 case BPF_JEQ: 11469 __reg_combine_min_max(true_src, true_dst); 11470 break; 11471 case BPF_JNE: 11472 __reg_combine_min_max(false_src, false_dst); 11473 break; 11474 } 11475 } 11476 11477 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 11478 struct bpf_reg_state *reg, u32 id, 11479 bool is_null) 11480 { 11481 if (type_may_be_null(reg->type) && reg->id == id && 11482 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 11483 /* Old offset (both fixed and variable parts) should have been 11484 * known-zero, because we don't allow pointer arithmetic on 11485 * pointers that might be NULL. If we see this happening, don't 11486 * convert the register. 11487 * 11488 * But in some cases, some helpers that return local kptrs 11489 * advance offset for the returned pointer. In those cases, it 11490 * is fine to expect to see reg->off. 11491 */ 11492 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 11493 return; 11494 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off)) 11495 return; 11496 if (is_null) { 11497 reg->type = SCALAR_VALUE; 11498 /* We don't need id and ref_obj_id from this point 11499 * onwards anymore, thus we should better reset it, 11500 * so that state pruning has chances to take effect. 11501 */ 11502 reg->id = 0; 11503 reg->ref_obj_id = 0; 11504 11505 return; 11506 } 11507 11508 mark_ptr_not_null_reg(reg); 11509 11510 if (!reg_may_point_to_spin_lock(reg)) { 11511 /* For not-NULL ptr, reg->ref_obj_id will be reset 11512 * in release_reference(). 11513 * 11514 * reg->id is still used by spin_lock ptr. Other 11515 * than spin_lock ptr type, reg->id can be reset. 11516 */ 11517 reg->id = 0; 11518 } 11519 } 11520 } 11521 11522 /* The logic is similar to find_good_pkt_pointers(), both could eventually 11523 * be folded together at some point. 11524 */ 11525 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 11526 bool is_null) 11527 { 11528 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 11529 struct bpf_reg_state *regs = state->regs, *reg; 11530 u32 ref_obj_id = regs[regno].ref_obj_id; 11531 u32 id = regs[regno].id; 11532 11533 if (ref_obj_id && ref_obj_id == id && is_null) 11534 /* regs[regno] is in the " == NULL" branch. 11535 * No one could have freed the reference state before 11536 * doing the NULL check. 11537 */ 11538 WARN_ON_ONCE(release_reference_state(state, id)); 11539 11540 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 11541 mark_ptr_or_null_reg(state, reg, id, is_null); 11542 })); 11543 } 11544 11545 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 11546 struct bpf_reg_state *dst_reg, 11547 struct bpf_reg_state *src_reg, 11548 struct bpf_verifier_state *this_branch, 11549 struct bpf_verifier_state *other_branch) 11550 { 11551 if (BPF_SRC(insn->code) != BPF_X) 11552 return false; 11553 11554 /* Pointers are always 64-bit. */ 11555 if (BPF_CLASS(insn->code) == BPF_JMP32) 11556 return false; 11557 11558 switch (BPF_OP(insn->code)) { 11559 case BPF_JGT: 11560 if ((dst_reg->type == PTR_TO_PACKET && 11561 src_reg->type == PTR_TO_PACKET_END) || 11562 (dst_reg->type == PTR_TO_PACKET_META && 11563 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11564 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 11565 find_good_pkt_pointers(this_branch, dst_reg, 11566 dst_reg->type, false); 11567 mark_pkt_end(other_branch, insn->dst_reg, true); 11568 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11569 src_reg->type == PTR_TO_PACKET) || 11570 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11571 src_reg->type == PTR_TO_PACKET_META)) { 11572 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 11573 find_good_pkt_pointers(other_branch, src_reg, 11574 src_reg->type, true); 11575 mark_pkt_end(this_branch, insn->src_reg, false); 11576 } else { 11577 return false; 11578 } 11579 break; 11580 case BPF_JLT: 11581 if ((dst_reg->type == PTR_TO_PACKET && 11582 src_reg->type == PTR_TO_PACKET_END) || 11583 (dst_reg->type == PTR_TO_PACKET_META && 11584 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11585 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 11586 find_good_pkt_pointers(other_branch, dst_reg, 11587 dst_reg->type, true); 11588 mark_pkt_end(this_branch, insn->dst_reg, false); 11589 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11590 src_reg->type == PTR_TO_PACKET) || 11591 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11592 src_reg->type == PTR_TO_PACKET_META)) { 11593 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 11594 find_good_pkt_pointers(this_branch, src_reg, 11595 src_reg->type, false); 11596 mark_pkt_end(other_branch, insn->src_reg, true); 11597 } else { 11598 return false; 11599 } 11600 break; 11601 case BPF_JGE: 11602 if ((dst_reg->type == PTR_TO_PACKET && 11603 src_reg->type == PTR_TO_PACKET_END) || 11604 (dst_reg->type == PTR_TO_PACKET_META && 11605 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11606 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 11607 find_good_pkt_pointers(this_branch, dst_reg, 11608 dst_reg->type, true); 11609 mark_pkt_end(other_branch, insn->dst_reg, false); 11610 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11611 src_reg->type == PTR_TO_PACKET) || 11612 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11613 src_reg->type == PTR_TO_PACKET_META)) { 11614 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 11615 find_good_pkt_pointers(other_branch, src_reg, 11616 src_reg->type, false); 11617 mark_pkt_end(this_branch, insn->src_reg, true); 11618 } else { 11619 return false; 11620 } 11621 break; 11622 case BPF_JLE: 11623 if ((dst_reg->type == PTR_TO_PACKET && 11624 src_reg->type == PTR_TO_PACKET_END) || 11625 (dst_reg->type == PTR_TO_PACKET_META && 11626 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11627 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 11628 find_good_pkt_pointers(other_branch, dst_reg, 11629 dst_reg->type, false); 11630 mark_pkt_end(this_branch, insn->dst_reg, true); 11631 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11632 src_reg->type == PTR_TO_PACKET) || 11633 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11634 src_reg->type == PTR_TO_PACKET_META)) { 11635 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 11636 find_good_pkt_pointers(this_branch, src_reg, 11637 src_reg->type, true); 11638 mark_pkt_end(other_branch, insn->src_reg, false); 11639 } else { 11640 return false; 11641 } 11642 break; 11643 default: 11644 return false; 11645 } 11646 11647 return true; 11648 } 11649 11650 static void find_equal_scalars(struct bpf_verifier_state *vstate, 11651 struct bpf_reg_state *known_reg) 11652 { 11653 struct bpf_func_state *state; 11654 struct bpf_reg_state *reg; 11655 11656 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 11657 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 11658 *reg = *known_reg; 11659 })); 11660 } 11661 11662 static int check_cond_jmp_op(struct bpf_verifier_env *env, 11663 struct bpf_insn *insn, int *insn_idx) 11664 { 11665 struct bpf_verifier_state *this_branch = env->cur_state; 11666 struct bpf_verifier_state *other_branch; 11667 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 11668 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 11669 struct bpf_reg_state *eq_branch_regs; 11670 u8 opcode = BPF_OP(insn->code); 11671 bool is_jmp32; 11672 int pred = -1; 11673 int err; 11674 11675 /* Only conditional jumps are expected to reach here. */ 11676 if (opcode == BPF_JA || opcode > BPF_JSLE) { 11677 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 11678 return -EINVAL; 11679 } 11680 11681 if (BPF_SRC(insn->code) == BPF_X) { 11682 if (insn->imm != 0) { 11683 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 11684 return -EINVAL; 11685 } 11686 11687 /* check src1 operand */ 11688 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11689 if (err) 11690 return err; 11691 11692 if (is_pointer_value(env, insn->src_reg)) { 11693 verbose(env, "R%d pointer comparison prohibited\n", 11694 insn->src_reg); 11695 return -EACCES; 11696 } 11697 src_reg = ®s[insn->src_reg]; 11698 } else { 11699 if (insn->src_reg != BPF_REG_0) { 11700 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 11701 return -EINVAL; 11702 } 11703 } 11704 11705 /* check src2 operand */ 11706 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11707 if (err) 11708 return err; 11709 11710 dst_reg = ®s[insn->dst_reg]; 11711 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 11712 11713 if (BPF_SRC(insn->code) == BPF_K) { 11714 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 11715 } else if (src_reg->type == SCALAR_VALUE && 11716 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 11717 pred = is_branch_taken(dst_reg, 11718 tnum_subreg(src_reg->var_off).value, 11719 opcode, 11720 is_jmp32); 11721 } else if (src_reg->type == SCALAR_VALUE && 11722 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 11723 pred = is_branch_taken(dst_reg, 11724 src_reg->var_off.value, 11725 opcode, 11726 is_jmp32); 11727 } else if (reg_is_pkt_pointer_any(dst_reg) && 11728 reg_is_pkt_pointer_any(src_reg) && 11729 !is_jmp32) { 11730 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 11731 } 11732 11733 if (pred >= 0) { 11734 /* If we get here with a dst_reg pointer type it is because 11735 * above is_branch_taken() special cased the 0 comparison. 11736 */ 11737 if (!__is_pointer_value(false, dst_reg)) 11738 err = mark_chain_precision(env, insn->dst_reg); 11739 if (BPF_SRC(insn->code) == BPF_X && !err && 11740 !__is_pointer_value(false, src_reg)) 11741 err = mark_chain_precision(env, insn->src_reg); 11742 if (err) 11743 return err; 11744 } 11745 11746 if (pred == 1) { 11747 /* Only follow the goto, ignore fall-through. If needed, push 11748 * the fall-through branch for simulation under speculative 11749 * execution. 11750 */ 11751 if (!env->bypass_spec_v1 && 11752 !sanitize_speculative_path(env, insn, *insn_idx + 1, 11753 *insn_idx)) 11754 return -EFAULT; 11755 *insn_idx += insn->off; 11756 return 0; 11757 } else if (pred == 0) { 11758 /* Only follow the fall-through branch, since that's where the 11759 * program will go. If needed, push the goto branch for 11760 * simulation under speculative execution. 11761 */ 11762 if (!env->bypass_spec_v1 && 11763 !sanitize_speculative_path(env, insn, 11764 *insn_idx + insn->off + 1, 11765 *insn_idx)) 11766 return -EFAULT; 11767 return 0; 11768 } 11769 11770 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 11771 false); 11772 if (!other_branch) 11773 return -EFAULT; 11774 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 11775 11776 /* detect if we are comparing against a constant value so we can adjust 11777 * our min/max values for our dst register. 11778 * this is only legit if both are scalars (or pointers to the same 11779 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 11780 * because otherwise the different base pointers mean the offsets aren't 11781 * comparable. 11782 */ 11783 if (BPF_SRC(insn->code) == BPF_X) { 11784 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 11785 11786 if (dst_reg->type == SCALAR_VALUE && 11787 src_reg->type == SCALAR_VALUE) { 11788 if (tnum_is_const(src_reg->var_off) || 11789 (is_jmp32 && 11790 tnum_is_const(tnum_subreg(src_reg->var_off)))) 11791 reg_set_min_max(&other_branch_regs[insn->dst_reg], 11792 dst_reg, 11793 src_reg->var_off.value, 11794 tnum_subreg(src_reg->var_off).value, 11795 opcode, is_jmp32); 11796 else if (tnum_is_const(dst_reg->var_off) || 11797 (is_jmp32 && 11798 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 11799 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 11800 src_reg, 11801 dst_reg->var_off.value, 11802 tnum_subreg(dst_reg->var_off).value, 11803 opcode, is_jmp32); 11804 else if (!is_jmp32 && 11805 (opcode == BPF_JEQ || opcode == BPF_JNE)) 11806 /* Comparing for equality, we can combine knowledge */ 11807 reg_combine_min_max(&other_branch_regs[insn->src_reg], 11808 &other_branch_regs[insn->dst_reg], 11809 src_reg, dst_reg, opcode); 11810 if (src_reg->id && 11811 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 11812 find_equal_scalars(this_branch, src_reg); 11813 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 11814 } 11815 11816 } 11817 } else if (dst_reg->type == SCALAR_VALUE) { 11818 reg_set_min_max(&other_branch_regs[insn->dst_reg], 11819 dst_reg, insn->imm, (u32)insn->imm, 11820 opcode, is_jmp32); 11821 } 11822 11823 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 11824 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 11825 find_equal_scalars(this_branch, dst_reg); 11826 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 11827 } 11828 11829 /* if one pointer register is compared to another pointer 11830 * register check if PTR_MAYBE_NULL could be lifted. 11831 * E.g. register A - maybe null 11832 * register B - not null 11833 * for JNE A, B, ... - A is not null in the false branch; 11834 * for JEQ A, B, ... - A is not null in the true branch. 11835 * 11836 * Since PTR_TO_BTF_ID points to a kernel struct that does 11837 * not need to be null checked by the BPF program, i.e., 11838 * could be null even without PTR_MAYBE_NULL marking, so 11839 * only propagate nullness when neither reg is that type. 11840 */ 11841 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 11842 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 11843 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 11844 base_type(src_reg->type) != PTR_TO_BTF_ID && 11845 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 11846 eq_branch_regs = NULL; 11847 switch (opcode) { 11848 case BPF_JEQ: 11849 eq_branch_regs = other_branch_regs; 11850 break; 11851 case BPF_JNE: 11852 eq_branch_regs = regs; 11853 break; 11854 default: 11855 /* do nothing */ 11856 break; 11857 } 11858 if (eq_branch_regs) { 11859 if (type_may_be_null(src_reg->type)) 11860 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 11861 else 11862 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 11863 } 11864 } 11865 11866 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 11867 * NOTE: these optimizations below are related with pointer comparison 11868 * which will never be JMP32. 11869 */ 11870 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 11871 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 11872 type_may_be_null(dst_reg->type)) { 11873 /* Mark all identical registers in each branch as either 11874 * safe or unknown depending R == 0 or R != 0 conditional. 11875 */ 11876 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 11877 opcode == BPF_JNE); 11878 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 11879 opcode == BPF_JEQ); 11880 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 11881 this_branch, other_branch) && 11882 is_pointer_value(env, insn->dst_reg)) { 11883 verbose(env, "R%d pointer comparison prohibited\n", 11884 insn->dst_reg); 11885 return -EACCES; 11886 } 11887 if (env->log.level & BPF_LOG_LEVEL) 11888 print_insn_state(env, this_branch->frame[this_branch->curframe]); 11889 return 0; 11890 } 11891 11892 /* verify BPF_LD_IMM64 instruction */ 11893 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 11894 { 11895 struct bpf_insn_aux_data *aux = cur_aux(env); 11896 struct bpf_reg_state *regs = cur_regs(env); 11897 struct bpf_reg_state *dst_reg; 11898 struct bpf_map *map; 11899 int err; 11900 11901 if (BPF_SIZE(insn->code) != BPF_DW) { 11902 verbose(env, "invalid BPF_LD_IMM insn\n"); 11903 return -EINVAL; 11904 } 11905 if (insn->off != 0) { 11906 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 11907 return -EINVAL; 11908 } 11909 11910 err = check_reg_arg(env, insn->dst_reg, DST_OP); 11911 if (err) 11912 return err; 11913 11914 dst_reg = ®s[insn->dst_reg]; 11915 if (insn->src_reg == 0) { 11916 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 11917 11918 dst_reg->type = SCALAR_VALUE; 11919 __mark_reg_known(®s[insn->dst_reg], imm); 11920 return 0; 11921 } 11922 11923 /* All special src_reg cases are listed below. From this point onwards 11924 * we either succeed and assign a corresponding dst_reg->type after 11925 * zeroing the offset, or fail and reject the program. 11926 */ 11927 mark_reg_known_zero(env, regs, insn->dst_reg); 11928 11929 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 11930 dst_reg->type = aux->btf_var.reg_type; 11931 switch (base_type(dst_reg->type)) { 11932 case PTR_TO_MEM: 11933 dst_reg->mem_size = aux->btf_var.mem_size; 11934 break; 11935 case PTR_TO_BTF_ID: 11936 dst_reg->btf = aux->btf_var.btf; 11937 dst_reg->btf_id = aux->btf_var.btf_id; 11938 break; 11939 default: 11940 verbose(env, "bpf verifier is misconfigured\n"); 11941 return -EFAULT; 11942 } 11943 return 0; 11944 } 11945 11946 if (insn->src_reg == BPF_PSEUDO_FUNC) { 11947 struct bpf_prog_aux *aux = env->prog->aux; 11948 u32 subprogno = find_subprog(env, 11949 env->insn_idx + insn->imm + 1); 11950 11951 if (!aux->func_info) { 11952 verbose(env, "missing btf func_info\n"); 11953 return -EINVAL; 11954 } 11955 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 11956 verbose(env, "callback function not static\n"); 11957 return -EINVAL; 11958 } 11959 11960 dst_reg->type = PTR_TO_FUNC; 11961 dst_reg->subprogno = subprogno; 11962 return 0; 11963 } 11964 11965 map = env->used_maps[aux->map_index]; 11966 dst_reg->map_ptr = map; 11967 11968 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 11969 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 11970 dst_reg->type = PTR_TO_MAP_VALUE; 11971 dst_reg->off = aux->map_off; 11972 WARN_ON_ONCE(map->max_entries != 1); 11973 /* We want reg->id to be same (0) as map_value is not distinct */ 11974 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 11975 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 11976 dst_reg->type = CONST_PTR_TO_MAP; 11977 } else { 11978 verbose(env, "bpf verifier is misconfigured\n"); 11979 return -EINVAL; 11980 } 11981 11982 return 0; 11983 } 11984 11985 static bool may_access_skb(enum bpf_prog_type type) 11986 { 11987 switch (type) { 11988 case BPF_PROG_TYPE_SOCKET_FILTER: 11989 case BPF_PROG_TYPE_SCHED_CLS: 11990 case BPF_PROG_TYPE_SCHED_ACT: 11991 return true; 11992 default: 11993 return false; 11994 } 11995 } 11996 11997 /* verify safety of LD_ABS|LD_IND instructions: 11998 * - they can only appear in the programs where ctx == skb 11999 * - since they are wrappers of function calls, they scratch R1-R5 registers, 12000 * preserve R6-R9, and store return value into R0 12001 * 12002 * Implicit input: 12003 * ctx == skb == R6 == CTX 12004 * 12005 * Explicit input: 12006 * SRC == any register 12007 * IMM == 32-bit immediate 12008 * 12009 * Output: 12010 * R0 - 8/16/32-bit skb data converted to cpu endianness 12011 */ 12012 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 12013 { 12014 struct bpf_reg_state *regs = cur_regs(env); 12015 static const int ctx_reg = BPF_REG_6; 12016 u8 mode = BPF_MODE(insn->code); 12017 int i, err; 12018 12019 if (!may_access_skb(resolve_prog_type(env->prog))) { 12020 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 12021 return -EINVAL; 12022 } 12023 12024 if (!env->ops->gen_ld_abs) { 12025 verbose(env, "bpf verifier is misconfigured\n"); 12026 return -EINVAL; 12027 } 12028 12029 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 12030 BPF_SIZE(insn->code) == BPF_DW || 12031 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 12032 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 12033 return -EINVAL; 12034 } 12035 12036 /* check whether implicit source operand (register R6) is readable */ 12037 err = check_reg_arg(env, ctx_reg, SRC_OP); 12038 if (err) 12039 return err; 12040 12041 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 12042 * gen_ld_abs() may terminate the program at runtime, leading to 12043 * reference leak. 12044 */ 12045 err = check_reference_leak(env); 12046 if (err) { 12047 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 12048 return err; 12049 } 12050 12051 if (env->cur_state->active_lock.ptr) { 12052 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 12053 return -EINVAL; 12054 } 12055 12056 if (env->cur_state->active_rcu_lock) { 12057 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 12058 return -EINVAL; 12059 } 12060 12061 if (regs[ctx_reg].type != PTR_TO_CTX) { 12062 verbose(env, 12063 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 12064 return -EINVAL; 12065 } 12066 12067 if (mode == BPF_IND) { 12068 /* check explicit source operand */ 12069 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12070 if (err) 12071 return err; 12072 } 12073 12074 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 12075 if (err < 0) 12076 return err; 12077 12078 /* reset caller saved regs to unreadable */ 12079 for (i = 0; i < CALLER_SAVED_REGS; i++) { 12080 mark_reg_not_init(env, regs, caller_saved[i]); 12081 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 12082 } 12083 12084 /* mark destination R0 register as readable, since it contains 12085 * the value fetched from the packet. 12086 * Already marked as written above. 12087 */ 12088 mark_reg_unknown(env, regs, BPF_REG_0); 12089 /* ld_abs load up to 32-bit skb data. */ 12090 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 12091 return 0; 12092 } 12093 12094 static int check_return_code(struct bpf_verifier_env *env) 12095 { 12096 struct tnum enforce_attach_type_range = tnum_unknown; 12097 const struct bpf_prog *prog = env->prog; 12098 struct bpf_reg_state *reg; 12099 struct tnum range = tnum_range(0, 1); 12100 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12101 int err; 12102 struct bpf_func_state *frame = env->cur_state->frame[0]; 12103 const bool is_subprog = frame->subprogno; 12104 12105 /* LSM and struct_ops func-ptr's return type could be "void" */ 12106 if (!is_subprog) { 12107 switch (prog_type) { 12108 case BPF_PROG_TYPE_LSM: 12109 if (prog->expected_attach_type == BPF_LSM_CGROUP) 12110 /* See below, can be 0 or 0-1 depending on hook. */ 12111 break; 12112 fallthrough; 12113 case BPF_PROG_TYPE_STRUCT_OPS: 12114 if (!prog->aux->attach_func_proto->type) 12115 return 0; 12116 break; 12117 default: 12118 break; 12119 } 12120 } 12121 12122 /* eBPF calling convention is such that R0 is used 12123 * to return the value from eBPF program. 12124 * Make sure that it's readable at this time 12125 * of bpf_exit, which means that program wrote 12126 * something into it earlier 12127 */ 12128 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 12129 if (err) 12130 return err; 12131 12132 if (is_pointer_value(env, BPF_REG_0)) { 12133 verbose(env, "R0 leaks addr as return value\n"); 12134 return -EACCES; 12135 } 12136 12137 reg = cur_regs(env) + BPF_REG_0; 12138 12139 if (frame->in_async_callback_fn) { 12140 /* enforce return zero from async callbacks like timer */ 12141 if (reg->type != SCALAR_VALUE) { 12142 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 12143 reg_type_str(env, reg->type)); 12144 return -EINVAL; 12145 } 12146 12147 if (!tnum_in(tnum_const(0), reg->var_off)) { 12148 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 12149 return -EINVAL; 12150 } 12151 return 0; 12152 } 12153 12154 if (is_subprog) { 12155 if (reg->type != SCALAR_VALUE) { 12156 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 12157 reg_type_str(env, reg->type)); 12158 return -EINVAL; 12159 } 12160 return 0; 12161 } 12162 12163 switch (prog_type) { 12164 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 12165 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 12166 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 12167 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 12168 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 12169 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 12170 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 12171 range = tnum_range(1, 1); 12172 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 12173 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 12174 range = tnum_range(0, 3); 12175 break; 12176 case BPF_PROG_TYPE_CGROUP_SKB: 12177 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 12178 range = tnum_range(0, 3); 12179 enforce_attach_type_range = tnum_range(2, 3); 12180 } 12181 break; 12182 case BPF_PROG_TYPE_CGROUP_SOCK: 12183 case BPF_PROG_TYPE_SOCK_OPS: 12184 case BPF_PROG_TYPE_CGROUP_DEVICE: 12185 case BPF_PROG_TYPE_CGROUP_SYSCTL: 12186 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 12187 break; 12188 case BPF_PROG_TYPE_RAW_TRACEPOINT: 12189 if (!env->prog->aux->attach_btf_id) 12190 return 0; 12191 range = tnum_const(0); 12192 break; 12193 case BPF_PROG_TYPE_TRACING: 12194 switch (env->prog->expected_attach_type) { 12195 case BPF_TRACE_FENTRY: 12196 case BPF_TRACE_FEXIT: 12197 range = tnum_const(0); 12198 break; 12199 case BPF_TRACE_RAW_TP: 12200 case BPF_MODIFY_RETURN: 12201 return 0; 12202 case BPF_TRACE_ITER: 12203 break; 12204 default: 12205 return -ENOTSUPP; 12206 } 12207 break; 12208 case BPF_PROG_TYPE_SK_LOOKUP: 12209 range = tnum_range(SK_DROP, SK_PASS); 12210 break; 12211 12212 case BPF_PROG_TYPE_LSM: 12213 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 12214 /* Regular BPF_PROG_TYPE_LSM programs can return 12215 * any value. 12216 */ 12217 return 0; 12218 } 12219 if (!env->prog->aux->attach_func_proto->type) { 12220 /* Make sure programs that attach to void 12221 * hooks don't try to modify return value. 12222 */ 12223 range = tnum_range(1, 1); 12224 } 12225 break; 12226 12227 case BPF_PROG_TYPE_EXT: 12228 /* freplace program can return anything as its return value 12229 * depends on the to-be-replaced kernel func or bpf program. 12230 */ 12231 default: 12232 return 0; 12233 } 12234 12235 if (reg->type != SCALAR_VALUE) { 12236 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 12237 reg_type_str(env, reg->type)); 12238 return -EINVAL; 12239 } 12240 12241 if (!tnum_in(range, reg->var_off)) { 12242 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 12243 if (prog->expected_attach_type == BPF_LSM_CGROUP && 12244 prog_type == BPF_PROG_TYPE_LSM && 12245 !prog->aux->attach_func_proto->type) 12246 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 12247 return -EINVAL; 12248 } 12249 12250 if (!tnum_is_unknown(enforce_attach_type_range) && 12251 tnum_in(enforce_attach_type_range, reg->var_off)) 12252 env->prog->enforce_expected_attach_type = 1; 12253 return 0; 12254 } 12255 12256 /* non-recursive DFS pseudo code 12257 * 1 procedure DFS-iterative(G,v): 12258 * 2 label v as discovered 12259 * 3 let S be a stack 12260 * 4 S.push(v) 12261 * 5 while S is not empty 12262 * 6 t <- S.peek() 12263 * 7 if t is what we're looking for: 12264 * 8 return t 12265 * 9 for all edges e in G.adjacentEdges(t) do 12266 * 10 if edge e is already labelled 12267 * 11 continue with the next edge 12268 * 12 w <- G.adjacentVertex(t,e) 12269 * 13 if vertex w is not discovered and not explored 12270 * 14 label e as tree-edge 12271 * 15 label w as discovered 12272 * 16 S.push(w) 12273 * 17 continue at 5 12274 * 18 else if vertex w is discovered 12275 * 19 label e as back-edge 12276 * 20 else 12277 * 21 // vertex w is explored 12278 * 22 label e as forward- or cross-edge 12279 * 23 label t as explored 12280 * 24 S.pop() 12281 * 12282 * convention: 12283 * 0x10 - discovered 12284 * 0x11 - discovered and fall-through edge labelled 12285 * 0x12 - discovered and fall-through and branch edges labelled 12286 * 0x20 - explored 12287 */ 12288 12289 enum { 12290 DISCOVERED = 0x10, 12291 EXPLORED = 0x20, 12292 FALLTHROUGH = 1, 12293 BRANCH = 2, 12294 }; 12295 12296 static u32 state_htab_size(struct bpf_verifier_env *env) 12297 { 12298 return env->prog->len; 12299 } 12300 12301 static struct bpf_verifier_state_list **explored_state( 12302 struct bpf_verifier_env *env, 12303 int idx) 12304 { 12305 struct bpf_verifier_state *cur = env->cur_state; 12306 struct bpf_func_state *state = cur->frame[cur->curframe]; 12307 12308 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 12309 } 12310 12311 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 12312 { 12313 env->insn_aux_data[idx].prune_point = true; 12314 } 12315 12316 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 12317 { 12318 return env->insn_aux_data[insn_idx].prune_point; 12319 } 12320 12321 enum { 12322 DONE_EXPLORING = 0, 12323 KEEP_EXPLORING = 1, 12324 }; 12325 12326 /* t, w, e - match pseudo-code above: 12327 * t - index of current instruction 12328 * w - next instruction 12329 * e - edge 12330 */ 12331 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 12332 bool loop_ok) 12333 { 12334 int *insn_stack = env->cfg.insn_stack; 12335 int *insn_state = env->cfg.insn_state; 12336 12337 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 12338 return DONE_EXPLORING; 12339 12340 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 12341 return DONE_EXPLORING; 12342 12343 if (w < 0 || w >= env->prog->len) { 12344 verbose_linfo(env, t, "%d: ", t); 12345 verbose(env, "jump out of range from insn %d to %d\n", t, w); 12346 return -EINVAL; 12347 } 12348 12349 if (e == BRANCH) { 12350 /* mark branch target for state pruning */ 12351 mark_prune_point(env, w); 12352 mark_jmp_point(env, w); 12353 } 12354 12355 if (insn_state[w] == 0) { 12356 /* tree-edge */ 12357 insn_state[t] = DISCOVERED | e; 12358 insn_state[w] = DISCOVERED; 12359 if (env->cfg.cur_stack >= env->prog->len) 12360 return -E2BIG; 12361 insn_stack[env->cfg.cur_stack++] = w; 12362 return KEEP_EXPLORING; 12363 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 12364 if (loop_ok && env->bpf_capable) 12365 return DONE_EXPLORING; 12366 verbose_linfo(env, t, "%d: ", t); 12367 verbose_linfo(env, w, "%d: ", w); 12368 verbose(env, "back-edge from insn %d to %d\n", t, w); 12369 return -EINVAL; 12370 } else if (insn_state[w] == EXPLORED) { 12371 /* forward- or cross-edge */ 12372 insn_state[t] = DISCOVERED | e; 12373 } else { 12374 verbose(env, "insn state internal bug\n"); 12375 return -EFAULT; 12376 } 12377 return DONE_EXPLORING; 12378 } 12379 12380 static int visit_func_call_insn(int t, struct bpf_insn *insns, 12381 struct bpf_verifier_env *env, 12382 bool visit_callee) 12383 { 12384 int ret; 12385 12386 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 12387 if (ret) 12388 return ret; 12389 12390 mark_prune_point(env, t + 1); 12391 /* when we exit from subprog, we need to record non-linear history */ 12392 mark_jmp_point(env, t + 1); 12393 12394 if (visit_callee) { 12395 mark_prune_point(env, t); 12396 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 12397 /* It's ok to allow recursion from CFG point of 12398 * view. __check_func_call() will do the actual 12399 * check. 12400 */ 12401 bpf_pseudo_func(insns + t)); 12402 } 12403 return ret; 12404 } 12405 12406 /* Visits the instruction at index t and returns one of the following: 12407 * < 0 - an error occurred 12408 * DONE_EXPLORING - the instruction was fully explored 12409 * KEEP_EXPLORING - there is still work to be done before it is fully explored 12410 */ 12411 static int visit_insn(int t, struct bpf_verifier_env *env) 12412 { 12413 struct bpf_insn *insns = env->prog->insnsi; 12414 int ret; 12415 12416 if (bpf_pseudo_func(insns + t)) 12417 return visit_func_call_insn(t, insns, env, true); 12418 12419 /* All non-branch instructions have a single fall-through edge. */ 12420 if (BPF_CLASS(insns[t].code) != BPF_JMP && 12421 BPF_CLASS(insns[t].code) != BPF_JMP32) 12422 return push_insn(t, t + 1, FALLTHROUGH, env, false); 12423 12424 switch (BPF_OP(insns[t].code)) { 12425 case BPF_EXIT: 12426 return DONE_EXPLORING; 12427 12428 case BPF_CALL: 12429 if (insns[t].imm == BPF_FUNC_timer_set_callback) 12430 /* Mark this call insn as a prune point to trigger 12431 * is_state_visited() check before call itself is 12432 * processed by __check_func_call(). Otherwise new 12433 * async state will be pushed for further exploration. 12434 */ 12435 mark_prune_point(env, t); 12436 return visit_func_call_insn(t, insns, env, 12437 insns[t].src_reg == BPF_PSEUDO_CALL); 12438 12439 case BPF_JA: 12440 if (BPF_SRC(insns[t].code) != BPF_K) 12441 return -EINVAL; 12442 12443 /* unconditional jump with single edge */ 12444 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env, 12445 true); 12446 if (ret) 12447 return ret; 12448 12449 mark_prune_point(env, t + insns[t].off + 1); 12450 mark_jmp_point(env, t + insns[t].off + 1); 12451 12452 return ret; 12453 12454 default: 12455 /* conditional jump with two edges */ 12456 mark_prune_point(env, t); 12457 12458 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 12459 if (ret) 12460 return ret; 12461 12462 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true); 12463 } 12464 } 12465 12466 /* non-recursive depth-first-search to detect loops in BPF program 12467 * loop == back-edge in directed graph 12468 */ 12469 static int check_cfg(struct bpf_verifier_env *env) 12470 { 12471 int insn_cnt = env->prog->len; 12472 int *insn_stack, *insn_state; 12473 int ret = 0; 12474 int i; 12475 12476 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 12477 if (!insn_state) 12478 return -ENOMEM; 12479 12480 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 12481 if (!insn_stack) { 12482 kvfree(insn_state); 12483 return -ENOMEM; 12484 } 12485 12486 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 12487 insn_stack[0] = 0; /* 0 is the first instruction */ 12488 env->cfg.cur_stack = 1; 12489 12490 while (env->cfg.cur_stack > 0) { 12491 int t = insn_stack[env->cfg.cur_stack - 1]; 12492 12493 ret = visit_insn(t, env); 12494 switch (ret) { 12495 case DONE_EXPLORING: 12496 insn_state[t] = EXPLORED; 12497 env->cfg.cur_stack--; 12498 break; 12499 case KEEP_EXPLORING: 12500 break; 12501 default: 12502 if (ret > 0) { 12503 verbose(env, "visit_insn internal bug\n"); 12504 ret = -EFAULT; 12505 } 12506 goto err_free; 12507 } 12508 } 12509 12510 if (env->cfg.cur_stack < 0) { 12511 verbose(env, "pop stack internal bug\n"); 12512 ret = -EFAULT; 12513 goto err_free; 12514 } 12515 12516 for (i = 0; i < insn_cnt; i++) { 12517 if (insn_state[i] != EXPLORED) { 12518 verbose(env, "unreachable insn %d\n", i); 12519 ret = -EINVAL; 12520 goto err_free; 12521 } 12522 } 12523 ret = 0; /* cfg looks good */ 12524 12525 err_free: 12526 kvfree(insn_state); 12527 kvfree(insn_stack); 12528 env->cfg.insn_state = env->cfg.insn_stack = NULL; 12529 return ret; 12530 } 12531 12532 static int check_abnormal_return(struct bpf_verifier_env *env) 12533 { 12534 int i; 12535 12536 for (i = 1; i < env->subprog_cnt; i++) { 12537 if (env->subprog_info[i].has_ld_abs) { 12538 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 12539 return -EINVAL; 12540 } 12541 if (env->subprog_info[i].has_tail_call) { 12542 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 12543 return -EINVAL; 12544 } 12545 } 12546 return 0; 12547 } 12548 12549 /* The minimum supported BTF func info size */ 12550 #define MIN_BPF_FUNCINFO_SIZE 8 12551 #define MAX_FUNCINFO_REC_SIZE 252 12552 12553 static int check_btf_func(struct bpf_verifier_env *env, 12554 const union bpf_attr *attr, 12555 bpfptr_t uattr) 12556 { 12557 const struct btf_type *type, *func_proto, *ret_type; 12558 u32 i, nfuncs, urec_size, min_size; 12559 u32 krec_size = sizeof(struct bpf_func_info); 12560 struct bpf_func_info *krecord; 12561 struct bpf_func_info_aux *info_aux = NULL; 12562 struct bpf_prog *prog; 12563 const struct btf *btf; 12564 bpfptr_t urecord; 12565 u32 prev_offset = 0; 12566 bool scalar_return; 12567 int ret = -ENOMEM; 12568 12569 nfuncs = attr->func_info_cnt; 12570 if (!nfuncs) { 12571 if (check_abnormal_return(env)) 12572 return -EINVAL; 12573 return 0; 12574 } 12575 12576 if (nfuncs != env->subprog_cnt) { 12577 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 12578 return -EINVAL; 12579 } 12580 12581 urec_size = attr->func_info_rec_size; 12582 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 12583 urec_size > MAX_FUNCINFO_REC_SIZE || 12584 urec_size % sizeof(u32)) { 12585 verbose(env, "invalid func info rec size %u\n", urec_size); 12586 return -EINVAL; 12587 } 12588 12589 prog = env->prog; 12590 btf = prog->aux->btf; 12591 12592 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 12593 min_size = min_t(u32, krec_size, urec_size); 12594 12595 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 12596 if (!krecord) 12597 return -ENOMEM; 12598 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 12599 if (!info_aux) 12600 goto err_free; 12601 12602 for (i = 0; i < nfuncs; i++) { 12603 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 12604 if (ret) { 12605 if (ret == -E2BIG) { 12606 verbose(env, "nonzero tailing record in func info"); 12607 /* set the size kernel expects so loader can zero 12608 * out the rest of the record. 12609 */ 12610 if (copy_to_bpfptr_offset(uattr, 12611 offsetof(union bpf_attr, func_info_rec_size), 12612 &min_size, sizeof(min_size))) 12613 ret = -EFAULT; 12614 } 12615 goto err_free; 12616 } 12617 12618 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 12619 ret = -EFAULT; 12620 goto err_free; 12621 } 12622 12623 /* check insn_off */ 12624 ret = -EINVAL; 12625 if (i == 0) { 12626 if (krecord[i].insn_off) { 12627 verbose(env, 12628 "nonzero insn_off %u for the first func info record", 12629 krecord[i].insn_off); 12630 goto err_free; 12631 } 12632 } else if (krecord[i].insn_off <= prev_offset) { 12633 verbose(env, 12634 "same or smaller insn offset (%u) than previous func info record (%u)", 12635 krecord[i].insn_off, prev_offset); 12636 goto err_free; 12637 } 12638 12639 if (env->subprog_info[i].start != krecord[i].insn_off) { 12640 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 12641 goto err_free; 12642 } 12643 12644 /* check type_id */ 12645 type = btf_type_by_id(btf, krecord[i].type_id); 12646 if (!type || !btf_type_is_func(type)) { 12647 verbose(env, "invalid type id %d in func info", 12648 krecord[i].type_id); 12649 goto err_free; 12650 } 12651 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 12652 12653 func_proto = btf_type_by_id(btf, type->type); 12654 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 12655 /* btf_func_check() already verified it during BTF load */ 12656 goto err_free; 12657 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 12658 scalar_return = 12659 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 12660 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 12661 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 12662 goto err_free; 12663 } 12664 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 12665 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 12666 goto err_free; 12667 } 12668 12669 prev_offset = krecord[i].insn_off; 12670 bpfptr_add(&urecord, urec_size); 12671 } 12672 12673 prog->aux->func_info = krecord; 12674 prog->aux->func_info_cnt = nfuncs; 12675 prog->aux->func_info_aux = info_aux; 12676 return 0; 12677 12678 err_free: 12679 kvfree(krecord); 12680 kfree(info_aux); 12681 return ret; 12682 } 12683 12684 static void adjust_btf_func(struct bpf_verifier_env *env) 12685 { 12686 struct bpf_prog_aux *aux = env->prog->aux; 12687 int i; 12688 12689 if (!aux->func_info) 12690 return; 12691 12692 for (i = 0; i < env->subprog_cnt; i++) 12693 aux->func_info[i].insn_off = env->subprog_info[i].start; 12694 } 12695 12696 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 12697 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 12698 12699 static int check_btf_line(struct bpf_verifier_env *env, 12700 const union bpf_attr *attr, 12701 bpfptr_t uattr) 12702 { 12703 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 12704 struct bpf_subprog_info *sub; 12705 struct bpf_line_info *linfo; 12706 struct bpf_prog *prog; 12707 const struct btf *btf; 12708 bpfptr_t ulinfo; 12709 int err; 12710 12711 nr_linfo = attr->line_info_cnt; 12712 if (!nr_linfo) 12713 return 0; 12714 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 12715 return -EINVAL; 12716 12717 rec_size = attr->line_info_rec_size; 12718 if (rec_size < MIN_BPF_LINEINFO_SIZE || 12719 rec_size > MAX_LINEINFO_REC_SIZE || 12720 rec_size & (sizeof(u32) - 1)) 12721 return -EINVAL; 12722 12723 /* Need to zero it in case the userspace may 12724 * pass in a smaller bpf_line_info object. 12725 */ 12726 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 12727 GFP_KERNEL | __GFP_NOWARN); 12728 if (!linfo) 12729 return -ENOMEM; 12730 12731 prog = env->prog; 12732 btf = prog->aux->btf; 12733 12734 s = 0; 12735 sub = env->subprog_info; 12736 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 12737 expected_size = sizeof(struct bpf_line_info); 12738 ncopy = min_t(u32, expected_size, rec_size); 12739 for (i = 0; i < nr_linfo; i++) { 12740 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 12741 if (err) { 12742 if (err == -E2BIG) { 12743 verbose(env, "nonzero tailing record in line_info"); 12744 if (copy_to_bpfptr_offset(uattr, 12745 offsetof(union bpf_attr, line_info_rec_size), 12746 &expected_size, sizeof(expected_size))) 12747 err = -EFAULT; 12748 } 12749 goto err_free; 12750 } 12751 12752 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 12753 err = -EFAULT; 12754 goto err_free; 12755 } 12756 12757 /* 12758 * Check insn_off to ensure 12759 * 1) strictly increasing AND 12760 * 2) bounded by prog->len 12761 * 12762 * The linfo[0].insn_off == 0 check logically falls into 12763 * the later "missing bpf_line_info for func..." case 12764 * because the first linfo[0].insn_off must be the 12765 * first sub also and the first sub must have 12766 * subprog_info[0].start == 0. 12767 */ 12768 if ((i && linfo[i].insn_off <= prev_offset) || 12769 linfo[i].insn_off >= prog->len) { 12770 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 12771 i, linfo[i].insn_off, prev_offset, 12772 prog->len); 12773 err = -EINVAL; 12774 goto err_free; 12775 } 12776 12777 if (!prog->insnsi[linfo[i].insn_off].code) { 12778 verbose(env, 12779 "Invalid insn code at line_info[%u].insn_off\n", 12780 i); 12781 err = -EINVAL; 12782 goto err_free; 12783 } 12784 12785 if (!btf_name_by_offset(btf, linfo[i].line_off) || 12786 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 12787 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 12788 err = -EINVAL; 12789 goto err_free; 12790 } 12791 12792 if (s != env->subprog_cnt) { 12793 if (linfo[i].insn_off == sub[s].start) { 12794 sub[s].linfo_idx = i; 12795 s++; 12796 } else if (sub[s].start < linfo[i].insn_off) { 12797 verbose(env, "missing bpf_line_info for func#%u\n", s); 12798 err = -EINVAL; 12799 goto err_free; 12800 } 12801 } 12802 12803 prev_offset = linfo[i].insn_off; 12804 bpfptr_add(&ulinfo, rec_size); 12805 } 12806 12807 if (s != env->subprog_cnt) { 12808 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 12809 env->subprog_cnt - s, s); 12810 err = -EINVAL; 12811 goto err_free; 12812 } 12813 12814 prog->aux->linfo = linfo; 12815 prog->aux->nr_linfo = nr_linfo; 12816 12817 return 0; 12818 12819 err_free: 12820 kvfree(linfo); 12821 return err; 12822 } 12823 12824 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 12825 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 12826 12827 static int check_core_relo(struct bpf_verifier_env *env, 12828 const union bpf_attr *attr, 12829 bpfptr_t uattr) 12830 { 12831 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 12832 struct bpf_core_relo core_relo = {}; 12833 struct bpf_prog *prog = env->prog; 12834 const struct btf *btf = prog->aux->btf; 12835 struct bpf_core_ctx ctx = { 12836 .log = &env->log, 12837 .btf = btf, 12838 }; 12839 bpfptr_t u_core_relo; 12840 int err; 12841 12842 nr_core_relo = attr->core_relo_cnt; 12843 if (!nr_core_relo) 12844 return 0; 12845 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 12846 return -EINVAL; 12847 12848 rec_size = attr->core_relo_rec_size; 12849 if (rec_size < MIN_CORE_RELO_SIZE || 12850 rec_size > MAX_CORE_RELO_SIZE || 12851 rec_size % sizeof(u32)) 12852 return -EINVAL; 12853 12854 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 12855 expected_size = sizeof(struct bpf_core_relo); 12856 ncopy = min_t(u32, expected_size, rec_size); 12857 12858 /* Unlike func_info and line_info, copy and apply each CO-RE 12859 * relocation record one at a time. 12860 */ 12861 for (i = 0; i < nr_core_relo; i++) { 12862 /* future proofing when sizeof(bpf_core_relo) changes */ 12863 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 12864 if (err) { 12865 if (err == -E2BIG) { 12866 verbose(env, "nonzero tailing record in core_relo"); 12867 if (copy_to_bpfptr_offset(uattr, 12868 offsetof(union bpf_attr, core_relo_rec_size), 12869 &expected_size, sizeof(expected_size))) 12870 err = -EFAULT; 12871 } 12872 break; 12873 } 12874 12875 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 12876 err = -EFAULT; 12877 break; 12878 } 12879 12880 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 12881 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 12882 i, core_relo.insn_off, prog->len); 12883 err = -EINVAL; 12884 break; 12885 } 12886 12887 err = bpf_core_apply(&ctx, &core_relo, i, 12888 &prog->insnsi[core_relo.insn_off / 8]); 12889 if (err) 12890 break; 12891 bpfptr_add(&u_core_relo, rec_size); 12892 } 12893 return err; 12894 } 12895 12896 static int check_btf_info(struct bpf_verifier_env *env, 12897 const union bpf_attr *attr, 12898 bpfptr_t uattr) 12899 { 12900 struct btf *btf; 12901 int err; 12902 12903 if (!attr->func_info_cnt && !attr->line_info_cnt) { 12904 if (check_abnormal_return(env)) 12905 return -EINVAL; 12906 return 0; 12907 } 12908 12909 btf = btf_get_by_fd(attr->prog_btf_fd); 12910 if (IS_ERR(btf)) 12911 return PTR_ERR(btf); 12912 if (btf_is_kernel(btf)) { 12913 btf_put(btf); 12914 return -EACCES; 12915 } 12916 env->prog->aux->btf = btf; 12917 12918 err = check_btf_func(env, attr, uattr); 12919 if (err) 12920 return err; 12921 12922 err = check_btf_line(env, attr, uattr); 12923 if (err) 12924 return err; 12925 12926 err = check_core_relo(env, attr, uattr); 12927 if (err) 12928 return err; 12929 12930 return 0; 12931 } 12932 12933 /* check %cur's range satisfies %old's */ 12934 static bool range_within(struct bpf_reg_state *old, 12935 struct bpf_reg_state *cur) 12936 { 12937 return old->umin_value <= cur->umin_value && 12938 old->umax_value >= cur->umax_value && 12939 old->smin_value <= cur->smin_value && 12940 old->smax_value >= cur->smax_value && 12941 old->u32_min_value <= cur->u32_min_value && 12942 old->u32_max_value >= cur->u32_max_value && 12943 old->s32_min_value <= cur->s32_min_value && 12944 old->s32_max_value >= cur->s32_max_value; 12945 } 12946 12947 /* If in the old state two registers had the same id, then they need to have 12948 * the same id in the new state as well. But that id could be different from 12949 * the old state, so we need to track the mapping from old to new ids. 12950 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 12951 * regs with old id 5 must also have new id 9 for the new state to be safe. But 12952 * regs with a different old id could still have new id 9, we don't care about 12953 * that. 12954 * So we look through our idmap to see if this old id has been seen before. If 12955 * so, we require the new id to match; otherwise, we add the id pair to the map. 12956 */ 12957 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap) 12958 { 12959 unsigned int i; 12960 12961 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 12962 if (!idmap[i].old) { 12963 /* Reached an empty slot; haven't seen this id before */ 12964 idmap[i].old = old_id; 12965 idmap[i].cur = cur_id; 12966 return true; 12967 } 12968 if (idmap[i].old == old_id) 12969 return idmap[i].cur == cur_id; 12970 } 12971 /* We ran out of idmap slots, which should be impossible */ 12972 WARN_ON_ONCE(1); 12973 return false; 12974 } 12975 12976 static void clean_func_state(struct bpf_verifier_env *env, 12977 struct bpf_func_state *st) 12978 { 12979 enum bpf_reg_liveness live; 12980 int i, j; 12981 12982 for (i = 0; i < BPF_REG_FP; i++) { 12983 live = st->regs[i].live; 12984 /* liveness must not touch this register anymore */ 12985 st->regs[i].live |= REG_LIVE_DONE; 12986 if (!(live & REG_LIVE_READ)) 12987 /* since the register is unused, clear its state 12988 * to make further comparison simpler 12989 */ 12990 __mark_reg_not_init(env, &st->regs[i]); 12991 } 12992 12993 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 12994 live = st->stack[i].spilled_ptr.live; 12995 /* liveness must not touch this stack slot anymore */ 12996 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 12997 if (!(live & REG_LIVE_READ)) { 12998 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 12999 for (j = 0; j < BPF_REG_SIZE; j++) 13000 st->stack[i].slot_type[j] = STACK_INVALID; 13001 } 13002 } 13003 } 13004 13005 static void clean_verifier_state(struct bpf_verifier_env *env, 13006 struct bpf_verifier_state *st) 13007 { 13008 int i; 13009 13010 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 13011 /* all regs in this state in all frames were already marked */ 13012 return; 13013 13014 for (i = 0; i <= st->curframe; i++) 13015 clean_func_state(env, st->frame[i]); 13016 } 13017 13018 /* the parentage chains form a tree. 13019 * the verifier states are added to state lists at given insn and 13020 * pushed into state stack for future exploration. 13021 * when the verifier reaches bpf_exit insn some of the verifer states 13022 * stored in the state lists have their final liveness state already, 13023 * but a lot of states will get revised from liveness point of view when 13024 * the verifier explores other branches. 13025 * Example: 13026 * 1: r0 = 1 13027 * 2: if r1 == 100 goto pc+1 13028 * 3: r0 = 2 13029 * 4: exit 13030 * when the verifier reaches exit insn the register r0 in the state list of 13031 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 13032 * of insn 2 and goes exploring further. At the insn 4 it will walk the 13033 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 13034 * 13035 * Since the verifier pushes the branch states as it sees them while exploring 13036 * the program the condition of walking the branch instruction for the second 13037 * time means that all states below this branch were already explored and 13038 * their final liveness marks are already propagated. 13039 * Hence when the verifier completes the search of state list in is_state_visited() 13040 * we can call this clean_live_states() function to mark all liveness states 13041 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 13042 * will not be used. 13043 * This function also clears the registers and stack for states that !READ 13044 * to simplify state merging. 13045 * 13046 * Important note here that walking the same branch instruction in the callee 13047 * doesn't meant that the states are DONE. The verifier has to compare 13048 * the callsites 13049 */ 13050 static void clean_live_states(struct bpf_verifier_env *env, int insn, 13051 struct bpf_verifier_state *cur) 13052 { 13053 struct bpf_verifier_state_list *sl; 13054 int i; 13055 13056 sl = *explored_state(env, insn); 13057 while (sl) { 13058 if (sl->state.branches) 13059 goto next; 13060 if (sl->state.insn_idx != insn || 13061 sl->state.curframe != cur->curframe) 13062 goto next; 13063 for (i = 0; i <= cur->curframe; i++) 13064 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 13065 goto next; 13066 clean_verifier_state(env, &sl->state); 13067 next: 13068 sl = sl->next; 13069 } 13070 } 13071 13072 /* Returns true if (rold safe implies rcur safe) */ 13073 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 13074 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap) 13075 { 13076 bool equal; 13077 13078 if (!(rold->live & REG_LIVE_READ)) 13079 /* explored state didn't use this */ 13080 return true; 13081 13082 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0; 13083 13084 if (rold->type == NOT_INIT) 13085 /* explored state can't have used this */ 13086 return true; 13087 if (rcur->type == NOT_INIT) 13088 return false; 13089 switch (base_type(rold->type)) { 13090 case SCALAR_VALUE: 13091 if (equal) 13092 return true; 13093 if (env->explore_alu_limits) 13094 return false; 13095 if (rcur->type == SCALAR_VALUE) { 13096 if (!rold->precise) 13097 return true; 13098 /* new val must satisfy old val knowledge */ 13099 return range_within(rold, rcur) && 13100 tnum_in(rold->var_off, rcur->var_off); 13101 } else { 13102 /* We're trying to use a pointer in place of a scalar. 13103 * Even if the scalar was unbounded, this could lead to 13104 * pointer leaks because scalars are allowed to leak 13105 * while pointers are not. We could make this safe in 13106 * special cases if root is calling us, but it's 13107 * probably not worth the hassle. 13108 */ 13109 return false; 13110 } 13111 case PTR_TO_MAP_KEY: 13112 case PTR_TO_MAP_VALUE: 13113 /* a PTR_TO_MAP_VALUE could be safe to use as a 13114 * PTR_TO_MAP_VALUE_OR_NULL into the same map. 13115 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- 13116 * checked, doing so could have affected others with the same 13117 * id, and we can't check for that because we lost the id when 13118 * we converted to a PTR_TO_MAP_VALUE. 13119 */ 13120 if (type_may_be_null(rold->type)) { 13121 if (!type_may_be_null(rcur->type)) 13122 return false; 13123 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) 13124 return false; 13125 /* Check our ids match any regs they're supposed to */ 13126 return check_ids(rold->id, rcur->id, idmap); 13127 } 13128 13129 /* If the new min/max/var_off satisfy the old ones and 13130 * everything else matches, we are OK. 13131 * 'id' is not compared, since it's only used for maps with 13132 * bpf_spin_lock inside map element and in such cases if 13133 * the rest of the prog is valid for one map element then 13134 * it's valid for all map elements regardless of the key 13135 * used in bpf_map_lookup() 13136 */ 13137 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 13138 range_within(rold, rcur) && 13139 tnum_in(rold->var_off, rcur->var_off) && 13140 check_ids(rold->id, rcur->id, idmap); 13141 case PTR_TO_PACKET_META: 13142 case PTR_TO_PACKET: 13143 if (rcur->type != rold->type) 13144 return false; 13145 /* We must have at least as much range as the old ptr 13146 * did, so that any accesses which were safe before are 13147 * still safe. This is true even if old range < old off, 13148 * since someone could have accessed through (ptr - k), or 13149 * even done ptr -= k in a register, to get a safe access. 13150 */ 13151 if (rold->range > rcur->range) 13152 return false; 13153 /* If the offsets don't match, we can't trust our alignment; 13154 * nor can we be sure that we won't fall out of range. 13155 */ 13156 if (rold->off != rcur->off) 13157 return false; 13158 /* id relations must be preserved */ 13159 if (rold->id && !check_ids(rold->id, rcur->id, idmap)) 13160 return false; 13161 /* new val must satisfy old val knowledge */ 13162 return range_within(rold, rcur) && 13163 tnum_in(rold->var_off, rcur->var_off); 13164 case PTR_TO_STACK: 13165 /* two stack pointers are equal only if they're pointing to 13166 * the same stack frame, since fp-8 in foo != fp-8 in bar 13167 */ 13168 return equal && rold->frameno == rcur->frameno; 13169 default: 13170 /* Only valid matches are exact, which memcmp() */ 13171 return equal; 13172 } 13173 13174 /* Shouldn't get here; if we do, say it's not safe */ 13175 WARN_ON_ONCE(1); 13176 return false; 13177 } 13178 13179 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 13180 struct bpf_func_state *cur, struct bpf_id_pair *idmap) 13181 { 13182 int i, spi; 13183 13184 /* walk slots of the explored stack and ignore any additional 13185 * slots in the current stack, since explored(safe) state 13186 * didn't use them 13187 */ 13188 for (i = 0; i < old->allocated_stack; i++) { 13189 spi = i / BPF_REG_SIZE; 13190 13191 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 13192 i += BPF_REG_SIZE - 1; 13193 /* explored state didn't use this */ 13194 continue; 13195 } 13196 13197 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 13198 continue; 13199 13200 /* explored stack has more populated slots than current stack 13201 * and these slots were used 13202 */ 13203 if (i >= cur->allocated_stack) 13204 return false; 13205 13206 /* if old state was safe with misc data in the stack 13207 * it will be safe with zero-initialized stack. 13208 * The opposite is not true 13209 */ 13210 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 13211 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 13212 continue; 13213 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 13214 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 13215 /* Ex: old explored (safe) state has STACK_SPILL in 13216 * this stack slot, but current has STACK_MISC -> 13217 * this verifier states are not equivalent, 13218 * return false to continue verification of this path 13219 */ 13220 return false; 13221 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 13222 continue; 13223 if (!is_spilled_reg(&old->stack[spi])) 13224 continue; 13225 if (!regsafe(env, &old->stack[spi].spilled_ptr, 13226 &cur->stack[spi].spilled_ptr, idmap)) 13227 /* when explored and current stack slot are both storing 13228 * spilled registers, check that stored pointers types 13229 * are the same as well. 13230 * Ex: explored safe path could have stored 13231 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 13232 * but current path has stored: 13233 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 13234 * such verifier states are not equivalent. 13235 * return false to continue verification of this path 13236 */ 13237 return false; 13238 } 13239 return true; 13240 } 13241 13242 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur) 13243 { 13244 if (old->acquired_refs != cur->acquired_refs) 13245 return false; 13246 return !memcmp(old->refs, cur->refs, 13247 sizeof(*old->refs) * old->acquired_refs); 13248 } 13249 13250 /* compare two verifier states 13251 * 13252 * all states stored in state_list are known to be valid, since 13253 * verifier reached 'bpf_exit' instruction through them 13254 * 13255 * this function is called when verifier exploring different branches of 13256 * execution popped from the state stack. If it sees an old state that has 13257 * more strict register state and more strict stack state then this execution 13258 * branch doesn't need to be explored further, since verifier already 13259 * concluded that more strict state leads to valid finish. 13260 * 13261 * Therefore two states are equivalent if register state is more conservative 13262 * and explored stack state is more conservative than the current one. 13263 * Example: 13264 * explored current 13265 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 13266 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 13267 * 13268 * In other words if current stack state (one being explored) has more 13269 * valid slots than old one that already passed validation, it means 13270 * the verifier can stop exploring and conclude that current state is valid too 13271 * 13272 * Similarly with registers. If explored state has register type as invalid 13273 * whereas register type in current state is meaningful, it means that 13274 * the current state will reach 'bpf_exit' instruction safely 13275 */ 13276 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 13277 struct bpf_func_state *cur) 13278 { 13279 int i; 13280 13281 for (i = 0; i < MAX_BPF_REG; i++) 13282 if (!regsafe(env, &old->regs[i], &cur->regs[i], 13283 env->idmap_scratch)) 13284 return false; 13285 13286 if (!stacksafe(env, old, cur, env->idmap_scratch)) 13287 return false; 13288 13289 if (!refsafe(old, cur)) 13290 return false; 13291 13292 return true; 13293 } 13294 13295 static bool states_equal(struct bpf_verifier_env *env, 13296 struct bpf_verifier_state *old, 13297 struct bpf_verifier_state *cur) 13298 { 13299 int i; 13300 13301 if (old->curframe != cur->curframe) 13302 return false; 13303 13304 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch)); 13305 13306 /* Verification state from speculative execution simulation 13307 * must never prune a non-speculative execution one. 13308 */ 13309 if (old->speculative && !cur->speculative) 13310 return false; 13311 13312 if (old->active_lock.ptr != cur->active_lock.ptr) 13313 return false; 13314 13315 /* Old and cur active_lock's have to be either both present 13316 * or both absent. 13317 */ 13318 if (!!old->active_lock.id != !!cur->active_lock.id) 13319 return false; 13320 13321 if (old->active_lock.id && 13322 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch)) 13323 return false; 13324 13325 if (old->active_rcu_lock != cur->active_rcu_lock) 13326 return false; 13327 13328 /* for states to be equal callsites have to be the same 13329 * and all frame states need to be equivalent 13330 */ 13331 for (i = 0; i <= old->curframe; i++) { 13332 if (old->frame[i]->callsite != cur->frame[i]->callsite) 13333 return false; 13334 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 13335 return false; 13336 } 13337 return true; 13338 } 13339 13340 /* Return 0 if no propagation happened. Return negative error code if error 13341 * happened. Otherwise, return the propagated bit. 13342 */ 13343 static int propagate_liveness_reg(struct bpf_verifier_env *env, 13344 struct bpf_reg_state *reg, 13345 struct bpf_reg_state *parent_reg) 13346 { 13347 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 13348 u8 flag = reg->live & REG_LIVE_READ; 13349 int err; 13350 13351 /* When comes here, read flags of PARENT_REG or REG could be any of 13352 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 13353 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 13354 */ 13355 if (parent_flag == REG_LIVE_READ64 || 13356 /* Or if there is no read flag from REG. */ 13357 !flag || 13358 /* Or if the read flag from REG is the same as PARENT_REG. */ 13359 parent_flag == flag) 13360 return 0; 13361 13362 err = mark_reg_read(env, reg, parent_reg, flag); 13363 if (err) 13364 return err; 13365 13366 return flag; 13367 } 13368 13369 /* A write screens off any subsequent reads; but write marks come from the 13370 * straight-line code between a state and its parent. When we arrive at an 13371 * equivalent state (jump target or such) we didn't arrive by the straight-line 13372 * code, so read marks in the state must propagate to the parent regardless 13373 * of the state's write marks. That's what 'parent == state->parent' comparison 13374 * in mark_reg_read() is for. 13375 */ 13376 static int propagate_liveness(struct bpf_verifier_env *env, 13377 const struct bpf_verifier_state *vstate, 13378 struct bpf_verifier_state *vparent) 13379 { 13380 struct bpf_reg_state *state_reg, *parent_reg; 13381 struct bpf_func_state *state, *parent; 13382 int i, frame, err = 0; 13383 13384 if (vparent->curframe != vstate->curframe) { 13385 WARN(1, "propagate_live: parent frame %d current frame %d\n", 13386 vparent->curframe, vstate->curframe); 13387 return -EFAULT; 13388 } 13389 /* Propagate read liveness of registers... */ 13390 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 13391 for (frame = 0; frame <= vstate->curframe; frame++) { 13392 parent = vparent->frame[frame]; 13393 state = vstate->frame[frame]; 13394 parent_reg = parent->regs; 13395 state_reg = state->regs; 13396 /* We don't need to worry about FP liveness, it's read-only */ 13397 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 13398 err = propagate_liveness_reg(env, &state_reg[i], 13399 &parent_reg[i]); 13400 if (err < 0) 13401 return err; 13402 if (err == REG_LIVE_READ64) 13403 mark_insn_zext(env, &parent_reg[i]); 13404 } 13405 13406 /* Propagate stack slots. */ 13407 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 13408 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 13409 parent_reg = &parent->stack[i].spilled_ptr; 13410 state_reg = &state->stack[i].spilled_ptr; 13411 err = propagate_liveness_reg(env, state_reg, 13412 parent_reg); 13413 if (err < 0) 13414 return err; 13415 } 13416 } 13417 return 0; 13418 } 13419 13420 /* find precise scalars in the previous equivalent state and 13421 * propagate them into the current state 13422 */ 13423 static int propagate_precision(struct bpf_verifier_env *env, 13424 const struct bpf_verifier_state *old) 13425 { 13426 struct bpf_reg_state *state_reg; 13427 struct bpf_func_state *state; 13428 int i, err = 0, fr; 13429 13430 for (fr = old->curframe; fr >= 0; fr--) { 13431 state = old->frame[fr]; 13432 state_reg = state->regs; 13433 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 13434 if (state_reg->type != SCALAR_VALUE || 13435 !state_reg->precise) 13436 continue; 13437 if (env->log.level & BPF_LOG_LEVEL2) 13438 verbose(env, "frame %d: propagating r%d\n", i, fr); 13439 err = mark_chain_precision_frame(env, fr, i); 13440 if (err < 0) 13441 return err; 13442 } 13443 13444 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 13445 if (!is_spilled_reg(&state->stack[i])) 13446 continue; 13447 state_reg = &state->stack[i].spilled_ptr; 13448 if (state_reg->type != SCALAR_VALUE || 13449 !state_reg->precise) 13450 continue; 13451 if (env->log.level & BPF_LOG_LEVEL2) 13452 verbose(env, "frame %d: propagating fp%d\n", 13453 (-i - 1) * BPF_REG_SIZE, fr); 13454 err = mark_chain_precision_stack_frame(env, fr, i); 13455 if (err < 0) 13456 return err; 13457 } 13458 } 13459 return 0; 13460 } 13461 13462 static bool states_maybe_looping(struct bpf_verifier_state *old, 13463 struct bpf_verifier_state *cur) 13464 { 13465 struct bpf_func_state *fold, *fcur; 13466 int i, fr = cur->curframe; 13467 13468 if (old->curframe != fr) 13469 return false; 13470 13471 fold = old->frame[fr]; 13472 fcur = cur->frame[fr]; 13473 for (i = 0; i < MAX_BPF_REG; i++) 13474 if (memcmp(&fold->regs[i], &fcur->regs[i], 13475 offsetof(struct bpf_reg_state, parent))) 13476 return false; 13477 return true; 13478 } 13479 13480 13481 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 13482 { 13483 struct bpf_verifier_state_list *new_sl; 13484 struct bpf_verifier_state_list *sl, **pprev; 13485 struct bpf_verifier_state *cur = env->cur_state, *new; 13486 int i, j, err, states_cnt = 0; 13487 bool add_new_state = env->test_state_freq ? true : false; 13488 13489 /* bpf progs typically have pruning point every 4 instructions 13490 * http://vger.kernel.org/bpfconf2019.html#session-1 13491 * Do not add new state for future pruning if the verifier hasn't seen 13492 * at least 2 jumps and at least 8 instructions. 13493 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 13494 * In tests that amounts to up to 50% reduction into total verifier 13495 * memory consumption and 20% verifier time speedup. 13496 */ 13497 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 13498 env->insn_processed - env->prev_insn_processed >= 8) 13499 add_new_state = true; 13500 13501 pprev = explored_state(env, insn_idx); 13502 sl = *pprev; 13503 13504 clean_live_states(env, insn_idx, cur); 13505 13506 while (sl) { 13507 states_cnt++; 13508 if (sl->state.insn_idx != insn_idx) 13509 goto next; 13510 13511 if (sl->state.branches) { 13512 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 13513 13514 if (frame->in_async_callback_fn && 13515 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 13516 /* Different async_entry_cnt means that the verifier is 13517 * processing another entry into async callback. 13518 * Seeing the same state is not an indication of infinite 13519 * loop or infinite recursion. 13520 * But finding the same state doesn't mean that it's safe 13521 * to stop processing the current state. The previous state 13522 * hasn't yet reached bpf_exit, since state.branches > 0. 13523 * Checking in_async_callback_fn alone is not enough either. 13524 * Since the verifier still needs to catch infinite loops 13525 * inside async callbacks. 13526 */ 13527 } else if (states_maybe_looping(&sl->state, cur) && 13528 states_equal(env, &sl->state, cur)) { 13529 verbose_linfo(env, insn_idx, "; "); 13530 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 13531 return -EINVAL; 13532 } 13533 /* if the verifier is processing a loop, avoid adding new state 13534 * too often, since different loop iterations have distinct 13535 * states and may not help future pruning. 13536 * This threshold shouldn't be too low to make sure that 13537 * a loop with large bound will be rejected quickly. 13538 * The most abusive loop will be: 13539 * r1 += 1 13540 * if r1 < 1000000 goto pc-2 13541 * 1M insn_procssed limit / 100 == 10k peak states. 13542 * This threshold shouldn't be too high either, since states 13543 * at the end of the loop are likely to be useful in pruning. 13544 */ 13545 if (env->jmps_processed - env->prev_jmps_processed < 20 && 13546 env->insn_processed - env->prev_insn_processed < 100) 13547 add_new_state = false; 13548 goto miss; 13549 } 13550 if (states_equal(env, &sl->state, cur)) { 13551 sl->hit_cnt++; 13552 /* reached equivalent register/stack state, 13553 * prune the search. 13554 * Registers read by the continuation are read by us. 13555 * If we have any write marks in env->cur_state, they 13556 * will prevent corresponding reads in the continuation 13557 * from reaching our parent (an explored_state). Our 13558 * own state will get the read marks recorded, but 13559 * they'll be immediately forgotten as we're pruning 13560 * this state and will pop a new one. 13561 */ 13562 err = propagate_liveness(env, &sl->state, cur); 13563 13564 /* if previous state reached the exit with precision and 13565 * current state is equivalent to it (except precsion marks) 13566 * the precision needs to be propagated back in 13567 * the current state. 13568 */ 13569 err = err ? : push_jmp_history(env, cur); 13570 err = err ? : propagate_precision(env, &sl->state); 13571 if (err) 13572 return err; 13573 return 1; 13574 } 13575 miss: 13576 /* when new state is not going to be added do not increase miss count. 13577 * Otherwise several loop iterations will remove the state 13578 * recorded earlier. The goal of these heuristics is to have 13579 * states from some iterations of the loop (some in the beginning 13580 * and some at the end) to help pruning. 13581 */ 13582 if (add_new_state) 13583 sl->miss_cnt++; 13584 /* heuristic to determine whether this state is beneficial 13585 * to keep checking from state equivalence point of view. 13586 * Higher numbers increase max_states_per_insn and verification time, 13587 * but do not meaningfully decrease insn_processed. 13588 */ 13589 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 13590 /* the state is unlikely to be useful. Remove it to 13591 * speed up verification 13592 */ 13593 *pprev = sl->next; 13594 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 13595 u32 br = sl->state.branches; 13596 13597 WARN_ONCE(br, 13598 "BUG live_done but branches_to_explore %d\n", 13599 br); 13600 free_verifier_state(&sl->state, false); 13601 kfree(sl); 13602 env->peak_states--; 13603 } else { 13604 /* cannot free this state, since parentage chain may 13605 * walk it later. Add it for free_list instead to 13606 * be freed at the end of verification 13607 */ 13608 sl->next = env->free_list; 13609 env->free_list = sl; 13610 } 13611 sl = *pprev; 13612 continue; 13613 } 13614 next: 13615 pprev = &sl->next; 13616 sl = *pprev; 13617 } 13618 13619 if (env->max_states_per_insn < states_cnt) 13620 env->max_states_per_insn = states_cnt; 13621 13622 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 13623 return 0; 13624 13625 if (!add_new_state) 13626 return 0; 13627 13628 /* There were no equivalent states, remember the current one. 13629 * Technically the current state is not proven to be safe yet, 13630 * but it will either reach outer most bpf_exit (which means it's safe) 13631 * or it will be rejected. When there are no loops the verifier won't be 13632 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 13633 * again on the way to bpf_exit. 13634 * When looping the sl->state.branches will be > 0 and this state 13635 * will not be considered for equivalence until branches == 0. 13636 */ 13637 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 13638 if (!new_sl) 13639 return -ENOMEM; 13640 env->total_states++; 13641 env->peak_states++; 13642 env->prev_jmps_processed = env->jmps_processed; 13643 env->prev_insn_processed = env->insn_processed; 13644 13645 /* forget precise markings we inherited, see __mark_chain_precision */ 13646 if (env->bpf_capable) 13647 mark_all_scalars_imprecise(env, cur); 13648 13649 /* add new state to the head of linked list */ 13650 new = &new_sl->state; 13651 err = copy_verifier_state(new, cur); 13652 if (err) { 13653 free_verifier_state(new, false); 13654 kfree(new_sl); 13655 return err; 13656 } 13657 new->insn_idx = insn_idx; 13658 WARN_ONCE(new->branches != 1, 13659 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 13660 13661 cur->parent = new; 13662 cur->first_insn_idx = insn_idx; 13663 clear_jmp_history(cur); 13664 new_sl->next = *explored_state(env, insn_idx); 13665 *explored_state(env, insn_idx) = new_sl; 13666 /* connect new state to parentage chain. Current frame needs all 13667 * registers connected. Only r6 - r9 of the callers are alive (pushed 13668 * to the stack implicitly by JITs) so in callers' frames connect just 13669 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 13670 * the state of the call instruction (with WRITTEN set), and r0 comes 13671 * from callee with its full parentage chain, anyway. 13672 */ 13673 /* clear write marks in current state: the writes we did are not writes 13674 * our child did, so they don't screen off its reads from us. 13675 * (There are no read marks in current state, because reads always mark 13676 * their parent and current state never has children yet. Only 13677 * explored_states can get read marks.) 13678 */ 13679 for (j = 0; j <= cur->curframe; j++) { 13680 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 13681 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 13682 for (i = 0; i < BPF_REG_FP; i++) 13683 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 13684 } 13685 13686 /* all stack frames are accessible from callee, clear them all */ 13687 for (j = 0; j <= cur->curframe; j++) { 13688 struct bpf_func_state *frame = cur->frame[j]; 13689 struct bpf_func_state *newframe = new->frame[j]; 13690 13691 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 13692 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 13693 frame->stack[i].spilled_ptr.parent = 13694 &newframe->stack[i].spilled_ptr; 13695 } 13696 } 13697 return 0; 13698 } 13699 13700 /* Return true if it's OK to have the same insn return a different type. */ 13701 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 13702 { 13703 switch (base_type(type)) { 13704 case PTR_TO_CTX: 13705 case PTR_TO_SOCKET: 13706 case PTR_TO_SOCK_COMMON: 13707 case PTR_TO_TCP_SOCK: 13708 case PTR_TO_XDP_SOCK: 13709 case PTR_TO_BTF_ID: 13710 return false; 13711 default: 13712 return true; 13713 } 13714 } 13715 13716 /* If an instruction was previously used with particular pointer types, then we 13717 * need to be careful to avoid cases such as the below, where it may be ok 13718 * for one branch accessing the pointer, but not ok for the other branch: 13719 * 13720 * R1 = sock_ptr 13721 * goto X; 13722 * ... 13723 * R1 = some_other_valid_ptr; 13724 * goto X; 13725 * ... 13726 * R2 = *(u32 *)(R1 + 0); 13727 */ 13728 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 13729 { 13730 return src != prev && (!reg_type_mismatch_ok(src) || 13731 !reg_type_mismatch_ok(prev)); 13732 } 13733 13734 static int do_check(struct bpf_verifier_env *env) 13735 { 13736 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 13737 struct bpf_verifier_state *state = env->cur_state; 13738 struct bpf_insn *insns = env->prog->insnsi; 13739 struct bpf_reg_state *regs; 13740 int insn_cnt = env->prog->len; 13741 bool do_print_state = false; 13742 int prev_insn_idx = -1; 13743 13744 for (;;) { 13745 struct bpf_insn *insn; 13746 u8 class; 13747 int err; 13748 13749 env->prev_insn_idx = prev_insn_idx; 13750 if (env->insn_idx >= insn_cnt) { 13751 verbose(env, "invalid insn idx %d insn_cnt %d\n", 13752 env->insn_idx, insn_cnt); 13753 return -EFAULT; 13754 } 13755 13756 insn = &insns[env->insn_idx]; 13757 class = BPF_CLASS(insn->code); 13758 13759 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 13760 verbose(env, 13761 "BPF program is too large. Processed %d insn\n", 13762 env->insn_processed); 13763 return -E2BIG; 13764 } 13765 13766 state->last_insn_idx = env->prev_insn_idx; 13767 13768 if (is_prune_point(env, env->insn_idx)) { 13769 err = is_state_visited(env, env->insn_idx); 13770 if (err < 0) 13771 return err; 13772 if (err == 1) { 13773 /* found equivalent state, can prune the search */ 13774 if (env->log.level & BPF_LOG_LEVEL) { 13775 if (do_print_state) 13776 verbose(env, "\nfrom %d to %d%s: safe\n", 13777 env->prev_insn_idx, env->insn_idx, 13778 env->cur_state->speculative ? 13779 " (speculative execution)" : ""); 13780 else 13781 verbose(env, "%d: safe\n", env->insn_idx); 13782 } 13783 goto process_bpf_exit; 13784 } 13785 } 13786 13787 if (is_jmp_point(env, env->insn_idx)) { 13788 err = push_jmp_history(env, state); 13789 if (err) 13790 return err; 13791 } 13792 13793 if (signal_pending(current)) 13794 return -EAGAIN; 13795 13796 if (need_resched()) 13797 cond_resched(); 13798 13799 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 13800 verbose(env, "\nfrom %d to %d%s:", 13801 env->prev_insn_idx, env->insn_idx, 13802 env->cur_state->speculative ? 13803 " (speculative execution)" : ""); 13804 print_verifier_state(env, state->frame[state->curframe], true); 13805 do_print_state = false; 13806 } 13807 13808 if (env->log.level & BPF_LOG_LEVEL) { 13809 const struct bpf_insn_cbs cbs = { 13810 .cb_call = disasm_kfunc_name, 13811 .cb_print = verbose, 13812 .private_data = env, 13813 }; 13814 13815 if (verifier_state_scratched(env)) 13816 print_insn_state(env, state->frame[state->curframe]); 13817 13818 verbose_linfo(env, env->insn_idx, "; "); 13819 env->prev_log_len = env->log.len_used; 13820 verbose(env, "%d: ", env->insn_idx); 13821 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 13822 env->prev_insn_print_len = env->log.len_used - env->prev_log_len; 13823 env->prev_log_len = env->log.len_used; 13824 } 13825 13826 if (bpf_prog_is_dev_bound(env->prog->aux)) { 13827 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 13828 env->prev_insn_idx); 13829 if (err) 13830 return err; 13831 } 13832 13833 regs = cur_regs(env); 13834 sanitize_mark_insn_seen(env); 13835 prev_insn_idx = env->insn_idx; 13836 13837 if (class == BPF_ALU || class == BPF_ALU64) { 13838 err = check_alu_op(env, insn); 13839 if (err) 13840 return err; 13841 13842 } else if (class == BPF_LDX) { 13843 enum bpf_reg_type *prev_src_type, src_reg_type; 13844 13845 /* check for reserved fields is already done */ 13846 13847 /* check src operand */ 13848 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13849 if (err) 13850 return err; 13851 13852 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 13853 if (err) 13854 return err; 13855 13856 src_reg_type = regs[insn->src_reg].type; 13857 13858 /* check that memory (src_reg + off) is readable, 13859 * the state of dst_reg will be updated by this func 13860 */ 13861 err = check_mem_access(env, env->insn_idx, insn->src_reg, 13862 insn->off, BPF_SIZE(insn->code), 13863 BPF_READ, insn->dst_reg, false); 13864 if (err) 13865 return err; 13866 13867 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 13868 13869 if (*prev_src_type == NOT_INIT) { 13870 /* saw a valid insn 13871 * dst_reg = *(u32 *)(src_reg + off) 13872 * save type to validate intersecting paths 13873 */ 13874 *prev_src_type = src_reg_type; 13875 13876 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 13877 /* ABuser program is trying to use the same insn 13878 * dst_reg = *(u32*) (src_reg + off) 13879 * with different pointer types: 13880 * src_reg == ctx in one branch and 13881 * src_reg == stack|map in some other branch. 13882 * Reject it. 13883 */ 13884 verbose(env, "same insn cannot be used with different pointers\n"); 13885 return -EINVAL; 13886 } 13887 13888 } else if (class == BPF_STX) { 13889 enum bpf_reg_type *prev_dst_type, dst_reg_type; 13890 13891 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 13892 err = check_atomic(env, env->insn_idx, insn); 13893 if (err) 13894 return err; 13895 env->insn_idx++; 13896 continue; 13897 } 13898 13899 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 13900 verbose(env, "BPF_STX uses reserved fields\n"); 13901 return -EINVAL; 13902 } 13903 13904 /* check src1 operand */ 13905 err = check_reg_arg(env, insn->src_reg, SRC_OP); 13906 if (err) 13907 return err; 13908 /* check src2 operand */ 13909 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13910 if (err) 13911 return err; 13912 13913 dst_reg_type = regs[insn->dst_reg].type; 13914 13915 /* check that memory (dst_reg + off) is writeable */ 13916 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 13917 insn->off, BPF_SIZE(insn->code), 13918 BPF_WRITE, insn->src_reg, false); 13919 if (err) 13920 return err; 13921 13922 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 13923 13924 if (*prev_dst_type == NOT_INIT) { 13925 *prev_dst_type = dst_reg_type; 13926 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 13927 verbose(env, "same insn cannot be used with different pointers\n"); 13928 return -EINVAL; 13929 } 13930 13931 } else if (class == BPF_ST) { 13932 if (BPF_MODE(insn->code) != BPF_MEM || 13933 insn->src_reg != BPF_REG_0) { 13934 verbose(env, "BPF_ST uses reserved fields\n"); 13935 return -EINVAL; 13936 } 13937 /* check src operand */ 13938 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 13939 if (err) 13940 return err; 13941 13942 if (is_ctx_reg(env, insn->dst_reg)) { 13943 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 13944 insn->dst_reg, 13945 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 13946 return -EACCES; 13947 } 13948 13949 /* check that memory (dst_reg + off) is writeable */ 13950 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 13951 insn->off, BPF_SIZE(insn->code), 13952 BPF_WRITE, -1, false); 13953 if (err) 13954 return err; 13955 13956 } else if (class == BPF_JMP || class == BPF_JMP32) { 13957 u8 opcode = BPF_OP(insn->code); 13958 13959 env->jmps_processed++; 13960 if (opcode == BPF_CALL) { 13961 if (BPF_SRC(insn->code) != BPF_K || 13962 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 13963 && insn->off != 0) || 13964 (insn->src_reg != BPF_REG_0 && 13965 insn->src_reg != BPF_PSEUDO_CALL && 13966 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 13967 insn->dst_reg != BPF_REG_0 || 13968 class == BPF_JMP32) { 13969 verbose(env, "BPF_CALL uses reserved fields\n"); 13970 return -EINVAL; 13971 } 13972 13973 if (env->cur_state->active_lock.ptr) { 13974 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 13975 (insn->src_reg == BPF_PSEUDO_CALL) || 13976 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 13977 (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) { 13978 verbose(env, "function calls are not allowed while holding a lock\n"); 13979 return -EINVAL; 13980 } 13981 } 13982 if (insn->src_reg == BPF_PSEUDO_CALL) 13983 err = check_func_call(env, insn, &env->insn_idx); 13984 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 13985 err = check_kfunc_call(env, insn, &env->insn_idx); 13986 else 13987 err = check_helper_call(env, insn, &env->insn_idx); 13988 if (err) 13989 return err; 13990 } else if (opcode == BPF_JA) { 13991 if (BPF_SRC(insn->code) != BPF_K || 13992 insn->imm != 0 || 13993 insn->src_reg != BPF_REG_0 || 13994 insn->dst_reg != BPF_REG_0 || 13995 class == BPF_JMP32) { 13996 verbose(env, "BPF_JA uses reserved fields\n"); 13997 return -EINVAL; 13998 } 13999 14000 env->insn_idx += insn->off + 1; 14001 continue; 14002 14003 } else if (opcode == BPF_EXIT) { 14004 if (BPF_SRC(insn->code) != BPF_K || 14005 insn->imm != 0 || 14006 insn->src_reg != BPF_REG_0 || 14007 insn->dst_reg != BPF_REG_0 || 14008 class == BPF_JMP32) { 14009 verbose(env, "BPF_EXIT uses reserved fields\n"); 14010 return -EINVAL; 14011 } 14012 14013 if (env->cur_state->active_lock.ptr) { 14014 verbose(env, "bpf_spin_unlock is missing\n"); 14015 return -EINVAL; 14016 } 14017 14018 if (env->cur_state->active_rcu_lock) { 14019 verbose(env, "bpf_rcu_read_unlock is missing\n"); 14020 return -EINVAL; 14021 } 14022 14023 /* We must do check_reference_leak here before 14024 * prepare_func_exit to handle the case when 14025 * state->curframe > 0, it may be a callback 14026 * function, for which reference_state must 14027 * match caller reference state when it exits. 14028 */ 14029 err = check_reference_leak(env); 14030 if (err) 14031 return err; 14032 14033 if (state->curframe) { 14034 /* exit from nested function */ 14035 err = prepare_func_exit(env, &env->insn_idx); 14036 if (err) 14037 return err; 14038 do_print_state = true; 14039 continue; 14040 } 14041 14042 err = check_return_code(env); 14043 if (err) 14044 return err; 14045 process_bpf_exit: 14046 mark_verifier_state_scratched(env); 14047 update_branch_counts(env, env->cur_state); 14048 err = pop_stack(env, &prev_insn_idx, 14049 &env->insn_idx, pop_log); 14050 if (err < 0) { 14051 if (err != -ENOENT) 14052 return err; 14053 break; 14054 } else { 14055 do_print_state = true; 14056 continue; 14057 } 14058 } else { 14059 err = check_cond_jmp_op(env, insn, &env->insn_idx); 14060 if (err) 14061 return err; 14062 } 14063 } else if (class == BPF_LD) { 14064 u8 mode = BPF_MODE(insn->code); 14065 14066 if (mode == BPF_ABS || mode == BPF_IND) { 14067 err = check_ld_abs(env, insn); 14068 if (err) 14069 return err; 14070 14071 } else if (mode == BPF_IMM) { 14072 err = check_ld_imm(env, insn); 14073 if (err) 14074 return err; 14075 14076 env->insn_idx++; 14077 sanitize_mark_insn_seen(env); 14078 } else { 14079 verbose(env, "invalid BPF_LD mode\n"); 14080 return -EINVAL; 14081 } 14082 } else { 14083 verbose(env, "unknown insn class %d\n", class); 14084 return -EINVAL; 14085 } 14086 14087 env->insn_idx++; 14088 } 14089 14090 return 0; 14091 } 14092 14093 static int find_btf_percpu_datasec(struct btf *btf) 14094 { 14095 const struct btf_type *t; 14096 const char *tname; 14097 int i, n; 14098 14099 /* 14100 * Both vmlinux and module each have their own ".data..percpu" 14101 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 14102 * types to look at only module's own BTF types. 14103 */ 14104 n = btf_nr_types(btf); 14105 if (btf_is_module(btf)) 14106 i = btf_nr_types(btf_vmlinux); 14107 else 14108 i = 1; 14109 14110 for(; i < n; i++) { 14111 t = btf_type_by_id(btf, i); 14112 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 14113 continue; 14114 14115 tname = btf_name_by_offset(btf, t->name_off); 14116 if (!strcmp(tname, ".data..percpu")) 14117 return i; 14118 } 14119 14120 return -ENOENT; 14121 } 14122 14123 /* replace pseudo btf_id with kernel symbol address */ 14124 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 14125 struct bpf_insn *insn, 14126 struct bpf_insn_aux_data *aux) 14127 { 14128 const struct btf_var_secinfo *vsi; 14129 const struct btf_type *datasec; 14130 struct btf_mod_pair *btf_mod; 14131 const struct btf_type *t; 14132 const char *sym_name; 14133 bool percpu = false; 14134 u32 type, id = insn->imm; 14135 struct btf *btf; 14136 s32 datasec_id; 14137 u64 addr; 14138 int i, btf_fd, err; 14139 14140 btf_fd = insn[1].imm; 14141 if (btf_fd) { 14142 btf = btf_get_by_fd(btf_fd); 14143 if (IS_ERR(btf)) { 14144 verbose(env, "invalid module BTF object FD specified.\n"); 14145 return -EINVAL; 14146 } 14147 } else { 14148 if (!btf_vmlinux) { 14149 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 14150 return -EINVAL; 14151 } 14152 btf = btf_vmlinux; 14153 btf_get(btf); 14154 } 14155 14156 t = btf_type_by_id(btf, id); 14157 if (!t) { 14158 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 14159 err = -ENOENT; 14160 goto err_put; 14161 } 14162 14163 if (!btf_type_is_var(t)) { 14164 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id); 14165 err = -EINVAL; 14166 goto err_put; 14167 } 14168 14169 sym_name = btf_name_by_offset(btf, t->name_off); 14170 addr = kallsyms_lookup_name(sym_name); 14171 if (!addr) { 14172 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 14173 sym_name); 14174 err = -ENOENT; 14175 goto err_put; 14176 } 14177 14178 datasec_id = find_btf_percpu_datasec(btf); 14179 if (datasec_id > 0) { 14180 datasec = btf_type_by_id(btf, datasec_id); 14181 for_each_vsi(i, datasec, vsi) { 14182 if (vsi->type == id) { 14183 percpu = true; 14184 break; 14185 } 14186 } 14187 } 14188 14189 insn[0].imm = (u32)addr; 14190 insn[1].imm = addr >> 32; 14191 14192 type = t->type; 14193 t = btf_type_skip_modifiers(btf, type, NULL); 14194 if (percpu) { 14195 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 14196 aux->btf_var.btf = btf; 14197 aux->btf_var.btf_id = type; 14198 } else if (!btf_type_is_struct(t)) { 14199 const struct btf_type *ret; 14200 const char *tname; 14201 u32 tsize; 14202 14203 /* resolve the type size of ksym. */ 14204 ret = btf_resolve_size(btf, t, &tsize); 14205 if (IS_ERR(ret)) { 14206 tname = btf_name_by_offset(btf, t->name_off); 14207 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 14208 tname, PTR_ERR(ret)); 14209 err = -EINVAL; 14210 goto err_put; 14211 } 14212 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 14213 aux->btf_var.mem_size = tsize; 14214 } else { 14215 aux->btf_var.reg_type = PTR_TO_BTF_ID; 14216 aux->btf_var.btf = btf; 14217 aux->btf_var.btf_id = type; 14218 } 14219 14220 /* check whether we recorded this BTF (and maybe module) already */ 14221 for (i = 0; i < env->used_btf_cnt; i++) { 14222 if (env->used_btfs[i].btf == btf) { 14223 btf_put(btf); 14224 return 0; 14225 } 14226 } 14227 14228 if (env->used_btf_cnt >= MAX_USED_BTFS) { 14229 err = -E2BIG; 14230 goto err_put; 14231 } 14232 14233 btf_mod = &env->used_btfs[env->used_btf_cnt]; 14234 btf_mod->btf = btf; 14235 btf_mod->module = NULL; 14236 14237 /* if we reference variables from kernel module, bump its refcount */ 14238 if (btf_is_module(btf)) { 14239 btf_mod->module = btf_try_get_module(btf); 14240 if (!btf_mod->module) { 14241 err = -ENXIO; 14242 goto err_put; 14243 } 14244 } 14245 14246 env->used_btf_cnt++; 14247 14248 return 0; 14249 err_put: 14250 btf_put(btf); 14251 return err; 14252 } 14253 14254 static bool is_tracing_prog_type(enum bpf_prog_type type) 14255 { 14256 switch (type) { 14257 case BPF_PROG_TYPE_KPROBE: 14258 case BPF_PROG_TYPE_TRACEPOINT: 14259 case BPF_PROG_TYPE_PERF_EVENT: 14260 case BPF_PROG_TYPE_RAW_TRACEPOINT: 14261 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 14262 return true; 14263 default: 14264 return false; 14265 } 14266 } 14267 14268 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 14269 struct bpf_map *map, 14270 struct bpf_prog *prog) 14271 14272 { 14273 enum bpf_prog_type prog_type = resolve_prog_type(prog); 14274 14275 if (btf_record_has_field(map->record, BPF_LIST_HEAD)) { 14276 if (is_tracing_prog_type(prog_type)) { 14277 verbose(env, "tracing progs cannot use bpf_list_head yet\n"); 14278 return -EINVAL; 14279 } 14280 } 14281 14282 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 14283 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 14284 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 14285 return -EINVAL; 14286 } 14287 14288 if (is_tracing_prog_type(prog_type)) { 14289 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 14290 return -EINVAL; 14291 } 14292 14293 if (prog->aux->sleepable) { 14294 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 14295 return -EINVAL; 14296 } 14297 } 14298 14299 if (btf_record_has_field(map->record, BPF_TIMER)) { 14300 if (is_tracing_prog_type(prog_type)) { 14301 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 14302 return -EINVAL; 14303 } 14304 } 14305 14306 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) && 14307 !bpf_offload_prog_map_match(prog, map)) { 14308 verbose(env, "offload device mismatch between prog and map\n"); 14309 return -EINVAL; 14310 } 14311 14312 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 14313 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 14314 return -EINVAL; 14315 } 14316 14317 if (prog->aux->sleepable) 14318 switch (map->map_type) { 14319 case BPF_MAP_TYPE_HASH: 14320 case BPF_MAP_TYPE_LRU_HASH: 14321 case BPF_MAP_TYPE_ARRAY: 14322 case BPF_MAP_TYPE_PERCPU_HASH: 14323 case BPF_MAP_TYPE_PERCPU_ARRAY: 14324 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 14325 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 14326 case BPF_MAP_TYPE_HASH_OF_MAPS: 14327 case BPF_MAP_TYPE_RINGBUF: 14328 case BPF_MAP_TYPE_USER_RINGBUF: 14329 case BPF_MAP_TYPE_INODE_STORAGE: 14330 case BPF_MAP_TYPE_SK_STORAGE: 14331 case BPF_MAP_TYPE_TASK_STORAGE: 14332 case BPF_MAP_TYPE_CGRP_STORAGE: 14333 break; 14334 default: 14335 verbose(env, 14336 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 14337 return -EINVAL; 14338 } 14339 14340 return 0; 14341 } 14342 14343 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 14344 { 14345 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 14346 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 14347 } 14348 14349 /* find and rewrite pseudo imm in ld_imm64 instructions: 14350 * 14351 * 1. if it accesses map FD, replace it with actual map pointer. 14352 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 14353 * 14354 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 14355 */ 14356 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 14357 { 14358 struct bpf_insn *insn = env->prog->insnsi; 14359 int insn_cnt = env->prog->len; 14360 int i, j, err; 14361 14362 err = bpf_prog_calc_tag(env->prog); 14363 if (err) 14364 return err; 14365 14366 for (i = 0; i < insn_cnt; i++, insn++) { 14367 if (BPF_CLASS(insn->code) == BPF_LDX && 14368 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 14369 verbose(env, "BPF_LDX uses reserved fields\n"); 14370 return -EINVAL; 14371 } 14372 14373 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 14374 struct bpf_insn_aux_data *aux; 14375 struct bpf_map *map; 14376 struct fd f; 14377 u64 addr; 14378 u32 fd; 14379 14380 if (i == insn_cnt - 1 || insn[1].code != 0 || 14381 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 14382 insn[1].off != 0) { 14383 verbose(env, "invalid bpf_ld_imm64 insn\n"); 14384 return -EINVAL; 14385 } 14386 14387 if (insn[0].src_reg == 0) 14388 /* valid generic load 64-bit imm */ 14389 goto next_insn; 14390 14391 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 14392 aux = &env->insn_aux_data[i]; 14393 err = check_pseudo_btf_id(env, insn, aux); 14394 if (err) 14395 return err; 14396 goto next_insn; 14397 } 14398 14399 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 14400 aux = &env->insn_aux_data[i]; 14401 aux->ptr_type = PTR_TO_FUNC; 14402 goto next_insn; 14403 } 14404 14405 /* In final convert_pseudo_ld_imm64() step, this is 14406 * converted into regular 64-bit imm load insn. 14407 */ 14408 switch (insn[0].src_reg) { 14409 case BPF_PSEUDO_MAP_VALUE: 14410 case BPF_PSEUDO_MAP_IDX_VALUE: 14411 break; 14412 case BPF_PSEUDO_MAP_FD: 14413 case BPF_PSEUDO_MAP_IDX: 14414 if (insn[1].imm == 0) 14415 break; 14416 fallthrough; 14417 default: 14418 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 14419 return -EINVAL; 14420 } 14421 14422 switch (insn[0].src_reg) { 14423 case BPF_PSEUDO_MAP_IDX_VALUE: 14424 case BPF_PSEUDO_MAP_IDX: 14425 if (bpfptr_is_null(env->fd_array)) { 14426 verbose(env, "fd_idx without fd_array is invalid\n"); 14427 return -EPROTO; 14428 } 14429 if (copy_from_bpfptr_offset(&fd, env->fd_array, 14430 insn[0].imm * sizeof(fd), 14431 sizeof(fd))) 14432 return -EFAULT; 14433 break; 14434 default: 14435 fd = insn[0].imm; 14436 break; 14437 } 14438 14439 f = fdget(fd); 14440 map = __bpf_map_get(f); 14441 if (IS_ERR(map)) { 14442 verbose(env, "fd %d is not pointing to valid bpf_map\n", 14443 insn[0].imm); 14444 return PTR_ERR(map); 14445 } 14446 14447 err = check_map_prog_compatibility(env, map, env->prog); 14448 if (err) { 14449 fdput(f); 14450 return err; 14451 } 14452 14453 aux = &env->insn_aux_data[i]; 14454 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 14455 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 14456 addr = (unsigned long)map; 14457 } else { 14458 u32 off = insn[1].imm; 14459 14460 if (off >= BPF_MAX_VAR_OFF) { 14461 verbose(env, "direct value offset of %u is not allowed\n", off); 14462 fdput(f); 14463 return -EINVAL; 14464 } 14465 14466 if (!map->ops->map_direct_value_addr) { 14467 verbose(env, "no direct value access support for this map type\n"); 14468 fdput(f); 14469 return -EINVAL; 14470 } 14471 14472 err = map->ops->map_direct_value_addr(map, &addr, off); 14473 if (err) { 14474 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 14475 map->value_size, off); 14476 fdput(f); 14477 return err; 14478 } 14479 14480 aux->map_off = off; 14481 addr += off; 14482 } 14483 14484 insn[0].imm = (u32)addr; 14485 insn[1].imm = addr >> 32; 14486 14487 /* check whether we recorded this map already */ 14488 for (j = 0; j < env->used_map_cnt; j++) { 14489 if (env->used_maps[j] == map) { 14490 aux->map_index = j; 14491 fdput(f); 14492 goto next_insn; 14493 } 14494 } 14495 14496 if (env->used_map_cnt >= MAX_USED_MAPS) { 14497 fdput(f); 14498 return -E2BIG; 14499 } 14500 14501 /* hold the map. If the program is rejected by verifier, 14502 * the map will be released by release_maps() or it 14503 * will be used by the valid program until it's unloaded 14504 * and all maps are released in free_used_maps() 14505 */ 14506 bpf_map_inc(map); 14507 14508 aux->map_index = env->used_map_cnt; 14509 env->used_maps[env->used_map_cnt++] = map; 14510 14511 if (bpf_map_is_cgroup_storage(map) && 14512 bpf_cgroup_storage_assign(env->prog->aux, map)) { 14513 verbose(env, "only one cgroup storage of each type is allowed\n"); 14514 fdput(f); 14515 return -EBUSY; 14516 } 14517 14518 fdput(f); 14519 next_insn: 14520 insn++; 14521 i++; 14522 continue; 14523 } 14524 14525 /* Basic sanity check before we invest more work here. */ 14526 if (!bpf_opcode_in_insntable(insn->code)) { 14527 verbose(env, "unknown opcode %02x\n", insn->code); 14528 return -EINVAL; 14529 } 14530 } 14531 14532 /* now all pseudo BPF_LD_IMM64 instructions load valid 14533 * 'struct bpf_map *' into a register instead of user map_fd. 14534 * These pointers will be used later by verifier to validate map access. 14535 */ 14536 return 0; 14537 } 14538 14539 /* drop refcnt of maps used by the rejected program */ 14540 static void release_maps(struct bpf_verifier_env *env) 14541 { 14542 __bpf_free_used_maps(env->prog->aux, env->used_maps, 14543 env->used_map_cnt); 14544 } 14545 14546 /* drop refcnt of maps used by the rejected program */ 14547 static void release_btfs(struct bpf_verifier_env *env) 14548 { 14549 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 14550 env->used_btf_cnt); 14551 } 14552 14553 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 14554 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 14555 { 14556 struct bpf_insn *insn = env->prog->insnsi; 14557 int insn_cnt = env->prog->len; 14558 int i; 14559 14560 for (i = 0; i < insn_cnt; i++, insn++) { 14561 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 14562 continue; 14563 if (insn->src_reg == BPF_PSEUDO_FUNC) 14564 continue; 14565 insn->src_reg = 0; 14566 } 14567 } 14568 14569 /* single env->prog->insni[off] instruction was replaced with the range 14570 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 14571 * [0, off) and [off, end) to new locations, so the patched range stays zero 14572 */ 14573 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 14574 struct bpf_insn_aux_data *new_data, 14575 struct bpf_prog *new_prog, u32 off, u32 cnt) 14576 { 14577 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 14578 struct bpf_insn *insn = new_prog->insnsi; 14579 u32 old_seen = old_data[off].seen; 14580 u32 prog_len; 14581 int i; 14582 14583 /* aux info at OFF always needs adjustment, no matter fast path 14584 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 14585 * original insn at old prog. 14586 */ 14587 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 14588 14589 if (cnt == 1) 14590 return; 14591 prog_len = new_prog->len; 14592 14593 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 14594 memcpy(new_data + off + cnt - 1, old_data + off, 14595 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 14596 for (i = off; i < off + cnt - 1; i++) { 14597 /* Expand insni[off]'s seen count to the patched range. */ 14598 new_data[i].seen = old_seen; 14599 new_data[i].zext_dst = insn_has_def32(env, insn + i); 14600 } 14601 env->insn_aux_data = new_data; 14602 vfree(old_data); 14603 } 14604 14605 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 14606 { 14607 int i; 14608 14609 if (len == 1) 14610 return; 14611 /* NOTE: fake 'exit' subprog should be updated as well. */ 14612 for (i = 0; i <= env->subprog_cnt; i++) { 14613 if (env->subprog_info[i].start <= off) 14614 continue; 14615 env->subprog_info[i].start += len - 1; 14616 } 14617 } 14618 14619 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 14620 { 14621 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 14622 int i, sz = prog->aux->size_poke_tab; 14623 struct bpf_jit_poke_descriptor *desc; 14624 14625 for (i = 0; i < sz; i++) { 14626 desc = &tab[i]; 14627 if (desc->insn_idx <= off) 14628 continue; 14629 desc->insn_idx += len - 1; 14630 } 14631 } 14632 14633 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 14634 const struct bpf_insn *patch, u32 len) 14635 { 14636 struct bpf_prog *new_prog; 14637 struct bpf_insn_aux_data *new_data = NULL; 14638 14639 if (len > 1) { 14640 new_data = vzalloc(array_size(env->prog->len + len - 1, 14641 sizeof(struct bpf_insn_aux_data))); 14642 if (!new_data) 14643 return NULL; 14644 } 14645 14646 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 14647 if (IS_ERR(new_prog)) { 14648 if (PTR_ERR(new_prog) == -ERANGE) 14649 verbose(env, 14650 "insn %d cannot be patched due to 16-bit range\n", 14651 env->insn_aux_data[off].orig_idx); 14652 vfree(new_data); 14653 return NULL; 14654 } 14655 adjust_insn_aux_data(env, new_data, new_prog, off, len); 14656 adjust_subprog_starts(env, off, len); 14657 adjust_poke_descs(new_prog, off, len); 14658 return new_prog; 14659 } 14660 14661 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 14662 u32 off, u32 cnt) 14663 { 14664 int i, j; 14665 14666 /* find first prog starting at or after off (first to remove) */ 14667 for (i = 0; i < env->subprog_cnt; i++) 14668 if (env->subprog_info[i].start >= off) 14669 break; 14670 /* find first prog starting at or after off + cnt (first to stay) */ 14671 for (j = i; j < env->subprog_cnt; j++) 14672 if (env->subprog_info[j].start >= off + cnt) 14673 break; 14674 /* if j doesn't start exactly at off + cnt, we are just removing 14675 * the front of previous prog 14676 */ 14677 if (env->subprog_info[j].start != off + cnt) 14678 j--; 14679 14680 if (j > i) { 14681 struct bpf_prog_aux *aux = env->prog->aux; 14682 int move; 14683 14684 /* move fake 'exit' subprog as well */ 14685 move = env->subprog_cnt + 1 - j; 14686 14687 memmove(env->subprog_info + i, 14688 env->subprog_info + j, 14689 sizeof(*env->subprog_info) * move); 14690 env->subprog_cnt -= j - i; 14691 14692 /* remove func_info */ 14693 if (aux->func_info) { 14694 move = aux->func_info_cnt - j; 14695 14696 memmove(aux->func_info + i, 14697 aux->func_info + j, 14698 sizeof(*aux->func_info) * move); 14699 aux->func_info_cnt -= j - i; 14700 /* func_info->insn_off is set after all code rewrites, 14701 * in adjust_btf_func() - no need to adjust 14702 */ 14703 } 14704 } else { 14705 /* convert i from "first prog to remove" to "first to adjust" */ 14706 if (env->subprog_info[i].start == off) 14707 i++; 14708 } 14709 14710 /* update fake 'exit' subprog as well */ 14711 for (; i <= env->subprog_cnt; i++) 14712 env->subprog_info[i].start -= cnt; 14713 14714 return 0; 14715 } 14716 14717 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 14718 u32 cnt) 14719 { 14720 struct bpf_prog *prog = env->prog; 14721 u32 i, l_off, l_cnt, nr_linfo; 14722 struct bpf_line_info *linfo; 14723 14724 nr_linfo = prog->aux->nr_linfo; 14725 if (!nr_linfo) 14726 return 0; 14727 14728 linfo = prog->aux->linfo; 14729 14730 /* find first line info to remove, count lines to be removed */ 14731 for (i = 0; i < nr_linfo; i++) 14732 if (linfo[i].insn_off >= off) 14733 break; 14734 14735 l_off = i; 14736 l_cnt = 0; 14737 for (; i < nr_linfo; i++) 14738 if (linfo[i].insn_off < off + cnt) 14739 l_cnt++; 14740 else 14741 break; 14742 14743 /* First live insn doesn't match first live linfo, it needs to "inherit" 14744 * last removed linfo. prog is already modified, so prog->len == off 14745 * means no live instructions after (tail of the program was removed). 14746 */ 14747 if (prog->len != off && l_cnt && 14748 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 14749 l_cnt--; 14750 linfo[--i].insn_off = off + cnt; 14751 } 14752 14753 /* remove the line info which refer to the removed instructions */ 14754 if (l_cnt) { 14755 memmove(linfo + l_off, linfo + i, 14756 sizeof(*linfo) * (nr_linfo - i)); 14757 14758 prog->aux->nr_linfo -= l_cnt; 14759 nr_linfo = prog->aux->nr_linfo; 14760 } 14761 14762 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 14763 for (i = l_off; i < nr_linfo; i++) 14764 linfo[i].insn_off -= cnt; 14765 14766 /* fix up all subprogs (incl. 'exit') which start >= off */ 14767 for (i = 0; i <= env->subprog_cnt; i++) 14768 if (env->subprog_info[i].linfo_idx > l_off) { 14769 /* program may have started in the removed region but 14770 * may not be fully removed 14771 */ 14772 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 14773 env->subprog_info[i].linfo_idx -= l_cnt; 14774 else 14775 env->subprog_info[i].linfo_idx = l_off; 14776 } 14777 14778 return 0; 14779 } 14780 14781 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 14782 { 14783 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 14784 unsigned int orig_prog_len = env->prog->len; 14785 int err; 14786 14787 if (bpf_prog_is_dev_bound(env->prog->aux)) 14788 bpf_prog_offload_remove_insns(env, off, cnt); 14789 14790 err = bpf_remove_insns(env->prog, off, cnt); 14791 if (err) 14792 return err; 14793 14794 err = adjust_subprog_starts_after_remove(env, off, cnt); 14795 if (err) 14796 return err; 14797 14798 err = bpf_adj_linfo_after_remove(env, off, cnt); 14799 if (err) 14800 return err; 14801 14802 memmove(aux_data + off, aux_data + off + cnt, 14803 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 14804 14805 return 0; 14806 } 14807 14808 /* The verifier does more data flow analysis than llvm and will not 14809 * explore branches that are dead at run time. Malicious programs can 14810 * have dead code too. Therefore replace all dead at-run-time code 14811 * with 'ja -1'. 14812 * 14813 * Just nops are not optimal, e.g. if they would sit at the end of the 14814 * program and through another bug we would manage to jump there, then 14815 * we'd execute beyond program memory otherwise. Returning exception 14816 * code also wouldn't work since we can have subprogs where the dead 14817 * code could be located. 14818 */ 14819 static void sanitize_dead_code(struct bpf_verifier_env *env) 14820 { 14821 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 14822 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 14823 struct bpf_insn *insn = env->prog->insnsi; 14824 const int insn_cnt = env->prog->len; 14825 int i; 14826 14827 for (i = 0; i < insn_cnt; i++) { 14828 if (aux_data[i].seen) 14829 continue; 14830 memcpy(insn + i, &trap, sizeof(trap)); 14831 aux_data[i].zext_dst = false; 14832 } 14833 } 14834 14835 static bool insn_is_cond_jump(u8 code) 14836 { 14837 u8 op; 14838 14839 if (BPF_CLASS(code) == BPF_JMP32) 14840 return true; 14841 14842 if (BPF_CLASS(code) != BPF_JMP) 14843 return false; 14844 14845 op = BPF_OP(code); 14846 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 14847 } 14848 14849 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 14850 { 14851 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 14852 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 14853 struct bpf_insn *insn = env->prog->insnsi; 14854 const int insn_cnt = env->prog->len; 14855 int i; 14856 14857 for (i = 0; i < insn_cnt; i++, insn++) { 14858 if (!insn_is_cond_jump(insn->code)) 14859 continue; 14860 14861 if (!aux_data[i + 1].seen) 14862 ja.off = insn->off; 14863 else if (!aux_data[i + 1 + insn->off].seen) 14864 ja.off = 0; 14865 else 14866 continue; 14867 14868 if (bpf_prog_is_dev_bound(env->prog->aux)) 14869 bpf_prog_offload_replace_insn(env, i, &ja); 14870 14871 memcpy(insn, &ja, sizeof(ja)); 14872 } 14873 } 14874 14875 static int opt_remove_dead_code(struct bpf_verifier_env *env) 14876 { 14877 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 14878 int insn_cnt = env->prog->len; 14879 int i, err; 14880 14881 for (i = 0; i < insn_cnt; i++) { 14882 int j; 14883 14884 j = 0; 14885 while (i + j < insn_cnt && !aux_data[i + j].seen) 14886 j++; 14887 if (!j) 14888 continue; 14889 14890 err = verifier_remove_insns(env, i, j); 14891 if (err) 14892 return err; 14893 insn_cnt = env->prog->len; 14894 } 14895 14896 return 0; 14897 } 14898 14899 static int opt_remove_nops(struct bpf_verifier_env *env) 14900 { 14901 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 14902 struct bpf_insn *insn = env->prog->insnsi; 14903 int insn_cnt = env->prog->len; 14904 int i, err; 14905 14906 for (i = 0; i < insn_cnt; i++) { 14907 if (memcmp(&insn[i], &ja, sizeof(ja))) 14908 continue; 14909 14910 err = verifier_remove_insns(env, i, 1); 14911 if (err) 14912 return err; 14913 insn_cnt--; 14914 i--; 14915 } 14916 14917 return 0; 14918 } 14919 14920 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 14921 const union bpf_attr *attr) 14922 { 14923 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 14924 struct bpf_insn_aux_data *aux = env->insn_aux_data; 14925 int i, patch_len, delta = 0, len = env->prog->len; 14926 struct bpf_insn *insns = env->prog->insnsi; 14927 struct bpf_prog *new_prog; 14928 bool rnd_hi32; 14929 14930 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 14931 zext_patch[1] = BPF_ZEXT_REG(0); 14932 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 14933 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 14934 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 14935 for (i = 0; i < len; i++) { 14936 int adj_idx = i + delta; 14937 struct bpf_insn insn; 14938 int load_reg; 14939 14940 insn = insns[adj_idx]; 14941 load_reg = insn_def_regno(&insn); 14942 if (!aux[adj_idx].zext_dst) { 14943 u8 code, class; 14944 u32 imm_rnd; 14945 14946 if (!rnd_hi32) 14947 continue; 14948 14949 code = insn.code; 14950 class = BPF_CLASS(code); 14951 if (load_reg == -1) 14952 continue; 14953 14954 /* NOTE: arg "reg" (the fourth one) is only used for 14955 * BPF_STX + SRC_OP, so it is safe to pass NULL 14956 * here. 14957 */ 14958 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 14959 if (class == BPF_LD && 14960 BPF_MODE(code) == BPF_IMM) 14961 i++; 14962 continue; 14963 } 14964 14965 /* ctx load could be transformed into wider load. */ 14966 if (class == BPF_LDX && 14967 aux[adj_idx].ptr_type == PTR_TO_CTX) 14968 continue; 14969 14970 imm_rnd = get_random_u32(); 14971 rnd_hi32_patch[0] = insn; 14972 rnd_hi32_patch[1].imm = imm_rnd; 14973 rnd_hi32_patch[3].dst_reg = load_reg; 14974 patch = rnd_hi32_patch; 14975 patch_len = 4; 14976 goto apply_patch_buffer; 14977 } 14978 14979 /* Add in an zero-extend instruction if a) the JIT has requested 14980 * it or b) it's a CMPXCHG. 14981 * 14982 * The latter is because: BPF_CMPXCHG always loads a value into 14983 * R0, therefore always zero-extends. However some archs' 14984 * equivalent instruction only does this load when the 14985 * comparison is successful. This detail of CMPXCHG is 14986 * orthogonal to the general zero-extension behaviour of the 14987 * CPU, so it's treated independently of bpf_jit_needs_zext. 14988 */ 14989 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 14990 continue; 14991 14992 /* Zero-extension is done by the caller. */ 14993 if (bpf_pseudo_kfunc_call(&insn)) 14994 continue; 14995 14996 if (WARN_ON(load_reg == -1)) { 14997 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 14998 return -EFAULT; 14999 } 15000 15001 zext_patch[0] = insn; 15002 zext_patch[1].dst_reg = load_reg; 15003 zext_patch[1].src_reg = load_reg; 15004 patch = zext_patch; 15005 patch_len = 2; 15006 apply_patch_buffer: 15007 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 15008 if (!new_prog) 15009 return -ENOMEM; 15010 env->prog = new_prog; 15011 insns = new_prog->insnsi; 15012 aux = env->insn_aux_data; 15013 delta += patch_len - 1; 15014 } 15015 15016 return 0; 15017 } 15018 15019 /* convert load instructions that access fields of a context type into a 15020 * sequence of instructions that access fields of the underlying structure: 15021 * struct __sk_buff -> struct sk_buff 15022 * struct bpf_sock_ops -> struct sock 15023 */ 15024 static int convert_ctx_accesses(struct bpf_verifier_env *env) 15025 { 15026 const struct bpf_verifier_ops *ops = env->ops; 15027 int i, cnt, size, ctx_field_size, delta = 0; 15028 const int insn_cnt = env->prog->len; 15029 struct bpf_insn insn_buf[16], *insn; 15030 u32 target_size, size_default, off; 15031 struct bpf_prog *new_prog; 15032 enum bpf_access_type type; 15033 bool is_narrower_load; 15034 15035 if (ops->gen_prologue || env->seen_direct_write) { 15036 if (!ops->gen_prologue) { 15037 verbose(env, "bpf verifier is misconfigured\n"); 15038 return -EINVAL; 15039 } 15040 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 15041 env->prog); 15042 if (cnt >= ARRAY_SIZE(insn_buf)) { 15043 verbose(env, "bpf verifier is misconfigured\n"); 15044 return -EINVAL; 15045 } else if (cnt) { 15046 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 15047 if (!new_prog) 15048 return -ENOMEM; 15049 15050 env->prog = new_prog; 15051 delta += cnt - 1; 15052 } 15053 } 15054 15055 if (bpf_prog_is_dev_bound(env->prog->aux)) 15056 return 0; 15057 15058 insn = env->prog->insnsi + delta; 15059 15060 for (i = 0; i < insn_cnt; i++, insn++) { 15061 bpf_convert_ctx_access_t convert_ctx_access; 15062 bool ctx_access; 15063 15064 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 15065 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 15066 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 15067 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) { 15068 type = BPF_READ; 15069 ctx_access = true; 15070 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 15071 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 15072 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 15073 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 15074 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 15075 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 15076 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 15077 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 15078 type = BPF_WRITE; 15079 ctx_access = BPF_CLASS(insn->code) == BPF_STX; 15080 } else { 15081 continue; 15082 } 15083 15084 if (type == BPF_WRITE && 15085 env->insn_aux_data[i + delta].sanitize_stack_spill) { 15086 struct bpf_insn patch[] = { 15087 *insn, 15088 BPF_ST_NOSPEC(), 15089 }; 15090 15091 cnt = ARRAY_SIZE(patch); 15092 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 15093 if (!new_prog) 15094 return -ENOMEM; 15095 15096 delta += cnt - 1; 15097 env->prog = new_prog; 15098 insn = new_prog->insnsi + i + delta; 15099 continue; 15100 } 15101 15102 if (!ctx_access) 15103 continue; 15104 15105 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 15106 case PTR_TO_CTX: 15107 if (!ops->convert_ctx_access) 15108 continue; 15109 convert_ctx_access = ops->convert_ctx_access; 15110 break; 15111 case PTR_TO_SOCKET: 15112 case PTR_TO_SOCK_COMMON: 15113 convert_ctx_access = bpf_sock_convert_ctx_access; 15114 break; 15115 case PTR_TO_TCP_SOCK: 15116 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 15117 break; 15118 case PTR_TO_XDP_SOCK: 15119 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 15120 break; 15121 case PTR_TO_BTF_ID: 15122 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 15123 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 15124 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 15125 * be said once it is marked PTR_UNTRUSTED, hence we must handle 15126 * any faults for loads into such types. BPF_WRITE is disallowed 15127 * for this case. 15128 */ 15129 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 15130 if (type == BPF_READ) { 15131 insn->code = BPF_LDX | BPF_PROBE_MEM | 15132 BPF_SIZE((insn)->code); 15133 env->prog->aux->num_exentries++; 15134 } 15135 continue; 15136 default: 15137 continue; 15138 } 15139 15140 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 15141 size = BPF_LDST_BYTES(insn); 15142 15143 /* If the read access is a narrower load of the field, 15144 * convert to a 4/8-byte load, to minimum program type specific 15145 * convert_ctx_access changes. If conversion is successful, 15146 * we will apply proper mask to the result. 15147 */ 15148 is_narrower_load = size < ctx_field_size; 15149 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 15150 off = insn->off; 15151 if (is_narrower_load) { 15152 u8 size_code; 15153 15154 if (type == BPF_WRITE) { 15155 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 15156 return -EINVAL; 15157 } 15158 15159 size_code = BPF_H; 15160 if (ctx_field_size == 4) 15161 size_code = BPF_W; 15162 else if (ctx_field_size == 8) 15163 size_code = BPF_DW; 15164 15165 insn->off = off & ~(size_default - 1); 15166 insn->code = BPF_LDX | BPF_MEM | size_code; 15167 } 15168 15169 target_size = 0; 15170 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 15171 &target_size); 15172 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 15173 (ctx_field_size && !target_size)) { 15174 verbose(env, "bpf verifier is misconfigured\n"); 15175 return -EINVAL; 15176 } 15177 15178 if (is_narrower_load && size < target_size) { 15179 u8 shift = bpf_ctx_narrow_access_offset( 15180 off, size, size_default) * 8; 15181 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 15182 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 15183 return -EINVAL; 15184 } 15185 if (ctx_field_size <= 4) { 15186 if (shift) 15187 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 15188 insn->dst_reg, 15189 shift); 15190 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 15191 (1 << size * 8) - 1); 15192 } else { 15193 if (shift) 15194 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 15195 insn->dst_reg, 15196 shift); 15197 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 15198 (1ULL << size * 8) - 1); 15199 } 15200 } 15201 15202 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15203 if (!new_prog) 15204 return -ENOMEM; 15205 15206 delta += cnt - 1; 15207 15208 /* keep walking new program and skip insns we just inserted */ 15209 env->prog = new_prog; 15210 insn = new_prog->insnsi + i + delta; 15211 } 15212 15213 return 0; 15214 } 15215 15216 static int jit_subprogs(struct bpf_verifier_env *env) 15217 { 15218 struct bpf_prog *prog = env->prog, **func, *tmp; 15219 int i, j, subprog_start, subprog_end = 0, len, subprog; 15220 struct bpf_map *map_ptr; 15221 struct bpf_insn *insn; 15222 void *old_bpf_func; 15223 int err, num_exentries; 15224 15225 if (env->subprog_cnt <= 1) 15226 return 0; 15227 15228 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 15229 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 15230 continue; 15231 15232 /* Upon error here we cannot fall back to interpreter but 15233 * need a hard reject of the program. Thus -EFAULT is 15234 * propagated in any case. 15235 */ 15236 subprog = find_subprog(env, i + insn->imm + 1); 15237 if (subprog < 0) { 15238 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 15239 i + insn->imm + 1); 15240 return -EFAULT; 15241 } 15242 /* temporarily remember subprog id inside insn instead of 15243 * aux_data, since next loop will split up all insns into funcs 15244 */ 15245 insn->off = subprog; 15246 /* remember original imm in case JIT fails and fallback 15247 * to interpreter will be needed 15248 */ 15249 env->insn_aux_data[i].call_imm = insn->imm; 15250 /* point imm to __bpf_call_base+1 from JITs point of view */ 15251 insn->imm = 1; 15252 if (bpf_pseudo_func(insn)) 15253 /* jit (e.g. x86_64) may emit fewer instructions 15254 * if it learns a u32 imm is the same as a u64 imm. 15255 * Force a non zero here. 15256 */ 15257 insn[1].imm = 1; 15258 } 15259 15260 err = bpf_prog_alloc_jited_linfo(prog); 15261 if (err) 15262 goto out_undo_insn; 15263 15264 err = -ENOMEM; 15265 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 15266 if (!func) 15267 goto out_undo_insn; 15268 15269 for (i = 0; i < env->subprog_cnt; i++) { 15270 subprog_start = subprog_end; 15271 subprog_end = env->subprog_info[i + 1].start; 15272 15273 len = subprog_end - subprog_start; 15274 /* bpf_prog_run() doesn't call subprogs directly, 15275 * hence main prog stats include the runtime of subprogs. 15276 * subprogs don't have IDs and not reachable via prog_get_next_id 15277 * func[i]->stats will never be accessed and stays NULL 15278 */ 15279 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 15280 if (!func[i]) 15281 goto out_free; 15282 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 15283 len * sizeof(struct bpf_insn)); 15284 func[i]->type = prog->type; 15285 func[i]->len = len; 15286 if (bpf_prog_calc_tag(func[i])) 15287 goto out_free; 15288 func[i]->is_func = 1; 15289 func[i]->aux->func_idx = i; 15290 /* Below members will be freed only at prog->aux */ 15291 func[i]->aux->btf = prog->aux->btf; 15292 func[i]->aux->func_info = prog->aux->func_info; 15293 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 15294 func[i]->aux->poke_tab = prog->aux->poke_tab; 15295 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 15296 15297 for (j = 0; j < prog->aux->size_poke_tab; j++) { 15298 struct bpf_jit_poke_descriptor *poke; 15299 15300 poke = &prog->aux->poke_tab[j]; 15301 if (poke->insn_idx < subprog_end && 15302 poke->insn_idx >= subprog_start) 15303 poke->aux = func[i]->aux; 15304 } 15305 15306 func[i]->aux->name[0] = 'F'; 15307 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 15308 func[i]->jit_requested = 1; 15309 func[i]->blinding_requested = prog->blinding_requested; 15310 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 15311 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 15312 func[i]->aux->linfo = prog->aux->linfo; 15313 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 15314 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 15315 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 15316 num_exentries = 0; 15317 insn = func[i]->insnsi; 15318 for (j = 0; j < func[i]->len; j++, insn++) { 15319 if (BPF_CLASS(insn->code) == BPF_LDX && 15320 BPF_MODE(insn->code) == BPF_PROBE_MEM) 15321 num_exentries++; 15322 } 15323 func[i]->aux->num_exentries = num_exentries; 15324 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 15325 func[i] = bpf_int_jit_compile(func[i]); 15326 if (!func[i]->jited) { 15327 err = -ENOTSUPP; 15328 goto out_free; 15329 } 15330 cond_resched(); 15331 } 15332 15333 /* at this point all bpf functions were successfully JITed 15334 * now populate all bpf_calls with correct addresses and 15335 * run last pass of JIT 15336 */ 15337 for (i = 0; i < env->subprog_cnt; i++) { 15338 insn = func[i]->insnsi; 15339 for (j = 0; j < func[i]->len; j++, insn++) { 15340 if (bpf_pseudo_func(insn)) { 15341 subprog = insn->off; 15342 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 15343 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 15344 continue; 15345 } 15346 if (!bpf_pseudo_call(insn)) 15347 continue; 15348 subprog = insn->off; 15349 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 15350 } 15351 15352 /* we use the aux data to keep a list of the start addresses 15353 * of the JITed images for each function in the program 15354 * 15355 * for some architectures, such as powerpc64, the imm field 15356 * might not be large enough to hold the offset of the start 15357 * address of the callee's JITed image from __bpf_call_base 15358 * 15359 * in such cases, we can lookup the start address of a callee 15360 * by using its subprog id, available from the off field of 15361 * the call instruction, as an index for this list 15362 */ 15363 func[i]->aux->func = func; 15364 func[i]->aux->func_cnt = env->subprog_cnt; 15365 } 15366 for (i = 0; i < env->subprog_cnt; i++) { 15367 old_bpf_func = func[i]->bpf_func; 15368 tmp = bpf_int_jit_compile(func[i]); 15369 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 15370 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 15371 err = -ENOTSUPP; 15372 goto out_free; 15373 } 15374 cond_resched(); 15375 } 15376 15377 /* finally lock prog and jit images for all functions and 15378 * populate kallsysm 15379 */ 15380 for (i = 0; i < env->subprog_cnt; i++) { 15381 bpf_prog_lock_ro(func[i]); 15382 bpf_prog_kallsyms_add(func[i]); 15383 } 15384 15385 /* Last step: make now unused interpreter insns from main 15386 * prog consistent for later dump requests, so they can 15387 * later look the same as if they were interpreted only. 15388 */ 15389 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 15390 if (bpf_pseudo_func(insn)) { 15391 insn[0].imm = env->insn_aux_data[i].call_imm; 15392 insn[1].imm = insn->off; 15393 insn->off = 0; 15394 continue; 15395 } 15396 if (!bpf_pseudo_call(insn)) 15397 continue; 15398 insn->off = env->insn_aux_data[i].call_imm; 15399 subprog = find_subprog(env, i + insn->off + 1); 15400 insn->imm = subprog; 15401 } 15402 15403 prog->jited = 1; 15404 prog->bpf_func = func[0]->bpf_func; 15405 prog->jited_len = func[0]->jited_len; 15406 prog->aux->func = func; 15407 prog->aux->func_cnt = env->subprog_cnt; 15408 bpf_prog_jit_attempt_done(prog); 15409 return 0; 15410 out_free: 15411 /* We failed JIT'ing, so at this point we need to unregister poke 15412 * descriptors from subprogs, so that kernel is not attempting to 15413 * patch it anymore as we're freeing the subprog JIT memory. 15414 */ 15415 for (i = 0; i < prog->aux->size_poke_tab; i++) { 15416 map_ptr = prog->aux->poke_tab[i].tail_call.map; 15417 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 15418 } 15419 /* At this point we're guaranteed that poke descriptors are not 15420 * live anymore. We can just unlink its descriptor table as it's 15421 * released with the main prog. 15422 */ 15423 for (i = 0; i < env->subprog_cnt; i++) { 15424 if (!func[i]) 15425 continue; 15426 func[i]->aux->poke_tab = NULL; 15427 bpf_jit_free(func[i]); 15428 } 15429 kfree(func); 15430 out_undo_insn: 15431 /* cleanup main prog to be interpreted */ 15432 prog->jit_requested = 0; 15433 prog->blinding_requested = 0; 15434 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 15435 if (!bpf_pseudo_call(insn)) 15436 continue; 15437 insn->off = 0; 15438 insn->imm = env->insn_aux_data[i].call_imm; 15439 } 15440 bpf_prog_jit_attempt_done(prog); 15441 return err; 15442 } 15443 15444 static int fixup_call_args(struct bpf_verifier_env *env) 15445 { 15446 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 15447 struct bpf_prog *prog = env->prog; 15448 struct bpf_insn *insn = prog->insnsi; 15449 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 15450 int i, depth; 15451 #endif 15452 int err = 0; 15453 15454 if (env->prog->jit_requested && 15455 !bpf_prog_is_dev_bound(env->prog->aux)) { 15456 err = jit_subprogs(env); 15457 if (err == 0) 15458 return 0; 15459 if (err == -EFAULT) 15460 return err; 15461 } 15462 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 15463 if (has_kfunc_call) { 15464 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 15465 return -EINVAL; 15466 } 15467 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 15468 /* When JIT fails the progs with bpf2bpf calls and tail_calls 15469 * have to be rejected, since interpreter doesn't support them yet. 15470 */ 15471 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 15472 return -EINVAL; 15473 } 15474 for (i = 0; i < prog->len; i++, insn++) { 15475 if (bpf_pseudo_func(insn)) { 15476 /* When JIT fails the progs with callback calls 15477 * have to be rejected, since interpreter doesn't support them yet. 15478 */ 15479 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 15480 return -EINVAL; 15481 } 15482 15483 if (!bpf_pseudo_call(insn)) 15484 continue; 15485 depth = get_callee_stack_depth(env, insn, i); 15486 if (depth < 0) 15487 return depth; 15488 bpf_patch_call_args(insn, depth); 15489 } 15490 err = 0; 15491 #endif 15492 return err; 15493 } 15494 15495 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 15496 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 15497 { 15498 const struct bpf_kfunc_desc *desc; 15499 15500 if (!insn->imm) { 15501 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 15502 return -EINVAL; 15503 } 15504 15505 /* insn->imm has the btf func_id. Replace it with 15506 * an address (relative to __bpf_call_base). 15507 */ 15508 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 15509 if (!desc) { 15510 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 15511 insn->imm); 15512 return -EFAULT; 15513 } 15514 15515 *cnt = 0; 15516 insn->imm = desc->imm; 15517 if (insn->off) 15518 return 0; 15519 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 15520 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 15521 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 15522 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 15523 15524 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 15525 insn_buf[1] = addr[0]; 15526 insn_buf[2] = addr[1]; 15527 insn_buf[3] = *insn; 15528 *cnt = 4; 15529 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 15530 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 15531 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 15532 15533 insn_buf[0] = addr[0]; 15534 insn_buf[1] = addr[1]; 15535 insn_buf[2] = *insn; 15536 *cnt = 3; 15537 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 15538 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 15539 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 15540 *cnt = 1; 15541 } 15542 return 0; 15543 } 15544 15545 /* Do various post-verification rewrites in a single program pass. 15546 * These rewrites simplify JIT and interpreter implementations. 15547 */ 15548 static int do_misc_fixups(struct bpf_verifier_env *env) 15549 { 15550 struct bpf_prog *prog = env->prog; 15551 enum bpf_attach_type eatype = prog->expected_attach_type; 15552 enum bpf_prog_type prog_type = resolve_prog_type(prog); 15553 struct bpf_insn *insn = prog->insnsi; 15554 const struct bpf_func_proto *fn; 15555 const int insn_cnt = prog->len; 15556 const struct bpf_map_ops *ops; 15557 struct bpf_insn_aux_data *aux; 15558 struct bpf_insn insn_buf[16]; 15559 struct bpf_prog *new_prog; 15560 struct bpf_map *map_ptr; 15561 int i, ret, cnt, delta = 0; 15562 15563 for (i = 0; i < insn_cnt; i++, insn++) { 15564 /* Make divide-by-zero exceptions impossible. */ 15565 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 15566 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 15567 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 15568 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 15569 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 15570 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 15571 struct bpf_insn *patchlet; 15572 struct bpf_insn chk_and_div[] = { 15573 /* [R,W]x div 0 -> 0 */ 15574 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 15575 BPF_JNE | BPF_K, insn->src_reg, 15576 0, 2, 0), 15577 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 15578 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 15579 *insn, 15580 }; 15581 struct bpf_insn chk_and_mod[] = { 15582 /* [R,W]x mod 0 -> [R,W]x */ 15583 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 15584 BPF_JEQ | BPF_K, insn->src_reg, 15585 0, 1 + (is64 ? 0 : 1), 0), 15586 *insn, 15587 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 15588 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 15589 }; 15590 15591 patchlet = isdiv ? chk_and_div : chk_and_mod; 15592 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 15593 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 15594 15595 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 15596 if (!new_prog) 15597 return -ENOMEM; 15598 15599 delta += cnt - 1; 15600 env->prog = prog = new_prog; 15601 insn = new_prog->insnsi + i + delta; 15602 continue; 15603 } 15604 15605 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 15606 if (BPF_CLASS(insn->code) == BPF_LD && 15607 (BPF_MODE(insn->code) == BPF_ABS || 15608 BPF_MODE(insn->code) == BPF_IND)) { 15609 cnt = env->ops->gen_ld_abs(insn, insn_buf); 15610 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 15611 verbose(env, "bpf verifier is misconfigured\n"); 15612 return -EINVAL; 15613 } 15614 15615 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15616 if (!new_prog) 15617 return -ENOMEM; 15618 15619 delta += cnt - 1; 15620 env->prog = prog = new_prog; 15621 insn = new_prog->insnsi + i + delta; 15622 continue; 15623 } 15624 15625 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 15626 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 15627 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 15628 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 15629 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 15630 struct bpf_insn *patch = &insn_buf[0]; 15631 bool issrc, isneg, isimm; 15632 u32 off_reg; 15633 15634 aux = &env->insn_aux_data[i + delta]; 15635 if (!aux->alu_state || 15636 aux->alu_state == BPF_ALU_NON_POINTER) 15637 continue; 15638 15639 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 15640 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 15641 BPF_ALU_SANITIZE_SRC; 15642 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 15643 15644 off_reg = issrc ? insn->src_reg : insn->dst_reg; 15645 if (isimm) { 15646 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 15647 } else { 15648 if (isneg) 15649 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 15650 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 15651 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 15652 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 15653 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 15654 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 15655 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 15656 } 15657 if (!issrc) 15658 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 15659 insn->src_reg = BPF_REG_AX; 15660 if (isneg) 15661 insn->code = insn->code == code_add ? 15662 code_sub : code_add; 15663 *patch++ = *insn; 15664 if (issrc && isneg && !isimm) 15665 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 15666 cnt = patch - insn_buf; 15667 15668 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15669 if (!new_prog) 15670 return -ENOMEM; 15671 15672 delta += cnt - 1; 15673 env->prog = prog = new_prog; 15674 insn = new_prog->insnsi + i + delta; 15675 continue; 15676 } 15677 15678 if (insn->code != (BPF_JMP | BPF_CALL)) 15679 continue; 15680 if (insn->src_reg == BPF_PSEUDO_CALL) 15681 continue; 15682 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15683 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 15684 if (ret) 15685 return ret; 15686 if (cnt == 0) 15687 continue; 15688 15689 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15690 if (!new_prog) 15691 return -ENOMEM; 15692 15693 delta += cnt - 1; 15694 env->prog = prog = new_prog; 15695 insn = new_prog->insnsi + i + delta; 15696 continue; 15697 } 15698 15699 if (insn->imm == BPF_FUNC_get_route_realm) 15700 prog->dst_needed = 1; 15701 if (insn->imm == BPF_FUNC_get_prandom_u32) 15702 bpf_user_rnd_init_once(); 15703 if (insn->imm == BPF_FUNC_override_return) 15704 prog->kprobe_override = 1; 15705 if (insn->imm == BPF_FUNC_tail_call) { 15706 /* If we tail call into other programs, we 15707 * cannot make any assumptions since they can 15708 * be replaced dynamically during runtime in 15709 * the program array. 15710 */ 15711 prog->cb_access = 1; 15712 if (!allow_tail_call_in_subprogs(env)) 15713 prog->aux->stack_depth = MAX_BPF_STACK; 15714 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 15715 15716 /* mark bpf_tail_call as different opcode to avoid 15717 * conditional branch in the interpreter for every normal 15718 * call and to prevent accidental JITing by JIT compiler 15719 * that doesn't support bpf_tail_call yet 15720 */ 15721 insn->imm = 0; 15722 insn->code = BPF_JMP | BPF_TAIL_CALL; 15723 15724 aux = &env->insn_aux_data[i + delta]; 15725 if (env->bpf_capable && !prog->blinding_requested && 15726 prog->jit_requested && 15727 !bpf_map_key_poisoned(aux) && 15728 !bpf_map_ptr_poisoned(aux) && 15729 !bpf_map_ptr_unpriv(aux)) { 15730 struct bpf_jit_poke_descriptor desc = { 15731 .reason = BPF_POKE_REASON_TAIL_CALL, 15732 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 15733 .tail_call.key = bpf_map_key_immediate(aux), 15734 .insn_idx = i + delta, 15735 }; 15736 15737 ret = bpf_jit_add_poke_descriptor(prog, &desc); 15738 if (ret < 0) { 15739 verbose(env, "adding tail call poke descriptor failed\n"); 15740 return ret; 15741 } 15742 15743 insn->imm = ret + 1; 15744 continue; 15745 } 15746 15747 if (!bpf_map_ptr_unpriv(aux)) 15748 continue; 15749 15750 /* instead of changing every JIT dealing with tail_call 15751 * emit two extra insns: 15752 * if (index >= max_entries) goto out; 15753 * index &= array->index_mask; 15754 * to avoid out-of-bounds cpu speculation 15755 */ 15756 if (bpf_map_ptr_poisoned(aux)) { 15757 verbose(env, "tail_call abusing map_ptr\n"); 15758 return -EINVAL; 15759 } 15760 15761 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 15762 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 15763 map_ptr->max_entries, 2); 15764 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 15765 container_of(map_ptr, 15766 struct bpf_array, 15767 map)->index_mask); 15768 insn_buf[2] = *insn; 15769 cnt = 3; 15770 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15771 if (!new_prog) 15772 return -ENOMEM; 15773 15774 delta += cnt - 1; 15775 env->prog = prog = new_prog; 15776 insn = new_prog->insnsi + i + delta; 15777 continue; 15778 } 15779 15780 if (insn->imm == BPF_FUNC_timer_set_callback) { 15781 /* The verifier will process callback_fn as many times as necessary 15782 * with different maps and the register states prepared by 15783 * set_timer_callback_state will be accurate. 15784 * 15785 * The following use case is valid: 15786 * map1 is shared by prog1, prog2, prog3. 15787 * prog1 calls bpf_timer_init for some map1 elements 15788 * prog2 calls bpf_timer_set_callback for some map1 elements. 15789 * Those that were not bpf_timer_init-ed will return -EINVAL. 15790 * prog3 calls bpf_timer_start for some map1 elements. 15791 * Those that were not both bpf_timer_init-ed and 15792 * bpf_timer_set_callback-ed will return -EINVAL. 15793 */ 15794 struct bpf_insn ld_addrs[2] = { 15795 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 15796 }; 15797 15798 insn_buf[0] = ld_addrs[0]; 15799 insn_buf[1] = ld_addrs[1]; 15800 insn_buf[2] = *insn; 15801 cnt = 3; 15802 15803 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15804 if (!new_prog) 15805 return -ENOMEM; 15806 15807 delta += cnt - 1; 15808 env->prog = prog = new_prog; 15809 insn = new_prog->insnsi + i + delta; 15810 goto patch_call_imm; 15811 } 15812 15813 if (is_storage_get_function(insn->imm)) { 15814 if (!env->prog->aux->sleepable || 15815 env->insn_aux_data[i + delta].storage_get_func_atomic) 15816 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 15817 else 15818 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 15819 insn_buf[1] = *insn; 15820 cnt = 2; 15821 15822 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15823 if (!new_prog) 15824 return -ENOMEM; 15825 15826 delta += cnt - 1; 15827 env->prog = prog = new_prog; 15828 insn = new_prog->insnsi + i + delta; 15829 goto patch_call_imm; 15830 } 15831 15832 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 15833 * and other inlining handlers are currently limited to 64 bit 15834 * only. 15835 */ 15836 if (prog->jit_requested && BITS_PER_LONG == 64 && 15837 (insn->imm == BPF_FUNC_map_lookup_elem || 15838 insn->imm == BPF_FUNC_map_update_elem || 15839 insn->imm == BPF_FUNC_map_delete_elem || 15840 insn->imm == BPF_FUNC_map_push_elem || 15841 insn->imm == BPF_FUNC_map_pop_elem || 15842 insn->imm == BPF_FUNC_map_peek_elem || 15843 insn->imm == BPF_FUNC_redirect_map || 15844 insn->imm == BPF_FUNC_for_each_map_elem || 15845 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 15846 aux = &env->insn_aux_data[i + delta]; 15847 if (bpf_map_ptr_poisoned(aux)) 15848 goto patch_call_imm; 15849 15850 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 15851 ops = map_ptr->ops; 15852 if (insn->imm == BPF_FUNC_map_lookup_elem && 15853 ops->map_gen_lookup) { 15854 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 15855 if (cnt == -EOPNOTSUPP) 15856 goto patch_map_ops_generic; 15857 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 15858 verbose(env, "bpf verifier is misconfigured\n"); 15859 return -EINVAL; 15860 } 15861 15862 new_prog = bpf_patch_insn_data(env, i + delta, 15863 insn_buf, cnt); 15864 if (!new_prog) 15865 return -ENOMEM; 15866 15867 delta += cnt - 1; 15868 env->prog = prog = new_prog; 15869 insn = new_prog->insnsi + i + delta; 15870 continue; 15871 } 15872 15873 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 15874 (void *(*)(struct bpf_map *map, void *key))NULL)); 15875 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 15876 (int (*)(struct bpf_map *map, void *key))NULL)); 15877 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 15878 (int (*)(struct bpf_map *map, void *key, void *value, 15879 u64 flags))NULL)); 15880 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 15881 (int (*)(struct bpf_map *map, void *value, 15882 u64 flags))NULL)); 15883 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 15884 (int (*)(struct bpf_map *map, void *value))NULL)); 15885 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 15886 (int (*)(struct bpf_map *map, void *value))NULL)); 15887 BUILD_BUG_ON(!__same_type(ops->map_redirect, 15888 (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 15889 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 15890 (int (*)(struct bpf_map *map, 15891 bpf_callback_t callback_fn, 15892 void *callback_ctx, 15893 u64 flags))NULL)); 15894 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 15895 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 15896 15897 patch_map_ops_generic: 15898 switch (insn->imm) { 15899 case BPF_FUNC_map_lookup_elem: 15900 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 15901 continue; 15902 case BPF_FUNC_map_update_elem: 15903 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 15904 continue; 15905 case BPF_FUNC_map_delete_elem: 15906 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 15907 continue; 15908 case BPF_FUNC_map_push_elem: 15909 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 15910 continue; 15911 case BPF_FUNC_map_pop_elem: 15912 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 15913 continue; 15914 case BPF_FUNC_map_peek_elem: 15915 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 15916 continue; 15917 case BPF_FUNC_redirect_map: 15918 insn->imm = BPF_CALL_IMM(ops->map_redirect); 15919 continue; 15920 case BPF_FUNC_for_each_map_elem: 15921 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 15922 continue; 15923 case BPF_FUNC_map_lookup_percpu_elem: 15924 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 15925 continue; 15926 } 15927 15928 goto patch_call_imm; 15929 } 15930 15931 /* Implement bpf_jiffies64 inline. */ 15932 if (prog->jit_requested && BITS_PER_LONG == 64 && 15933 insn->imm == BPF_FUNC_jiffies64) { 15934 struct bpf_insn ld_jiffies_addr[2] = { 15935 BPF_LD_IMM64(BPF_REG_0, 15936 (unsigned long)&jiffies), 15937 }; 15938 15939 insn_buf[0] = ld_jiffies_addr[0]; 15940 insn_buf[1] = ld_jiffies_addr[1]; 15941 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 15942 BPF_REG_0, 0); 15943 cnt = 3; 15944 15945 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 15946 cnt); 15947 if (!new_prog) 15948 return -ENOMEM; 15949 15950 delta += cnt - 1; 15951 env->prog = prog = new_prog; 15952 insn = new_prog->insnsi + i + delta; 15953 continue; 15954 } 15955 15956 /* Implement bpf_get_func_arg inline. */ 15957 if (prog_type == BPF_PROG_TYPE_TRACING && 15958 insn->imm == BPF_FUNC_get_func_arg) { 15959 /* Load nr_args from ctx - 8 */ 15960 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 15961 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 15962 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 15963 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 15964 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 15965 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 15966 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 15967 insn_buf[7] = BPF_JMP_A(1); 15968 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 15969 cnt = 9; 15970 15971 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15972 if (!new_prog) 15973 return -ENOMEM; 15974 15975 delta += cnt - 1; 15976 env->prog = prog = new_prog; 15977 insn = new_prog->insnsi + i + delta; 15978 continue; 15979 } 15980 15981 /* Implement bpf_get_func_ret inline. */ 15982 if (prog_type == BPF_PROG_TYPE_TRACING && 15983 insn->imm == BPF_FUNC_get_func_ret) { 15984 if (eatype == BPF_TRACE_FEXIT || 15985 eatype == BPF_MODIFY_RETURN) { 15986 /* Load nr_args from ctx - 8 */ 15987 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 15988 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 15989 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 15990 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 15991 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 15992 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 15993 cnt = 6; 15994 } else { 15995 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 15996 cnt = 1; 15997 } 15998 15999 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16000 if (!new_prog) 16001 return -ENOMEM; 16002 16003 delta += cnt - 1; 16004 env->prog = prog = new_prog; 16005 insn = new_prog->insnsi + i + delta; 16006 continue; 16007 } 16008 16009 /* Implement get_func_arg_cnt inline. */ 16010 if (prog_type == BPF_PROG_TYPE_TRACING && 16011 insn->imm == BPF_FUNC_get_func_arg_cnt) { 16012 /* Load nr_args from ctx - 8 */ 16013 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 16014 16015 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 16016 if (!new_prog) 16017 return -ENOMEM; 16018 16019 env->prog = prog = new_prog; 16020 insn = new_prog->insnsi + i + delta; 16021 continue; 16022 } 16023 16024 /* Implement bpf_get_func_ip inline. */ 16025 if (prog_type == BPF_PROG_TYPE_TRACING && 16026 insn->imm == BPF_FUNC_get_func_ip) { 16027 /* Load IP address from ctx - 16 */ 16028 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 16029 16030 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 16031 if (!new_prog) 16032 return -ENOMEM; 16033 16034 env->prog = prog = new_prog; 16035 insn = new_prog->insnsi + i + delta; 16036 continue; 16037 } 16038 16039 patch_call_imm: 16040 fn = env->ops->get_func_proto(insn->imm, env->prog); 16041 /* all functions that have prototype and verifier allowed 16042 * programs to call them, must be real in-kernel functions 16043 */ 16044 if (!fn->func) { 16045 verbose(env, 16046 "kernel subsystem misconfigured func %s#%d\n", 16047 func_id_name(insn->imm), insn->imm); 16048 return -EFAULT; 16049 } 16050 insn->imm = fn->func - __bpf_call_base; 16051 } 16052 16053 /* Since poke tab is now finalized, publish aux to tracker. */ 16054 for (i = 0; i < prog->aux->size_poke_tab; i++) { 16055 map_ptr = prog->aux->poke_tab[i].tail_call.map; 16056 if (!map_ptr->ops->map_poke_track || 16057 !map_ptr->ops->map_poke_untrack || 16058 !map_ptr->ops->map_poke_run) { 16059 verbose(env, "bpf verifier is misconfigured\n"); 16060 return -EINVAL; 16061 } 16062 16063 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 16064 if (ret < 0) { 16065 verbose(env, "tracking tail call prog failed\n"); 16066 return ret; 16067 } 16068 } 16069 16070 sort_kfunc_descs_by_imm(env->prog); 16071 16072 return 0; 16073 } 16074 16075 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 16076 int position, 16077 s32 stack_base, 16078 u32 callback_subprogno, 16079 u32 *cnt) 16080 { 16081 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 16082 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 16083 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 16084 int reg_loop_max = BPF_REG_6; 16085 int reg_loop_cnt = BPF_REG_7; 16086 int reg_loop_ctx = BPF_REG_8; 16087 16088 struct bpf_prog *new_prog; 16089 u32 callback_start; 16090 u32 call_insn_offset; 16091 s32 callback_offset; 16092 16093 /* This represents an inlined version of bpf_iter.c:bpf_loop, 16094 * be careful to modify this code in sync. 16095 */ 16096 struct bpf_insn insn_buf[] = { 16097 /* Return error and jump to the end of the patch if 16098 * expected number of iterations is too big. 16099 */ 16100 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 16101 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 16102 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 16103 /* spill R6, R7, R8 to use these as loop vars */ 16104 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 16105 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 16106 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 16107 /* initialize loop vars */ 16108 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 16109 BPF_MOV32_IMM(reg_loop_cnt, 0), 16110 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 16111 /* loop header, 16112 * if reg_loop_cnt >= reg_loop_max skip the loop body 16113 */ 16114 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 16115 /* callback call, 16116 * correct callback offset would be set after patching 16117 */ 16118 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 16119 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 16120 BPF_CALL_REL(0), 16121 /* increment loop counter */ 16122 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 16123 /* jump to loop header if callback returned 0 */ 16124 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 16125 /* return value of bpf_loop, 16126 * set R0 to the number of iterations 16127 */ 16128 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 16129 /* restore original values of R6, R7, R8 */ 16130 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 16131 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 16132 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 16133 }; 16134 16135 *cnt = ARRAY_SIZE(insn_buf); 16136 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 16137 if (!new_prog) 16138 return new_prog; 16139 16140 /* callback start is known only after patching */ 16141 callback_start = env->subprog_info[callback_subprogno].start; 16142 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 16143 call_insn_offset = position + 12; 16144 callback_offset = callback_start - call_insn_offset - 1; 16145 new_prog->insnsi[call_insn_offset].imm = callback_offset; 16146 16147 return new_prog; 16148 } 16149 16150 static bool is_bpf_loop_call(struct bpf_insn *insn) 16151 { 16152 return insn->code == (BPF_JMP | BPF_CALL) && 16153 insn->src_reg == 0 && 16154 insn->imm == BPF_FUNC_loop; 16155 } 16156 16157 /* For all sub-programs in the program (including main) check 16158 * insn_aux_data to see if there are bpf_loop calls that require 16159 * inlining. If such calls are found the calls are replaced with a 16160 * sequence of instructions produced by `inline_bpf_loop` function and 16161 * subprog stack_depth is increased by the size of 3 registers. 16162 * This stack space is used to spill values of the R6, R7, R8. These 16163 * registers are used to store the loop bound, counter and context 16164 * variables. 16165 */ 16166 static int optimize_bpf_loop(struct bpf_verifier_env *env) 16167 { 16168 struct bpf_subprog_info *subprogs = env->subprog_info; 16169 int i, cur_subprog = 0, cnt, delta = 0; 16170 struct bpf_insn *insn = env->prog->insnsi; 16171 int insn_cnt = env->prog->len; 16172 u16 stack_depth = subprogs[cur_subprog].stack_depth; 16173 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 16174 u16 stack_depth_extra = 0; 16175 16176 for (i = 0; i < insn_cnt; i++, insn++) { 16177 struct bpf_loop_inline_state *inline_state = 16178 &env->insn_aux_data[i + delta].loop_inline_state; 16179 16180 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 16181 struct bpf_prog *new_prog; 16182 16183 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 16184 new_prog = inline_bpf_loop(env, 16185 i + delta, 16186 -(stack_depth + stack_depth_extra), 16187 inline_state->callback_subprogno, 16188 &cnt); 16189 if (!new_prog) 16190 return -ENOMEM; 16191 16192 delta += cnt - 1; 16193 env->prog = new_prog; 16194 insn = new_prog->insnsi + i + delta; 16195 } 16196 16197 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 16198 subprogs[cur_subprog].stack_depth += stack_depth_extra; 16199 cur_subprog++; 16200 stack_depth = subprogs[cur_subprog].stack_depth; 16201 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 16202 stack_depth_extra = 0; 16203 } 16204 } 16205 16206 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 16207 16208 return 0; 16209 } 16210 16211 static void free_states(struct bpf_verifier_env *env) 16212 { 16213 struct bpf_verifier_state_list *sl, *sln; 16214 int i; 16215 16216 sl = env->free_list; 16217 while (sl) { 16218 sln = sl->next; 16219 free_verifier_state(&sl->state, false); 16220 kfree(sl); 16221 sl = sln; 16222 } 16223 env->free_list = NULL; 16224 16225 if (!env->explored_states) 16226 return; 16227 16228 for (i = 0; i < state_htab_size(env); i++) { 16229 sl = env->explored_states[i]; 16230 16231 while (sl) { 16232 sln = sl->next; 16233 free_verifier_state(&sl->state, false); 16234 kfree(sl); 16235 sl = sln; 16236 } 16237 env->explored_states[i] = NULL; 16238 } 16239 } 16240 16241 static int do_check_common(struct bpf_verifier_env *env, int subprog) 16242 { 16243 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 16244 struct bpf_verifier_state *state; 16245 struct bpf_reg_state *regs; 16246 int ret, i; 16247 16248 env->prev_linfo = NULL; 16249 env->pass_cnt++; 16250 16251 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 16252 if (!state) 16253 return -ENOMEM; 16254 state->curframe = 0; 16255 state->speculative = false; 16256 state->branches = 1; 16257 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 16258 if (!state->frame[0]) { 16259 kfree(state); 16260 return -ENOMEM; 16261 } 16262 env->cur_state = state; 16263 init_func_state(env, state->frame[0], 16264 BPF_MAIN_FUNC /* callsite */, 16265 0 /* frameno */, 16266 subprog); 16267 state->first_insn_idx = env->subprog_info[subprog].start; 16268 state->last_insn_idx = -1; 16269 16270 regs = state->frame[state->curframe]->regs; 16271 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 16272 ret = btf_prepare_func_args(env, subprog, regs); 16273 if (ret) 16274 goto out; 16275 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 16276 if (regs[i].type == PTR_TO_CTX) 16277 mark_reg_known_zero(env, regs, i); 16278 else if (regs[i].type == SCALAR_VALUE) 16279 mark_reg_unknown(env, regs, i); 16280 else if (base_type(regs[i].type) == PTR_TO_MEM) { 16281 const u32 mem_size = regs[i].mem_size; 16282 16283 mark_reg_known_zero(env, regs, i); 16284 regs[i].mem_size = mem_size; 16285 regs[i].id = ++env->id_gen; 16286 } 16287 } 16288 } else { 16289 /* 1st arg to a function */ 16290 regs[BPF_REG_1].type = PTR_TO_CTX; 16291 mark_reg_known_zero(env, regs, BPF_REG_1); 16292 ret = btf_check_subprog_arg_match(env, subprog, regs); 16293 if (ret == -EFAULT) 16294 /* unlikely verifier bug. abort. 16295 * ret == 0 and ret < 0 are sadly acceptable for 16296 * main() function due to backward compatibility. 16297 * Like socket filter program may be written as: 16298 * int bpf_prog(struct pt_regs *ctx) 16299 * and never dereference that ctx in the program. 16300 * 'struct pt_regs' is a type mismatch for socket 16301 * filter that should be using 'struct __sk_buff'. 16302 */ 16303 goto out; 16304 } 16305 16306 ret = do_check(env); 16307 out: 16308 /* check for NULL is necessary, since cur_state can be freed inside 16309 * do_check() under memory pressure. 16310 */ 16311 if (env->cur_state) { 16312 free_verifier_state(env->cur_state, true); 16313 env->cur_state = NULL; 16314 } 16315 while (!pop_stack(env, NULL, NULL, false)); 16316 if (!ret && pop_log) 16317 bpf_vlog_reset(&env->log, 0); 16318 free_states(env); 16319 return ret; 16320 } 16321 16322 /* Verify all global functions in a BPF program one by one based on their BTF. 16323 * All global functions must pass verification. Otherwise the whole program is rejected. 16324 * Consider: 16325 * int bar(int); 16326 * int foo(int f) 16327 * { 16328 * return bar(f); 16329 * } 16330 * int bar(int b) 16331 * { 16332 * ... 16333 * } 16334 * foo() will be verified first for R1=any_scalar_value. During verification it 16335 * will be assumed that bar() already verified successfully and call to bar() 16336 * from foo() will be checked for type match only. Later bar() will be verified 16337 * independently to check that it's safe for R1=any_scalar_value. 16338 */ 16339 static int do_check_subprogs(struct bpf_verifier_env *env) 16340 { 16341 struct bpf_prog_aux *aux = env->prog->aux; 16342 int i, ret; 16343 16344 if (!aux->func_info) 16345 return 0; 16346 16347 for (i = 1; i < env->subprog_cnt; i++) { 16348 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 16349 continue; 16350 env->insn_idx = env->subprog_info[i].start; 16351 WARN_ON_ONCE(env->insn_idx == 0); 16352 ret = do_check_common(env, i); 16353 if (ret) { 16354 return ret; 16355 } else if (env->log.level & BPF_LOG_LEVEL) { 16356 verbose(env, 16357 "Func#%d is safe for any args that match its prototype\n", 16358 i); 16359 } 16360 } 16361 return 0; 16362 } 16363 16364 static int do_check_main(struct bpf_verifier_env *env) 16365 { 16366 int ret; 16367 16368 env->insn_idx = 0; 16369 ret = do_check_common(env, 0); 16370 if (!ret) 16371 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 16372 return ret; 16373 } 16374 16375 16376 static void print_verification_stats(struct bpf_verifier_env *env) 16377 { 16378 int i; 16379 16380 if (env->log.level & BPF_LOG_STATS) { 16381 verbose(env, "verification time %lld usec\n", 16382 div_u64(env->verification_time, 1000)); 16383 verbose(env, "stack depth "); 16384 for (i = 0; i < env->subprog_cnt; i++) { 16385 u32 depth = env->subprog_info[i].stack_depth; 16386 16387 verbose(env, "%d", depth); 16388 if (i + 1 < env->subprog_cnt) 16389 verbose(env, "+"); 16390 } 16391 verbose(env, "\n"); 16392 } 16393 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 16394 "total_states %d peak_states %d mark_read %d\n", 16395 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 16396 env->max_states_per_insn, env->total_states, 16397 env->peak_states, env->longest_mark_read_walk); 16398 } 16399 16400 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 16401 { 16402 const struct btf_type *t, *func_proto; 16403 const struct bpf_struct_ops *st_ops; 16404 const struct btf_member *member; 16405 struct bpf_prog *prog = env->prog; 16406 u32 btf_id, member_idx; 16407 const char *mname; 16408 16409 if (!prog->gpl_compatible) { 16410 verbose(env, "struct ops programs must have a GPL compatible license\n"); 16411 return -EINVAL; 16412 } 16413 16414 btf_id = prog->aux->attach_btf_id; 16415 st_ops = bpf_struct_ops_find(btf_id); 16416 if (!st_ops) { 16417 verbose(env, "attach_btf_id %u is not a supported struct\n", 16418 btf_id); 16419 return -ENOTSUPP; 16420 } 16421 16422 t = st_ops->type; 16423 member_idx = prog->expected_attach_type; 16424 if (member_idx >= btf_type_vlen(t)) { 16425 verbose(env, "attach to invalid member idx %u of struct %s\n", 16426 member_idx, st_ops->name); 16427 return -EINVAL; 16428 } 16429 16430 member = &btf_type_member(t)[member_idx]; 16431 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 16432 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 16433 NULL); 16434 if (!func_proto) { 16435 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 16436 mname, member_idx, st_ops->name); 16437 return -EINVAL; 16438 } 16439 16440 if (st_ops->check_member) { 16441 int err = st_ops->check_member(t, member); 16442 16443 if (err) { 16444 verbose(env, "attach to unsupported member %s of struct %s\n", 16445 mname, st_ops->name); 16446 return err; 16447 } 16448 } 16449 16450 prog->aux->attach_func_proto = func_proto; 16451 prog->aux->attach_func_name = mname; 16452 env->ops = st_ops->verifier_ops; 16453 16454 return 0; 16455 } 16456 #define SECURITY_PREFIX "security_" 16457 16458 static int check_attach_modify_return(unsigned long addr, const char *func_name) 16459 { 16460 if (within_error_injection_list(addr) || 16461 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 16462 return 0; 16463 16464 return -EINVAL; 16465 } 16466 16467 /* list of non-sleepable functions that are otherwise on 16468 * ALLOW_ERROR_INJECTION list 16469 */ 16470 BTF_SET_START(btf_non_sleepable_error_inject) 16471 /* Three functions below can be called from sleepable and non-sleepable context. 16472 * Assume non-sleepable from bpf safety point of view. 16473 */ 16474 BTF_ID(func, __filemap_add_folio) 16475 BTF_ID(func, should_fail_alloc_page) 16476 BTF_ID(func, should_failslab) 16477 BTF_SET_END(btf_non_sleepable_error_inject) 16478 16479 static int check_non_sleepable_error_inject(u32 btf_id) 16480 { 16481 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 16482 } 16483 16484 int bpf_check_attach_target(struct bpf_verifier_log *log, 16485 const struct bpf_prog *prog, 16486 const struct bpf_prog *tgt_prog, 16487 u32 btf_id, 16488 struct bpf_attach_target_info *tgt_info) 16489 { 16490 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 16491 const char prefix[] = "btf_trace_"; 16492 int ret = 0, subprog = -1, i; 16493 const struct btf_type *t; 16494 bool conservative = true; 16495 const char *tname; 16496 struct btf *btf; 16497 long addr = 0; 16498 16499 if (!btf_id) { 16500 bpf_log(log, "Tracing programs must provide btf_id\n"); 16501 return -EINVAL; 16502 } 16503 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 16504 if (!btf) { 16505 bpf_log(log, 16506 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 16507 return -EINVAL; 16508 } 16509 t = btf_type_by_id(btf, btf_id); 16510 if (!t) { 16511 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 16512 return -EINVAL; 16513 } 16514 tname = btf_name_by_offset(btf, t->name_off); 16515 if (!tname) { 16516 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 16517 return -EINVAL; 16518 } 16519 if (tgt_prog) { 16520 struct bpf_prog_aux *aux = tgt_prog->aux; 16521 16522 for (i = 0; i < aux->func_info_cnt; i++) 16523 if (aux->func_info[i].type_id == btf_id) { 16524 subprog = i; 16525 break; 16526 } 16527 if (subprog == -1) { 16528 bpf_log(log, "Subprog %s doesn't exist\n", tname); 16529 return -EINVAL; 16530 } 16531 conservative = aux->func_info_aux[subprog].unreliable; 16532 if (prog_extension) { 16533 if (conservative) { 16534 bpf_log(log, 16535 "Cannot replace static functions\n"); 16536 return -EINVAL; 16537 } 16538 if (!prog->jit_requested) { 16539 bpf_log(log, 16540 "Extension programs should be JITed\n"); 16541 return -EINVAL; 16542 } 16543 } 16544 if (!tgt_prog->jited) { 16545 bpf_log(log, "Can attach to only JITed progs\n"); 16546 return -EINVAL; 16547 } 16548 if (tgt_prog->type == prog->type) { 16549 /* Cannot fentry/fexit another fentry/fexit program. 16550 * Cannot attach program extension to another extension. 16551 * It's ok to attach fentry/fexit to extension program. 16552 */ 16553 bpf_log(log, "Cannot recursively attach\n"); 16554 return -EINVAL; 16555 } 16556 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 16557 prog_extension && 16558 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 16559 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 16560 /* Program extensions can extend all program types 16561 * except fentry/fexit. The reason is the following. 16562 * The fentry/fexit programs are used for performance 16563 * analysis, stats and can be attached to any program 16564 * type except themselves. When extension program is 16565 * replacing XDP function it is necessary to allow 16566 * performance analysis of all functions. Both original 16567 * XDP program and its program extension. Hence 16568 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 16569 * allowed. If extending of fentry/fexit was allowed it 16570 * would be possible to create long call chain 16571 * fentry->extension->fentry->extension beyond 16572 * reasonable stack size. Hence extending fentry is not 16573 * allowed. 16574 */ 16575 bpf_log(log, "Cannot extend fentry/fexit\n"); 16576 return -EINVAL; 16577 } 16578 } else { 16579 if (prog_extension) { 16580 bpf_log(log, "Cannot replace kernel functions\n"); 16581 return -EINVAL; 16582 } 16583 } 16584 16585 switch (prog->expected_attach_type) { 16586 case BPF_TRACE_RAW_TP: 16587 if (tgt_prog) { 16588 bpf_log(log, 16589 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 16590 return -EINVAL; 16591 } 16592 if (!btf_type_is_typedef(t)) { 16593 bpf_log(log, "attach_btf_id %u is not a typedef\n", 16594 btf_id); 16595 return -EINVAL; 16596 } 16597 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 16598 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 16599 btf_id, tname); 16600 return -EINVAL; 16601 } 16602 tname += sizeof(prefix) - 1; 16603 t = btf_type_by_id(btf, t->type); 16604 if (!btf_type_is_ptr(t)) 16605 /* should never happen in valid vmlinux build */ 16606 return -EINVAL; 16607 t = btf_type_by_id(btf, t->type); 16608 if (!btf_type_is_func_proto(t)) 16609 /* should never happen in valid vmlinux build */ 16610 return -EINVAL; 16611 16612 break; 16613 case BPF_TRACE_ITER: 16614 if (!btf_type_is_func(t)) { 16615 bpf_log(log, "attach_btf_id %u is not a function\n", 16616 btf_id); 16617 return -EINVAL; 16618 } 16619 t = btf_type_by_id(btf, t->type); 16620 if (!btf_type_is_func_proto(t)) 16621 return -EINVAL; 16622 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 16623 if (ret) 16624 return ret; 16625 break; 16626 default: 16627 if (!prog_extension) 16628 return -EINVAL; 16629 fallthrough; 16630 case BPF_MODIFY_RETURN: 16631 case BPF_LSM_MAC: 16632 case BPF_LSM_CGROUP: 16633 case BPF_TRACE_FENTRY: 16634 case BPF_TRACE_FEXIT: 16635 if (!btf_type_is_func(t)) { 16636 bpf_log(log, "attach_btf_id %u is not a function\n", 16637 btf_id); 16638 return -EINVAL; 16639 } 16640 if (prog_extension && 16641 btf_check_type_match(log, prog, btf, t)) 16642 return -EINVAL; 16643 t = btf_type_by_id(btf, t->type); 16644 if (!btf_type_is_func_proto(t)) 16645 return -EINVAL; 16646 16647 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 16648 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 16649 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 16650 return -EINVAL; 16651 16652 if (tgt_prog && conservative) 16653 t = NULL; 16654 16655 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 16656 if (ret < 0) 16657 return ret; 16658 16659 if (tgt_prog) { 16660 if (subprog == 0) 16661 addr = (long) tgt_prog->bpf_func; 16662 else 16663 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 16664 } else { 16665 addr = kallsyms_lookup_name(tname); 16666 if (!addr) { 16667 bpf_log(log, 16668 "The address of function %s cannot be found\n", 16669 tname); 16670 return -ENOENT; 16671 } 16672 } 16673 16674 if (prog->aux->sleepable) { 16675 ret = -EINVAL; 16676 switch (prog->type) { 16677 case BPF_PROG_TYPE_TRACING: 16678 16679 /* fentry/fexit/fmod_ret progs can be sleepable if they are 16680 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 16681 */ 16682 if (!check_non_sleepable_error_inject(btf_id) && 16683 within_error_injection_list(addr)) 16684 ret = 0; 16685 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 16686 * in the fmodret id set with the KF_SLEEPABLE flag. 16687 */ 16688 else { 16689 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id); 16690 16691 if (flags && (*flags & KF_SLEEPABLE)) 16692 ret = 0; 16693 } 16694 break; 16695 case BPF_PROG_TYPE_LSM: 16696 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 16697 * Only some of them are sleepable. 16698 */ 16699 if (bpf_lsm_is_sleepable_hook(btf_id)) 16700 ret = 0; 16701 break; 16702 default: 16703 break; 16704 } 16705 if (ret) { 16706 bpf_log(log, "%s is not sleepable\n", tname); 16707 return ret; 16708 } 16709 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 16710 if (tgt_prog) { 16711 bpf_log(log, "can't modify return codes of BPF programs\n"); 16712 return -EINVAL; 16713 } 16714 ret = -EINVAL; 16715 if (btf_kfunc_is_modify_return(btf, btf_id) || 16716 !check_attach_modify_return(addr, tname)) 16717 ret = 0; 16718 if (ret) { 16719 bpf_log(log, "%s() is not modifiable\n", tname); 16720 return ret; 16721 } 16722 } 16723 16724 break; 16725 } 16726 tgt_info->tgt_addr = addr; 16727 tgt_info->tgt_name = tname; 16728 tgt_info->tgt_type = t; 16729 return 0; 16730 } 16731 16732 BTF_SET_START(btf_id_deny) 16733 BTF_ID_UNUSED 16734 #ifdef CONFIG_SMP 16735 BTF_ID(func, migrate_disable) 16736 BTF_ID(func, migrate_enable) 16737 #endif 16738 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 16739 BTF_ID(func, rcu_read_unlock_strict) 16740 #endif 16741 BTF_SET_END(btf_id_deny) 16742 16743 static int check_attach_btf_id(struct bpf_verifier_env *env) 16744 { 16745 struct bpf_prog *prog = env->prog; 16746 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 16747 struct bpf_attach_target_info tgt_info = {}; 16748 u32 btf_id = prog->aux->attach_btf_id; 16749 struct bpf_trampoline *tr; 16750 int ret; 16751 u64 key; 16752 16753 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 16754 if (prog->aux->sleepable) 16755 /* attach_btf_id checked to be zero already */ 16756 return 0; 16757 verbose(env, "Syscall programs can only be sleepable\n"); 16758 return -EINVAL; 16759 } 16760 16761 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING && 16762 prog->type != BPF_PROG_TYPE_LSM && prog->type != BPF_PROG_TYPE_KPROBE) { 16763 verbose(env, "Only fentry/fexit/fmod_ret, lsm, and kprobe/uprobe programs can be sleepable\n"); 16764 return -EINVAL; 16765 } 16766 16767 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 16768 return check_struct_ops_btf_id(env); 16769 16770 if (prog->type != BPF_PROG_TYPE_TRACING && 16771 prog->type != BPF_PROG_TYPE_LSM && 16772 prog->type != BPF_PROG_TYPE_EXT) 16773 return 0; 16774 16775 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 16776 if (ret) 16777 return ret; 16778 16779 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 16780 /* to make freplace equivalent to their targets, they need to 16781 * inherit env->ops and expected_attach_type for the rest of the 16782 * verification 16783 */ 16784 env->ops = bpf_verifier_ops[tgt_prog->type]; 16785 prog->expected_attach_type = tgt_prog->expected_attach_type; 16786 } 16787 16788 /* store info about the attachment target that will be used later */ 16789 prog->aux->attach_func_proto = tgt_info.tgt_type; 16790 prog->aux->attach_func_name = tgt_info.tgt_name; 16791 16792 if (tgt_prog) { 16793 prog->aux->saved_dst_prog_type = tgt_prog->type; 16794 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 16795 } 16796 16797 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 16798 prog->aux->attach_btf_trace = true; 16799 return 0; 16800 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 16801 if (!bpf_iter_prog_supported(prog)) 16802 return -EINVAL; 16803 return 0; 16804 } 16805 16806 if (prog->type == BPF_PROG_TYPE_LSM) { 16807 ret = bpf_lsm_verify_prog(&env->log, prog); 16808 if (ret < 0) 16809 return ret; 16810 } else if (prog->type == BPF_PROG_TYPE_TRACING && 16811 btf_id_set_contains(&btf_id_deny, btf_id)) { 16812 return -EINVAL; 16813 } 16814 16815 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 16816 tr = bpf_trampoline_get(key, &tgt_info); 16817 if (!tr) 16818 return -ENOMEM; 16819 16820 prog->aux->dst_trampoline = tr; 16821 return 0; 16822 } 16823 16824 struct btf *bpf_get_btf_vmlinux(void) 16825 { 16826 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 16827 mutex_lock(&bpf_verifier_lock); 16828 if (!btf_vmlinux) 16829 btf_vmlinux = btf_parse_vmlinux(); 16830 mutex_unlock(&bpf_verifier_lock); 16831 } 16832 return btf_vmlinux; 16833 } 16834 16835 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr) 16836 { 16837 u64 start_time = ktime_get_ns(); 16838 struct bpf_verifier_env *env; 16839 struct bpf_verifier_log *log; 16840 int i, len, ret = -EINVAL; 16841 bool is_priv; 16842 16843 /* no program is valid */ 16844 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 16845 return -EINVAL; 16846 16847 /* 'struct bpf_verifier_env' can be global, but since it's not small, 16848 * allocate/free it every time bpf_check() is called 16849 */ 16850 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 16851 if (!env) 16852 return -ENOMEM; 16853 log = &env->log; 16854 16855 len = (*prog)->len; 16856 env->insn_aux_data = 16857 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 16858 ret = -ENOMEM; 16859 if (!env->insn_aux_data) 16860 goto err_free_env; 16861 for (i = 0; i < len; i++) 16862 env->insn_aux_data[i].orig_idx = i; 16863 env->prog = *prog; 16864 env->ops = bpf_verifier_ops[env->prog->type]; 16865 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 16866 is_priv = bpf_capable(); 16867 16868 bpf_get_btf_vmlinux(); 16869 16870 /* grab the mutex to protect few globals used by verifier */ 16871 if (!is_priv) 16872 mutex_lock(&bpf_verifier_lock); 16873 16874 if (attr->log_level || attr->log_buf || attr->log_size) { 16875 /* user requested verbose verifier output 16876 * and supplied buffer to store the verification trace 16877 */ 16878 log->level = attr->log_level; 16879 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 16880 log->len_total = attr->log_size; 16881 16882 /* log attributes have to be sane */ 16883 if (!bpf_verifier_log_attr_valid(log)) { 16884 ret = -EINVAL; 16885 goto err_unlock; 16886 } 16887 } 16888 16889 mark_verifier_state_clean(env); 16890 16891 if (IS_ERR(btf_vmlinux)) { 16892 /* Either gcc or pahole or kernel are broken. */ 16893 verbose(env, "in-kernel BTF is malformed\n"); 16894 ret = PTR_ERR(btf_vmlinux); 16895 goto skip_full_check; 16896 } 16897 16898 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 16899 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 16900 env->strict_alignment = true; 16901 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 16902 env->strict_alignment = false; 16903 16904 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 16905 env->allow_uninit_stack = bpf_allow_uninit_stack(); 16906 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 16907 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 16908 env->bpf_capable = bpf_capable(); 16909 env->rcu_tag_supported = btf_vmlinux && 16910 btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0; 16911 16912 if (is_priv) 16913 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 16914 16915 env->explored_states = kvcalloc(state_htab_size(env), 16916 sizeof(struct bpf_verifier_state_list *), 16917 GFP_USER); 16918 ret = -ENOMEM; 16919 if (!env->explored_states) 16920 goto skip_full_check; 16921 16922 ret = add_subprog_and_kfunc(env); 16923 if (ret < 0) 16924 goto skip_full_check; 16925 16926 ret = check_subprogs(env); 16927 if (ret < 0) 16928 goto skip_full_check; 16929 16930 ret = check_btf_info(env, attr, uattr); 16931 if (ret < 0) 16932 goto skip_full_check; 16933 16934 ret = check_attach_btf_id(env); 16935 if (ret) 16936 goto skip_full_check; 16937 16938 ret = resolve_pseudo_ldimm64(env); 16939 if (ret < 0) 16940 goto skip_full_check; 16941 16942 if (bpf_prog_is_dev_bound(env->prog->aux)) { 16943 ret = bpf_prog_offload_verifier_prep(env->prog); 16944 if (ret) 16945 goto skip_full_check; 16946 } 16947 16948 ret = check_cfg(env); 16949 if (ret < 0) 16950 goto skip_full_check; 16951 16952 ret = do_check_subprogs(env); 16953 ret = ret ?: do_check_main(env); 16954 16955 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux)) 16956 ret = bpf_prog_offload_finalize(env); 16957 16958 skip_full_check: 16959 kvfree(env->explored_states); 16960 16961 if (ret == 0) 16962 ret = check_max_stack_depth(env); 16963 16964 /* instruction rewrites happen after this point */ 16965 if (ret == 0) 16966 ret = optimize_bpf_loop(env); 16967 16968 if (is_priv) { 16969 if (ret == 0) 16970 opt_hard_wire_dead_code_branches(env); 16971 if (ret == 0) 16972 ret = opt_remove_dead_code(env); 16973 if (ret == 0) 16974 ret = opt_remove_nops(env); 16975 } else { 16976 if (ret == 0) 16977 sanitize_dead_code(env); 16978 } 16979 16980 if (ret == 0) 16981 /* program is valid, convert *(u32*)(ctx + off) accesses */ 16982 ret = convert_ctx_accesses(env); 16983 16984 if (ret == 0) 16985 ret = do_misc_fixups(env); 16986 16987 /* do 32-bit optimization after insn patching has done so those patched 16988 * insns could be handled correctly. 16989 */ 16990 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) { 16991 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 16992 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 16993 : false; 16994 } 16995 16996 if (ret == 0) 16997 ret = fixup_call_args(env); 16998 16999 env->verification_time = ktime_get_ns() - start_time; 17000 print_verification_stats(env); 17001 env->prog->aux->verified_insns = env->insn_processed; 17002 17003 if (log->level && bpf_verifier_log_full(log)) 17004 ret = -ENOSPC; 17005 if (log->level && !log->ubuf) { 17006 ret = -EFAULT; 17007 goto err_release_maps; 17008 } 17009 17010 if (ret) 17011 goto err_release_maps; 17012 17013 if (env->used_map_cnt) { 17014 /* if program passed verifier, update used_maps in bpf_prog_info */ 17015 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 17016 sizeof(env->used_maps[0]), 17017 GFP_KERNEL); 17018 17019 if (!env->prog->aux->used_maps) { 17020 ret = -ENOMEM; 17021 goto err_release_maps; 17022 } 17023 17024 memcpy(env->prog->aux->used_maps, env->used_maps, 17025 sizeof(env->used_maps[0]) * env->used_map_cnt); 17026 env->prog->aux->used_map_cnt = env->used_map_cnt; 17027 } 17028 if (env->used_btf_cnt) { 17029 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 17030 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 17031 sizeof(env->used_btfs[0]), 17032 GFP_KERNEL); 17033 if (!env->prog->aux->used_btfs) { 17034 ret = -ENOMEM; 17035 goto err_release_maps; 17036 } 17037 17038 memcpy(env->prog->aux->used_btfs, env->used_btfs, 17039 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 17040 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 17041 } 17042 if (env->used_map_cnt || env->used_btf_cnt) { 17043 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 17044 * bpf_ld_imm64 instructions 17045 */ 17046 convert_pseudo_ld_imm64(env); 17047 } 17048 17049 adjust_btf_func(env); 17050 17051 err_release_maps: 17052 if (!env->prog->aux->used_maps) 17053 /* if we didn't copy map pointers into bpf_prog_info, release 17054 * them now. Otherwise free_used_maps() will release them. 17055 */ 17056 release_maps(env); 17057 if (!env->prog->aux->used_btfs) 17058 release_btfs(env); 17059 17060 /* extension progs temporarily inherit the attach_type of their targets 17061 for verification purposes, so set it back to zero before returning 17062 */ 17063 if (env->prog->type == BPF_PROG_TYPE_EXT) 17064 env->prog->expected_attach_type = 0; 17065 17066 *prog = env->prog; 17067 err_unlock: 17068 if (!is_priv) 17069 mutex_unlock(&bpf_verifier_lock); 17070 vfree(env->insn_aux_data); 17071 err_free_env: 17072 kfree(env); 17073 return ret; 17074 } 17075