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 dynptr_id; 259 int map_uid; 260 int func_id; 261 struct btf *btf; 262 u32 btf_id; 263 struct btf *ret_btf; 264 u32 ret_btf_id; 265 u32 subprogno; 266 struct btf_field *kptr_field; 267 u8 uninit_dynptr_regno; 268 }; 269 270 struct btf *btf_vmlinux; 271 272 static DEFINE_MUTEX(bpf_verifier_lock); 273 274 static const struct bpf_line_info * 275 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 276 { 277 const struct bpf_line_info *linfo; 278 const struct bpf_prog *prog; 279 u32 i, nr_linfo; 280 281 prog = env->prog; 282 nr_linfo = prog->aux->nr_linfo; 283 284 if (!nr_linfo || insn_off >= prog->len) 285 return NULL; 286 287 linfo = prog->aux->linfo; 288 for (i = 1; i < nr_linfo; i++) 289 if (insn_off < linfo[i].insn_off) 290 break; 291 292 return &linfo[i - 1]; 293 } 294 295 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, 296 va_list args) 297 { 298 unsigned int n; 299 300 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); 301 302 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, 303 "verifier log line truncated - local buffer too short\n"); 304 305 if (log->level == BPF_LOG_KERNEL) { 306 bool newline = n > 0 && log->kbuf[n - 1] == '\n'; 307 308 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n"); 309 return; 310 } 311 312 n = min(log->len_total - log->len_used - 1, n); 313 log->kbuf[n] = '\0'; 314 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) 315 log->len_used += n; 316 else 317 log->ubuf = NULL; 318 } 319 320 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos) 321 { 322 char zero = 0; 323 324 if (!bpf_verifier_log_needed(log)) 325 return; 326 327 log->len_used = new_pos; 328 if (put_user(zero, log->ubuf + new_pos)) 329 log->ubuf = NULL; 330 } 331 332 /* log_level controls verbosity level of eBPF verifier. 333 * bpf_verifier_log_write() is used to dump the verification trace to the log, 334 * so the user can figure out what's wrong with the program 335 */ 336 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 337 const char *fmt, ...) 338 { 339 va_list args; 340 341 if (!bpf_verifier_log_needed(&env->log)) 342 return; 343 344 va_start(args, fmt); 345 bpf_verifier_vlog(&env->log, fmt, args); 346 va_end(args); 347 } 348 EXPORT_SYMBOL_GPL(bpf_verifier_log_write); 349 350 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 351 { 352 struct bpf_verifier_env *env = private_data; 353 va_list args; 354 355 if (!bpf_verifier_log_needed(&env->log)) 356 return; 357 358 va_start(args, fmt); 359 bpf_verifier_vlog(&env->log, fmt, args); 360 va_end(args); 361 } 362 363 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log, 364 const char *fmt, ...) 365 { 366 va_list args; 367 368 if (!bpf_verifier_log_needed(log)) 369 return; 370 371 va_start(args, fmt); 372 bpf_verifier_vlog(log, fmt, args); 373 va_end(args); 374 } 375 EXPORT_SYMBOL_GPL(bpf_log); 376 377 static const char *ltrim(const char *s) 378 { 379 while (isspace(*s)) 380 s++; 381 382 return s; 383 } 384 385 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 386 u32 insn_off, 387 const char *prefix_fmt, ...) 388 { 389 const struct bpf_line_info *linfo; 390 391 if (!bpf_verifier_log_needed(&env->log)) 392 return; 393 394 linfo = find_linfo(env, insn_off); 395 if (!linfo || linfo == env->prev_linfo) 396 return; 397 398 if (prefix_fmt) { 399 va_list args; 400 401 va_start(args, prefix_fmt); 402 bpf_verifier_vlog(&env->log, prefix_fmt, args); 403 va_end(args); 404 } 405 406 verbose(env, "%s\n", 407 ltrim(btf_name_by_offset(env->prog->aux->btf, 408 linfo->line_off))); 409 410 env->prev_linfo = linfo; 411 } 412 413 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 414 struct bpf_reg_state *reg, 415 struct tnum *range, const char *ctx, 416 const char *reg_name) 417 { 418 char tn_buf[48]; 419 420 verbose(env, "At %s the register %s ", ctx, reg_name); 421 if (!tnum_is_unknown(reg->var_off)) { 422 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 423 verbose(env, "has value %s", tn_buf); 424 } else { 425 verbose(env, "has unknown scalar value"); 426 } 427 tnum_strn(tn_buf, sizeof(tn_buf), *range); 428 verbose(env, " should have been in %s\n", tn_buf); 429 } 430 431 static bool type_is_pkt_pointer(enum bpf_reg_type type) 432 { 433 type = base_type(type); 434 return type == PTR_TO_PACKET || 435 type == PTR_TO_PACKET_META; 436 } 437 438 static bool type_is_sk_pointer(enum bpf_reg_type type) 439 { 440 return type == PTR_TO_SOCKET || 441 type == PTR_TO_SOCK_COMMON || 442 type == PTR_TO_TCP_SOCK || 443 type == PTR_TO_XDP_SOCK; 444 } 445 446 static bool reg_type_not_null(enum bpf_reg_type type) 447 { 448 return type == PTR_TO_SOCKET || 449 type == PTR_TO_TCP_SOCK || 450 type == PTR_TO_MAP_VALUE || 451 type == PTR_TO_MAP_KEY || 452 type == PTR_TO_SOCK_COMMON; 453 } 454 455 static bool type_is_ptr_alloc_obj(u32 type) 456 { 457 return base_type(type) == PTR_TO_BTF_ID && type_flag(type) & MEM_ALLOC; 458 } 459 460 static struct btf_record *reg_btf_record(const struct bpf_reg_state *reg) 461 { 462 struct btf_record *rec = NULL; 463 struct btf_struct_meta *meta; 464 465 if (reg->type == PTR_TO_MAP_VALUE) { 466 rec = reg->map_ptr->record; 467 } else if (type_is_ptr_alloc_obj(reg->type)) { 468 meta = btf_find_struct_meta(reg->btf, reg->btf_id); 469 if (meta) 470 rec = meta->record; 471 } 472 return rec; 473 } 474 475 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 476 { 477 return btf_record_has_field(reg_btf_record(reg), BPF_SPIN_LOCK); 478 } 479 480 static bool type_is_rdonly_mem(u32 type) 481 { 482 return type & MEM_RDONLY; 483 } 484 485 static bool type_may_be_null(u32 type) 486 { 487 return type & PTR_MAYBE_NULL; 488 } 489 490 static bool is_acquire_function(enum bpf_func_id func_id, 491 const struct bpf_map *map) 492 { 493 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 494 495 if (func_id == BPF_FUNC_sk_lookup_tcp || 496 func_id == BPF_FUNC_sk_lookup_udp || 497 func_id == BPF_FUNC_skc_lookup_tcp || 498 func_id == BPF_FUNC_ringbuf_reserve || 499 func_id == BPF_FUNC_kptr_xchg) 500 return true; 501 502 if (func_id == BPF_FUNC_map_lookup_elem && 503 (map_type == BPF_MAP_TYPE_SOCKMAP || 504 map_type == BPF_MAP_TYPE_SOCKHASH)) 505 return true; 506 507 return false; 508 } 509 510 static bool is_ptr_cast_function(enum bpf_func_id func_id) 511 { 512 return func_id == BPF_FUNC_tcp_sock || 513 func_id == BPF_FUNC_sk_fullsock || 514 func_id == BPF_FUNC_skc_to_tcp_sock || 515 func_id == BPF_FUNC_skc_to_tcp6_sock || 516 func_id == BPF_FUNC_skc_to_udp6_sock || 517 func_id == BPF_FUNC_skc_to_mptcp_sock || 518 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 519 func_id == BPF_FUNC_skc_to_tcp_request_sock; 520 } 521 522 static bool is_dynptr_ref_function(enum bpf_func_id func_id) 523 { 524 return func_id == BPF_FUNC_dynptr_data; 525 } 526 527 static bool is_callback_calling_function(enum bpf_func_id func_id) 528 { 529 return func_id == BPF_FUNC_for_each_map_elem || 530 func_id == BPF_FUNC_timer_set_callback || 531 func_id == BPF_FUNC_find_vma || 532 func_id == BPF_FUNC_loop || 533 func_id == BPF_FUNC_user_ringbuf_drain; 534 } 535 536 static bool is_storage_get_function(enum bpf_func_id func_id) 537 { 538 return func_id == BPF_FUNC_sk_storage_get || 539 func_id == BPF_FUNC_inode_storage_get || 540 func_id == BPF_FUNC_task_storage_get || 541 func_id == BPF_FUNC_cgrp_storage_get; 542 } 543 544 static bool helper_multiple_ref_obj_use(enum bpf_func_id func_id, 545 const struct bpf_map *map) 546 { 547 int ref_obj_uses = 0; 548 549 if (is_ptr_cast_function(func_id)) 550 ref_obj_uses++; 551 if (is_acquire_function(func_id, map)) 552 ref_obj_uses++; 553 if (is_dynptr_ref_function(func_id)) 554 ref_obj_uses++; 555 556 return ref_obj_uses > 1; 557 } 558 559 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 560 { 561 return BPF_CLASS(insn->code) == BPF_STX && 562 BPF_MODE(insn->code) == BPF_ATOMIC && 563 insn->imm == BPF_CMPXCHG; 564 } 565 566 /* string representation of 'enum bpf_reg_type' 567 * 568 * Note that reg_type_str() can not appear more than once in a single verbose() 569 * statement. 570 */ 571 static const char *reg_type_str(struct bpf_verifier_env *env, 572 enum bpf_reg_type type) 573 { 574 char postfix[16] = {0}, prefix[64] = {0}; 575 static const char * const str[] = { 576 [NOT_INIT] = "?", 577 [SCALAR_VALUE] = "scalar", 578 [PTR_TO_CTX] = "ctx", 579 [CONST_PTR_TO_MAP] = "map_ptr", 580 [PTR_TO_MAP_VALUE] = "map_value", 581 [PTR_TO_STACK] = "fp", 582 [PTR_TO_PACKET] = "pkt", 583 [PTR_TO_PACKET_META] = "pkt_meta", 584 [PTR_TO_PACKET_END] = "pkt_end", 585 [PTR_TO_FLOW_KEYS] = "flow_keys", 586 [PTR_TO_SOCKET] = "sock", 587 [PTR_TO_SOCK_COMMON] = "sock_common", 588 [PTR_TO_TCP_SOCK] = "tcp_sock", 589 [PTR_TO_TP_BUFFER] = "tp_buffer", 590 [PTR_TO_XDP_SOCK] = "xdp_sock", 591 [PTR_TO_BTF_ID] = "ptr_", 592 [PTR_TO_MEM] = "mem", 593 [PTR_TO_BUF] = "buf", 594 [PTR_TO_FUNC] = "func", 595 [PTR_TO_MAP_KEY] = "map_key", 596 [CONST_PTR_TO_DYNPTR] = "dynptr_ptr", 597 }; 598 599 if (type & PTR_MAYBE_NULL) { 600 if (base_type(type) == PTR_TO_BTF_ID) 601 strncpy(postfix, "or_null_", 16); 602 else 603 strncpy(postfix, "_or_null", 16); 604 } 605 606 snprintf(prefix, sizeof(prefix), "%s%s%s%s%s%s%s", 607 type & MEM_RDONLY ? "rdonly_" : "", 608 type & MEM_RINGBUF ? "ringbuf_" : "", 609 type & MEM_USER ? "user_" : "", 610 type & MEM_PERCPU ? "percpu_" : "", 611 type & MEM_RCU ? "rcu_" : "", 612 type & PTR_UNTRUSTED ? "untrusted_" : "", 613 type & PTR_TRUSTED ? "trusted_" : "" 614 ); 615 616 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s", 617 prefix, str[base_type(type)], postfix); 618 return env->type_str_buf; 619 } 620 621 static char slot_type_char[] = { 622 [STACK_INVALID] = '?', 623 [STACK_SPILL] = 'r', 624 [STACK_MISC] = 'm', 625 [STACK_ZERO] = '0', 626 [STACK_DYNPTR] = 'd', 627 }; 628 629 static void print_liveness(struct bpf_verifier_env *env, 630 enum bpf_reg_liveness live) 631 { 632 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 633 verbose(env, "_"); 634 if (live & REG_LIVE_READ) 635 verbose(env, "r"); 636 if (live & REG_LIVE_WRITTEN) 637 verbose(env, "w"); 638 if (live & REG_LIVE_DONE) 639 verbose(env, "D"); 640 } 641 642 static int __get_spi(s32 off) 643 { 644 return (-off - 1) / BPF_REG_SIZE; 645 } 646 647 static struct bpf_func_state *func(struct bpf_verifier_env *env, 648 const struct bpf_reg_state *reg) 649 { 650 struct bpf_verifier_state *cur = env->cur_state; 651 652 return cur->frame[reg->frameno]; 653 } 654 655 static bool is_spi_bounds_valid(struct bpf_func_state *state, int spi, int nr_slots) 656 { 657 int allocated_slots = state->allocated_stack / BPF_REG_SIZE; 658 659 /* We need to check that slots between [spi - nr_slots + 1, spi] are 660 * within [0, allocated_stack). 661 * 662 * Please note that the spi grows downwards. For example, a dynptr 663 * takes the size of two stack slots; the first slot will be at 664 * spi and the second slot will be at spi - 1. 665 */ 666 return spi - nr_slots + 1 >= 0 && spi < allocated_slots; 667 } 668 669 static int dynptr_get_spi(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 670 { 671 int off, spi; 672 673 if (!tnum_is_const(reg->var_off)) { 674 verbose(env, "dynptr has to be at a constant offset\n"); 675 return -EINVAL; 676 } 677 678 off = reg->off + reg->var_off.value; 679 if (off % BPF_REG_SIZE) { 680 verbose(env, "cannot pass in dynptr at an offset=%d\n", off); 681 return -EINVAL; 682 } 683 684 spi = __get_spi(off); 685 if (spi < 1) { 686 verbose(env, "cannot pass in dynptr at an offset=%d\n", off); 687 return -EINVAL; 688 } 689 690 if (!is_spi_bounds_valid(func(env, reg), spi, BPF_DYNPTR_NR_SLOTS)) 691 return -ERANGE; 692 return spi; 693 } 694 695 static const char *kernel_type_name(const struct btf* btf, u32 id) 696 { 697 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 698 } 699 700 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 701 { 702 env->scratched_regs |= 1U << regno; 703 } 704 705 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 706 { 707 env->scratched_stack_slots |= 1ULL << spi; 708 } 709 710 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 711 { 712 return (env->scratched_regs >> regno) & 1; 713 } 714 715 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 716 { 717 return (env->scratched_stack_slots >> regno) & 1; 718 } 719 720 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 721 { 722 return env->scratched_regs || env->scratched_stack_slots; 723 } 724 725 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 726 { 727 env->scratched_regs = 0U; 728 env->scratched_stack_slots = 0ULL; 729 } 730 731 /* Used for printing the entire verifier state. */ 732 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 733 { 734 env->scratched_regs = ~0U; 735 env->scratched_stack_slots = ~0ULL; 736 } 737 738 static enum bpf_dynptr_type arg_to_dynptr_type(enum bpf_arg_type arg_type) 739 { 740 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 741 case DYNPTR_TYPE_LOCAL: 742 return BPF_DYNPTR_TYPE_LOCAL; 743 case DYNPTR_TYPE_RINGBUF: 744 return BPF_DYNPTR_TYPE_RINGBUF; 745 default: 746 return BPF_DYNPTR_TYPE_INVALID; 747 } 748 } 749 750 static bool dynptr_type_refcounted(enum bpf_dynptr_type type) 751 { 752 return type == BPF_DYNPTR_TYPE_RINGBUF; 753 } 754 755 static void __mark_dynptr_reg(struct bpf_reg_state *reg, 756 enum bpf_dynptr_type type, 757 bool first_slot, int dynptr_id); 758 759 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 760 struct bpf_reg_state *reg); 761 762 static void mark_dynptr_stack_regs(struct bpf_verifier_env *env, 763 struct bpf_reg_state *sreg1, 764 struct bpf_reg_state *sreg2, 765 enum bpf_dynptr_type type) 766 { 767 int id = ++env->id_gen; 768 769 __mark_dynptr_reg(sreg1, type, true, id); 770 __mark_dynptr_reg(sreg2, type, false, id); 771 } 772 773 static void mark_dynptr_cb_reg(struct bpf_verifier_env *env, 774 struct bpf_reg_state *reg, 775 enum bpf_dynptr_type type) 776 { 777 __mark_dynptr_reg(reg, type, true, ++env->id_gen); 778 } 779 780 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 781 struct bpf_func_state *state, int spi); 782 783 static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 784 enum bpf_arg_type arg_type, int insn_idx) 785 { 786 struct bpf_func_state *state = func(env, reg); 787 enum bpf_dynptr_type type; 788 int spi, i, id, err; 789 790 spi = dynptr_get_spi(env, reg); 791 if (spi < 0) 792 return spi; 793 794 /* We cannot assume both spi and spi - 1 belong to the same dynptr, 795 * hence we need to call destroy_if_dynptr_stack_slot twice for both, 796 * to ensure that for the following example: 797 * [d1][d1][d2][d2] 798 * spi 3 2 1 0 799 * So marking spi = 2 should lead to destruction of both d1 and d2. In 800 * case they do belong to same dynptr, second call won't see slot_type 801 * as STACK_DYNPTR and will simply skip destruction. 802 */ 803 err = destroy_if_dynptr_stack_slot(env, state, spi); 804 if (err) 805 return err; 806 err = destroy_if_dynptr_stack_slot(env, state, spi - 1); 807 if (err) 808 return err; 809 810 for (i = 0; i < BPF_REG_SIZE; i++) { 811 state->stack[spi].slot_type[i] = STACK_DYNPTR; 812 state->stack[spi - 1].slot_type[i] = STACK_DYNPTR; 813 } 814 815 type = arg_to_dynptr_type(arg_type); 816 if (type == BPF_DYNPTR_TYPE_INVALID) 817 return -EINVAL; 818 819 mark_dynptr_stack_regs(env, &state->stack[spi].spilled_ptr, 820 &state->stack[spi - 1].spilled_ptr, type); 821 822 if (dynptr_type_refcounted(type)) { 823 /* The id is used to track proper releasing */ 824 id = acquire_reference_state(env, insn_idx); 825 if (id < 0) 826 return id; 827 828 state->stack[spi].spilled_ptr.ref_obj_id = id; 829 state->stack[spi - 1].spilled_ptr.ref_obj_id = id; 830 } 831 832 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 833 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 834 835 return 0; 836 } 837 838 static int unmark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 839 { 840 struct bpf_func_state *state = func(env, reg); 841 int spi, i; 842 843 spi = dynptr_get_spi(env, reg); 844 if (spi < 0) 845 return spi; 846 847 for (i = 0; i < BPF_REG_SIZE; i++) { 848 state->stack[spi].slot_type[i] = STACK_INVALID; 849 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 850 } 851 852 /* Invalidate any slices associated with this dynptr */ 853 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) 854 WARN_ON_ONCE(release_reference(env, state->stack[spi].spilled_ptr.ref_obj_id)); 855 856 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 857 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 858 859 /* Why do we need to set REG_LIVE_WRITTEN for STACK_INVALID slot? 860 * 861 * While we don't allow reading STACK_INVALID, it is still possible to 862 * do <8 byte writes marking some but not all slots as STACK_MISC. Then, 863 * helpers or insns can do partial read of that part without failing, 864 * but check_stack_range_initialized, check_stack_read_var_off, and 865 * check_stack_read_fixed_off will do mark_reg_read for all 8-bytes of 866 * the slot conservatively. Hence we need to prevent those liveness 867 * marking walks. 868 * 869 * This was not a problem before because STACK_INVALID is only set by 870 * default (where the default reg state has its reg->parent as NULL), or 871 * in clean_live_states after REG_LIVE_DONE (at which point 872 * mark_reg_read won't walk reg->parent chain), but not randomly during 873 * verifier state exploration (like we did above). Hence, for our case 874 * parentage chain will still be live (i.e. reg->parent may be 875 * non-NULL), while earlier reg->parent was NULL, so we need 876 * REG_LIVE_WRITTEN to screen off read marker propagation when it is 877 * done later on reads or by mark_dynptr_read as well to unnecessary 878 * mark registers in verifier state. 879 */ 880 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 881 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 882 883 return 0; 884 } 885 886 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 887 struct bpf_reg_state *reg); 888 889 static int destroy_if_dynptr_stack_slot(struct bpf_verifier_env *env, 890 struct bpf_func_state *state, int spi) 891 { 892 struct bpf_func_state *fstate; 893 struct bpf_reg_state *dreg; 894 int i, dynptr_id; 895 896 /* We always ensure that STACK_DYNPTR is never set partially, 897 * hence just checking for slot_type[0] is enough. This is 898 * different for STACK_SPILL, where it may be only set for 899 * 1 byte, so code has to use is_spilled_reg. 900 */ 901 if (state->stack[spi].slot_type[0] != STACK_DYNPTR) 902 return 0; 903 904 /* Reposition spi to first slot */ 905 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 906 spi = spi + 1; 907 908 if (dynptr_type_refcounted(state->stack[spi].spilled_ptr.dynptr.type)) { 909 verbose(env, "cannot overwrite referenced dynptr\n"); 910 return -EINVAL; 911 } 912 913 mark_stack_slot_scratched(env, spi); 914 mark_stack_slot_scratched(env, spi - 1); 915 916 /* Writing partially to one dynptr stack slot destroys both. */ 917 for (i = 0; i < BPF_REG_SIZE; i++) { 918 state->stack[spi].slot_type[i] = STACK_INVALID; 919 state->stack[spi - 1].slot_type[i] = STACK_INVALID; 920 } 921 922 dynptr_id = state->stack[spi].spilled_ptr.id; 923 /* Invalidate any slices associated with this dynptr */ 924 bpf_for_each_reg_in_vstate(env->cur_state, fstate, dreg, ({ 925 /* Dynptr slices are only PTR_TO_MEM_OR_NULL and PTR_TO_MEM */ 926 if (dreg->type != (PTR_TO_MEM | PTR_MAYBE_NULL) && dreg->type != PTR_TO_MEM) 927 continue; 928 if (dreg->dynptr_id == dynptr_id) { 929 if (!env->allow_ptr_leaks) 930 __mark_reg_not_init(env, dreg); 931 else 932 __mark_reg_unknown(env, dreg); 933 } 934 })); 935 936 /* Do not release reference state, we are destroying dynptr on stack, 937 * not using some helper to release it. Just reset register. 938 */ 939 __mark_reg_not_init(env, &state->stack[spi].spilled_ptr); 940 __mark_reg_not_init(env, &state->stack[spi - 1].spilled_ptr); 941 942 /* Same reason as unmark_stack_slots_dynptr above */ 943 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 944 state->stack[spi - 1].spilled_ptr.live |= REG_LIVE_WRITTEN; 945 946 return 0; 947 } 948 949 static bool is_dynptr_reg_valid_uninit(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 950 int spi) 951 { 952 if (reg->type == CONST_PTR_TO_DYNPTR) 953 return false; 954 955 /* For -ERANGE (i.e. spi not falling into allocated stack slots), we 956 * will do check_mem_access to check and update stack bounds later, so 957 * return true for that case. 958 */ 959 if (spi < 0) 960 return spi == -ERANGE; 961 /* We allow overwriting existing unreferenced STACK_DYNPTR slots, see 962 * mark_stack_slots_dynptr which calls destroy_if_dynptr_stack_slot to 963 * ensure dynptr objects at the slots we are touching are completely 964 * destructed before we reinitialize them for a new one. For referenced 965 * ones, destroy_if_dynptr_stack_slot returns an error early instead of 966 * delaying it until the end where the user will get "Unreleased 967 * reference" error. 968 */ 969 return true; 970 } 971 972 static bool is_dynptr_reg_valid_init(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 973 int spi) 974 { 975 struct bpf_func_state *state = func(env, reg); 976 int i; 977 978 /* This already represents first slot of initialized bpf_dynptr */ 979 if (reg->type == CONST_PTR_TO_DYNPTR) 980 return true; 981 982 if (spi < 0) 983 return false; 984 if (!state->stack[spi].spilled_ptr.dynptr.first_slot) 985 return false; 986 987 for (i = 0; i < BPF_REG_SIZE; i++) { 988 if (state->stack[spi].slot_type[i] != STACK_DYNPTR || 989 state->stack[spi - 1].slot_type[i] != STACK_DYNPTR) 990 return false; 991 } 992 993 return true; 994 } 995 996 static bool is_dynptr_type_expected(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 997 enum bpf_arg_type arg_type) 998 { 999 struct bpf_func_state *state = func(env, reg); 1000 enum bpf_dynptr_type dynptr_type; 1001 int spi; 1002 1003 /* ARG_PTR_TO_DYNPTR takes any type of dynptr */ 1004 if (arg_type == ARG_PTR_TO_DYNPTR) 1005 return true; 1006 1007 dynptr_type = arg_to_dynptr_type(arg_type); 1008 if (reg->type == CONST_PTR_TO_DYNPTR) { 1009 return reg->dynptr.type == dynptr_type; 1010 } else { 1011 spi = dynptr_get_spi(env, reg); 1012 if (spi < 0) 1013 return false; 1014 return state->stack[spi].spilled_ptr.dynptr.type == dynptr_type; 1015 } 1016 } 1017 1018 /* The reg state of a pointer or a bounded scalar was saved when 1019 * it was spilled to the stack. 1020 */ 1021 static bool is_spilled_reg(const struct bpf_stack_state *stack) 1022 { 1023 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 1024 } 1025 1026 static void scrub_spilled_slot(u8 *stype) 1027 { 1028 if (*stype != STACK_INVALID) 1029 *stype = STACK_MISC; 1030 } 1031 1032 static void print_verifier_state(struct bpf_verifier_env *env, 1033 const struct bpf_func_state *state, 1034 bool print_all) 1035 { 1036 const struct bpf_reg_state *reg; 1037 enum bpf_reg_type t; 1038 int i; 1039 1040 if (state->frameno) 1041 verbose(env, " frame%d:", state->frameno); 1042 for (i = 0; i < MAX_BPF_REG; i++) { 1043 reg = &state->regs[i]; 1044 t = reg->type; 1045 if (t == NOT_INIT) 1046 continue; 1047 if (!print_all && !reg_scratched(env, i)) 1048 continue; 1049 verbose(env, " R%d", i); 1050 print_liveness(env, reg->live); 1051 verbose(env, "="); 1052 if (t == SCALAR_VALUE && reg->precise) 1053 verbose(env, "P"); 1054 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 1055 tnum_is_const(reg->var_off)) { 1056 /* reg->off should be 0 for SCALAR_VALUE */ 1057 verbose(env, "%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1058 verbose(env, "%lld", reg->var_off.value + reg->off); 1059 } else { 1060 const char *sep = ""; 1061 1062 verbose(env, "%s", reg_type_str(env, t)); 1063 if (base_type(t) == PTR_TO_BTF_ID) 1064 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id)); 1065 verbose(env, "("); 1066 /* 1067 * _a stands for append, was shortened to avoid multiline statements below. 1068 * This macro is used to output a comma separated list of attributes. 1069 */ 1070 #define verbose_a(fmt, ...) ({ verbose(env, "%s" fmt, sep, __VA_ARGS__); sep = ","; }) 1071 1072 if (reg->id) 1073 verbose_a("id=%d", reg->id); 1074 if (reg->ref_obj_id) 1075 verbose_a("ref_obj_id=%d", reg->ref_obj_id); 1076 if (t != SCALAR_VALUE) 1077 verbose_a("off=%d", reg->off); 1078 if (type_is_pkt_pointer(t)) 1079 verbose_a("r=%d", reg->range); 1080 else if (base_type(t) == CONST_PTR_TO_MAP || 1081 base_type(t) == PTR_TO_MAP_KEY || 1082 base_type(t) == PTR_TO_MAP_VALUE) 1083 verbose_a("ks=%d,vs=%d", 1084 reg->map_ptr->key_size, 1085 reg->map_ptr->value_size); 1086 if (tnum_is_const(reg->var_off)) { 1087 /* Typically an immediate SCALAR_VALUE, but 1088 * could be a pointer whose offset is too big 1089 * for reg->off 1090 */ 1091 verbose_a("imm=%llx", reg->var_off.value); 1092 } else { 1093 if (reg->smin_value != reg->umin_value && 1094 reg->smin_value != S64_MIN) 1095 verbose_a("smin=%lld", (long long)reg->smin_value); 1096 if (reg->smax_value != reg->umax_value && 1097 reg->smax_value != S64_MAX) 1098 verbose_a("smax=%lld", (long long)reg->smax_value); 1099 if (reg->umin_value != 0) 1100 verbose_a("umin=%llu", (unsigned long long)reg->umin_value); 1101 if (reg->umax_value != U64_MAX) 1102 verbose_a("umax=%llu", (unsigned long long)reg->umax_value); 1103 if (!tnum_is_unknown(reg->var_off)) { 1104 char tn_buf[48]; 1105 1106 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1107 verbose_a("var_off=%s", tn_buf); 1108 } 1109 if (reg->s32_min_value != reg->smin_value && 1110 reg->s32_min_value != S32_MIN) 1111 verbose_a("s32_min=%d", (int)(reg->s32_min_value)); 1112 if (reg->s32_max_value != reg->smax_value && 1113 reg->s32_max_value != S32_MAX) 1114 verbose_a("s32_max=%d", (int)(reg->s32_max_value)); 1115 if (reg->u32_min_value != reg->umin_value && 1116 reg->u32_min_value != U32_MIN) 1117 verbose_a("u32_min=%d", (int)(reg->u32_min_value)); 1118 if (reg->u32_max_value != reg->umax_value && 1119 reg->u32_max_value != U32_MAX) 1120 verbose_a("u32_max=%d", (int)(reg->u32_max_value)); 1121 } 1122 #undef verbose_a 1123 1124 verbose(env, ")"); 1125 } 1126 } 1127 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 1128 char types_buf[BPF_REG_SIZE + 1]; 1129 bool valid = false; 1130 int j; 1131 1132 for (j = 0; j < BPF_REG_SIZE; j++) { 1133 if (state->stack[i].slot_type[j] != STACK_INVALID) 1134 valid = true; 1135 types_buf[j] = slot_type_char[ 1136 state->stack[i].slot_type[j]]; 1137 } 1138 types_buf[BPF_REG_SIZE] = 0; 1139 if (!valid) 1140 continue; 1141 if (!print_all && !stack_slot_scratched(env, i)) 1142 continue; 1143 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 1144 print_liveness(env, state->stack[i].spilled_ptr.live); 1145 if (is_spilled_reg(&state->stack[i])) { 1146 reg = &state->stack[i].spilled_ptr; 1147 t = reg->type; 1148 verbose(env, "=%s", t == SCALAR_VALUE ? "" : reg_type_str(env, t)); 1149 if (t == SCALAR_VALUE && reg->precise) 1150 verbose(env, "P"); 1151 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 1152 verbose(env, "%lld", reg->var_off.value + reg->off); 1153 } else { 1154 verbose(env, "=%s", types_buf); 1155 } 1156 } 1157 if (state->acquired_refs && state->refs[0].id) { 1158 verbose(env, " refs=%d", state->refs[0].id); 1159 for (i = 1; i < state->acquired_refs; i++) 1160 if (state->refs[i].id) 1161 verbose(env, ",%d", state->refs[i].id); 1162 } 1163 if (state->in_callback_fn) 1164 verbose(env, " cb"); 1165 if (state->in_async_callback_fn) 1166 verbose(env, " async_cb"); 1167 verbose(env, "\n"); 1168 mark_verifier_state_clean(env); 1169 } 1170 1171 static inline u32 vlog_alignment(u32 pos) 1172 { 1173 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 1174 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 1175 } 1176 1177 static void print_insn_state(struct bpf_verifier_env *env, 1178 const struct bpf_func_state *state) 1179 { 1180 if (env->prev_log_len && env->prev_log_len == env->log.len_used) { 1181 /* remove new line character */ 1182 bpf_vlog_reset(&env->log, env->prev_log_len - 1); 1183 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' '); 1184 } else { 1185 verbose(env, "%d:", env->insn_idx); 1186 } 1187 print_verifier_state(env, state, false); 1188 } 1189 1190 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 1191 * small to hold src. This is different from krealloc since we don't want to preserve 1192 * the contents of dst. 1193 * 1194 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 1195 * not be allocated. 1196 */ 1197 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 1198 { 1199 size_t alloc_bytes; 1200 void *orig = dst; 1201 size_t bytes; 1202 1203 if (ZERO_OR_NULL_PTR(src)) 1204 goto out; 1205 1206 if (unlikely(check_mul_overflow(n, size, &bytes))) 1207 return NULL; 1208 1209 alloc_bytes = max(ksize(orig), kmalloc_size_roundup(bytes)); 1210 dst = krealloc(orig, alloc_bytes, flags); 1211 if (!dst) { 1212 kfree(orig); 1213 return NULL; 1214 } 1215 1216 memcpy(dst, src, bytes); 1217 out: 1218 return dst ? dst : ZERO_SIZE_PTR; 1219 } 1220 1221 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 1222 * small to hold new_n items. new items are zeroed out if the array grows. 1223 * 1224 * Contrary to krealloc_array, does not free arr if new_n is zero. 1225 */ 1226 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 1227 { 1228 size_t alloc_size; 1229 void *new_arr; 1230 1231 if (!new_n || old_n == new_n) 1232 goto out; 1233 1234 alloc_size = kmalloc_size_roundup(size_mul(new_n, size)); 1235 new_arr = krealloc(arr, alloc_size, GFP_KERNEL); 1236 if (!new_arr) { 1237 kfree(arr); 1238 return NULL; 1239 } 1240 arr = new_arr; 1241 1242 if (new_n > old_n) 1243 memset(arr + old_n * size, 0, (new_n - old_n) * size); 1244 1245 out: 1246 return arr ? arr : ZERO_SIZE_PTR; 1247 } 1248 1249 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1250 { 1251 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 1252 sizeof(struct bpf_reference_state), GFP_KERNEL); 1253 if (!dst->refs) 1254 return -ENOMEM; 1255 1256 dst->acquired_refs = src->acquired_refs; 1257 return 0; 1258 } 1259 1260 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 1261 { 1262 size_t n = src->allocated_stack / BPF_REG_SIZE; 1263 1264 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 1265 GFP_KERNEL); 1266 if (!dst->stack) 1267 return -ENOMEM; 1268 1269 dst->allocated_stack = src->allocated_stack; 1270 return 0; 1271 } 1272 1273 static int resize_reference_state(struct bpf_func_state *state, size_t n) 1274 { 1275 state->refs = realloc_array(state->refs, state->acquired_refs, n, 1276 sizeof(struct bpf_reference_state)); 1277 if (!state->refs) 1278 return -ENOMEM; 1279 1280 state->acquired_refs = n; 1281 return 0; 1282 } 1283 1284 static int grow_stack_state(struct bpf_func_state *state, int size) 1285 { 1286 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 1287 1288 if (old_n >= n) 1289 return 0; 1290 1291 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 1292 if (!state->stack) 1293 return -ENOMEM; 1294 1295 state->allocated_stack = size; 1296 return 0; 1297 } 1298 1299 /* Acquire a pointer id from the env and update the state->refs to include 1300 * this new pointer reference. 1301 * On success, returns a valid pointer id to associate with the register 1302 * On failure, returns a negative errno. 1303 */ 1304 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 1305 { 1306 struct bpf_func_state *state = cur_func(env); 1307 int new_ofs = state->acquired_refs; 1308 int id, err; 1309 1310 err = resize_reference_state(state, state->acquired_refs + 1); 1311 if (err) 1312 return err; 1313 id = ++env->id_gen; 1314 state->refs[new_ofs].id = id; 1315 state->refs[new_ofs].insn_idx = insn_idx; 1316 state->refs[new_ofs].callback_ref = state->in_callback_fn ? state->frameno : 0; 1317 1318 return id; 1319 } 1320 1321 /* release function corresponding to acquire_reference_state(). Idempotent. */ 1322 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 1323 { 1324 int i, last_idx; 1325 1326 last_idx = state->acquired_refs - 1; 1327 for (i = 0; i < state->acquired_refs; i++) { 1328 if (state->refs[i].id == ptr_id) { 1329 /* Cannot release caller references in callbacks */ 1330 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 1331 return -EINVAL; 1332 if (last_idx && i != last_idx) 1333 memcpy(&state->refs[i], &state->refs[last_idx], 1334 sizeof(*state->refs)); 1335 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 1336 state->acquired_refs--; 1337 return 0; 1338 } 1339 } 1340 return -EINVAL; 1341 } 1342 1343 static void free_func_state(struct bpf_func_state *state) 1344 { 1345 if (!state) 1346 return; 1347 kfree(state->refs); 1348 kfree(state->stack); 1349 kfree(state); 1350 } 1351 1352 static void clear_jmp_history(struct bpf_verifier_state *state) 1353 { 1354 kfree(state->jmp_history); 1355 state->jmp_history = NULL; 1356 state->jmp_history_cnt = 0; 1357 } 1358 1359 static void free_verifier_state(struct bpf_verifier_state *state, 1360 bool free_self) 1361 { 1362 int i; 1363 1364 for (i = 0; i <= state->curframe; i++) { 1365 free_func_state(state->frame[i]); 1366 state->frame[i] = NULL; 1367 } 1368 clear_jmp_history(state); 1369 if (free_self) 1370 kfree(state); 1371 } 1372 1373 /* copy verifier state from src to dst growing dst stack space 1374 * when necessary to accommodate larger src stack 1375 */ 1376 static int copy_func_state(struct bpf_func_state *dst, 1377 const struct bpf_func_state *src) 1378 { 1379 int err; 1380 1381 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 1382 err = copy_reference_state(dst, src); 1383 if (err) 1384 return err; 1385 return copy_stack_state(dst, src); 1386 } 1387 1388 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1389 const struct bpf_verifier_state *src) 1390 { 1391 struct bpf_func_state *dst; 1392 int i, err; 1393 1394 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1395 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1396 GFP_USER); 1397 if (!dst_state->jmp_history) 1398 return -ENOMEM; 1399 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1400 1401 /* if dst has more stack frames then src frame, free them */ 1402 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1403 free_func_state(dst_state->frame[i]); 1404 dst_state->frame[i] = NULL; 1405 } 1406 dst_state->speculative = src->speculative; 1407 dst_state->active_rcu_lock = src->active_rcu_lock; 1408 dst_state->curframe = src->curframe; 1409 dst_state->active_lock.ptr = src->active_lock.ptr; 1410 dst_state->active_lock.id = src->active_lock.id; 1411 dst_state->branches = src->branches; 1412 dst_state->parent = src->parent; 1413 dst_state->first_insn_idx = src->first_insn_idx; 1414 dst_state->last_insn_idx = src->last_insn_idx; 1415 for (i = 0; i <= src->curframe; i++) { 1416 dst = dst_state->frame[i]; 1417 if (!dst) { 1418 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1419 if (!dst) 1420 return -ENOMEM; 1421 dst_state->frame[i] = dst; 1422 } 1423 err = copy_func_state(dst, src->frame[i]); 1424 if (err) 1425 return err; 1426 } 1427 return 0; 1428 } 1429 1430 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1431 { 1432 while (st) { 1433 u32 br = --st->branches; 1434 1435 /* WARN_ON(br > 1) technically makes sense here, 1436 * but see comment in push_stack(), hence: 1437 */ 1438 WARN_ONCE((int)br < 0, 1439 "BUG update_branch_counts:branches_to_explore=%d\n", 1440 br); 1441 if (br) 1442 break; 1443 st = st->parent; 1444 } 1445 } 1446 1447 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1448 int *insn_idx, bool pop_log) 1449 { 1450 struct bpf_verifier_state *cur = env->cur_state; 1451 struct bpf_verifier_stack_elem *elem, *head = env->head; 1452 int err; 1453 1454 if (env->head == NULL) 1455 return -ENOENT; 1456 1457 if (cur) { 1458 err = copy_verifier_state(cur, &head->st); 1459 if (err) 1460 return err; 1461 } 1462 if (pop_log) 1463 bpf_vlog_reset(&env->log, head->log_pos); 1464 if (insn_idx) 1465 *insn_idx = head->insn_idx; 1466 if (prev_insn_idx) 1467 *prev_insn_idx = head->prev_insn_idx; 1468 elem = head->next; 1469 free_verifier_state(&head->st, false); 1470 kfree(head); 1471 env->head = elem; 1472 env->stack_size--; 1473 return 0; 1474 } 1475 1476 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1477 int insn_idx, int prev_insn_idx, 1478 bool speculative) 1479 { 1480 struct bpf_verifier_state *cur = env->cur_state; 1481 struct bpf_verifier_stack_elem *elem; 1482 int err; 1483 1484 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1485 if (!elem) 1486 goto err; 1487 1488 elem->insn_idx = insn_idx; 1489 elem->prev_insn_idx = prev_insn_idx; 1490 elem->next = env->head; 1491 elem->log_pos = env->log.len_used; 1492 env->head = elem; 1493 env->stack_size++; 1494 err = copy_verifier_state(&elem->st, cur); 1495 if (err) 1496 goto err; 1497 elem->st.speculative |= speculative; 1498 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1499 verbose(env, "The sequence of %d jumps is too complex.\n", 1500 env->stack_size); 1501 goto err; 1502 } 1503 if (elem->st.parent) { 1504 ++elem->st.parent->branches; 1505 /* WARN_ON(branches > 2) technically makes sense here, 1506 * but 1507 * 1. speculative states will bump 'branches' for non-branch 1508 * instructions 1509 * 2. is_state_visited() heuristics may decide not to create 1510 * a new state for a sequence of branches and all such current 1511 * and cloned states will be pointing to a single parent state 1512 * which might have large 'branches' count. 1513 */ 1514 } 1515 return &elem->st; 1516 err: 1517 free_verifier_state(env->cur_state, true); 1518 env->cur_state = NULL; 1519 /* pop all elements and return */ 1520 while (!pop_stack(env, NULL, NULL, false)); 1521 return NULL; 1522 } 1523 1524 #define CALLER_SAVED_REGS 6 1525 static const int caller_saved[CALLER_SAVED_REGS] = { 1526 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1527 }; 1528 1529 /* This helper doesn't clear reg->id */ 1530 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1531 { 1532 reg->var_off = tnum_const(imm); 1533 reg->smin_value = (s64)imm; 1534 reg->smax_value = (s64)imm; 1535 reg->umin_value = imm; 1536 reg->umax_value = imm; 1537 1538 reg->s32_min_value = (s32)imm; 1539 reg->s32_max_value = (s32)imm; 1540 reg->u32_min_value = (u32)imm; 1541 reg->u32_max_value = (u32)imm; 1542 } 1543 1544 /* Mark the unknown part of a register (variable offset or scalar value) as 1545 * known to have the value @imm. 1546 */ 1547 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1548 { 1549 /* Clear off and union(map_ptr, range) */ 1550 memset(((u8 *)reg) + sizeof(reg->type), 0, 1551 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1552 reg->id = 0; 1553 reg->ref_obj_id = 0; 1554 ___mark_reg_known(reg, imm); 1555 } 1556 1557 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1558 { 1559 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1560 reg->s32_min_value = (s32)imm; 1561 reg->s32_max_value = (s32)imm; 1562 reg->u32_min_value = (u32)imm; 1563 reg->u32_max_value = (u32)imm; 1564 } 1565 1566 /* Mark the 'variable offset' part of a register as zero. This should be 1567 * used only on registers holding a pointer type. 1568 */ 1569 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1570 { 1571 __mark_reg_known(reg, 0); 1572 } 1573 1574 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1575 { 1576 __mark_reg_known(reg, 0); 1577 reg->type = SCALAR_VALUE; 1578 } 1579 1580 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1581 struct bpf_reg_state *regs, u32 regno) 1582 { 1583 if (WARN_ON(regno >= MAX_BPF_REG)) { 1584 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1585 /* Something bad happened, let's kill all regs */ 1586 for (regno = 0; regno < MAX_BPF_REG; regno++) 1587 __mark_reg_not_init(env, regs + regno); 1588 return; 1589 } 1590 __mark_reg_known_zero(regs + regno); 1591 } 1592 1593 static void __mark_dynptr_reg(struct bpf_reg_state *reg, enum bpf_dynptr_type type, 1594 bool first_slot, int dynptr_id) 1595 { 1596 /* reg->type has no meaning for STACK_DYNPTR, but when we set reg for 1597 * callback arguments, it does need to be CONST_PTR_TO_DYNPTR, so simply 1598 * set it unconditionally as it is ignored for STACK_DYNPTR anyway. 1599 */ 1600 __mark_reg_known_zero(reg); 1601 reg->type = CONST_PTR_TO_DYNPTR; 1602 /* Give each dynptr a unique id to uniquely associate slices to it. */ 1603 reg->id = dynptr_id; 1604 reg->dynptr.type = type; 1605 reg->dynptr.first_slot = first_slot; 1606 } 1607 1608 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1609 { 1610 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1611 const struct bpf_map *map = reg->map_ptr; 1612 1613 if (map->inner_map_meta) { 1614 reg->type = CONST_PTR_TO_MAP; 1615 reg->map_ptr = map->inner_map_meta; 1616 /* transfer reg's id which is unique for every map_lookup_elem 1617 * as UID of the inner map. 1618 */ 1619 if (btf_record_has_field(map->inner_map_meta->record, BPF_TIMER)) 1620 reg->map_uid = reg->id; 1621 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1622 reg->type = PTR_TO_XDP_SOCK; 1623 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1624 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1625 reg->type = PTR_TO_SOCKET; 1626 } else { 1627 reg->type = PTR_TO_MAP_VALUE; 1628 } 1629 return; 1630 } 1631 1632 reg->type &= ~PTR_MAYBE_NULL; 1633 } 1634 1635 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1636 { 1637 return type_is_pkt_pointer(reg->type); 1638 } 1639 1640 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1641 { 1642 return reg_is_pkt_pointer(reg) || 1643 reg->type == PTR_TO_PACKET_END; 1644 } 1645 1646 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1647 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1648 enum bpf_reg_type which) 1649 { 1650 /* The register can already have a range from prior markings. 1651 * This is fine as long as it hasn't been advanced from its 1652 * origin. 1653 */ 1654 return reg->type == which && 1655 reg->id == 0 && 1656 reg->off == 0 && 1657 tnum_equals_const(reg->var_off, 0); 1658 } 1659 1660 /* Reset the min/max bounds of a register */ 1661 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1662 { 1663 reg->smin_value = S64_MIN; 1664 reg->smax_value = S64_MAX; 1665 reg->umin_value = 0; 1666 reg->umax_value = U64_MAX; 1667 1668 reg->s32_min_value = S32_MIN; 1669 reg->s32_max_value = S32_MAX; 1670 reg->u32_min_value = 0; 1671 reg->u32_max_value = U32_MAX; 1672 } 1673 1674 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1675 { 1676 reg->smin_value = S64_MIN; 1677 reg->smax_value = S64_MAX; 1678 reg->umin_value = 0; 1679 reg->umax_value = U64_MAX; 1680 } 1681 1682 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1683 { 1684 reg->s32_min_value = S32_MIN; 1685 reg->s32_max_value = S32_MAX; 1686 reg->u32_min_value = 0; 1687 reg->u32_max_value = U32_MAX; 1688 } 1689 1690 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1691 { 1692 struct tnum var32_off = tnum_subreg(reg->var_off); 1693 1694 /* min signed is max(sign bit) | min(other bits) */ 1695 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1696 var32_off.value | (var32_off.mask & S32_MIN)); 1697 /* max signed is min(sign bit) | max(other bits) */ 1698 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1699 var32_off.value | (var32_off.mask & S32_MAX)); 1700 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1701 reg->u32_max_value = min(reg->u32_max_value, 1702 (u32)(var32_off.value | var32_off.mask)); 1703 } 1704 1705 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1706 { 1707 /* min signed is max(sign bit) | min(other bits) */ 1708 reg->smin_value = max_t(s64, reg->smin_value, 1709 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1710 /* max signed is min(sign bit) | max(other bits) */ 1711 reg->smax_value = min_t(s64, reg->smax_value, 1712 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1713 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1714 reg->umax_value = min(reg->umax_value, 1715 reg->var_off.value | reg->var_off.mask); 1716 } 1717 1718 static void __update_reg_bounds(struct bpf_reg_state *reg) 1719 { 1720 __update_reg32_bounds(reg); 1721 __update_reg64_bounds(reg); 1722 } 1723 1724 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1725 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1726 { 1727 /* Learn sign from signed bounds. 1728 * If we cannot cross the sign boundary, then signed and unsigned bounds 1729 * are the same, so combine. This works even in the negative case, e.g. 1730 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1731 */ 1732 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 1733 reg->s32_min_value = reg->u32_min_value = 1734 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1735 reg->s32_max_value = reg->u32_max_value = 1736 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1737 return; 1738 } 1739 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1740 * boundary, so we must be careful. 1741 */ 1742 if ((s32)reg->u32_max_value >= 0) { 1743 /* Positive. We can't learn anything from the smin, but smax 1744 * is positive, hence safe. 1745 */ 1746 reg->s32_min_value = reg->u32_min_value; 1747 reg->s32_max_value = reg->u32_max_value = 1748 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1749 } else if ((s32)reg->u32_min_value < 0) { 1750 /* Negative. We can't learn anything from the smax, but smin 1751 * is negative, hence safe. 1752 */ 1753 reg->s32_min_value = reg->u32_min_value = 1754 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1755 reg->s32_max_value = reg->u32_max_value; 1756 } 1757 } 1758 1759 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 1760 { 1761 /* Learn sign from signed bounds. 1762 * If we cannot cross the sign boundary, then signed and unsigned bounds 1763 * are the same, so combine. This works even in the negative case, e.g. 1764 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1765 */ 1766 if (reg->smin_value >= 0 || reg->smax_value < 0) { 1767 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1768 reg->umin_value); 1769 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1770 reg->umax_value); 1771 return; 1772 } 1773 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1774 * boundary, so we must be careful. 1775 */ 1776 if ((s64)reg->umax_value >= 0) { 1777 /* Positive. We can't learn anything from the smin, but smax 1778 * is positive, hence safe. 1779 */ 1780 reg->smin_value = reg->umin_value; 1781 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1782 reg->umax_value); 1783 } else if ((s64)reg->umin_value < 0) { 1784 /* Negative. We can't learn anything from the smax, but smin 1785 * is negative, hence safe. 1786 */ 1787 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1788 reg->umin_value); 1789 reg->smax_value = reg->umax_value; 1790 } 1791 } 1792 1793 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 1794 { 1795 __reg32_deduce_bounds(reg); 1796 __reg64_deduce_bounds(reg); 1797 } 1798 1799 /* Attempts to improve var_off based on unsigned min/max information */ 1800 static void __reg_bound_offset(struct bpf_reg_state *reg) 1801 { 1802 struct tnum var64_off = tnum_intersect(reg->var_off, 1803 tnum_range(reg->umin_value, 1804 reg->umax_value)); 1805 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off), 1806 tnum_range(reg->u32_min_value, 1807 reg->u32_max_value)); 1808 1809 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 1810 } 1811 1812 static void reg_bounds_sync(struct bpf_reg_state *reg) 1813 { 1814 /* We might have learned new bounds from the var_off. */ 1815 __update_reg_bounds(reg); 1816 /* We might have learned something about the sign bit. */ 1817 __reg_deduce_bounds(reg); 1818 /* We might have learned some bits from the bounds. */ 1819 __reg_bound_offset(reg); 1820 /* Intersecting with the old var_off might have improved our bounds 1821 * slightly, e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1822 * then new var_off is (0; 0x7f...fc) which improves our umax. 1823 */ 1824 __update_reg_bounds(reg); 1825 } 1826 1827 static bool __reg32_bound_s64(s32 a) 1828 { 1829 return a >= 0 && a <= S32_MAX; 1830 } 1831 1832 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 1833 { 1834 reg->umin_value = reg->u32_min_value; 1835 reg->umax_value = reg->u32_max_value; 1836 1837 /* Attempt to pull 32-bit signed bounds into 64-bit bounds but must 1838 * be positive otherwise set to worse case bounds and refine later 1839 * from tnum. 1840 */ 1841 if (__reg32_bound_s64(reg->s32_min_value) && 1842 __reg32_bound_s64(reg->s32_max_value)) { 1843 reg->smin_value = reg->s32_min_value; 1844 reg->smax_value = reg->s32_max_value; 1845 } else { 1846 reg->smin_value = 0; 1847 reg->smax_value = U32_MAX; 1848 } 1849 } 1850 1851 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 1852 { 1853 /* special case when 64-bit register has upper 32-bit register 1854 * zeroed. Typically happens after zext or <<32, >>32 sequence 1855 * allowing us to use 32-bit bounds directly, 1856 */ 1857 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 1858 __reg_assign_32_into_64(reg); 1859 } else { 1860 /* Otherwise the best we can do is push lower 32bit known and 1861 * unknown bits into register (var_off set from jmp logic) 1862 * then learn as much as possible from the 64-bit tnum 1863 * known and unknown bits. The previous smin/smax bounds are 1864 * invalid here because of jmp32 compare so mark them unknown 1865 * so they do not impact tnum bounds calculation. 1866 */ 1867 __mark_reg64_unbounded(reg); 1868 } 1869 reg_bounds_sync(reg); 1870 } 1871 1872 static bool __reg64_bound_s32(s64 a) 1873 { 1874 return a >= S32_MIN && a <= S32_MAX; 1875 } 1876 1877 static bool __reg64_bound_u32(u64 a) 1878 { 1879 return a >= U32_MIN && a <= U32_MAX; 1880 } 1881 1882 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 1883 { 1884 __mark_reg32_unbounded(reg); 1885 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 1886 reg->s32_min_value = (s32)reg->smin_value; 1887 reg->s32_max_value = (s32)reg->smax_value; 1888 } 1889 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 1890 reg->u32_min_value = (u32)reg->umin_value; 1891 reg->u32_max_value = (u32)reg->umax_value; 1892 } 1893 reg_bounds_sync(reg); 1894 } 1895 1896 /* Mark a register as having a completely unknown (scalar) value. */ 1897 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1898 struct bpf_reg_state *reg) 1899 { 1900 /* 1901 * Clear type, off, and union(map_ptr, range) and 1902 * padding between 'type' and union 1903 */ 1904 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 1905 reg->type = SCALAR_VALUE; 1906 reg->id = 0; 1907 reg->ref_obj_id = 0; 1908 reg->var_off = tnum_unknown; 1909 reg->frameno = 0; 1910 reg->precise = !env->bpf_capable; 1911 __mark_reg_unbounded(reg); 1912 } 1913 1914 static void mark_reg_unknown(struct bpf_verifier_env *env, 1915 struct bpf_reg_state *regs, u32 regno) 1916 { 1917 if (WARN_ON(regno >= MAX_BPF_REG)) { 1918 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 1919 /* Something bad happened, let's kill all regs except FP */ 1920 for (regno = 0; regno < BPF_REG_FP; regno++) 1921 __mark_reg_not_init(env, regs + regno); 1922 return; 1923 } 1924 __mark_reg_unknown(env, regs + regno); 1925 } 1926 1927 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1928 struct bpf_reg_state *reg) 1929 { 1930 __mark_reg_unknown(env, reg); 1931 reg->type = NOT_INIT; 1932 } 1933 1934 static void mark_reg_not_init(struct bpf_verifier_env *env, 1935 struct bpf_reg_state *regs, u32 regno) 1936 { 1937 if (WARN_ON(regno >= MAX_BPF_REG)) { 1938 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 1939 /* Something bad happened, let's kill all regs except FP */ 1940 for (regno = 0; regno < BPF_REG_FP; regno++) 1941 __mark_reg_not_init(env, regs + regno); 1942 return; 1943 } 1944 __mark_reg_not_init(env, regs + regno); 1945 } 1946 1947 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 1948 struct bpf_reg_state *regs, u32 regno, 1949 enum bpf_reg_type reg_type, 1950 struct btf *btf, u32 btf_id, 1951 enum bpf_type_flag flag) 1952 { 1953 if (reg_type == SCALAR_VALUE) { 1954 mark_reg_unknown(env, regs, regno); 1955 return; 1956 } 1957 mark_reg_known_zero(env, regs, regno); 1958 regs[regno].type = PTR_TO_BTF_ID | flag; 1959 regs[regno].btf = btf; 1960 regs[regno].btf_id = btf_id; 1961 } 1962 1963 #define DEF_NOT_SUBREG (0) 1964 static void init_reg_state(struct bpf_verifier_env *env, 1965 struct bpf_func_state *state) 1966 { 1967 struct bpf_reg_state *regs = state->regs; 1968 int i; 1969 1970 for (i = 0; i < MAX_BPF_REG; i++) { 1971 mark_reg_not_init(env, regs, i); 1972 regs[i].live = REG_LIVE_NONE; 1973 regs[i].parent = NULL; 1974 regs[i].subreg_def = DEF_NOT_SUBREG; 1975 } 1976 1977 /* frame pointer */ 1978 regs[BPF_REG_FP].type = PTR_TO_STACK; 1979 mark_reg_known_zero(env, regs, BPF_REG_FP); 1980 regs[BPF_REG_FP].frameno = state->frameno; 1981 } 1982 1983 #define BPF_MAIN_FUNC (-1) 1984 static void init_func_state(struct bpf_verifier_env *env, 1985 struct bpf_func_state *state, 1986 int callsite, int frameno, int subprogno) 1987 { 1988 state->callsite = callsite; 1989 state->frameno = frameno; 1990 state->subprogno = subprogno; 1991 state->callback_ret_range = tnum_range(0, 0); 1992 init_reg_state(env, state); 1993 mark_verifier_state_scratched(env); 1994 } 1995 1996 /* Similar to push_stack(), but for async callbacks */ 1997 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 1998 int insn_idx, int prev_insn_idx, 1999 int subprog) 2000 { 2001 struct bpf_verifier_stack_elem *elem; 2002 struct bpf_func_state *frame; 2003 2004 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 2005 if (!elem) 2006 goto err; 2007 2008 elem->insn_idx = insn_idx; 2009 elem->prev_insn_idx = prev_insn_idx; 2010 elem->next = env->head; 2011 elem->log_pos = env->log.len_used; 2012 env->head = elem; 2013 env->stack_size++; 2014 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 2015 verbose(env, 2016 "The sequence of %d jumps is too complex for async cb.\n", 2017 env->stack_size); 2018 goto err; 2019 } 2020 /* Unlike push_stack() do not copy_verifier_state(). 2021 * The caller state doesn't matter. 2022 * This is async callback. It starts in a fresh stack. 2023 * Initialize it similar to do_check_common(). 2024 */ 2025 elem->st.branches = 1; 2026 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 2027 if (!frame) 2028 goto err; 2029 init_func_state(env, frame, 2030 BPF_MAIN_FUNC /* callsite */, 2031 0 /* frameno within this callchain */, 2032 subprog /* subprog number within this prog */); 2033 elem->st.frame[0] = frame; 2034 return &elem->st; 2035 err: 2036 free_verifier_state(env->cur_state, true); 2037 env->cur_state = NULL; 2038 /* pop all elements and return */ 2039 while (!pop_stack(env, NULL, NULL, false)); 2040 return NULL; 2041 } 2042 2043 2044 enum reg_arg_type { 2045 SRC_OP, /* register is used as source operand */ 2046 DST_OP, /* register is used as destination operand */ 2047 DST_OP_NO_MARK /* same as above, check only, don't mark */ 2048 }; 2049 2050 static int cmp_subprogs(const void *a, const void *b) 2051 { 2052 return ((struct bpf_subprog_info *)a)->start - 2053 ((struct bpf_subprog_info *)b)->start; 2054 } 2055 2056 static int find_subprog(struct bpf_verifier_env *env, int off) 2057 { 2058 struct bpf_subprog_info *p; 2059 2060 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 2061 sizeof(env->subprog_info[0]), cmp_subprogs); 2062 if (!p) 2063 return -ENOENT; 2064 return p - env->subprog_info; 2065 2066 } 2067 2068 static int add_subprog(struct bpf_verifier_env *env, int off) 2069 { 2070 int insn_cnt = env->prog->len; 2071 int ret; 2072 2073 if (off >= insn_cnt || off < 0) { 2074 verbose(env, "call to invalid destination\n"); 2075 return -EINVAL; 2076 } 2077 ret = find_subprog(env, off); 2078 if (ret >= 0) 2079 return ret; 2080 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 2081 verbose(env, "too many subprograms\n"); 2082 return -E2BIG; 2083 } 2084 /* determine subprog starts. The end is one before the next starts */ 2085 env->subprog_info[env->subprog_cnt++].start = off; 2086 sort(env->subprog_info, env->subprog_cnt, 2087 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 2088 return env->subprog_cnt - 1; 2089 } 2090 2091 #define MAX_KFUNC_DESCS 256 2092 #define MAX_KFUNC_BTFS 256 2093 2094 struct bpf_kfunc_desc { 2095 struct btf_func_model func_model; 2096 u32 func_id; 2097 s32 imm; 2098 u16 offset; 2099 }; 2100 2101 struct bpf_kfunc_btf { 2102 struct btf *btf; 2103 struct module *module; 2104 u16 offset; 2105 }; 2106 2107 struct bpf_kfunc_desc_tab { 2108 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 2109 u32 nr_descs; 2110 }; 2111 2112 struct bpf_kfunc_btf_tab { 2113 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 2114 u32 nr_descs; 2115 }; 2116 2117 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 2118 { 2119 const struct bpf_kfunc_desc *d0 = a; 2120 const struct bpf_kfunc_desc *d1 = b; 2121 2122 /* func_id is not greater than BTF_MAX_TYPE */ 2123 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 2124 } 2125 2126 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 2127 { 2128 const struct bpf_kfunc_btf *d0 = a; 2129 const struct bpf_kfunc_btf *d1 = b; 2130 2131 return d0->offset - d1->offset; 2132 } 2133 2134 static const struct bpf_kfunc_desc * 2135 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 2136 { 2137 struct bpf_kfunc_desc desc = { 2138 .func_id = func_id, 2139 .offset = offset, 2140 }; 2141 struct bpf_kfunc_desc_tab *tab; 2142 2143 tab = prog->aux->kfunc_tab; 2144 return bsearch(&desc, tab->descs, tab->nr_descs, 2145 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 2146 } 2147 2148 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 2149 s16 offset) 2150 { 2151 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 2152 struct bpf_kfunc_btf_tab *tab; 2153 struct bpf_kfunc_btf *b; 2154 struct module *mod; 2155 struct btf *btf; 2156 int btf_fd; 2157 2158 tab = env->prog->aux->kfunc_btf_tab; 2159 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 2160 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 2161 if (!b) { 2162 if (tab->nr_descs == MAX_KFUNC_BTFS) { 2163 verbose(env, "too many different module BTFs\n"); 2164 return ERR_PTR(-E2BIG); 2165 } 2166 2167 if (bpfptr_is_null(env->fd_array)) { 2168 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 2169 return ERR_PTR(-EPROTO); 2170 } 2171 2172 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 2173 offset * sizeof(btf_fd), 2174 sizeof(btf_fd))) 2175 return ERR_PTR(-EFAULT); 2176 2177 btf = btf_get_by_fd(btf_fd); 2178 if (IS_ERR(btf)) { 2179 verbose(env, "invalid module BTF fd specified\n"); 2180 return btf; 2181 } 2182 2183 if (!btf_is_module(btf)) { 2184 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 2185 btf_put(btf); 2186 return ERR_PTR(-EINVAL); 2187 } 2188 2189 mod = btf_try_get_module(btf); 2190 if (!mod) { 2191 btf_put(btf); 2192 return ERR_PTR(-ENXIO); 2193 } 2194 2195 b = &tab->descs[tab->nr_descs++]; 2196 b->btf = btf; 2197 b->module = mod; 2198 b->offset = offset; 2199 2200 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2201 kfunc_btf_cmp_by_off, NULL); 2202 } 2203 return b->btf; 2204 } 2205 2206 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 2207 { 2208 if (!tab) 2209 return; 2210 2211 while (tab->nr_descs--) { 2212 module_put(tab->descs[tab->nr_descs].module); 2213 btf_put(tab->descs[tab->nr_descs].btf); 2214 } 2215 kfree(tab); 2216 } 2217 2218 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, s16 offset) 2219 { 2220 if (offset) { 2221 if (offset < 0) { 2222 /* In the future, this can be allowed to increase limit 2223 * of fd index into fd_array, interpreted as u16. 2224 */ 2225 verbose(env, "negative offset disallowed for kernel module function call\n"); 2226 return ERR_PTR(-EINVAL); 2227 } 2228 2229 return __find_kfunc_desc_btf(env, offset); 2230 } 2231 return btf_vmlinux ?: ERR_PTR(-ENOENT); 2232 } 2233 2234 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 2235 { 2236 const struct btf_type *func, *func_proto; 2237 struct bpf_kfunc_btf_tab *btf_tab; 2238 struct bpf_kfunc_desc_tab *tab; 2239 struct bpf_prog_aux *prog_aux; 2240 struct bpf_kfunc_desc *desc; 2241 const char *func_name; 2242 struct btf *desc_btf; 2243 unsigned long call_imm; 2244 unsigned long addr; 2245 int err; 2246 2247 prog_aux = env->prog->aux; 2248 tab = prog_aux->kfunc_tab; 2249 btf_tab = prog_aux->kfunc_btf_tab; 2250 if (!tab) { 2251 if (!btf_vmlinux) { 2252 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 2253 return -ENOTSUPP; 2254 } 2255 2256 if (!env->prog->jit_requested) { 2257 verbose(env, "JIT is required for calling kernel function\n"); 2258 return -ENOTSUPP; 2259 } 2260 2261 if (!bpf_jit_supports_kfunc_call()) { 2262 verbose(env, "JIT does not support calling kernel function\n"); 2263 return -ENOTSUPP; 2264 } 2265 2266 if (!env->prog->gpl_compatible) { 2267 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 2268 return -EINVAL; 2269 } 2270 2271 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 2272 if (!tab) 2273 return -ENOMEM; 2274 prog_aux->kfunc_tab = tab; 2275 } 2276 2277 /* func_id == 0 is always invalid, but instead of returning an error, be 2278 * conservative and wait until the code elimination pass before returning 2279 * error, so that invalid calls that get pruned out can be in BPF programs 2280 * loaded from userspace. It is also required that offset be untouched 2281 * for such calls. 2282 */ 2283 if (!func_id && !offset) 2284 return 0; 2285 2286 if (!btf_tab && offset) { 2287 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 2288 if (!btf_tab) 2289 return -ENOMEM; 2290 prog_aux->kfunc_btf_tab = btf_tab; 2291 } 2292 2293 desc_btf = find_kfunc_desc_btf(env, offset); 2294 if (IS_ERR(desc_btf)) { 2295 verbose(env, "failed to find BTF for kernel function\n"); 2296 return PTR_ERR(desc_btf); 2297 } 2298 2299 if (find_kfunc_desc(env->prog, func_id, offset)) 2300 return 0; 2301 2302 if (tab->nr_descs == MAX_KFUNC_DESCS) { 2303 verbose(env, "too many different kernel function calls\n"); 2304 return -E2BIG; 2305 } 2306 2307 func = btf_type_by_id(desc_btf, func_id); 2308 if (!func || !btf_type_is_func(func)) { 2309 verbose(env, "kernel btf_id %u is not a function\n", 2310 func_id); 2311 return -EINVAL; 2312 } 2313 func_proto = btf_type_by_id(desc_btf, func->type); 2314 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 2315 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 2316 func_id); 2317 return -EINVAL; 2318 } 2319 2320 func_name = btf_name_by_offset(desc_btf, func->name_off); 2321 addr = kallsyms_lookup_name(func_name); 2322 if (!addr) { 2323 verbose(env, "cannot find address for kernel function %s\n", 2324 func_name); 2325 return -EINVAL; 2326 } 2327 2328 call_imm = BPF_CALL_IMM(addr); 2329 /* Check whether or not the relative offset overflows desc->imm */ 2330 if ((unsigned long)(s32)call_imm != call_imm) { 2331 verbose(env, "address of kernel function %s is out of range\n", 2332 func_name); 2333 return -EINVAL; 2334 } 2335 2336 if (bpf_dev_bound_kfunc_id(func_id)) { 2337 err = bpf_dev_bound_kfunc_check(&env->log, prog_aux); 2338 if (err) 2339 return err; 2340 } 2341 2342 desc = &tab->descs[tab->nr_descs++]; 2343 desc->func_id = func_id; 2344 desc->imm = call_imm; 2345 desc->offset = offset; 2346 err = btf_distill_func_proto(&env->log, desc_btf, 2347 func_proto, func_name, 2348 &desc->func_model); 2349 if (!err) 2350 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2351 kfunc_desc_cmp_by_id_off, NULL); 2352 return err; 2353 } 2354 2355 static int kfunc_desc_cmp_by_imm(const void *a, const void *b) 2356 { 2357 const struct bpf_kfunc_desc *d0 = a; 2358 const struct bpf_kfunc_desc *d1 = b; 2359 2360 if (d0->imm > d1->imm) 2361 return 1; 2362 else if (d0->imm < d1->imm) 2363 return -1; 2364 return 0; 2365 } 2366 2367 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog) 2368 { 2369 struct bpf_kfunc_desc_tab *tab; 2370 2371 tab = prog->aux->kfunc_tab; 2372 if (!tab) 2373 return; 2374 2375 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 2376 kfunc_desc_cmp_by_imm, NULL); 2377 } 2378 2379 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 2380 { 2381 return !!prog->aux->kfunc_tab; 2382 } 2383 2384 const struct btf_func_model * 2385 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 2386 const struct bpf_insn *insn) 2387 { 2388 const struct bpf_kfunc_desc desc = { 2389 .imm = insn->imm, 2390 }; 2391 const struct bpf_kfunc_desc *res; 2392 struct bpf_kfunc_desc_tab *tab; 2393 2394 tab = prog->aux->kfunc_tab; 2395 res = bsearch(&desc, tab->descs, tab->nr_descs, 2396 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm); 2397 2398 return res ? &res->func_model : NULL; 2399 } 2400 2401 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 2402 { 2403 struct bpf_subprog_info *subprog = env->subprog_info; 2404 struct bpf_insn *insn = env->prog->insnsi; 2405 int i, ret, insn_cnt = env->prog->len; 2406 2407 /* Add entry function. */ 2408 ret = add_subprog(env, 0); 2409 if (ret) 2410 return ret; 2411 2412 for (i = 0; i < insn_cnt; i++, insn++) { 2413 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 2414 !bpf_pseudo_kfunc_call(insn)) 2415 continue; 2416 2417 if (!env->bpf_capable) { 2418 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 2419 return -EPERM; 2420 } 2421 2422 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2423 ret = add_subprog(env, i + insn->imm + 1); 2424 else 2425 ret = add_kfunc_call(env, insn->imm, insn->off); 2426 2427 if (ret < 0) 2428 return ret; 2429 } 2430 2431 /* Add a fake 'exit' subprog which could simplify subprog iteration 2432 * logic. 'subprog_cnt' should not be increased. 2433 */ 2434 subprog[env->subprog_cnt].start = insn_cnt; 2435 2436 if (env->log.level & BPF_LOG_LEVEL2) 2437 for (i = 0; i < env->subprog_cnt; i++) 2438 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2439 2440 return 0; 2441 } 2442 2443 static int check_subprogs(struct bpf_verifier_env *env) 2444 { 2445 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2446 struct bpf_subprog_info *subprog = env->subprog_info; 2447 struct bpf_insn *insn = env->prog->insnsi; 2448 int insn_cnt = env->prog->len; 2449 2450 /* now check that all jumps are within the same subprog */ 2451 subprog_start = subprog[cur_subprog].start; 2452 subprog_end = subprog[cur_subprog + 1].start; 2453 for (i = 0; i < insn_cnt; i++) { 2454 u8 code = insn[i].code; 2455 2456 if (code == (BPF_JMP | BPF_CALL) && 2457 insn[i].imm == BPF_FUNC_tail_call && 2458 insn[i].src_reg != BPF_PSEUDO_CALL) 2459 subprog[cur_subprog].has_tail_call = true; 2460 if (BPF_CLASS(code) == BPF_LD && 2461 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2462 subprog[cur_subprog].has_ld_abs = true; 2463 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2464 goto next; 2465 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2466 goto next; 2467 off = i + insn[i].off + 1; 2468 if (off < subprog_start || off >= subprog_end) { 2469 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2470 return -EINVAL; 2471 } 2472 next: 2473 if (i == subprog_end - 1) { 2474 /* to avoid fall-through from one subprog into another 2475 * the last insn of the subprog should be either exit 2476 * or unconditional jump back 2477 */ 2478 if (code != (BPF_JMP | BPF_EXIT) && 2479 code != (BPF_JMP | BPF_JA)) { 2480 verbose(env, "last insn is not an exit or jmp\n"); 2481 return -EINVAL; 2482 } 2483 subprog_start = subprog_end; 2484 cur_subprog++; 2485 if (cur_subprog < env->subprog_cnt) 2486 subprog_end = subprog[cur_subprog + 1].start; 2487 } 2488 } 2489 return 0; 2490 } 2491 2492 /* Parentage chain of this register (or stack slot) should take care of all 2493 * issues like callee-saved registers, stack slot allocation time, etc. 2494 */ 2495 static int mark_reg_read(struct bpf_verifier_env *env, 2496 const struct bpf_reg_state *state, 2497 struct bpf_reg_state *parent, u8 flag) 2498 { 2499 bool writes = parent == state->parent; /* Observe write marks */ 2500 int cnt = 0; 2501 2502 while (parent) { 2503 /* if read wasn't screened by an earlier write ... */ 2504 if (writes && state->live & REG_LIVE_WRITTEN) 2505 break; 2506 if (parent->live & REG_LIVE_DONE) { 2507 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2508 reg_type_str(env, parent->type), 2509 parent->var_off.value, parent->off); 2510 return -EFAULT; 2511 } 2512 /* The first condition is more likely to be true than the 2513 * second, checked it first. 2514 */ 2515 if ((parent->live & REG_LIVE_READ) == flag || 2516 parent->live & REG_LIVE_READ64) 2517 /* The parentage chain never changes and 2518 * this parent was already marked as LIVE_READ. 2519 * There is no need to keep walking the chain again and 2520 * keep re-marking all parents as LIVE_READ. 2521 * This case happens when the same register is read 2522 * multiple times without writes into it in-between. 2523 * Also, if parent has the stronger REG_LIVE_READ64 set, 2524 * then no need to set the weak REG_LIVE_READ32. 2525 */ 2526 break; 2527 /* ... then we depend on parent's value */ 2528 parent->live |= flag; 2529 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 2530 if (flag == REG_LIVE_READ64) 2531 parent->live &= ~REG_LIVE_READ32; 2532 state = parent; 2533 parent = state->parent; 2534 writes = true; 2535 cnt++; 2536 } 2537 2538 if (env->longest_mark_read_walk < cnt) 2539 env->longest_mark_read_walk = cnt; 2540 return 0; 2541 } 2542 2543 static int mark_dynptr_read(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 2544 { 2545 struct bpf_func_state *state = func(env, reg); 2546 int spi, ret; 2547 2548 /* For CONST_PTR_TO_DYNPTR, it must have already been done by 2549 * check_reg_arg in check_helper_call and mark_btf_func_reg_size in 2550 * check_kfunc_call. 2551 */ 2552 if (reg->type == CONST_PTR_TO_DYNPTR) 2553 return 0; 2554 spi = dynptr_get_spi(env, reg); 2555 if (spi < 0) 2556 return spi; 2557 /* Caller ensures dynptr is valid and initialized, which means spi is in 2558 * bounds and spi is the first dynptr slot. Simply mark stack slot as 2559 * read. 2560 */ 2561 ret = mark_reg_read(env, &state->stack[spi].spilled_ptr, 2562 state->stack[spi].spilled_ptr.parent, REG_LIVE_READ64); 2563 if (ret) 2564 return ret; 2565 return mark_reg_read(env, &state->stack[spi - 1].spilled_ptr, 2566 state->stack[spi - 1].spilled_ptr.parent, REG_LIVE_READ64); 2567 } 2568 2569 /* This function is supposed to be used by the following 32-bit optimization 2570 * code only. It returns TRUE if the source or destination register operates 2571 * on 64-bit, otherwise return FALSE. 2572 */ 2573 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 2574 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 2575 { 2576 u8 code, class, op; 2577 2578 code = insn->code; 2579 class = BPF_CLASS(code); 2580 op = BPF_OP(code); 2581 if (class == BPF_JMP) { 2582 /* BPF_EXIT for "main" will reach here. Return TRUE 2583 * conservatively. 2584 */ 2585 if (op == BPF_EXIT) 2586 return true; 2587 if (op == BPF_CALL) { 2588 /* BPF to BPF call will reach here because of marking 2589 * caller saved clobber with DST_OP_NO_MARK for which we 2590 * don't care the register def because they are anyway 2591 * marked as NOT_INIT already. 2592 */ 2593 if (insn->src_reg == BPF_PSEUDO_CALL) 2594 return false; 2595 /* Helper call will reach here because of arg type 2596 * check, conservatively return TRUE. 2597 */ 2598 if (t == SRC_OP) 2599 return true; 2600 2601 return false; 2602 } 2603 } 2604 2605 if (class == BPF_ALU64 || class == BPF_JMP || 2606 /* BPF_END always use BPF_ALU class. */ 2607 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 2608 return true; 2609 2610 if (class == BPF_ALU || class == BPF_JMP32) 2611 return false; 2612 2613 if (class == BPF_LDX) { 2614 if (t != SRC_OP) 2615 return BPF_SIZE(code) == BPF_DW; 2616 /* LDX source must be ptr. */ 2617 return true; 2618 } 2619 2620 if (class == BPF_STX) { 2621 /* BPF_STX (including atomic variants) has multiple source 2622 * operands, one of which is a ptr. Check whether the caller is 2623 * asking about it. 2624 */ 2625 if (t == SRC_OP && reg->type != SCALAR_VALUE) 2626 return true; 2627 return BPF_SIZE(code) == BPF_DW; 2628 } 2629 2630 if (class == BPF_LD) { 2631 u8 mode = BPF_MODE(code); 2632 2633 /* LD_IMM64 */ 2634 if (mode == BPF_IMM) 2635 return true; 2636 2637 /* Both LD_IND and LD_ABS return 32-bit data. */ 2638 if (t != SRC_OP) 2639 return false; 2640 2641 /* Implicit ctx ptr. */ 2642 if (regno == BPF_REG_6) 2643 return true; 2644 2645 /* Explicit source could be any width. */ 2646 return true; 2647 } 2648 2649 if (class == BPF_ST) 2650 /* The only source register for BPF_ST is a ptr. */ 2651 return true; 2652 2653 /* Conservatively return true at default. */ 2654 return true; 2655 } 2656 2657 /* Return the regno defined by the insn, or -1. */ 2658 static int insn_def_regno(const struct bpf_insn *insn) 2659 { 2660 switch (BPF_CLASS(insn->code)) { 2661 case BPF_JMP: 2662 case BPF_JMP32: 2663 case BPF_ST: 2664 return -1; 2665 case BPF_STX: 2666 if (BPF_MODE(insn->code) == BPF_ATOMIC && 2667 (insn->imm & BPF_FETCH)) { 2668 if (insn->imm == BPF_CMPXCHG) 2669 return BPF_REG_0; 2670 else 2671 return insn->src_reg; 2672 } else { 2673 return -1; 2674 } 2675 default: 2676 return insn->dst_reg; 2677 } 2678 } 2679 2680 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 2681 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 2682 { 2683 int dst_reg = insn_def_regno(insn); 2684 2685 if (dst_reg == -1) 2686 return false; 2687 2688 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 2689 } 2690 2691 static void mark_insn_zext(struct bpf_verifier_env *env, 2692 struct bpf_reg_state *reg) 2693 { 2694 s32 def_idx = reg->subreg_def; 2695 2696 if (def_idx == DEF_NOT_SUBREG) 2697 return; 2698 2699 env->insn_aux_data[def_idx - 1].zext_dst = true; 2700 /* The dst will be zero extended, so won't be sub-register anymore. */ 2701 reg->subreg_def = DEF_NOT_SUBREG; 2702 } 2703 2704 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 2705 enum reg_arg_type t) 2706 { 2707 struct bpf_verifier_state *vstate = env->cur_state; 2708 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2709 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 2710 struct bpf_reg_state *reg, *regs = state->regs; 2711 bool rw64; 2712 2713 if (regno >= MAX_BPF_REG) { 2714 verbose(env, "R%d is invalid\n", regno); 2715 return -EINVAL; 2716 } 2717 2718 mark_reg_scratched(env, regno); 2719 2720 reg = ®s[regno]; 2721 rw64 = is_reg64(env, insn, regno, reg, t); 2722 if (t == SRC_OP) { 2723 /* check whether register used as source operand can be read */ 2724 if (reg->type == NOT_INIT) { 2725 verbose(env, "R%d !read_ok\n", regno); 2726 return -EACCES; 2727 } 2728 /* We don't need to worry about FP liveness because it's read-only */ 2729 if (regno == BPF_REG_FP) 2730 return 0; 2731 2732 if (rw64) 2733 mark_insn_zext(env, reg); 2734 2735 return mark_reg_read(env, reg, reg->parent, 2736 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 2737 } else { 2738 /* check whether register used as dest operand can be written to */ 2739 if (regno == BPF_REG_FP) { 2740 verbose(env, "frame pointer is read only\n"); 2741 return -EACCES; 2742 } 2743 reg->live |= REG_LIVE_WRITTEN; 2744 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 2745 if (t == DST_OP) 2746 mark_reg_unknown(env, regs, regno); 2747 } 2748 return 0; 2749 } 2750 2751 static void mark_jmp_point(struct bpf_verifier_env *env, int idx) 2752 { 2753 env->insn_aux_data[idx].jmp_point = true; 2754 } 2755 2756 static bool is_jmp_point(struct bpf_verifier_env *env, int insn_idx) 2757 { 2758 return env->insn_aux_data[insn_idx].jmp_point; 2759 } 2760 2761 /* for any branch, call, exit record the history of jmps in the given state */ 2762 static int push_jmp_history(struct bpf_verifier_env *env, 2763 struct bpf_verifier_state *cur) 2764 { 2765 u32 cnt = cur->jmp_history_cnt; 2766 struct bpf_idx_pair *p; 2767 size_t alloc_size; 2768 2769 if (!is_jmp_point(env, env->insn_idx)) 2770 return 0; 2771 2772 cnt++; 2773 alloc_size = kmalloc_size_roundup(size_mul(cnt, sizeof(*p))); 2774 p = krealloc(cur->jmp_history, alloc_size, GFP_USER); 2775 if (!p) 2776 return -ENOMEM; 2777 p[cnt - 1].idx = env->insn_idx; 2778 p[cnt - 1].prev_idx = env->prev_insn_idx; 2779 cur->jmp_history = p; 2780 cur->jmp_history_cnt = cnt; 2781 return 0; 2782 } 2783 2784 /* Backtrack one insn at a time. If idx is not at the top of recorded 2785 * history then previous instruction came from straight line execution. 2786 */ 2787 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 2788 u32 *history) 2789 { 2790 u32 cnt = *history; 2791 2792 if (cnt && st->jmp_history[cnt - 1].idx == i) { 2793 i = st->jmp_history[cnt - 1].prev_idx; 2794 (*history)--; 2795 } else { 2796 i--; 2797 } 2798 return i; 2799 } 2800 2801 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 2802 { 2803 const struct btf_type *func; 2804 struct btf *desc_btf; 2805 2806 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 2807 return NULL; 2808 2809 desc_btf = find_kfunc_desc_btf(data, insn->off); 2810 if (IS_ERR(desc_btf)) 2811 return "<error>"; 2812 2813 func = btf_type_by_id(desc_btf, insn->imm); 2814 return btf_name_by_offset(desc_btf, func->name_off); 2815 } 2816 2817 /* For given verifier state backtrack_insn() is called from the last insn to 2818 * the first insn. Its purpose is to compute a bitmask of registers and 2819 * stack slots that needs precision in the parent verifier state. 2820 */ 2821 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 2822 u32 *reg_mask, u64 *stack_mask) 2823 { 2824 const struct bpf_insn_cbs cbs = { 2825 .cb_call = disasm_kfunc_name, 2826 .cb_print = verbose, 2827 .private_data = env, 2828 }; 2829 struct bpf_insn *insn = env->prog->insnsi + idx; 2830 u8 class = BPF_CLASS(insn->code); 2831 u8 opcode = BPF_OP(insn->code); 2832 u8 mode = BPF_MODE(insn->code); 2833 u32 dreg = 1u << insn->dst_reg; 2834 u32 sreg = 1u << insn->src_reg; 2835 u32 spi; 2836 2837 if (insn->code == 0) 2838 return 0; 2839 if (env->log.level & BPF_LOG_LEVEL2) { 2840 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask); 2841 verbose(env, "%d: ", idx); 2842 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 2843 } 2844 2845 if (class == BPF_ALU || class == BPF_ALU64) { 2846 if (!(*reg_mask & dreg)) 2847 return 0; 2848 if (opcode == BPF_MOV) { 2849 if (BPF_SRC(insn->code) == BPF_X) { 2850 /* dreg = sreg 2851 * dreg needs precision after this insn 2852 * sreg needs precision before this insn 2853 */ 2854 *reg_mask &= ~dreg; 2855 *reg_mask |= sreg; 2856 } else { 2857 /* dreg = K 2858 * dreg needs precision after this insn. 2859 * Corresponding register is already marked 2860 * as precise=true in this verifier state. 2861 * No further markings in parent are necessary 2862 */ 2863 *reg_mask &= ~dreg; 2864 } 2865 } else { 2866 if (BPF_SRC(insn->code) == BPF_X) { 2867 /* dreg += sreg 2868 * both dreg and sreg need precision 2869 * before this insn 2870 */ 2871 *reg_mask |= sreg; 2872 } /* else dreg += K 2873 * dreg still needs precision before this insn 2874 */ 2875 } 2876 } else if (class == BPF_LDX) { 2877 if (!(*reg_mask & dreg)) 2878 return 0; 2879 *reg_mask &= ~dreg; 2880 2881 /* scalars can only be spilled into stack w/o losing precision. 2882 * Load from any other memory can be zero extended. 2883 * The desire to keep that precision is already indicated 2884 * by 'precise' mark in corresponding register of this state. 2885 * No further tracking necessary. 2886 */ 2887 if (insn->src_reg != BPF_REG_FP) 2888 return 0; 2889 2890 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 2891 * that [fp - off] slot contains scalar that needs to be 2892 * tracked with precision 2893 */ 2894 spi = (-insn->off - 1) / BPF_REG_SIZE; 2895 if (spi >= 64) { 2896 verbose(env, "BUG spi %d\n", spi); 2897 WARN_ONCE(1, "verifier backtracking bug"); 2898 return -EFAULT; 2899 } 2900 *stack_mask |= 1ull << spi; 2901 } else if (class == BPF_STX || class == BPF_ST) { 2902 if (*reg_mask & dreg) 2903 /* stx & st shouldn't be using _scalar_ dst_reg 2904 * to access memory. It means backtracking 2905 * encountered a case of pointer subtraction. 2906 */ 2907 return -ENOTSUPP; 2908 /* scalars can only be spilled into stack */ 2909 if (insn->dst_reg != BPF_REG_FP) 2910 return 0; 2911 spi = (-insn->off - 1) / BPF_REG_SIZE; 2912 if (spi >= 64) { 2913 verbose(env, "BUG spi %d\n", spi); 2914 WARN_ONCE(1, "verifier backtracking bug"); 2915 return -EFAULT; 2916 } 2917 if (!(*stack_mask & (1ull << spi))) 2918 return 0; 2919 *stack_mask &= ~(1ull << spi); 2920 if (class == BPF_STX) 2921 *reg_mask |= sreg; 2922 } else if (class == BPF_JMP || class == BPF_JMP32) { 2923 if (opcode == BPF_CALL) { 2924 if (insn->src_reg == BPF_PSEUDO_CALL) 2925 return -ENOTSUPP; 2926 /* BPF helpers that invoke callback subprogs are 2927 * equivalent to BPF_PSEUDO_CALL above 2928 */ 2929 if (insn->src_reg == 0 && is_callback_calling_function(insn->imm)) 2930 return -ENOTSUPP; 2931 /* regular helper call sets R0 */ 2932 *reg_mask &= ~1; 2933 if (*reg_mask & 0x3f) { 2934 /* if backtracing was looking for registers R1-R5 2935 * they should have been found already. 2936 */ 2937 verbose(env, "BUG regs %x\n", *reg_mask); 2938 WARN_ONCE(1, "verifier backtracking bug"); 2939 return -EFAULT; 2940 } 2941 } else if (opcode == BPF_EXIT) { 2942 return -ENOTSUPP; 2943 } 2944 } else if (class == BPF_LD) { 2945 if (!(*reg_mask & dreg)) 2946 return 0; 2947 *reg_mask &= ~dreg; 2948 /* It's ld_imm64 or ld_abs or ld_ind. 2949 * For ld_imm64 no further tracking of precision 2950 * into parent is necessary 2951 */ 2952 if (mode == BPF_IND || mode == BPF_ABS) 2953 /* to be analyzed */ 2954 return -ENOTSUPP; 2955 } 2956 return 0; 2957 } 2958 2959 /* the scalar precision tracking algorithm: 2960 * . at the start all registers have precise=false. 2961 * . scalar ranges are tracked as normal through alu and jmp insns. 2962 * . once precise value of the scalar register is used in: 2963 * . ptr + scalar alu 2964 * . if (scalar cond K|scalar) 2965 * . helper_call(.., scalar, ...) where ARG_CONST is expected 2966 * backtrack through the verifier states and mark all registers and 2967 * stack slots with spilled constants that these scalar regisers 2968 * should be precise. 2969 * . during state pruning two registers (or spilled stack slots) 2970 * are equivalent if both are not precise. 2971 * 2972 * Note the verifier cannot simply walk register parentage chain, 2973 * since many different registers and stack slots could have been 2974 * used to compute single precise scalar. 2975 * 2976 * The approach of starting with precise=true for all registers and then 2977 * backtrack to mark a register as not precise when the verifier detects 2978 * that program doesn't care about specific value (e.g., when helper 2979 * takes register as ARG_ANYTHING parameter) is not safe. 2980 * 2981 * It's ok to walk single parentage chain of the verifier states. 2982 * It's possible that this backtracking will go all the way till 1st insn. 2983 * All other branches will be explored for needing precision later. 2984 * 2985 * The backtracking needs to deal with cases like: 2986 * 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) 2987 * r9 -= r8 2988 * r5 = r9 2989 * if r5 > 0x79f goto pc+7 2990 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 2991 * r5 += 1 2992 * ... 2993 * call bpf_perf_event_output#25 2994 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 2995 * 2996 * and this case: 2997 * r6 = 1 2998 * call foo // uses callee's r6 inside to compute r0 2999 * r0 += r6 3000 * if r0 == 0 goto 3001 * 3002 * to track above reg_mask/stack_mask needs to be independent for each frame. 3003 * 3004 * Also if parent's curframe > frame where backtracking started, 3005 * the verifier need to mark registers in both frames, otherwise callees 3006 * may incorrectly prune callers. This is similar to 3007 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 3008 * 3009 * For now backtracking falls back into conservative marking. 3010 */ 3011 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 3012 struct bpf_verifier_state *st) 3013 { 3014 struct bpf_func_state *func; 3015 struct bpf_reg_state *reg; 3016 int i, j; 3017 3018 /* big hammer: mark all scalars precise in this path. 3019 * pop_stack may still get !precise scalars. 3020 * We also skip current state and go straight to first parent state, 3021 * because precision markings in current non-checkpointed state are 3022 * not needed. See why in the comment in __mark_chain_precision below. 3023 */ 3024 for (st = st->parent; st; st = st->parent) { 3025 for (i = 0; i <= st->curframe; i++) { 3026 func = st->frame[i]; 3027 for (j = 0; j < BPF_REG_FP; j++) { 3028 reg = &func->regs[j]; 3029 if (reg->type != SCALAR_VALUE) 3030 continue; 3031 reg->precise = true; 3032 } 3033 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3034 if (!is_spilled_reg(&func->stack[j])) 3035 continue; 3036 reg = &func->stack[j].spilled_ptr; 3037 if (reg->type != SCALAR_VALUE) 3038 continue; 3039 reg->precise = true; 3040 } 3041 } 3042 } 3043 } 3044 3045 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 3046 { 3047 struct bpf_func_state *func; 3048 struct bpf_reg_state *reg; 3049 int i, j; 3050 3051 for (i = 0; i <= st->curframe; i++) { 3052 func = st->frame[i]; 3053 for (j = 0; j < BPF_REG_FP; j++) { 3054 reg = &func->regs[j]; 3055 if (reg->type != SCALAR_VALUE) 3056 continue; 3057 reg->precise = false; 3058 } 3059 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 3060 if (!is_spilled_reg(&func->stack[j])) 3061 continue; 3062 reg = &func->stack[j].spilled_ptr; 3063 if (reg->type != SCALAR_VALUE) 3064 continue; 3065 reg->precise = false; 3066 } 3067 } 3068 } 3069 3070 /* 3071 * __mark_chain_precision() backtracks BPF program instruction sequence and 3072 * chain of verifier states making sure that register *regno* (if regno >= 0) 3073 * and/or stack slot *spi* (if spi >= 0) are marked as precisely tracked 3074 * SCALARS, as well as any other registers and slots that contribute to 3075 * a tracked state of given registers/stack slots, depending on specific BPF 3076 * assembly instructions (see backtrack_insns() for exact instruction handling 3077 * logic). This backtracking relies on recorded jmp_history and is able to 3078 * traverse entire chain of parent states. This process ends only when all the 3079 * necessary registers/slots and their transitive dependencies are marked as 3080 * precise. 3081 * 3082 * One important and subtle aspect is that precise marks *do not matter* in 3083 * the currently verified state (current state). It is important to understand 3084 * why this is the case. 3085 * 3086 * First, note that current state is the state that is not yet "checkpointed", 3087 * i.e., it is not yet put into env->explored_states, and it has no children 3088 * states as well. It's ephemeral, and can end up either a) being discarded if 3089 * compatible explored state is found at some point or BPF_EXIT instruction is 3090 * reached or b) checkpointed and put into env->explored_states, branching out 3091 * into one or more children states. 3092 * 3093 * In the former case, precise markings in current state are completely 3094 * ignored by state comparison code (see regsafe() for details). Only 3095 * checkpointed ("old") state precise markings are important, and if old 3096 * state's register/slot is precise, regsafe() assumes current state's 3097 * register/slot as precise and checks value ranges exactly and precisely. If 3098 * states turn out to be compatible, current state's necessary precise 3099 * markings and any required parent states' precise markings are enforced 3100 * after the fact with propagate_precision() logic, after the fact. But it's 3101 * important to realize that in this case, even after marking current state 3102 * registers/slots as precise, we immediately discard current state. So what 3103 * actually matters is any of the precise markings propagated into current 3104 * state's parent states, which are always checkpointed (due to b) case above). 3105 * As such, for scenario a) it doesn't matter if current state has precise 3106 * markings set or not. 3107 * 3108 * Now, for the scenario b), checkpointing and forking into child(ren) 3109 * state(s). Note that before current state gets to checkpointing step, any 3110 * processed instruction always assumes precise SCALAR register/slot 3111 * knowledge: if precise value or range is useful to prune jump branch, BPF 3112 * verifier takes this opportunity enthusiastically. Similarly, when 3113 * register's value is used to calculate offset or memory address, exact 3114 * knowledge of SCALAR range is assumed, checked, and enforced. So, similar to 3115 * what we mentioned above about state comparison ignoring precise markings 3116 * during state comparison, BPF verifier ignores and also assumes precise 3117 * markings *at will* during instruction verification process. But as verifier 3118 * assumes precision, it also propagates any precision dependencies across 3119 * parent states, which are not yet finalized, so can be further restricted 3120 * based on new knowledge gained from restrictions enforced by their children 3121 * states. This is so that once those parent states are finalized, i.e., when 3122 * they have no more active children state, state comparison logic in 3123 * is_state_visited() would enforce strict and precise SCALAR ranges, if 3124 * required for correctness. 3125 * 3126 * To build a bit more intuition, note also that once a state is checkpointed, 3127 * the path we took to get to that state is not important. This is crucial 3128 * property for state pruning. When state is checkpointed and finalized at 3129 * some instruction index, it can be correctly and safely used to "short 3130 * circuit" any *compatible* state that reaches exactly the same instruction 3131 * index. I.e., if we jumped to that instruction from a completely different 3132 * code path than original finalized state was derived from, it doesn't 3133 * matter, current state can be discarded because from that instruction 3134 * forward having a compatible state will ensure we will safely reach the 3135 * exit. States describe preconditions for further exploration, but completely 3136 * forget the history of how we got here. 3137 * 3138 * This also means that even if we needed precise SCALAR range to get to 3139 * finalized state, but from that point forward *that same* SCALAR register is 3140 * never used in a precise context (i.e., it's precise value is not needed for 3141 * correctness), it's correct and safe to mark such register as "imprecise" 3142 * (i.e., precise marking set to false). This is what we rely on when we do 3143 * not set precise marking in current state. If no child state requires 3144 * precision for any given SCALAR register, it's safe to dictate that it can 3145 * be imprecise. If any child state does require this register to be precise, 3146 * we'll mark it precise later retroactively during precise markings 3147 * propagation from child state to parent states. 3148 * 3149 * Skipping precise marking setting in current state is a mild version of 3150 * relying on the above observation. But we can utilize this property even 3151 * more aggressively by proactively forgetting any precise marking in the 3152 * current state (which we inherited from the parent state), right before we 3153 * checkpoint it and branch off into new child state. This is done by 3154 * mark_all_scalars_imprecise() to hopefully get more permissive and generic 3155 * finalized states which help in short circuiting more future states. 3156 */ 3157 static int __mark_chain_precision(struct bpf_verifier_env *env, int frame, int regno, 3158 int spi) 3159 { 3160 struct bpf_verifier_state *st = env->cur_state; 3161 int first_idx = st->first_insn_idx; 3162 int last_idx = env->insn_idx; 3163 struct bpf_func_state *func; 3164 struct bpf_reg_state *reg; 3165 u32 reg_mask = regno >= 0 ? 1u << regno : 0; 3166 u64 stack_mask = spi >= 0 ? 1ull << spi : 0; 3167 bool skip_first = true; 3168 bool new_marks = false; 3169 int i, err; 3170 3171 if (!env->bpf_capable) 3172 return 0; 3173 3174 /* Do sanity checks against current state of register and/or stack 3175 * slot, but don't set precise flag in current state, as precision 3176 * tracking in the current state is unnecessary. 3177 */ 3178 func = st->frame[frame]; 3179 if (regno >= 0) { 3180 reg = &func->regs[regno]; 3181 if (reg->type != SCALAR_VALUE) { 3182 WARN_ONCE(1, "backtracing misuse"); 3183 return -EFAULT; 3184 } 3185 new_marks = true; 3186 } 3187 3188 while (spi >= 0) { 3189 if (!is_spilled_reg(&func->stack[spi])) { 3190 stack_mask = 0; 3191 break; 3192 } 3193 reg = &func->stack[spi].spilled_ptr; 3194 if (reg->type != SCALAR_VALUE) { 3195 stack_mask = 0; 3196 break; 3197 } 3198 new_marks = true; 3199 break; 3200 } 3201 3202 if (!new_marks) 3203 return 0; 3204 if (!reg_mask && !stack_mask) 3205 return 0; 3206 3207 for (;;) { 3208 DECLARE_BITMAP(mask, 64); 3209 u32 history = st->jmp_history_cnt; 3210 3211 if (env->log.level & BPF_LOG_LEVEL2) 3212 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx); 3213 3214 if (last_idx < 0) { 3215 /* we are at the entry into subprog, which 3216 * is expected for global funcs, but only if 3217 * requested precise registers are R1-R5 3218 * (which are global func's input arguments) 3219 */ 3220 if (st->curframe == 0 && 3221 st->frame[0]->subprogno > 0 && 3222 st->frame[0]->callsite == BPF_MAIN_FUNC && 3223 stack_mask == 0 && (reg_mask & ~0x3e) == 0) { 3224 bitmap_from_u64(mask, reg_mask); 3225 for_each_set_bit(i, mask, 32) { 3226 reg = &st->frame[0]->regs[i]; 3227 if (reg->type != SCALAR_VALUE) { 3228 reg_mask &= ~(1u << i); 3229 continue; 3230 } 3231 reg->precise = true; 3232 } 3233 return 0; 3234 } 3235 3236 verbose(env, "BUG backtracing func entry subprog %d reg_mask %x stack_mask %llx\n", 3237 st->frame[0]->subprogno, reg_mask, stack_mask); 3238 WARN_ONCE(1, "verifier backtracking bug"); 3239 return -EFAULT; 3240 } 3241 3242 for (i = last_idx;;) { 3243 if (skip_first) { 3244 err = 0; 3245 skip_first = false; 3246 } else { 3247 err = backtrack_insn(env, i, ®_mask, &stack_mask); 3248 } 3249 if (err == -ENOTSUPP) { 3250 mark_all_scalars_precise(env, st); 3251 return 0; 3252 } else if (err) { 3253 return err; 3254 } 3255 if (!reg_mask && !stack_mask) 3256 /* Found assignment(s) into tracked register in this state. 3257 * Since this state is already marked, just return. 3258 * Nothing to be tracked further in the parent state. 3259 */ 3260 return 0; 3261 if (i == first_idx) 3262 break; 3263 i = get_prev_insn_idx(st, i, &history); 3264 if (i >= env->prog->len) { 3265 /* This can happen if backtracking reached insn 0 3266 * and there are still reg_mask or stack_mask 3267 * to backtrack. 3268 * It means the backtracking missed the spot where 3269 * particular register was initialized with a constant. 3270 */ 3271 verbose(env, "BUG backtracking idx %d\n", i); 3272 WARN_ONCE(1, "verifier backtracking bug"); 3273 return -EFAULT; 3274 } 3275 } 3276 st = st->parent; 3277 if (!st) 3278 break; 3279 3280 new_marks = false; 3281 func = st->frame[frame]; 3282 bitmap_from_u64(mask, reg_mask); 3283 for_each_set_bit(i, mask, 32) { 3284 reg = &func->regs[i]; 3285 if (reg->type != SCALAR_VALUE) { 3286 reg_mask &= ~(1u << i); 3287 continue; 3288 } 3289 if (!reg->precise) 3290 new_marks = true; 3291 reg->precise = true; 3292 } 3293 3294 bitmap_from_u64(mask, stack_mask); 3295 for_each_set_bit(i, mask, 64) { 3296 if (i >= func->allocated_stack / BPF_REG_SIZE) { 3297 /* the sequence of instructions: 3298 * 2: (bf) r3 = r10 3299 * 3: (7b) *(u64 *)(r3 -8) = r0 3300 * 4: (79) r4 = *(u64 *)(r10 -8) 3301 * doesn't contain jmps. It's backtracked 3302 * as a single block. 3303 * During backtracking insn 3 is not recognized as 3304 * stack access, so at the end of backtracking 3305 * stack slot fp-8 is still marked in stack_mask. 3306 * However the parent state may not have accessed 3307 * fp-8 and it's "unallocated" stack space. 3308 * In such case fallback to conservative. 3309 */ 3310 mark_all_scalars_precise(env, st); 3311 return 0; 3312 } 3313 3314 if (!is_spilled_reg(&func->stack[i])) { 3315 stack_mask &= ~(1ull << i); 3316 continue; 3317 } 3318 reg = &func->stack[i].spilled_ptr; 3319 if (reg->type != SCALAR_VALUE) { 3320 stack_mask &= ~(1ull << i); 3321 continue; 3322 } 3323 if (!reg->precise) 3324 new_marks = true; 3325 reg->precise = true; 3326 } 3327 if (env->log.level & BPF_LOG_LEVEL2) { 3328 verbose(env, "parent %s regs=%x stack=%llx marks:", 3329 new_marks ? "didn't have" : "already had", 3330 reg_mask, stack_mask); 3331 print_verifier_state(env, func, true); 3332 } 3333 3334 if (!reg_mask && !stack_mask) 3335 break; 3336 if (!new_marks) 3337 break; 3338 3339 last_idx = st->last_insn_idx; 3340 first_idx = st->first_insn_idx; 3341 } 3342 return 0; 3343 } 3344 3345 int mark_chain_precision(struct bpf_verifier_env *env, int regno) 3346 { 3347 return __mark_chain_precision(env, env->cur_state->curframe, regno, -1); 3348 } 3349 3350 static int mark_chain_precision_frame(struct bpf_verifier_env *env, int frame, int regno) 3351 { 3352 return __mark_chain_precision(env, frame, regno, -1); 3353 } 3354 3355 static int mark_chain_precision_stack_frame(struct bpf_verifier_env *env, int frame, int spi) 3356 { 3357 return __mark_chain_precision(env, frame, -1, spi); 3358 } 3359 3360 static bool is_spillable_regtype(enum bpf_reg_type type) 3361 { 3362 switch (base_type(type)) { 3363 case PTR_TO_MAP_VALUE: 3364 case PTR_TO_STACK: 3365 case PTR_TO_CTX: 3366 case PTR_TO_PACKET: 3367 case PTR_TO_PACKET_META: 3368 case PTR_TO_PACKET_END: 3369 case PTR_TO_FLOW_KEYS: 3370 case CONST_PTR_TO_MAP: 3371 case PTR_TO_SOCKET: 3372 case PTR_TO_SOCK_COMMON: 3373 case PTR_TO_TCP_SOCK: 3374 case PTR_TO_XDP_SOCK: 3375 case PTR_TO_BTF_ID: 3376 case PTR_TO_BUF: 3377 case PTR_TO_MEM: 3378 case PTR_TO_FUNC: 3379 case PTR_TO_MAP_KEY: 3380 return true; 3381 default: 3382 return false; 3383 } 3384 } 3385 3386 /* Does this register contain a constant zero? */ 3387 static bool register_is_null(struct bpf_reg_state *reg) 3388 { 3389 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 3390 } 3391 3392 static bool register_is_const(struct bpf_reg_state *reg) 3393 { 3394 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 3395 } 3396 3397 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 3398 { 3399 return tnum_is_unknown(reg->var_off) && 3400 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 3401 reg->umin_value == 0 && reg->umax_value == U64_MAX && 3402 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 3403 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 3404 } 3405 3406 static bool register_is_bounded(struct bpf_reg_state *reg) 3407 { 3408 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 3409 } 3410 3411 static bool __is_pointer_value(bool allow_ptr_leaks, 3412 const struct bpf_reg_state *reg) 3413 { 3414 if (allow_ptr_leaks) 3415 return false; 3416 3417 return reg->type != SCALAR_VALUE; 3418 } 3419 3420 static void save_register_state(struct bpf_func_state *state, 3421 int spi, struct bpf_reg_state *reg, 3422 int size) 3423 { 3424 int i; 3425 3426 state->stack[spi].spilled_ptr = *reg; 3427 if (size == BPF_REG_SIZE) 3428 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 3429 3430 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 3431 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 3432 3433 /* size < 8 bytes spill */ 3434 for (; i; i--) 3435 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 3436 } 3437 3438 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 3439 * stack boundary and alignment are checked in check_mem_access() 3440 */ 3441 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 3442 /* stack frame we're writing to */ 3443 struct bpf_func_state *state, 3444 int off, int size, int value_regno, 3445 int insn_idx) 3446 { 3447 struct bpf_func_state *cur; /* state of the current function */ 3448 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 3449 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg; 3450 struct bpf_reg_state *reg = NULL; 3451 3452 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 3453 if (err) 3454 return err; 3455 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 3456 * so it's aligned access and [off, off + size) are within stack limits 3457 */ 3458 if (!env->allow_ptr_leaks && 3459 state->stack[spi].slot_type[0] == STACK_SPILL && 3460 size != BPF_REG_SIZE) { 3461 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 3462 return -EACCES; 3463 } 3464 3465 cur = env->cur_state->frame[env->cur_state->curframe]; 3466 if (value_regno >= 0) 3467 reg = &cur->regs[value_regno]; 3468 if (!env->bypass_spec_v4) { 3469 bool sanitize = reg && is_spillable_regtype(reg->type); 3470 3471 for (i = 0; i < size; i++) { 3472 if (state->stack[spi].slot_type[i] == STACK_INVALID) { 3473 sanitize = true; 3474 break; 3475 } 3476 } 3477 3478 if (sanitize) 3479 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 3480 } 3481 3482 err = destroy_if_dynptr_stack_slot(env, state, spi); 3483 if (err) 3484 return err; 3485 3486 mark_stack_slot_scratched(env, spi); 3487 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 3488 !register_is_null(reg) && env->bpf_capable) { 3489 if (dst_reg != BPF_REG_FP) { 3490 /* The backtracking logic can only recognize explicit 3491 * stack slot address like [fp - 8]. Other spill of 3492 * scalar via different register has to be conservative. 3493 * Backtrack from here and mark all registers as precise 3494 * that contributed into 'reg' being a constant. 3495 */ 3496 err = mark_chain_precision(env, value_regno); 3497 if (err) 3498 return err; 3499 } 3500 save_register_state(state, spi, reg, size); 3501 } else if (reg && is_spillable_regtype(reg->type)) { 3502 /* register containing pointer is being spilled into stack */ 3503 if (size != BPF_REG_SIZE) { 3504 verbose_linfo(env, insn_idx, "; "); 3505 verbose(env, "invalid size of register spill\n"); 3506 return -EACCES; 3507 } 3508 if (state != cur && reg->type == PTR_TO_STACK) { 3509 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 3510 return -EINVAL; 3511 } 3512 save_register_state(state, spi, reg, size); 3513 } else { 3514 u8 type = STACK_MISC; 3515 3516 /* regular write of data into stack destroys any spilled ptr */ 3517 state->stack[spi].spilled_ptr.type = NOT_INIT; 3518 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */ 3519 if (is_spilled_reg(&state->stack[spi])) 3520 for (i = 0; i < BPF_REG_SIZE; i++) 3521 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 3522 3523 /* only mark the slot as written if all 8 bytes were written 3524 * otherwise read propagation may incorrectly stop too soon 3525 * when stack slots are partially written. 3526 * This heuristic means that read propagation will be 3527 * conservative, since it will add reg_live_read marks 3528 * to stack slots all the way to first state when programs 3529 * writes+reads less than 8 bytes 3530 */ 3531 if (size == BPF_REG_SIZE) 3532 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 3533 3534 /* when we zero initialize stack slots mark them as such */ 3535 if (reg && register_is_null(reg)) { 3536 /* backtracking doesn't work for STACK_ZERO yet. */ 3537 err = mark_chain_precision(env, value_regno); 3538 if (err) 3539 return err; 3540 type = STACK_ZERO; 3541 } 3542 3543 /* Mark slots affected by this stack write. */ 3544 for (i = 0; i < size; i++) 3545 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 3546 type; 3547 } 3548 return 0; 3549 } 3550 3551 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 3552 * known to contain a variable offset. 3553 * This function checks whether the write is permitted and conservatively 3554 * tracks the effects of the write, considering that each stack slot in the 3555 * dynamic range is potentially written to. 3556 * 3557 * 'off' includes 'regno->off'. 3558 * 'value_regno' can be -1, meaning that an unknown value is being written to 3559 * the stack. 3560 * 3561 * Spilled pointers in range are not marked as written because we don't know 3562 * what's going to be actually written. This means that read propagation for 3563 * future reads cannot be terminated by this write. 3564 * 3565 * For privileged programs, uninitialized stack slots are considered 3566 * initialized by this write (even though we don't know exactly what offsets 3567 * are going to be written to). The idea is that we don't want the verifier to 3568 * reject future reads that access slots written to through variable offsets. 3569 */ 3570 static int check_stack_write_var_off(struct bpf_verifier_env *env, 3571 /* func where register points to */ 3572 struct bpf_func_state *state, 3573 int ptr_regno, int off, int size, 3574 int value_regno, int insn_idx) 3575 { 3576 struct bpf_func_state *cur; /* state of the current function */ 3577 int min_off, max_off; 3578 int i, err; 3579 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 3580 bool writing_zero = false; 3581 /* set if the fact that we're writing a zero is used to let any 3582 * stack slots remain STACK_ZERO 3583 */ 3584 bool zero_used = false; 3585 3586 cur = env->cur_state->frame[env->cur_state->curframe]; 3587 ptr_reg = &cur->regs[ptr_regno]; 3588 min_off = ptr_reg->smin_value + off; 3589 max_off = ptr_reg->smax_value + off + size; 3590 if (value_regno >= 0) 3591 value_reg = &cur->regs[value_regno]; 3592 if (value_reg && register_is_null(value_reg)) 3593 writing_zero = true; 3594 3595 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 3596 if (err) 3597 return err; 3598 3599 for (i = min_off; i < max_off; i++) { 3600 int spi; 3601 3602 spi = __get_spi(i); 3603 err = destroy_if_dynptr_stack_slot(env, state, spi); 3604 if (err) 3605 return err; 3606 } 3607 3608 /* Variable offset writes destroy any spilled pointers in range. */ 3609 for (i = min_off; i < max_off; i++) { 3610 u8 new_type, *stype; 3611 int slot, spi; 3612 3613 slot = -i - 1; 3614 spi = slot / BPF_REG_SIZE; 3615 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3616 mark_stack_slot_scratched(env, spi); 3617 3618 if (!env->allow_ptr_leaks && *stype != STACK_MISC && *stype != STACK_ZERO) { 3619 /* Reject the write if range we may write to has not 3620 * been initialized beforehand. If we didn't reject 3621 * here, the ptr status would be erased below (even 3622 * though not all slots are actually overwritten), 3623 * possibly opening the door to leaks. 3624 * 3625 * We do however catch STACK_INVALID case below, and 3626 * only allow reading possibly uninitialized memory 3627 * later for CAP_PERFMON, as the write may not happen to 3628 * that slot. 3629 */ 3630 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3631 insn_idx, i); 3632 return -EINVAL; 3633 } 3634 3635 /* Erase all spilled pointers. */ 3636 state->stack[spi].spilled_ptr.type = NOT_INIT; 3637 3638 /* Update the slot type. */ 3639 new_type = STACK_MISC; 3640 if (writing_zero && *stype == STACK_ZERO) { 3641 new_type = STACK_ZERO; 3642 zero_used = true; 3643 } 3644 /* If the slot is STACK_INVALID, we check whether it's OK to 3645 * pretend that it will be initialized by this write. The slot 3646 * might not actually be written to, and so if we mark it as 3647 * initialized future reads might leak uninitialized memory. 3648 * For privileged programs, we will accept such reads to slots 3649 * that may or may not be written because, if we're reject 3650 * them, the error would be too confusing. 3651 */ 3652 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 3653 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3654 insn_idx, i); 3655 return -EINVAL; 3656 } 3657 *stype = new_type; 3658 } 3659 if (zero_used) { 3660 /* backtracking doesn't work for STACK_ZERO yet. */ 3661 err = mark_chain_precision(env, value_regno); 3662 if (err) 3663 return err; 3664 } 3665 return 0; 3666 } 3667 3668 /* When register 'dst_regno' is assigned some values from stack[min_off, 3669 * max_off), we set the register's type according to the types of the 3670 * respective stack slots. If all the stack values are known to be zeros, then 3671 * so is the destination reg. Otherwise, the register is considered to be 3672 * SCALAR. This function does not deal with register filling; the caller must 3673 * ensure that all spilled registers in the stack range have been marked as 3674 * read. 3675 */ 3676 static void mark_reg_stack_read(struct bpf_verifier_env *env, 3677 /* func where src register points to */ 3678 struct bpf_func_state *ptr_state, 3679 int min_off, int max_off, int dst_regno) 3680 { 3681 struct bpf_verifier_state *vstate = env->cur_state; 3682 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3683 int i, slot, spi; 3684 u8 *stype; 3685 int zeros = 0; 3686 3687 for (i = min_off; i < max_off; i++) { 3688 slot = -i - 1; 3689 spi = slot / BPF_REG_SIZE; 3690 stype = ptr_state->stack[spi].slot_type; 3691 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 3692 break; 3693 zeros++; 3694 } 3695 if (zeros == max_off - min_off) { 3696 /* any access_size read into register is zero extended, 3697 * so the whole register == const_zero 3698 */ 3699 __mark_reg_const_zero(&state->regs[dst_regno]); 3700 /* backtracking doesn't support STACK_ZERO yet, 3701 * so mark it precise here, so that later 3702 * backtracking can stop here. 3703 * Backtracking may not need this if this register 3704 * doesn't participate in pointer adjustment. 3705 * Forward propagation of precise flag is not 3706 * necessary either. This mark is only to stop 3707 * backtracking. Any register that contributed 3708 * to const 0 was marked precise before spill. 3709 */ 3710 state->regs[dst_regno].precise = true; 3711 } else { 3712 /* have read misc data from the stack */ 3713 mark_reg_unknown(env, state->regs, dst_regno); 3714 } 3715 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3716 } 3717 3718 /* Read the stack at 'off' and put the results into the register indicated by 3719 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3720 * spilled reg. 3721 * 3722 * 'dst_regno' can be -1, meaning that the read value is not going to a 3723 * register. 3724 * 3725 * The access is assumed to be within the current stack bounds. 3726 */ 3727 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3728 /* func where src register points to */ 3729 struct bpf_func_state *reg_state, 3730 int off, int size, int dst_regno) 3731 { 3732 struct bpf_verifier_state *vstate = env->cur_state; 3733 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3734 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3735 struct bpf_reg_state *reg; 3736 u8 *stype, type; 3737 3738 stype = reg_state->stack[spi].slot_type; 3739 reg = ®_state->stack[spi].spilled_ptr; 3740 3741 if (is_spilled_reg(®_state->stack[spi])) { 3742 u8 spill_size = 1; 3743 3744 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3745 spill_size++; 3746 3747 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3748 if (reg->type != SCALAR_VALUE) { 3749 verbose_linfo(env, env->insn_idx, "; "); 3750 verbose(env, "invalid size of register fill\n"); 3751 return -EACCES; 3752 } 3753 3754 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3755 if (dst_regno < 0) 3756 return 0; 3757 3758 if (!(off % BPF_REG_SIZE) && size == spill_size) { 3759 /* The earlier check_reg_arg() has decided the 3760 * subreg_def for this insn. Save it first. 3761 */ 3762 s32 subreg_def = state->regs[dst_regno].subreg_def; 3763 3764 state->regs[dst_regno] = *reg; 3765 state->regs[dst_regno].subreg_def = subreg_def; 3766 } else { 3767 for (i = 0; i < size; i++) { 3768 type = stype[(slot - i) % BPF_REG_SIZE]; 3769 if (type == STACK_SPILL) 3770 continue; 3771 if (type == STACK_MISC) 3772 continue; 3773 verbose(env, "invalid read from stack off %d+%d size %d\n", 3774 off, i, size); 3775 return -EACCES; 3776 } 3777 mark_reg_unknown(env, state->regs, dst_regno); 3778 } 3779 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3780 return 0; 3781 } 3782 3783 if (dst_regno >= 0) { 3784 /* restore register state from stack */ 3785 state->regs[dst_regno] = *reg; 3786 /* mark reg as written since spilled pointer state likely 3787 * has its liveness marks cleared by is_state_visited() 3788 * which resets stack/reg liveness for state transitions 3789 */ 3790 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3791 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3792 /* If dst_regno==-1, the caller is asking us whether 3793 * it is acceptable to use this value as a SCALAR_VALUE 3794 * (e.g. for XADD). 3795 * We must not allow unprivileged callers to do that 3796 * with spilled pointers. 3797 */ 3798 verbose(env, "leaking pointer from stack off %d\n", 3799 off); 3800 return -EACCES; 3801 } 3802 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3803 } else { 3804 for (i = 0; i < size; i++) { 3805 type = stype[(slot - i) % BPF_REG_SIZE]; 3806 if (type == STACK_MISC) 3807 continue; 3808 if (type == STACK_ZERO) 3809 continue; 3810 verbose(env, "invalid read from stack off %d+%d size %d\n", 3811 off, i, size); 3812 return -EACCES; 3813 } 3814 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3815 if (dst_regno >= 0) 3816 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3817 } 3818 return 0; 3819 } 3820 3821 enum bpf_access_src { 3822 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3823 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3824 }; 3825 3826 static int check_stack_range_initialized(struct bpf_verifier_env *env, 3827 int regno, int off, int access_size, 3828 bool zero_size_allowed, 3829 enum bpf_access_src type, 3830 struct bpf_call_arg_meta *meta); 3831 3832 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3833 { 3834 return cur_regs(env) + regno; 3835 } 3836 3837 /* Read the stack at 'ptr_regno + off' and put the result into the register 3838 * 'dst_regno'. 3839 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 3840 * but not its variable offset. 3841 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3842 * 3843 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3844 * filling registers (i.e. reads of spilled register cannot be detected when 3845 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3846 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 3847 * offset; for a fixed offset check_stack_read_fixed_off should be used 3848 * instead. 3849 */ 3850 static int check_stack_read_var_off(struct bpf_verifier_env *env, 3851 int ptr_regno, int off, int size, int dst_regno) 3852 { 3853 /* The state of the source register. */ 3854 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3855 struct bpf_func_state *ptr_state = func(env, reg); 3856 int err; 3857 int min_off, max_off; 3858 3859 /* Note that we pass a NULL meta, so raw access will not be permitted. 3860 */ 3861 err = check_stack_range_initialized(env, ptr_regno, off, size, 3862 false, ACCESS_DIRECT, NULL); 3863 if (err) 3864 return err; 3865 3866 min_off = reg->smin_value + off; 3867 max_off = reg->smax_value + off; 3868 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 3869 return 0; 3870 } 3871 3872 /* check_stack_read dispatches to check_stack_read_fixed_off or 3873 * check_stack_read_var_off. 3874 * 3875 * The caller must ensure that the offset falls within the allocated stack 3876 * bounds. 3877 * 3878 * 'dst_regno' is a register which will receive the value from the stack. It 3879 * can be -1, meaning that the read value is not going to a register. 3880 */ 3881 static int check_stack_read(struct bpf_verifier_env *env, 3882 int ptr_regno, int off, int size, 3883 int dst_regno) 3884 { 3885 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3886 struct bpf_func_state *state = func(env, reg); 3887 int err; 3888 /* Some accesses are only permitted with a static offset. */ 3889 bool var_off = !tnum_is_const(reg->var_off); 3890 3891 /* The offset is required to be static when reads don't go to a 3892 * register, in order to not leak pointers (see 3893 * check_stack_read_fixed_off). 3894 */ 3895 if (dst_regno < 0 && var_off) { 3896 char tn_buf[48]; 3897 3898 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3899 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 3900 tn_buf, off, size); 3901 return -EACCES; 3902 } 3903 /* Variable offset is prohibited for unprivileged mode for simplicity 3904 * since it requires corresponding support in Spectre masking for stack 3905 * ALU. See also retrieve_ptr_limit(). 3906 */ 3907 if (!env->bypass_spec_v1 && var_off) { 3908 char tn_buf[48]; 3909 3910 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3911 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 3912 ptr_regno, tn_buf); 3913 return -EACCES; 3914 } 3915 3916 if (!var_off) { 3917 off += reg->var_off.value; 3918 err = check_stack_read_fixed_off(env, state, off, size, 3919 dst_regno); 3920 } else { 3921 /* Variable offset stack reads need more conservative handling 3922 * than fixed offset ones. Note that dst_regno >= 0 on this 3923 * branch. 3924 */ 3925 err = check_stack_read_var_off(env, ptr_regno, off, size, 3926 dst_regno); 3927 } 3928 return err; 3929 } 3930 3931 3932 /* check_stack_write dispatches to check_stack_write_fixed_off or 3933 * check_stack_write_var_off. 3934 * 3935 * 'ptr_regno' is the register used as a pointer into the stack. 3936 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 3937 * 'value_regno' is the register whose value we're writing to the stack. It can 3938 * be -1, meaning that we're not writing from a register. 3939 * 3940 * The caller must ensure that the offset falls within the maximum stack size. 3941 */ 3942 static int check_stack_write(struct bpf_verifier_env *env, 3943 int ptr_regno, int off, int size, 3944 int value_regno, int insn_idx) 3945 { 3946 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3947 struct bpf_func_state *state = func(env, reg); 3948 int err; 3949 3950 if (tnum_is_const(reg->var_off)) { 3951 off += reg->var_off.value; 3952 err = check_stack_write_fixed_off(env, state, off, size, 3953 value_regno, insn_idx); 3954 } else { 3955 /* Variable offset stack reads need more conservative handling 3956 * than fixed offset ones. 3957 */ 3958 err = check_stack_write_var_off(env, state, 3959 ptr_regno, off, size, 3960 value_regno, insn_idx); 3961 } 3962 return err; 3963 } 3964 3965 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 3966 int off, int size, enum bpf_access_type type) 3967 { 3968 struct bpf_reg_state *regs = cur_regs(env); 3969 struct bpf_map *map = regs[regno].map_ptr; 3970 u32 cap = bpf_map_flags_to_cap(map); 3971 3972 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 3973 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 3974 map->value_size, off, size); 3975 return -EACCES; 3976 } 3977 3978 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 3979 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 3980 map->value_size, off, size); 3981 return -EACCES; 3982 } 3983 3984 return 0; 3985 } 3986 3987 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 3988 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 3989 int off, int size, u32 mem_size, 3990 bool zero_size_allowed) 3991 { 3992 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 3993 struct bpf_reg_state *reg; 3994 3995 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 3996 return 0; 3997 3998 reg = &cur_regs(env)[regno]; 3999 switch (reg->type) { 4000 case PTR_TO_MAP_KEY: 4001 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 4002 mem_size, off, size); 4003 break; 4004 case PTR_TO_MAP_VALUE: 4005 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 4006 mem_size, off, size); 4007 break; 4008 case PTR_TO_PACKET: 4009 case PTR_TO_PACKET_META: 4010 case PTR_TO_PACKET_END: 4011 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 4012 off, size, regno, reg->id, off, mem_size); 4013 break; 4014 case PTR_TO_MEM: 4015 default: 4016 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 4017 mem_size, off, size); 4018 } 4019 4020 return -EACCES; 4021 } 4022 4023 /* check read/write into a memory region with possible variable offset */ 4024 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 4025 int off, int size, u32 mem_size, 4026 bool zero_size_allowed) 4027 { 4028 struct bpf_verifier_state *vstate = env->cur_state; 4029 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4030 struct bpf_reg_state *reg = &state->regs[regno]; 4031 int err; 4032 4033 /* We may have adjusted the register pointing to memory region, so we 4034 * need to try adding each of min_value and max_value to off 4035 * to make sure our theoretical access will be safe. 4036 * 4037 * The minimum value is only important with signed 4038 * comparisons where we can't assume the floor of a 4039 * value is 0. If we are using signed variables for our 4040 * index'es we need to make sure that whatever we use 4041 * will have a set floor within our range. 4042 */ 4043 if (reg->smin_value < 0 && 4044 (reg->smin_value == S64_MIN || 4045 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 4046 reg->smin_value + off < 0)) { 4047 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4048 regno); 4049 return -EACCES; 4050 } 4051 err = __check_mem_access(env, regno, reg->smin_value + off, size, 4052 mem_size, zero_size_allowed); 4053 if (err) { 4054 verbose(env, "R%d min value is outside of the allowed memory range\n", 4055 regno); 4056 return err; 4057 } 4058 4059 /* If we haven't set a max value then we need to bail since we can't be 4060 * sure we won't do bad things. 4061 * If reg->umax_value + off could overflow, treat that as unbounded too. 4062 */ 4063 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 4064 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 4065 regno); 4066 return -EACCES; 4067 } 4068 err = __check_mem_access(env, regno, reg->umax_value + off, size, 4069 mem_size, zero_size_allowed); 4070 if (err) { 4071 verbose(env, "R%d max value is outside of the allowed memory range\n", 4072 regno); 4073 return err; 4074 } 4075 4076 return 0; 4077 } 4078 4079 static int __check_ptr_off_reg(struct bpf_verifier_env *env, 4080 const struct bpf_reg_state *reg, int regno, 4081 bool fixed_off_ok) 4082 { 4083 /* Access to this pointer-typed register or passing it to a helper 4084 * is only allowed in its original, unmodified form. 4085 */ 4086 4087 if (reg->off < 0) { 4088 verbose(env, "negative offset %s ptr R%d off=%d disallowed\n", 4089 reg_type_str(env, reg->type), regno, reg->off); 4090 return -EACCES; 4091 } 4092 4093 if (!fixed_off_ok && reg->off) { 4094 verbose(env, "dereference of modified %s ptr R%d off=%d disallowed\n", 4095 reg_type_str(env, reg->type), regno, reg->off); 4096 return -EACCES; 4097 } 4098 4099 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4100 char tn_buf[48]; 4101 4102 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4103 verbose(env, "variable %s access var_off=%s disallowed\n", 4104 reg_type_str(env, reg->type), tn_buf); 4105 return -EACCES; 4106 } 4107 4108 return 0; 4109 } 4110 4111 int check_ptr_off_reg(struct bpf_verifier_env *env, 4112 const struct bpf_reg_state *reg, int regno) 4113 { 4114 return __check_ptr_off_reg(env, reg, regno, false); 4115 } 4116 4117 static int map_kptr_match_type(struct bpf_verifier_env *env, 4118 struct btf_field *kptr_field, 4119 struct bpf_reg_state *reg, u32 regno) 4120 { 4121 const char *targ_name = kernel_type_name(kptr_field->kptr.btf, kptr_field->kptr.btf_id); 4122 int perm_flags = PTR_MAYBE_NULL | PTR_TRUSTED; 4123 const char *reg_name = ""; 4124 4125 /* Only unreferenced case accepts untrusted pointers */ 4126 if (kptr_field->type == BPF_KPTR_UNREF) 4127 perm_flags |= PTR_UNTRUSTED; 4128 4129 if (base_type(reg->type) != PTR_TO_BTF_ID || (type_flag(reg->type) & ~perm_flags)) 4130 goto bad_type; 4131 4132 if (!btf_is_kernel(reg->btf)) { 4133 verbose(env, "R%d must point to kernel BTF\n", regno); 4134 return -EINVAL; 4135 } 4136 /* We need to verify reg->type and reg->btf, before accessing reg->btf */ 4137 reg_name = kernel_type_name(reg->btf, reg->btf_id); 4138 4139 /* For ref_ptr case, release function check should ensure we get one 4140 * referenced PTR_TO_BTF_ID, and that its fixed offset is 0. For the 4141 * normal store of unreferenced kptr, we must ensure var_off is zero. 4142 * Since ref_ptr cannot be accessed directly by BPF insns, checks for 4143 * reg->off and reg->ref_obj_id are not needed here. 4144 */ 4145 if (__check_ptr_off_reg(env, reg, regno, true)) 4146 return -EACCES; 4147 4148 /* A full type match is needed, as BTF can be vmlinux or module BTF, and 4149 * we also need to take into account the reg->off. 4150 * 4151 * We want to support cases like: 4152 * 4153 * struct foo { 4154 * struct bar br; 4155 * struct baz bz; 4156 * }; 4157 * 4158 * struct foo *v; 4159 * v = func(); // PTR_TO_BTF_ID 4160 * val->foo = v; // reg->off is zero, btf and btf_id match type 4161 * val->bar = &v->br; // reg->off is still zero, but we need to retry with 4162 * // first member type of struct after comparison fails 4163 * val->baz = &v->bz; // reg->off is non-zero, so struct needs to be walked 4164 * // to match type 4165 * 4166 * In the kptr_ref case, check_func_arg_reg_off already ensures reg->off 4167 * is zero. We must also ensure that btf_struct_ids_match does not walk 4168 * the struct to match type against first member of struct, i.e. reject 4169 * second case from above. Hence, when type is BPF_KPTR_REF, we set 4170 * strict mode to true for type match. 4171 */ 4172 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 4173 kptr_field->kptr.btf, kptr_field->kptr.btf_id, 4174 kptr_field->type == BPF_KPTR_REF)) 4175 goto bad_type; 4176 return 0; 4177 bad_type: 4178 verbose(env, "invalid kptr access, R%d type=%s%s ", regno, 4179 reg_type_str(env, reg->type), reg_name); 4180 verbose(env, "expected=%s%s", reg_type_str(env, PTR_TO_BTF_ID), targ_name); 4181 if (kptr_field->type == BPF_KPTR_UNREF) 4182 verbose(env, " or %s%s\n", reg_type_str(env, PTR_TO_BTF_ID | PTR_UNTRUSTED), 4183 targ_name); 4184 else 4185 verbose(env, "\n"); 4186 return -EINVAL; 4187 } 4188 4189 static int check_map_kptr_access(struct bpf_verifier_env *env, u32 regno, 4190 int value_regno, int insn_idx, 4191 struct btf_field *kptr_field) 4192 { 4193 struct bpf_insn *insn = &env->prog->insnsi[insn_idx]; 4194 int class = BPF_CLASS(insn->code); 4195 struct bpf_reg_state *val_reg; 4196 4197 /* Things we already checked for in check_map_access and caller: 4198 * - Reject cases where variable offset may touch kptr 4199 * - size of access (must be BPF_DW) 4200 * - tnum_is_const(reg->var_off) 4201 * - kptr_field->offset == off + reg->var_off.value 4202 */ 4203 /* Only BPF_[LDX,STX,ST] | BPF_MEM | BPF_DW is supported */ 4204 if (BPF_MODE(insn->code) != BPF_MEM) { 4205 verbose(env, "kptr in map can only be accessed using BPF_MEM instruction mode\n"); 4206 return -EACCES; 4207 } 4208 4209 /* We only allow loading referenced kptr, since it will be marked as 4210 * untrusted, similar to unreferenced kptr. 4211 */ 4212 if (class != BPF_LDX && kptr_field->type == BPF_KPTR_REF) { 4213 verbose(env, "store to referenced kptr disallowed\n"); 4214 return -EACCES; 4215 } 4216 4217 if (class == BPF_LDX) { 4218 val_reg = reg_state(env, value_regno); 4219 /* We can simply mark the value_regno receiving the pointer 4220 * value from map as PTR_TO_BTF_ID, with the correct type. 4221 */ 4222 mark_btf_ld_reg(env, cur_regs(env), value_regno, PTR_TO_BTF_ID, kptr_field->kptr.btf, 4223 kptr_field->kptr.btf_id, PTR_MAYBE_NULL | PTR_UNTRUSTED); 4224 /* For mark_ptr_or_null_reg */ 4225 val_reg->id = ++env->id_gen; 4226 } else if (class == BPF_STX) { 4227 val_reg = reg_state(env, value_regno); 4228 if (!register_is_null(val_reg) && 4229 map_kptr_match_type(env, kptr_field, val_reg, value_regno)) 4230 return -EACCES; 4231 } else if (class == BPF_ST) { 4232 if (insn->imm) { 4233 verbose(env, "BPF_ST imm must be 0 when storing to kptr at off=%u\n", 4234 kptr_field->offset); 4235 return -EACCES; 4236 } 4237 } else { 4238 verbose(env, "kptr in map can only be accessed using BPF_LDX/BPF_STX/BPF_ST\n"); 4239 return -EACCES; 4240 } 4241 return 0; 4242 } 4243 4244 /* check read/write into a map element with possible variable offset */ 4245 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 4246 int off, int size, bool zero_size_allowed, 4247 enum bpf_access_src src) 4248 { 4249 struct bpf_verifier_state *vstate = env->cur_state; 4250 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4251 struct bpf_reg_state *reg = &state->regs[regno]; 4252 struct bpf_map *map = reg->map_ptr; 4253 struct btf_record *rec; 4254 int err, i; 4255 4256 err = check_mem_region_access(env, regno, off, size, map->value_size, 4257 zero_size_allowed); 4258 if (err) 4259 return err; 4260 4261 if (IS_ERR_OR_NULL(map->record)) 4262 return 0; 4263 rec = map->record; 4264 for (i = 0; i < rec->cnt; i++) { 4265 struct btf_field *field = &rec->fields[i]; 4266 u32 p = field->offset; 4267 4268 /* If any part of a field can be touched by load/store, reject 4269 * this program. To check that [x1, x2) overlaps with [y1, y2), 4270 * it is sufficient to check x1 < y2 && y1 < x2. 4271 */ 4272 if (reg->smin_value + off < p + btf_field_type_size(field->type) && 4273 p < reg->umax_value + off + size) { 4274 switch (field->type) { 4275 case BPF_KPTR_UNREF: 4276 case BPF_KPTR_REF: 4277 if (src != ACCESS_DIRECT) { 4278 verbose(env, "kptr cannot be accessed indirectly by helper\n"); 4279 return -EACCES; 4280 } 4281 if (!tnum_is_const(reg->var_off)) { 4282 verbose(env, "kptr access cannot have variable offset\n"); 4283 return -EACCES; 4284 } 4285 if (p != off + reg->var_off.value) { 4286 verbose(env, "kptr access misaligned expected=%u off=%llu\n", 4287 p, off + reg->var_off.value); 4288 return -EACCES; 4289 } 4290 if (size != bpf_size_to_bytes(BPF_DW)) { 4291 verbose(env, "kptr access size must be BPF_DW\n"); 4292 return -EACCES; 4293 } 4294 break; 4295 default: 4296 verbose(env, "%s cannot be accessed directly by load/store\n", 4297 btf_field_type_name(field->type)); 4298 return -EACCES; 4299 } 4300 } 4301 } 4302 return 0; 4303 } 4304 4305 #define MAX_PACKET_OFF 0xffff 4306 4307 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 4308 const struct bpf_call_arg_meta *meta, 4309 enum bpf_access_type t) 4310 { 4311 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 4312 4313 switch (prog_type) { 4314 /* Program types only with direct read access go here! */ 4315 case BPF_PROG_TYPE_LWT_IN: 4316 case BPF_PROG_TYPE_LWT_OUT: 4317 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 4318 case BPF_PROG_TYPE_SK_REUSEPORT: 4319 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4320 case BPF_PROG_TYPE_CGROUP_SKB: 4321 if (t == BPF_WRITE) 4322 return false; 4323 fallthrough; 4324 4325 /* Program types with direct read + write access go here! */ 4326 case BPF_PROG_TYPE_SCHED_CLS: 4327 case BPF_PROG_TYPE_SCHED_ACT: 4328 case BPF_PROG_TYPE_XDP: 4329 case BPF_PROG_TYPE_LWT_XMIT: 4330 case BPF_PROG_TYPE_SK_SKB: 4331 case BPF_PROG_TYPE_SK_MSG: 4332 if (meta) 4333 return meta->pkt_access; 4334 4335 env->seen_direct_write = true; 4336 return true; 4337 4338 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 4339 if (t == BPF_WRITE) 4340 env->seen_direct_write = true; 4341 4342 return true; 4343 4344 default: 4345 return false; 4346 } 4347 } 4348 4349 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 4350 int size, bool zero_size_allowed) 4351 { 4352 struct bpf_reg_state *regs = cur_regs(env); 4353 struct bpf_reg_state *reg = ®s[regno]; 4354 int err; 4355 4356 /* We may have added a variable offset to the packet pointer; but any 4357 * reg->range we have comes after that. We are only checking the fixed 4358 * offset. 4359 */ 4360 4361 /* We don't allow negative numbers, because we aren't tracking enough 4362 * detail to prove they're safe. 4363 */ 4364 if (reg->smin_value < 0) { 4365 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4366 regno); 4367 return -EACCES; 4368 } 4369 4370 err = reg->range < 0 ? -EINVAL : 4371 __check_mem_access(env, regno, off, size, reg->range, 4372 zero_size_allowed); 4373 if (err) { 4374 verbose(env, "R%d offset is outside of the packet\n", regno); 4375 return err; 4376 } 4377 4378 /* __check_mem_access has made sure "off + size - 1" is within u16. 4379 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 4380 * otherwise find_good_pkt_pointers would have refused to set range info 4381 * that __check_mem_access would have rejected this pkt access. 4382 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 4383 */ 4384 env->prog->aux->max_pkt_offset = 4385 max_t(u32, env->prog->aux->max_pkt_offset, 4386 off + reg->umax_value + size - 1); 4387 4388 return err; 4389 } 4390 4391 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 4392 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 4393 enum bpf_access_type t, enum bpf_reg_type *reg_type, 4394 struct btf **btf, u32 *btf_id) 4395 { 4396 struct bpf_insn_access_aux info = { 4397 .reg_type = *reg_type, 4398 .log = &env->log, 4399 }; 4400 4401 if (env->ops->is_valid_access && 4402 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 4403 /* A non zero info.ctx_field_size indicates that this field is a 4404 * candidate for later verifier transformation to load the whole 4405 * field and then apply a mask when accessed with a narrower 4406 * access than actual ctx access size. A zero info.ctx_field_size 4407 * will only allow for whole field access and rejects any other 4408 * type of narrower access. 4409 */ 4410 *reg_type = info.reg_type; 4411 4412 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 4413 *btf = info.btf; 4414 *btf_id = info.btf_id; 4415 } else { 4416 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 4417 } 4418 /* remember the offset of last byte accessed in ctx */ 4419 if (env->prog->aux->max_ctx_offset < off + size) 4420 env->prog->aux->max_ctx_offset = off + size; 4421 return 0; 4422 } 4423 4424 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 4425 return -EACCES; 4426 } 4427 4428 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 4429 int size) 4430 { 4431 if (size < 0 || off < 0 || 4432 (u64)off + size > sizeof(struct bpf_flow_keys)) { 4433 verbose(env, "invalid access to flow keys off=%d size=%d\n", 4434 off, size); 4435 return -EACCES; 4436 } 4437 return 0; 4438 } 4439 4440 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 4441 u32 regno, int off, int size, 4442 enum bpf_access_type t) 4443 { 4444 struct bpf_reg_state *regs = cur_regs(env); 4445 struct bpf_reg_state *reg = ®s[regno]; 4446 struct bpf_insn_access_aux info = {}; 4447 bool valid; 4448 4449 if (reg->smin_value < 0) { 4450 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 4451 regno); 4452 return -EACCES; 4453 } 4454 4455 switch (reg->type) { 4456 case PTR_TO_SOCK_COMMON: 4457 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 4458 break; 4459 case PTR_TO_SOCKET: 4460 valid = bpf_sock_is_valid_access(off, size, t, &info); 4461 break; 4462 case PTR_TO_TCP_SOCK: 4463 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 4464 break; 4465 case PTR_TO_XDP_SOCK: 4466 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 4467 break; 4468 default: 4469 valid = false; 4470 } 4471 4472 4473 if (valid) { 4474 env->insn_aux_data[insn_idx].ctx_field_size = 4475 info.ctx_field_size; 4476 return 0; 4477 } 4478 4479 verbose(env, "R%d invalid %s access off=%d size=%d\n", 4480 regno, reg_type_str(env, reg->type), off, size); 4481 4482 return -EACCES; 4483 } 4484 4485 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 4486 { 4487 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 4488 } 4489 4490 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 4491 { 4492 const struct bpf_reg_state *reg = reg_state(env, regno); 4493 4494 return reg->type == PTR_TO_CTX; 4495 } 4496 4497 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 4498 { 4499 const struct bpf_reg_state *reg = reg_state(env, regno); 4500 4501 return type_is_sk_pointer(reg->type); 4502 } 4503 4504 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 4505 { 4506 const struct bpf_reg_state *reg = reg_state(env, regno); 4507 4508 return type_is_pkt_pointer(reg->type); 4509 } 4510 4511 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 4512 { 4513 const struct bpf_reg_state *reg = reg_state(env, regno); 4514 4515 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 4516 return reg->type == PTR_TO_FLOW_KEYS; 4517 } 4518 4519 static bool is_trusted_reg(const struct bpf_reg_state *reg) 4520 { 4521 /* A referenced register is always trusted. */ 4522 if (reg->ref_obj_id) 4523 return true; 4524 4525 /* If a register is not referenced, it is trusted if it has the 4526 * MEM_ALLOC or PTR_TRUSTED type modifiers, and no others. Some of the 4527 * other type modifiers may be safe, but we elect to take an opt-in 4528 * approach here as some (e.g. PTR_UNTRUSTED and PTR_MAYBE_NULL) are 4529 * not. 4530 * 4531 * Eventually, we should make PTR_TRUSTED the single source of truth 4532 * for whether a register is trusted. 4533 */ 4534 return type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS && 4535 !bpf_type_has_unsafe_modifiers(reg->type); 4536 } 4537 4538 static bool is_rcu_reg(const struct bpf_reg_state *reg) 4539 { 4540 return reg->type & MEM_RCU; 4541 } 4542 4543 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 4544 const struct bpf_reg_state *reg, 4545 int off, int size, bool strict) 4546 { 4547 struct tnum reg_off; 4548 int ip_align; 4549 4550 /* Byte size accesses are always allowed. */ 4551 if (!strict || size == 1) 4552 return 0; 4553 4554 /* For platforms that do not have a Kconfig enabling 4555 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 4556 * NET_IP_ALIGN is universally set to '2'. And on platforms 4557 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 4558 * to this code only in strict mode where we want to emulate 4559 * the NET_IP_ALIGN==2 checking. Therefore use an 4560 * unconditional IP align value of '2'. 4561 */ 4562 ip_align = 2; 4563 4564 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 4565 if (!tnum_is_aligned(reg_off, size)) { 4566 char tn_buf[48]; 4567 4568 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4569 verbose(env, 4570 "misaligned packet access off %d+%s+%d+%d size %d\n", 4571 ip_align, tn_buf, reg->off, off, size); 4572 return -EACCES; 4573 } 4574 4575 return 0; 4576 } 4577 4578 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 4579 const struct bpf_reg_state *reg, 4580 const char *pointer_desc, 4581 int off, int size, bool strict) 4582 { 4583 struct tnum reg_off; 4584 4585 /* Byte size accesses are always allowed. */ 4586 if (!strict || size == 1) 4587 return 0; 4588 4589 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 4590 if (!tnum_is_aligned(reg_off, size)) { 4591 char tn_buf[48]; 4592 4593 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4594 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 4595 pointer_desc, tn_buf, reg->off, off, size); 4596 return -EACCES; 4597 } 4598 4599 return 0; 4600 } 4601 4602 static int check_ptr_alignment(struct bpf_verifier_env *env, 4603 const struct bpf_reg_state *reg, int off, 4604 int size, bool strict_alignment_once) 4605 { 4606 bool strict = env->strict_alignment || strict_alignment_once; 4607 const char *pointer_desc = ""; 4608 4609 switch (reg->type) { 4610 case PTR_TO_PACKET: 4611 case PTR_TO_PACKET_META: 4612 /* Special case, because of NET_IP_ALIGN. Given metadata sits 4613 * right in front, treat it the very same way. 4614 */ 4615 return check_pkt_ptr_alignment(env, reg, off, size, strict); 4616 case PTR_TO_FLOW_KEYS: 4617 pointer_desc = "flow keys "; 4618 break; 4619 case PTR_TO_MAP_KEY: 4620 pointer_desc = "key "; 4621 break; 4622 case PTR_TO_MAP_VALUE: 4623 pointer_desc = "value "; 4624 break; 4625 case PTR_TO_CTX: 4626 pointer_desc = "context "; 4627 break; 4628 case PTR_TO_STACK: 4629 pointer_desc = "stack "; 4630 /* The stack spill tracking logic in check_stack_write_fixed_off() 4631 * and check_stack_read_fixed_off() relies on stack accesses being 4632 * aligned. 4633 */ 4634 strict = true; 4635 break; 4636 case PTR_TO_SOCKET: 4637 pointer_desc = "sock "; 4638 break; 4639 case PTR_TO_SOCK_COMMON: 4640 pointer_desc = "sock_common "; 4641 break; 4642 case PTR_TO_TCP_SOCK: 4643 pointer_desc = "tcp_sock "; 4644 break; 4645 case PTR_TO_XDP_SOCK: 4646 pointer_desc = "xdp_sock "; 4647 break; 4648 default: 4649 break; 4650 } 4651 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 4652 strict); 4653 } 4654 4655 static int update_stack_depth(struct bpf_verifier_env *env, 4656 const struct bpf_func_state *func, 4657 int off) 4658 { 4659 u16 stack = env->subprog_info[func->subprogno].stack_depth; 4660 4661 if (stack >= -off) 4662 return 0; 4663 4664 /* update known max for given subprogram */ 4665 env->subprog_info[func->subprogno].stack_depth = -off; 4666 return 0; 4667 } 4668 4669 /* starting from main bpf function walk all instructions of the function 4670 * and recursively walk all callees that given function can call. 4671 * Ignore jump and exit insns. 4672 * Since recursion is prevented by check_cfg() this algorithm 4673 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 4674 */ 4675 static int check_max_stack_depth(struct bpf_verifier_env *env) 4676 { 4677 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 4678 struct bpf_subprog_info *subprog = env->subprog_info; 4679 struct bpf_insn *insn = env->prog->insnsi; 4680 bool tail_call_reachable = false; 4681 int ret_insn[MAX_CALL_FRAMES]; 4682 int ret_prog[MAX_CALL_FRAMES]; 4683 int j; 4684 4685 process_func: 4686 /* protect against potential stack overflow that might happen when 4687 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 4688 * depth for such case down to 256 so that the worst case scenario 4689 * would result in 8k stack size (32 which is tailcall limit * 256 = 4690 * 8k). 4691 * 4692 * To get the idea what might happen, see an example: 4693 * func1 -> sub rsp, 128 4694 * subfunc1 -> sub rsp, 256 4695 * tailcall1 -> add rsp, 256 4696 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 4697 * subfunc2 -> sub rsp, 64 4698 * subfunc22 -> sub rsp, 128 4699 * tailcall2 -> add rsp, 128 4700 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 4701 * 4702 * tailcall will unwind the current stack frame but it will not get rid 4703 * of caller's stack as shown on the example above. 4704 */ 4705 if (idx && subprog[idx].has_tail_call && depth >= 256) { 4706 verbose(env, 4707 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 4708 depth); 4709 return -EACCES; 4710 } 4711 /* round up to 32-bytes, since this is granularity 4712 * of interpreter stack size 4713 */ 4714 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 4715 if (depth > MAX_BPF_STACK) { 4716 verbose(env, "combined stack size of %d calls is %d. Too large\n", 4717 frame + 1, depth); 4718 return -EACCES; 4719 } 4720 continue_func: 4721 subprog_end = subprog[idx + 1].start; 4722 for (; i < subprog_end; i++) { 4723 int next_insn; 4724 4725 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 4726 continue; 4727 /* remember insn and function to return to */ 4728 ret_insn[frame] = i + 1; 4729 ret_prog[frame] = idx; 4730 4731 /* find the callee */ 4732 next_insn = i + insn[i].imm + 1; 4733 idx = find_subprog(env, next_insn); 4734 if (idx < 0) { 4735 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 4736 next_insn); 4737 return -EFAULT; 4738 } 4739 if (subprog[idx].is_async_cb) { 4740 if (subprog[idx].has_tail_call) { 4741 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 4742 return -EFAULT; 4743 } 4744 /* async callbacks don't increase bpf prog stack size */ 4745 continue; 4746 } 4747 i = next_insn; 4748 4749 if (subprog[idx].has_tail_call) 4750 tail_call_reachable = true; 4751 4752 frame++; 4753 if (frame >= MAX_CALL_FRAMES) { 4754 verbose(env, "the call stack of %d frames is too deep !\n", 4755 frame); 4756 return -E2BIG; 4757 } 4758 goto process_func; 4759 } 4760 /* if tail call got detected across bpf2bpf calls then mark each of the 4761 * currently present subprog frames as tail call reachable subprogs; 4762 * this info will be utilized by JIT so that we will be preserving the 4763 * tail call counter throughout bpf2bpf calls combined with tailcalls 4764 */ 4765 if (tail_call_reachable) 4766 for (j = 0; j < frame; j++) 4767 subprog[ret_prog[j]].tail_call_reachable = true; 4768 if (subprog[0].tail_call_reachable) 4769 env->prog->aux->tail_call_reachable = true; 4770 4771 /* end of for() loop means the last insn of the 'subprog' 4772 * was reached. Doesn't matter whether it was JA or EXIT 4773 */ 4774 if (frame == 0) 4775 return 0; 4776 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 4777 frame--; 4778 i = ret_insn[frame]; 4779 idx = ret_prog[frame]; 4780 goto continue_func; 4781 } 4782 4783 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 4784 static int get_callee_stack_depth(struct bpf_verifier_env *env, 4785 const struct bpf_insn *insn, int idx) 4786 { 4787 int start = idx + insn->imm + 1, subprog; 4788 4789 subprog = find_subprog(env, start); 4790 if (subprog < 0) { 4791 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 4792 start); 4793 return -EFAULT; 4794 } 4795 return env->subprog_info[subprog].stack_depth; 4796 } 4797 #endif 4798 4799 static int __check_buffer_access(struct bpf_verifier_env *env, 4800 const char *buf_info, 4801 const struct bpf_reg_state *reg, 4802 int regno, int off, int size) 4803 { 4804 if (off < 0) { 4805 verbose(env, 4806 "R%d invalid %s buffer access: off=%d, size=%d\n", 4807 regno, buf_info, off, size); 4808 return -EACCES; 4809 } 4810 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4811 char tn_buf[48]; 4812 4813 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4814 verbose(env, 4815 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 4816 regno, off, tn_buf); 4817 return -EACCES; 4818 } 4819 4820 return 0; 4821 } 4822 4823 static int check_tp_buffer_access(struct bpf_verifier_env *env, 4824 const struct bpf_reg_state *reg, 4825 int regno, int off, int size) 4826 { 4827 int err; 4828 4829 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 4830 if (err) 4831 return err; 4832 4833 if (off + size > env->prog->aux->max_tp_access) 4834 env->prog->aux->max_tp_access = off + size; 4835 4836 return 0; 4837 } 4838 4839 static int check_buffer_access(struct bpf_verifier_env *env, 4840 const struct bpf_reg_state *reg, 4841 int regno, int off, int size, 4842 bool zero_size_allowed, 4843 u32 *max_access) 4844 { 4845 const char *buf_info = type_is_rdonly_mem(reg->type) ? "rdonly" : "rdwr"; 4846 int err; 4847 4848 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 4849 if (err) 4850 return err; 4851 4852 if (off + size > *max_access) 4853 *max_access = off + size; 4854 4855 return 0; 4856 } 4857 4858 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 4859 static void zext_32_to_64(struct bpf_reg_state *reg) 4860 { 4861 reg->var_off = tnum_subreg(reg->var_off); 4862 __reg_assign_32_into_64(reg); 4863 } 4864 4865 /* truncate register to smaller size (in bytes) 4866 * must be called with size < BPF_REG_SIZE 4867 */ 4868 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 4869 { 4870 u64 mask; 4871 4872 /* clear high bits in bit representation */ 4873 reg->var_off = tnum_cast(reg->var_off, size); 4874 4875 /* fix arithmetic bounds */ 4876 mask = ((u64)1 << (size * 8)) - 1; 4877 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 4878 reg->umin_value &= mask; 4879 reg->umax_value &= mask; 4880 } else { 4881 reg->umin_value = 0; 4882 reg->umax_value = mask; 4883 } 4884 reg->smin_value = reg->umin_value; 4885 reg->smax_value = reg->umax_value; 4886 4887 /* If size is smaller than 32bit register the 32bit register 4888 * values are also truncated so we push 64-bit bounds into 4889 * 32-bit bounds. Above were truncated < 32-bits already. 4890 */ 4891 if (size >= 4) 4892 return; 4893 __reg_combine_64_into_32(reg); 4894 } 4895 4896 static bool bpf_map_is_rdonly(const struct bpf_map *map) 4897 { 4898 /* A map is considered read-only if the following condition are true: 4899 * 4900 * 1) BPF program side cannot change any of the map content. The 4901 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 4902 * and was set at map creation time. 4903 * 2) The map value(s) have been initialized from user space by a 4904 * loader and then "frozen", such that no new map update/delete 4905 * operations from syscall side are possible for the rest of 4906 * the map's lifetime from that point onwards. 4907 * 3) Any parallel/pending map update/delete operations from syscall 4908 * side have been completed. Only after that point, it's safe to 4909 * assume that map value(s) are immutable. 4910 */ 4911 return (map->map_flags & BPF_F_RDONLY_PROG) && 4912 READ_ONCE(map->frozen) && 4913 !bpf_map_write_active(map); 4914 } 4915 4916 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 4917 { 4918 void *ptr; 4919 u64 addr; 4920 int err; 4921 4922 err = map->ops->map_direct_value_addr(map, &addr, off); 4923 if (err) 4924 return err; 4925 ptr = (void *)(long)addr + off; 4926 4927 switch (size) { 4928 case sizeof(u8): 4929 *val = (u64)*(u8 *)ptr; 4930 break; 4931 case sizeof(u16): 4932 *val = (u64)*(u16 *)ptr; 4933 break; 4934 case sizeof(u32): 4935 *val = (u64)*(u32 *)ptr; 4936 break; 4937 case sizeof(u64): 4938 *val = *(u64 *)ptr; 4939 break; 4940 default: 4941 return -EINVAL; 4942 } 4943 return 0; 4944 } 4945 4946 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 4947 struct bpf_reg_state *regs, 4948 int regno, int off, int size, 4949 enum bpf_access_type atype, 4950 int value_regno) 4951 { 4952 struct bpf_reg_state *reg = regs + regno; 4953 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 4954 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 4955 enum bpf_type_flag flag = 0; 4956 u32 btf_id; 4957 int ret; 4958 4959 if (!env->allow_ptr_leaks) { 4960 verbose(env, 4961 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 4962 tname); 4963 return -EPERM; 4964 } 4965 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 4966 verbose(env, 4967 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 4968 tname); 4969 return -EINVAL; 4970 } 4971 if (off < 0) { 4972 verbose(env, 4973 "R%d is ptr_%s invalid negative access: off=%d\n", 4974 regno, tname, off); 4975 return -EACCES; 4976 } 4977 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4978 char tn_buf[48]; 4979 4980 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4981 verbose(env, 4982 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 4983 regno, tname, off, tn_buf); 4984 return -EACCES; 4985 } 4986 4987 if (reg->type & MEM_USER) { 4988 verbose(env, 4989 "R%d is ptr_%s access user memory: off=%d\n", 4990 regno, tname, off); 4991 return -EACCES; 4992 } 4993 4994 if (reg->type & MEM_PERCPU) { 4995 verbose(env, 4996 "R%d is ptr_%s access percpu memory: off=%d\n", 4997 regno, tname, off); 4998 return -EACCES; 4999 } 5000 5001 if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) { 5002 if (!btf_is_kernel(reg->btf)) { 5003 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 5004 return -EFAULT; 5005 } 5006 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag); 5007 } else { 5008 /* Writes are permitted with default btf_struct_access for 5009 * program allocated objects (which always have ref_obj_id > 0), 5010 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 5011 */ 5012 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 5013 verbose(env, "only read is supported\n"); 5014 return -EACCES; 5015 } 5016 5017 if (type_is_alloc(reg->type) && !reg->ref_obj_id) { 5018 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 5019 return -EFAULT; 5020 } 5021 5022 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag); 5023 } 5024 5025 if (ret < 0) 5026 return ret; 5027 5028 /* If this is an untrusted pointer, all pointers formed by walking it 5029 * also inherit the untrusted flag. 5030 */ 5031 if (type_flag(reg->type) & PTR_UNTRUSTED) 5032 flag |= PTR_UNTRUSTED; 5033 5034 /* By default any pointer obtained from walking a trusted pointer is 5035 * no longer trusted except the rcu case below. 5036 */ 5037 flag &= ~PTR_TRUSTED; 5038 5039 if (flag & MEM_RCU) { 5040 /* Mark value register as MEM_RCU only if it is protected by 5041 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU 5042 * itself can already indicate trustedness inside the rcu 5043 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since 5044 * it could be null in some cases. 5045 */ 5046 if (!env->cur_state->active_rcu_lock || 5047 !(is_trusted_reg(reg) || is_rcu_reg(reg))) 5048 flag &= ~MEM_RCU; 5049 else 5050 flag |= PTR_MAYBE_NULL; 5051 } else if (reg->type & MEM_RCU) { 5052 /* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged 5053 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively. 5054 */ 5055 flag |= PTR_UNTRUSTED; 5056 } 5057 5058 if (atype == BPF_READ && value_regno >= 0) 5059 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5060 5061 return 0; 5062 } 5063 5064 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5065 struct bpf_reg_state *regs, 5066 int regno, int off, int size, 5067 enum bpf_access_type atype, 5068 int value_regno) 5069 { 5070 struct bpf_reg_state *reg = regs + regno; 5071 struct bpf_map *map = reg->map_ptr; 5072 struct bpf_reg_state map_reg; 5073 enum bpf_type_flag flag = 0; 5074 const struct btf_type *t; 5075 const char *tname; 5076 u32 btf_id; 5077 int ret; 5078 5079 if (!btf_vmlinux) { 5080 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5081 return -ENOTSUPP; 5082 } 5083 5084 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5085 verbose(env, "map_ptr access not supported for map type %d\n", 5086 map->map_type); 5087 return -ENOTSUPP; 5088 } 5089 5090 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5091 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5092 5093 if (!env->allow_ptr_leaks) { 5094 verbose(env, 5095 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5096 tname); 5097 return -EPERM; 5098 } 5099 5100 if (off < 0) { 5101 verbose(env, "R%d is %s invalid negative access: off=%d\n", 5102 regno, tname, off); 5103 return -EACCES; 5104 } 5105 5106 if (atype != BPF_READ) { 5107 verbose(env, "only read from %s is supported\n", tname); 5108 return -EACCES; 5109 } 5110 5111 /* Simulate access to a PTR_TO_BTF_ID */ 5112 memset(&map_reg, 0, sizeof(map_reg)); 5113 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 5114 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag); 5115 if (ret < 0) 5116 return ret; 5117 5118 if (value_regno >= 0) 5119 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 5120 5121 return 0; 5122 } 5123 5124 /* Check that the stack access at the given offset is within bounds. The 5125 * maximum valid offset is -1. 5126 * 5127 * The minimum valid offset is -MAX_BPF_STACK for writes, and 5128 * -state->allocated_stack for reads. 5129 */ 5130 static int check_stack_slot_within_bounds(int off, 5131 struct bpf_func_state *state, 5132 enum bpf_access_type t) 5133 { 5134 int min_valid_off; 5135 5136 if (t == BPF_WRITE) 5137 min_valid_off = -MAX_BPF_STACK; 5138 else 5139 min_valid_off = -state->allocated_stack; 5140 5141 if (off < min_valid_off || off > -1) 5142 return -EACCES; 5143 return 0; 5144 } 5145 5146 /* Check that the stack access at 'regno + off' falls within the maximum stack 5147 * bounds. 5148 * 5149 * 'off' includes `regno->offset`, but not its dynamic part (if any). 5150 */ 5151 static int check_stack_access_within_bounds( 5152 struct bpf_verifier_env *env, 5153 int regno, int off, int access_size, 5154 enum bpf_access_src src, enum bpf_access_type type) 5155 { 5156 struct bpf_reg_state *regs = cur_regs(env); 5157 struct bpf_reg_state *reg = regs + regno; 5158 struct bpf_func_state *state = func(env, reg); 5159 int min_off, max_off; 5160 int err; 5161 char *err_extra; 5162 5163 if (src == ACCESS_HELPER) 5164 /* We don't know if helpers are reading or writing (or both). */ 5165 err_extra = " indirect access to"; 5166 else if (type == BPF_READ) 5167 err_extra = " read from"; 5168 else 5169 err_extra = " write to"; 5170 5171 if (tnum_is_const(reg->var_off)) { 5172 min_off = reg->var_off.value + off; 5173 if (access_size > 0) 5174 max_off = min_off + access_size - 1; 5175 else 5176 max_off = min_off; 5177 } else { 5178 if (reg->smax_value >= BPF_MAX_VAR_OFF || 5179 reg->smin_value <= -BPF_MAX_VAR_OFF) { 5180 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 5181 err_extra, regno); 5182 return -EACCES; 5183 } 5184 min_off = reg->smin_value + off; 5185 if (access_size > 0) 5186 max_off = reg->smax_value + off + access_size - 1; 5187 else 5188 max_off = min_off; 5189 } 5190 5191 err = check_stack_slot_within_bounds(min_off, state, type); 5192 if (!err) 5193 err = check_stack_slot_within_bounds(max_off, state, type); 5194 5195 if (err) { 5196 if (tnum_is_const(reg->var_off)) { 5197 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 5198 err_extra, regno, off, access_size); 5199 } else { 5200 char tn_buf[48]; 5201 5202 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5203 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 5204 err_extra, regno, tn_buf, access_size); 5205 } 5206 } 5207 return err; 5208 } 5209 5210 /* check whether memory at (regno + off) is accessible for t = (read | write) 5211 * if t==write, value_regno is a register which value is stored into memory 5212 * if t==read, value_regno is a register which will receive the value from memory 5213 * if t==write && value_regno==-1, some unknown value is stored into memory 5214 * if t==read && value_regno==-1, don't care what we read from memory 5215 */ 5216 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 5217 int off, int bpf_size, enum bpf_access_type t, 5218 int value_regno, bool strict_alignment_once) 5219 { 5220 struct bpf_reg_state *regs = cur_regs(env); 5221 struct bpf_reg_state *reg = regs + regno; 5222 struct bpf_func_state *state; 5223 int size, err = 0; 5224 5225 size = bpf_size_to_bytes(bpf_size); 5226 if (size < 0) 5227 return size; 5228 5229 /* alignment checks will add in reg->off themselves */ 5230 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 5231 if (err) 5232 return err; 5233 5234 /* for access checks, reg->off is just part of off */ 5235 off += reg->off; 5236 5237 if (reg->type == PTR_TO_MAP_KEY) { 5238 if (t == BPF_WRITE) { 5239 verbose(env, "write to change key R%d not allowed\n", regno); 5240 return -EACCES; 5241 } 5242 5243 err = check_mem_region_access(env, regno, off, size, 5244 reg->map_ptr->key_size, false); 5245 if (err) 5246 return err; 5247 if (value_regno >= 0) 5248 mark_reg_unknown(env, regs, value_regno); 5249 } else if (reg->type == PTR_TO_MAP_VALUE) { 5250 struct btf_field *kptr_field = NULL; 5251 5252 if (t == BPF_WRITE && value_regno >= 0 && 5253 is_pointer_value(env, value_regno)) { 5254 verbose(env, "R%d leaks addr into map\n", value_regno); 5255 return -EACCES; 5256 } 5257 err = check_map_access_type(env, regno, off, size, t); 5258 if (err) 5259 return err; 5260 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 5261 if (err) 5262 return err; 5263 if (tnum_is_const(reg->var_off)) 5264 kptr_field = btf_record_find(reg->map_ptr->record, 5265 off + reg->var_off.value, BPF_KPTR); 5266 if (kptr_field) { 5267 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 5268 } else if (t == BPF_READ && value_regno >= 0) { 5269 struct bpf_map *map = reg->map_ptr; 5270 5271 /* if map is read-only, track its contents as scalars */ 5272 if (tnum_is_const(reg->var_off) && 5273 bpf_map_is_rdonly(map) && 5274 map->ops->map_direct_value_addr) { 5275 int map_off = off + reg->var_off.value; 5276 u64 val = 0; 5277 5278 err = bpf_map_direct_read(map, map_off, size, 5279 &val); 5280 if (err) 5281 return err; 5282 5283 regs[value_regno].type = SCALAR_VALUE; 5284 __mark_reg_known(®s[value_regno], val); 5285 } else { 5286 mark_reg_unknown(env, regs, value_regno); 5287 } 5288 } 5289 } else if (base_type(reg->type) == PTR_TO_MEM) { 5290 bool rdonly_mem = type_is_rdonly_mem(reg->type); 5291 5292 if (type_may_be_null(reg->type)) { 5293 verbose(env, "R%d invalid mem access '%s'\n", regno, 5294 reg_type_str(env, reg->type)); 5295 return -EACCES; 5296 } 5297 5298 if (t == BPF_WRITE && rdonly_mem) { 5299 verbose(env, "R%d cannot write into %s\n", 5300 regno, reg_type_str(env, reg->type)); 5301 return -EACCES; 5302 } 5303 5304 if (t == BPF_WRITE && value_regno >= 0 && 5305 is_pointer_value(env, value_regno)) { 5306 verbose(env, "R%d leaks addr into mem\n", value_regno); 5307 return -EACCES; 5308 } 5309 5310 err = check_mem_region_access(env, regno, off, size, 5311 reg->mem_size, false); 5312 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 5313 mark_reg_unknown(env, regs, value_regno); 5314 } else if (reg->type == PTR_TO_CTX) { 5315 enum bpf_reg_type reg_type = SCALAR_VALUE; 5316 struct btf *btf = NULL; 5317 u32 btf_id = 0; 5318 5319 if (t == BPF_WRITE && value_regno >= 0 && 5320 is_pointer_value(env, value_regno)) { 5321 verbose(env, "R%d leaks addr into ctx\n", value_regno); 5322 return -EACCES; 5323 } 5324 5325 err = check_ptr_off_reg(env, reg, regno); 5326 if (err < 0) 5327 return err; 5328 5329 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 5330 &btf_id); 5331 if (err) 5332 verbose_linfo(env, insn_idx, "; "); 5333 if (!err && t == BPF_READ && value_regno >= 0) { 5334 /* ctx access returns either a scalar, or a 5335 * PTR_TO_PACKET[_META,_END]. In the latter 5336 * case, we know the offset is zero. 5337 */ 5338 if (reg_type == SCALAR_VALUE) { 5339 mark_reg_unknown(env, regs, value_regno); 5340 } else { 5341 mark_reg_known_zero(env, regs, 5342 value_regno); 5343 if (type_may_be_null(reg_type)) 5344 regs[value_regno].id = ++env->id_gen; 5345 /* A load of ctx field could have different 5346 * actual load size with the one encoded in the 5347 * insn. When the dst is PTR, it is for sure not 5348 * a sub-register. 5349 */ 5350 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 5351 if (base_type(reg_type) == PTR_TO_BTF_ID) { 5352 regs[value_regno].btf = btf; 5353 regs[value_regno].btf_id = btf_id; 5354 } 5355 } 5356 regs[value_regno].type = reg_type; 5357 } 5358 5359 } else if (reg->type == PTR_TO_STACK) { 5360 /* Basic bounds checks. */ 5361 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 5362 if (err) 5363 return err; 5364 5365 state = func(env, reg); 5366 err = update_stack_depth(env, state, off); 5367 if (err) 5368 return err; 5369 5370 if (t == BPF_READ) 5371 err = check_stack_read(env, regno, off, size, 5372 value_regno); 5373 else 5374 err = check_stack_write(env, regno, off, size, 5375 value_regno, insn_idx); 5376 } else if (reg_is_pkt_pointer(reg)) { 5377 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 5378 verbose(env, "cannot write into packet\n"); 5379 return -EACCES; 5380 } 5381 if (t == BPF_WRITE && value_regno >= 0 && 5382 is_pointer_value(env, value_regno)) { 5383 verbose(env, "R%d leaks addr into packet\n", 5384 value_regno); 5385 return -EACCES; 5386 } 5387 err = check_packet_access(env, regno, off, size, false); 5388 if (!err && t == BPF_READ && value_regno >= 0) 5389 mark_reg_unknown(env, regs, value_regno); 5390 } else if (reg->type == PTR_TO_FLOW_KEYS) { 5391 if (t == BPF_WRITE && value_regno >= 0 && 5392 is_pointer_value(env, value_regno)) { 5393 verbose(env, "R%d leaks addr into flow keys\n", 5394 value_regno); 5395 return -EACCES; 5396 } 5397 5398 err = check_flow_keys_access(env, off, size); 5399 if (!err && t == BPF_READ && value_regno >= 0) 5400 mark_reg_unknown(env, regs, value_regno); 5401 } else if (type_is_sk_pointer(reg->type)) { 5402 if (t == BPF_WRITE) { 5403 verbose(env, "R%d cannot write into %s\n", 5404 regno, reg_type_str(env, reg->type)); 5405 return -EACCES; 5406 } 5407 err = check_sock_access(env, insn_idx, regno, off, size, t); 5408 if (!err && value_regno >= 0) 5409 mark_reg_unknown(env, regs, value_regno); 5410 } else if (reg->type == PTR_TO_TP_BUFFER) { 5411 err = check_tp_buffer_access(env, reg, regno, off, size); 5412 if (!err && t == BPF_READ && value_regno >= 0) 5413 mark_reg_unknown(env, regs, value_regno); 5414 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 5415 !type_may_be_null(reg->type)) { 5416 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 5417 value_regno); 5418 } else if (reg->type == CONST_PTR_TO_MAP) { 5419 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 5420 value_regno); 5421 } else if (base_type(reg->type) == PTR_TO_BUF) { 5422 bool rdonly_mem = type_is_rdonly_mem(reg->type); 5423 u32 *max_access; 5424 5425 if (rdonly_mem) { 5426 if (t == BPF_WRITE) { 5427 verbose(env, "R%d cannot write into %s\n", 5428 regno, reg_type_str(env, reg->type)); 5429 return -EACCES; 5430 } 5431 max_access = &env->prog->aux->max_rdonly_access; 5432 } else { 5433 max_access = &env->prog->aux->max_rdwr_access; 5434 } 5435 5436 err = check_buffer_access(env, reg, regno, off, size, false, 5437 max_access); 5438 5439 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 5440 mark_reg_unknown(env, regs, value_regno); 5441 } else { 5442 verbose(env, "R%d invalid mem access '%s'\n", regno, 5443 reg_type_str(env, reg->type)); 5444 return -EACCES; 5445 } 5446 5447 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 5448 regs[value_regno].type == SCALAR_VALUE) { 5449 /* b/h/w load zero-extends, mark upper bits as known 0 */ 5450 coerce_reg_to_size(®s[value_regno], size); 5451 } 5452 return err; 5453 } 5454 5455 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 5456 { 5457 int load_reg; 5458 int err; 5459 5460 switch (insn->imm) { 5461 case BPF_ADD: 5462 case BPF_ADD | BPF_FETCH: 5463 case BPF_AND: 5464 case BPF_AND | BPF_FETCH: 5465 case BPF_OR: 5466 case BPF_OR | BPF_FETCH: 5467 case BPF_XOR: 5468 case BPF_XOR | BPF_FETCH: 5469 case BPF_XCHG: 5470 case BPF_CMPXCHG: 5471 break; 5472 default: 5473 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 5474 return -EINVAL; 5475 } 5476 5477 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 5478 verbose(env, "invalid atomic operand size\n"); 5479 return -EINVAL; 5480 } 5481 5482 /* check src1 operand */ 5483 err = check_reg_arg(env, insn->src_reg, SRC_OP); 5484 if (err) 5485 return err; 5486 5487 /* check src2 operand */ 5488 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 5489 if (err) 5490 return err; 5491 5492 if (insn->imm == BPF_CMPXCHG) { 5493 /* Check comparison of R0 with memory location */ 5494 const u32 aux_reg = BPF_REG_0; 5495 5496 err = check_reg_arg(env, aux_reg, SRC_OP); 5497 if (err) 5498 return err; 5499 5500 if (is_pointer_value(env, aux_reg)) { 5501 verbose(env, "R%d leaks addr into mem\n", aux_reg); 5502 return -EACCES; 5503 } 5504 } 5505 5506 if (is_pointer_value(env, insn->src_reg)) { 5507 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 5508 return -EACCES; 5509 } 5510 5511 if (is_ctx_reg(env, insn->dst_reg) || 5512 is_pkt_reg(env, insn->dst_reg) || 5513 is_flow_key_reg(env, insn->dst_reg) || 5514 is_sk_reg(env, insn->dst_reg)) { 5515 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 5516 insn->dst_reg, 5517 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 5518 return -EACCES; 5519 } 5520 5521 if (insn->imm & BPF_FETCH) { 5522 if (insn->imm == BPF_CMPXCHG) 5523 load_reg = BPF_REG_0; 5524 else 5525 load_reg = insn->src_reg; 5526 5527 /* check and record load of old value */ 5528 err = check_reg_arg(env, load_reg, DST_OP); 5529 if (err) 5530 return err; 5531 } else { 5532 /* This instruction accesses a memory location but doesn't 5533 * actually load it into a register. 5534 */ 5535 load_reg = -1; 5536 } 5537 5538 /* Check whether we can read the memory, with second call for fetch 5539 * case to simulate the register fill. 5540 */ 5541 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5542 BPF_SIZE(insn->code), BPF_READ, -1, true); 5543 if (!err && load_reg >= 0) 5544 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5545 BPF_SIZE(insn->code), BPF_READ, load_reg, 5546 true); 5547 if (err) 5548 return err; 5549 5550 /* Check whether we can write into the same memory. */ 5551 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5552 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 5553 if (err) 5554 return err; 5555 5556 return 0; 5557 } 5558 5559 /* When register 'regno' is used to read the stack (either directly or through 5560 * a helper function) make sure that it's within stack boundary and, depending 5561 * on the access type, that all elements of the stack are initialized. 5562 * 5563 * 'off' includes 'regno->off', but not its dynamic part (if any). 5564 * 5565 * All registers that have been spilled on the stack in the slots within the 5566 * read offsets are marked as read. 5567 */ 5568 static int check_stack_range_initialized( 5569 struct bpf_verifier_env *env, int regno, int off, 5570 int access_size, bool zero_size_allowed, 5571 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 5572 { 5573 struct bpf_reg_state *reg = reg_state(env, regno); 5574 struct bpf_func_state *state = func(env, reg); 5575 int err, min_off, max_off, i, j, slot, spi; 5576 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 5577 enum bpf_access_type bounds_check_type; 5578 /* Some accesses can write anything into the stack, others are 5579 * read-only. 5580 */ 5581 bool clobber = false; 5582 5583 if (access_size == 0 && !zero_size_allowed) { 5584 verbose(env, "invalid zero-sized read\n"); 5585 return -EACCES; 5586 } 5587 5588 if (type == ACCESS_HELPER) { 5589 /* The bounds checks for writes are more permissive than for 5590 * reads. However, if raw_mode is not set, we'll do extra 5591 * checks below. 5592 */ 5593 bounds_check_type = BPF_WRITE; 5594 clobber = true; 5595 } else { 5596 bounds_check_type = BPF_READ; 5597 } 5598 err = check_stack_access_within_bounds(env, regno, off, access_size, 5599 type, bounds_check_type); 5600 if (err) 5601 return err; 5602 5603 5604 if (tnum_is_const(reg->var_off)) { 5605 min_off = max_off = reg->var_off.value + off; 5606 } else { 5607 /* Variable offset is prohibited for unprivileged mode for 5608 * simplicity since it requires corresponding support in 5609 * Spectre masking for stack ALU. 5610 * See also retrieve_ptr_limit(). 5611 */ 5612 if (!env->bypass_spec_v1) { 5613 char tn_buf[48]; 5614 5615 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5616 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 5617 regno, err_extra, tn_buf); 5618 return -EACCES; 5619 } 5620 /* Only initialized buffer on stack is allowed to be accessed 5621 * with variable offset. With uninitialized buffer it's hard to 5622 * guarantee that whole memory is marked as initialized on 5623 * helper return since specific bounds are unknown what may 5624 * cause uninitialized stack leaking. 5625 */ 5626 if (meta && meta->raw_mode) 5627 meta = NULL; 5628 5629 min_off = reg->smin_value + off; 5630 max_off = reg->smax_value + off; 5631 } 5632 5633 if (meta && meta->raw_mode) { 5634 /* Ensure we won't be overwriting dynptrs when simulating byte 5635 * by byte access in check_helper_call using meta.access_size. 5636 * This would be a problem if we have a helper in the future 5637 * which takes: 5638 * 5639 * helper(uninit_mem, len, dynptr) 5640 * 5641 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 5642 * may end up writing to dynptr itself when touching memory from 5643 * arg 1. This can be relaxed on a case by case basis for known 5644 * safe cases, but reject due to the possibilitiy of aliasing by 5645 * default. 5646 */ 5647 for (i = min_off; i < max_off + access_size; i++) { 5648 int stack_off = -i - 1; 5649 5650 spi = __get_spi(i); 5651 /* raw_mode may write past allocated_stack */ 5652 if (state->allocated_stack <= stack_off) 5653 continue; 5654 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 5655 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 5656 return -EACCES; 5657 } 5658 } 5659 meta->access_size = access_size; 5660 meta->regno = regno; 5661 return 0; 5662 } 5663 5664 for (i = min_off; i < max_off + access_size; i++) { 5665 u8 *stype; 5666 5667 slot = -i - 1; 5668 spi = slot / BPF_REG_SIZE; 5669 if (state->allocated_stack <= slot) 5670 goto err; 5671 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 5672 if (*stype == STACK_MISC) 5673 goto mark; 5674 if (*stype == STACK_ZERO) { 5675 if (clobber) { 5676 /* helper can write anything into the stack */ 5677 *stype = STACK_MISC; 5678 } 5679 goto mark; 5680 } 5681 5682 if (is_spilled_reg(&state->stack[spi]) && 5683 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 5684 env->allow_ptr_leaks)) { 5685 if (clobber) { 5686 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 5687 for (j = 0; j < BPF_REG_SIZE; j++) 5688 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 5689 } 5690 goto mark; 5691 } 5692 5693 err: 5694 if (tnum_is_const(reg->var_off)) { 5695 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 5696 err_extra, regno, min_off, i - min_off, access_size); 5697 } else { 5698 char tn_buf[48]; 5699 5700 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5701 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 5702 err_extra, regno, tn_buf, i - min_off, access_size); 5703 } 5704 return -EACCES; 5705 mark: 5706 /* reading any byte out of 8-byte 'spill_slot' will cause 5707 * the whole slot to be marked as 'read' 5708 */ 5709 mark_reg_read(env, &state->stack[spi].spilled_ptr, 5710 state->stack[spi].spilled_ptr.parent, 5711 REG_LIVE_READ64); 5712 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 5713 * be sure that whether stack slot is written to or not. Hence, 5714 * we must still conservatively propagate reads upwards even if 5715 * helper may write to the entire memory range. 5716 */ 5717 } 5718 return update_stack_depth(env, state, min_off); 5719 } 5720 5721 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 5722 int access_size, bool zero_size_allowed, 5723 struct bpf_call_arg_meta *meta) 5724 { 5725 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5726 u32 *max_access; 5727 5728 switch (base_type(reg->type)) { 5729 case PTR_TO_PACKET: 5730 case PTR_TO_PACKET_META: 5731 return check_packet_access(env, regno, reg->off, access_size, 5732 zero_size_allowed); 5733 case PTR_TO_MAP_KEY: 5734 if (meta && meta->raw_mode) { 5735 verbose(env, "R%d cannot write into %s\n", regno, 5736 reg_type_str(env, reg->type)); 5737 return -EACCES; 5738 } 5739 return check_mem_region_access(env, regno, reg->off, access_size, 5740 reg->map_ptr->key_size, false); 5741 case PTR_TO_MAP_VALUE: 5742 if (check_map_access_type(env, regno, reg->off, access_size, 5743 meta && meta->raw_mode ? BPF_WRITE : 5744 BPF_READ)) 5745 return -EACCES; 5746 return check_map_access(env, regno, reg->off, access_size, 5747 zero_size_allowed, ACCESS_HELPER); 5748 case PTR_TO_MEM: 5749 if (type_is_rdonly_mem(reg->type)) { 5750 if (meta && meta->raw_mode) { 5751 verbose(env, "R%d cannot write into %s\n", regno, 5752 reg_type_str(env, reg->type)); 5753 return -EACCES; 5754 } 5755 } 5756 return check_mem_region_access(env, regno, reg->off, 5757 access_size, reg->mem_size, 5758 zero_size_allowed); 5759 case PTR_TO_BUF: 5760 if (type_is_rdonly_mem(reg->type)) { 5761 if (meta && meta->raw_mode) { 5762 verbose(env, "R%d cannot write into %s\n", regno, 5763 reg_type_str(env, reg->type)); 5764 return -EACCES; 5765 } 5766 5767 max_access = &env->prog->aux->max_rdonly_access; 5768 } else { 5769 max_access = &env->prog->aux->max_rdwr_access; 5770 } 5771 return check_buffer_access(env, reg, regno, reg->off, 5772 access_size, zero_size_allowed, 5773 max_access); 5774 case PTR_TO_STACK: 5775 return check_stack_range_initialized( 5776 env, 5777 regno, reg->off, access_size, 5778 zero_size_allowed, ACCESS_HELPER, meta); 5779 case PTR_TO_CTX: 5780 /* in case the function doesn't know how to access the context, 5781 * (because we are in a program of type SYSCALL for example), we 5782 * can not statically check its size. 5783 * Dynamically check it now. 5784 */ 5785 if (!env->ops->convert_ctx_access) { 5786 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 5787 int offset = access_size - 1; 5788 5789 /* Allow zero-byte read from PTR_TO_CTX */ 5790 if (access_size == 0) 5791 return zero_size_allowed ? 0 : -EACCES; 5792 5793 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 5794 atype, -1, false); 5795 } 5796 5797 fallthrough; 5798 default: /* scalar_value or invalid ptr */ 5799 /* Allow zero-byte read from NULL, regardless of pointer type */ 5800 if (zero_size_allowed && access_size == 0 && 5801 register_is_null(reg)) 5802 return 0; 5803 5804 verbose(env, "R%d type=%s ", regno, 5805 reg_type_str(env, reg->type)); 5806 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 5807 return -EACCES; 5808 } 5809 } 5810 5811 static int check_mem_size_reg(struct bpf_verifier_env *env, 5812 struct bpf_reg_state *reg, u32 regno, 5813 bool zero_size_allowed, 5814 struct bpf_call_arg_meta *meta) 5815 { 5816 int err; 5817 5818 /* This is used to refine r0 return value bounds for helpers 5819 * that enforce this value as an upper bound on return values. 5820 * See do_refine_retval_range() for helpers that can refine 5821 * the return value. C type of helper is u32 so we pull register 5822 * bound from umax_value however, if negative verifier errors 5823 * out. Only upper bounds can be learned because retval is an 5824 * int type and negative retvals are allowed. 5825 */ 5826 meta->msize_max_value = reg->umax_value; 5827 5828 /* The register is SCALAR_VALUE; the access check 5829 * happens using its boundaries. 5830 */ 5831 if (!tnum_is_const(reg->var_off)) 5832 /* For unprivileged variable accesses, disable raw 5833 * mode so that the program is required to 5834 * initialize all the memory that the helper could 5835 * just partially fill up. 5836 */ 5837 meta = NULL; 5838 5839 if (reg->smin_value < 0) { 5840 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 5841 regno); 5842 return -EACCES; 5843 } 5844 5845 if (reg->umin_value == 0) { 5846 err = check_helper_mem_access(env, regno - 1, 0, 5847 zero_size_allowed, 5848 meta); 5849 if (err) 5850 return err; 5851 } 5852 5853 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 5854 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 5855 regno); 5856 return -EACCES; 5857 } 5858 err = check_helper_mem_access(env, regno - 1, 5859 reg->umax_value, 5860 zero_size_allowed, meta); 5861 if (!err) 5862 err = mark_chain_precision(env, regno); 5863 return err; 5864 } 5865 5866 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5867 u32 regno, u32 mem_size) 5868 { 5869 bool may_be_null = type_may_be_null(reg->type); 5870 struct bpf_reg_state saved_reg; 5871 struct bpf_call_arg_meta meta; 5872 int err; 5873 5874 if (register_is_null(reg)) 5875 return 0; 5876 5877 memset(&meta, 0, sizeof(meta)); 5878 /* Assuming that the register contains a value check if the memory 5879 * access is safe. Temporarily save and restore the register's state as 5880 * the conversion shouldn't be visible to a caller. 5881 */ 5882 if (may_be_null) { 5883 saved_reg = *reg; 5884 mark_ptr_not_null_reg(reg); 5885 } 5886 5887 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 5888 /* Check access for BPF_WRITE */ 5889 meta.raw_mode = true; 5890 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 5891 5892 if (may_be_null) 5893 *reg = saved_reg; 5894 5895 return err; 5896 } 5897 5898 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5899 u32 regno) 5900 { 5901 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 5902 bool may_be_null = type_may_be_null(mem_reg->type); 5903 struct bpf_reg_state saved_reg; 5904 struct bpf_call_arg_meta meta; 5905 int err; 5906 5907 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 5908 5909 memset(&meta, 0, sizeof(meta)); 5910 5911 if (may_be_null) { 5912 saved_reg = *mem_reg; 5913 mark_ptr_not_null_reg(mem_reg); 5914 } 5915 5916 err = check_mem_size_reg(env, reg, regno, true, &meta); 5917 /* Check access for BPF_WRITE */ 5918 meta.raw_mode = true; 5919 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 5920 5921 if (may_be_null) 5922 *mem_reg = saved_reg; 5923 return err; 5924 } 5925 5926 /* Implementation details: 5927 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 5928 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 5929 * Two bpf_map_lookups (even with the same key) will have different reg->id. 5930 * Two separate bpf_obj_new will also have different reg->id. 5931 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 5932 * clears reg->id after value_or_null->value transition, since the verifier only 5933 * cares about the range of access to valid map value pointer and doesn't care 5934 * about actual address of the map element. 5935 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 5936 * reg->id > 0 after value_or_null->value transition. By doing so 5937 * two bpf_map_lookups will be considered two different pointers that 5938 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 5939 * returned from bpf_obj_new. 5940 * The verifier allows taking only one bpf_spin_lock at a time to avoid 5941 * dead-locks. 5942 * Since only one bpf_spin_lock is allowed the checks are simpler than 5943 * reg_is_refcounted() logic. The verifier needs to remember only 5944 * one spin_lock instead of array of acquired_refs. 5945 * cur_state->active_lock remembers which map value element or allocated 5946 * object got locked and clears it after bpf_spin_unlock. 5947 */ 5948 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 5949 bool is_lock) 5950 { 5951 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5952 struct bpf_verifier_state *cur = env->cur_state; 5953 bool is_const = tnum_is_const(reg->var_off); 5954 u64 val = reg->var_off.value; 5955 struct bpf_map *map = NULL; 5956 struct btf *btf = NULL; 5957 struct btf_record *rec; 5958 5959 if (!is_const) { 5960 verbose(env, 5961 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 5962 regno); 5963 return -EINVAL; 5964 } 5965 if (reg->type == PTR_TO_MAP_VALUE) { 5966 map = reg->map_ptr; 5967 if (!map->btf) { 5968 verbose(env, 5969 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 5970 map->name); 5971 return -EINVAL; 5972 } 5973 } else { 5974 btf = reg->btf; 5975 } 5976 5977 rec = reg_btf_record(reg); 5978 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 5979 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 5980 map ? map->name : "kptr"); 5981 return -EINVAL; 5982 } 5983 if (rec->spin_lock_off != val + reg->off) { 5984 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 5985 val + reg->off, rec->spin_lock_off); 5986 return -EINVAL; 5987 } 5988 if (is_lock) { 5989 if (cur->active_lock.ptr) { 5990 verbose(env, 5991 "Locking two bpf_spin_locks are not allowed\n"); 5992 return -EINVAL; 5993 } 5994 if (map) 5995 cur->active_lock.ptr = map; 5996 else 5997 cur->active_lock.ptr = btf; 5998 cur->active_lock.id = reg->id; 5999 } else { 6000 struct bpf_func_state *fstate = cur_func(env); 6001 void *ptr; 6002 int i; 6003 6004 if (map) 6005 ptr = map; 6006 else 6007 ptr = btf; 6008 6009 if (!cur->active_lock.ptr) { 6010 verbose(env, "bpf_spin_unlock without taking a lock\n"); 6011 return -EINVAL; 6012 } 6013 if (cur->active_lock.ptr != ptr || 6014 cur->active_lock.id != reg->id) { 6015 verbose(env, "bpf_spin_unlock of different lock\n"); 6016 return -EINVAL; 6017 } 6018 cur->active_lock.ptr = NULL; 6019 cur->active_lock.id = 0; 6020 6021 for (i = fstate->acquired_refs - 1; i >= 0; i--) { 6022 int err; 6023 6024 /* Complain on error because this reference state cannot 6025 * be freed before this point, as bpf_spin_lock critical 6026 * section does not allow functions that release the 6027 * allocated object immediately. 6028 */ 6029 if (!fstate->refs[i].release_on_unlock) 6030 continue; 6031 err = release_reference(env, fstate->refs[i].id); 6032 if (err) { 6033 verbose(env, "failed to release release_on_unlock reference"); 6034 return err; 6035 } 6036 } 6037 } 6038 return 0; 6039 } 6040 6041 static int process_timer_func(struct bpf_verifier_env *env, int regno, 6042 struct bpf_call_arg_meta *meta) 6043 { 6044 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6045 bool is_const = tnum_is_const(reg->var_off); 6046 struct bpf_map *map = reg->map_ptr; 6047 u64 val = reg->var_off.value; 6048 6049 if (!is_const) { 6050 verbose(env, 6051 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 6052 regno); 6053 return -EINVAL; 6054 } 6055 if (!map->btf) { 6056 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 6057 map->name); 6058 return -EINVAL; 6059 } 6060 if (!btf_record_has_field(map->record, BPF_TIMER)) { 6061 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 6062 return -EINVAL; 6063 } 6064 if (map->record->timer_off != val + reg->off) { 6065 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 6066 val + reg->off, map->record->timer_off); 6067 return -EINVAL; 6068 } 6069 if (meta->map_ptr) { 6070 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 6071 return -EFAULT; 6072 } 6073 meta->map_uid = reg->map_uid; 6074 meta->map_ptr = map; 6075 return 0; 6076 } 6077 6078 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 6079 struct bpf_call_arg_meta *meta) 6080 { 6081 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6082 struct bpf_map *map_ptr = reg->map_ptr; 6083 struct btf_field *kptr_field; 6084 u32 kptr_off; 6085 6086 if (!tnum_is_const(reg->var_off)) { 6087 verbose(env, 6088 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 6089 regno); 6090 return -EINVAL; 6091 } 6092 if (!map_ptr->btf) { 6093 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 6094 map_ptr->name); 6095 return -EINVAL; 6096 } 6097 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 6098 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 6099 return -EINVAL; 6100 } 6101 6102 meta->map_ptr = map_ptr; 6103 kptr_off = reg->off + reg->var_off.value; 6104 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 6105 if (!kptr_field) { 6106 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 6107 return -EACCES; 6108 } 6109 if (kptr_field->type != BPF_KPTR_REF) { 6110 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 6111 return -EACCES; 6112 } 6113 meta->kptr_field = kptr_field; 6114 return 0; 6115 } 6116 6117 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 6118 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 6119 * 6120 * In both cases we deal with the first 8 bytes, but need to mark the next 8 6121 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 6122 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 6123 * 6124 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 6125 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 6126 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 6127 * mutate the view of the dynptr and also possibly destroy it. In the latter 6128 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 6129 * memory that dynptr points to. 6130 * 6131 * The verifier will keep track both levels of mutation (bpf_dynptr's in 6132 * reg->type and the memory's in reg->dynptr.type), but there is no support for 6133 * readonly dynptr view yet, hence only the first case is tracked and checked. 6134 * 6135 * This is consistent with how C applies the const modifier to a struct object, 6136 * where the pointer itself inside bpf_dynptr becomes const but not what it 6137 * points to. 6138 * 6139 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 6140 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 6141 */ 6142 int process_dynptr_func(struct bpf_verifier_env *env, int regno, 6143 enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) 6144 { 6145 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6146 int spi = 0; 6147 6148 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 6149 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 6150 */ 6151 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 6152 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 6153 return -EFAULT; 6154 } 6155 /* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 6156 * check_func_arg_reg_off's logic. We only need to check offset 6157 * and its alignment for PTR_TO_STACK. 6158 */ 6159 if (reg->type == PTR_TO_STACK) { 6160 spi = dynptr_get_spi(env, reg); 6161 if (spi < 0 && spi != -ERANGE) 6162 return spi; 6163 } 6164 6165 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 6166 * constructing a mutable bpf_dynptr object. 6167 * 6168 * Currently, this is only possible with PTR_TO_STACK 6169 * pointing to a region of at least 16 bytes which doesn't 6170 * contain an existing bpf_dynptr. 6171 * 6172 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 6173 * mutated or destroyed. However, the memory it points to 6174 * may be mutated. 6175 * 6176 * None - Points to a initialized dynptr that can be mutated and 6177 * destroyed, including mutation of the memory it points 6178 * to. 6179 */ 6180 if (arg_type & MEM_UNINIT) { 6181 if (!is_dynptr_reg_valid_uninit(env, reg, spi)) { 6182 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 6183 return -EINVAL; 6184 } 6185 6186 /* We only support one dynptr being uninitialized at the moment, 6187 * which is sufficient for the helper functions we have right now. 6188 */ 6189 if (meta->uninit_dynptr_regno) { 6190 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n"); 6191 return -EFAULT; 6192 } 6193 6194 meta->uninit_dynptr_regno = regno; 6195 } else /* MEM_RDONLY and None case from above */ { 6196 int err; 6197 6198 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 6199 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 6200 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 6201 return -EINVAL; 6202 } 6203 6204 if (!is_dynptr_reg_valid_init(env, reg, spi)) { 6205 verbose(env, 6206 "Expected an initialized dynptr as arg #%d\n", 6207 regno); 6208 return -EINVAL; 6209 } 6210 6211 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 6212 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 6213 const char *err_extra = ""; 6214 6215 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 6216 case DYNPTR_TYPE_LOCAL: 6217 err_extra = "local"; 6218 break; 6219 case DYNPTR_TYPE_RINGBUF: 6220 err_extra = "ringbuf"; 6221 break; 6222 default: 6223 err_extra = "<unknown>"; 6224 break; 6225 } 6226 verbose(env, 6227 "Expected a dynptr of type %s as arg #%d\n", 6228 err_extra, regno); 6229 return -EINVAL; 6230 } 6231 6232 err = mark_dynptr_read(env, reg); 6233 if (err) 6234 return err; 6235 } 6236 return 0; 6237 } 6238 6239 static bool arg_type_is_mem_size(enum bpf_arg_type type) 6240 { 6241 return type == ARG_CONST_SIZE || 6242 type == ARG_CONST_SIZE_OR_ZERO; 6243 } 6244 6245 static bool arg_type_is_release(enum bpf_arg_type type) 6246 { 6247 return type & OBJ_RELEASE; 6248 } 6249 6250 static bool arg_type_is_dynptr(enum bpf_arg_type type) 6251 { 6252 return base_type(type) == ARG_PTR_TO_DYNPTR; 6253 } 6254 6255 static int int_ptr_type_to_size(enum bpf_arg_type type) 6256 { 6257 if (type == ARG_PTR_TO_INT) 6258 return sizeof(u32); 6259 else if (type == ARG_PTR_TO_LONG) 6260 return sizeof(u64); 6261 6262 return -EINVAL; 6263 } 6264 6265 static int resolve_map_arg_type(struct bpf_verifier_env *env, 6266 const struct bpf_call_arg_meta *meta, 6267 enum bpf_arg_type *arg_type) 6268 { 6269 if (!meta->map_ptr) { 6270 /* kernel subsystem misconfigured verifier */ 6271 verbose(env, "invalid map_ptr to access map->type\n"); 6272 return -EACCES; 6273 } 6274 6275 switch (meta->map_ptr->map_type) { 6276 case BPF_MAP_TYPE_SOCKMAP: 6277 case BPF_MAP_TYPE_SOCKHASH: 6278 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 6279 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 6280 } else { 6281 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 6282 return -EINVAL; 6283 } 6284 break; 6285 case BPF_MAP_TYPE_BLOOM_FILTER: 6286 if (meta->func_id == BPF_FUNC_map_peek_elem) 6287 *arg_type = ARG_PTR_TO_MAP_VALUE; 6288 break; 6289 default: 6290 break; 6291 } 6292 return 0; 6293 } 6294 6295 struct bpf_reg_types { 6296 const enum bpf_reg_type types[10]; 6297 u32 *btf_id; 6298 }; 6299 6300 static const struct bpf_reg_types sock_types = { 6301 .types = { 6302 PTR_TO_SOCK_COMMON, 6303 PTR_TO_SOCKET, 6304 PTR_TO_TCP_SOCK, 6305 PTR_TO_XDP_SOCK, 6306 }, 6307 }; 6308 6309 #ifdef CONFIG_NET 6310 static const struct bpf_reg_types btf_id_sock_common_types = { 6311 .types = { 6312 PTR_TO_SOCK_COMMON, 6313 PTR_TO_SOCKET, 6314 PTR_TO_TCP_SOCK, 6315 PTR_TO_XDP_SOCK, 6316 PTR_TO_BTF_ID, 6317 PTR_TO_BTF_ID | PTR_TRUSTED, 6318 }, 6319 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 6320 }; 6321 #endif 6322 6323 static const struct bpf_reg_types mem_types = { 6324 .types = { 6325 PTR_TO_STACK, 6326 PTR_TO_PACKET, 6327 PTR_TO_PACKET_META, 6328 PTR_TO_MAP_KEY, 6329 PTR_TO_MAP_VALUE, 6330 PTR_TO_MEM, 6331 PTR_TO_MEM | MEM_RINGBUF, 6332 PTR_TO_BUF, 6333 }, 6334 }; 6335 6336 static const struct bpf_reg_types int_ptr_types = { 6337 .types = { 6338 PTR_TO_STACK, 6339 PTR_TO_PACKET, 6340 PTR_TO_PACKET_META, 6341 PTR_TO_MAP_KEY, 6342 PTR_TO_MAP_VALUE, 6343 }, 6344 }; 6345 6346 static const struct bpf_reg_types spin_lock_types = { 6347 .types = { 6348 PTR_TO_MAP_VALUE, 6349 PTR_TO_BTF_ID | MEM_ALLOC, 6350 } 6351 }; 6352 6353 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 6354 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 6355 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 6356 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 6357 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 6358 static const struct bpf_reg_types btf_ptr_types = { 6359 .types = { 6360 PTR_TO_BTF_ID, 6361 PTR_TO_BTF_ID | PTR_TRUSTED, 6362 PTR_TO_BTF_ID | MEM_RCU, 6363 }, 6364 }; 6365 static const struct bpf_reg_types percpu_btf_ptr_types = { 6366 .types = { 6367 PTR_TO_BTF_ID | MEM_PERCPU, 6368 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 6369 } 6370 }; 6371 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 6372 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 6373 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 6374 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 6375 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 6376 static const struct bpf_reg_types dynptr_types = { 6377 .types = { 6378 PTR_TO_STACK, 6379 CONST_PTR_TO_DYNPTR, 6380 } 6381 }; 6382 6383 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 6384 [ARG_PTR_TO_MAP_KEY] = &mem_types, 6385 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 6386 [ARG_CONST_SIZE] = &scalar_types, 6387 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 6388 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 6389 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 6390 [ARG_PTR_TO_CTX] = &context_types, 6391 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 6392 #ifdef CONFIG_NET 6393 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 6394 #endif 6395 [ARG_PTR_TO_SOCKET] = &fullsock_types, 6396 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 6397 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 6398 [ARG_PTR_TO_MEM] = &mem_types, 6399 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 6400 [ARG_PTR_TO_INT] = &int_ptr_types, 6401 [ARG_PTR_TO_LONG] = &int_ptr_types, 6402 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 6403 [ARG_PTR_TO_FUNC] = &func_ptr_types, 6404 [ARG_PTR_TO_STACK] = &stack_ptr_types, 6405 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 6406 [ARG_PTR_TO_TIMER] = &timer_types, 6407 [ARG_PTR_TO_KPTR] = &kptr_types, 6408 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 6409 }; 6410 6411 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 6412 enum bpf_arg_type arg_type, 6413 const u32 *arg_btf_id, 6414 struct bpf_call_arg_meta *meta) 6415 { 6416 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6417 enum bpf_reg_type expected, type = reg->type; 6418 const struct bpf_reg_types *compatible; 6419 int i, j; 6420 6421 compatible = compatible_reg_types[base_type(arg_type)]; 6422 if (!compatible) { 6423 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 6424 return -EFAULT; 6425 } 6426 6427 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 6428 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 6429 * 6430 * Same for MAYBE_NULL: 6431 * 6432 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 6433 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 6434 * 6435 * Therefore we fold these flags depending on the arg_type before comparison. 6436 */ 6437 if (arg_type & MEM_RDONLY) 6438 type &= ~MEM_RDONLY; 6439 if (arg_type & PTR_MAYBE_NULL) 6440 type &= ~PTR_MAYBE_NULL; 6441 6442 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 6443 expected = compatible->types[i]; 6444 if (expected == NOT_INIT) 6445 break; 6446 6447 if (type == expected) 6448 goto found; 6449 } 6450 6451 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 6452 for (j = 0; j + 1 < i; j++) 6453 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 6454 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 6455 return -EACCES; 6456 6457 found: 6458 if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) { 6459 /* For bpf_sk_release, it needs to match against first member 6460 * 'struct sock_common', hence make an exception for it. This 6461 * allows bpf_sk_release to work for multiple socket types. 6462 */ 6463 bool strict_type_match = arg_type_is_release(arg_type) && 6464 meta->func_id != BPF_FUNC_sk_release; 6465 6466 if (!arg_btf_id) { 6467 if (!compatible->btf_id) { 6468 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 6469 return -EFAULT; 6470 } 6471 arg_btf_id = compatible->btf_id; 6472 } 6473 6474 if (meta->func_id == BPF_FUNC_kptr_xchg) { 6475 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 6476 return -EACCES; 6477 } else { 6478 if (arg_btf_id == BPF_PTR_POISON) { 6479 verbose(env, "verifier internal error:"); 6480 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 6481 regno); 6482 return -EACCES; 6483 } 6484 6485 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 6486 btf_vmlinux, *arg_btf_id, 6487 strict_type_match)) { 6488 verbose(env, "R%d is of type %s but %s is expected\n", 6489 regno, kernel_type_name(reg->btf, reg->btf_id), 6490 kernel_type_name(btf_vmlinux, *arg_btf_id)); 6491 return -EACCES; 6492 } 6493 } 6494 } else if (type_is_alloc(reg->type)) { 6495 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) { 6496 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 6497 return -EFAULT; 6498 } 6499 } 6500 6501 return 0; 6502 } 6503 6504 int check_func_arg_reg_off(struct bpf_verifier_env *env, 6505 const struct bpf_reg_state *reg, int regno, 6506 enum bpf_arg_type arg_type) 6507 { 6508 u32 type = reg->type; 6509 6510 /* When referenced register is passed to release function, its fixed 6511 * offset must be 0. 6512 * 6513 * We will check arg_type_is_release reg has ref_obj_id when storing 6514 * meta->release_regno. 6515 */ 6516 if (arg_type_is_release(arg_type)) { 6517 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 6518 * may not directly point to the object being released, but to 6519 * dynptr pointing to such object, which might be at some offset 6520 * on the stack. In that case, we simply to fallback to the 6521 * default handling. 6522 */ 6523 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 6524 return 0; 6525 /* Doing check_ptr_off_reg check for the offset will catch this 6526 * because fixed_off_ok is false, but checking here allows us 6527 * to give the user a better error message. 6528 */ 6529 if (reg->off) { 6530 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 6531 regno); 6532 return -EINVAL; 6533 } 6534 return __check_ptr_off_reg(env, reg, regno, false); 6535 } 6536 6537 switch (type) { 6538 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 6539 case PTR_TO_STACK: 6540 case PTR_TO_PACKET: 6541 case PTR_TO_PACKET_META: 6542 case PTR_TO_MAP_KEY: 6543 case PTR_TO_MAP_VALUE: 6544 case PTR_TO_MEM: 6545 case PTR_TO_MEM | MEM_RDONLY: 6546 case PTR_TO_MEM | MEM_RINGBUF: 6547 case PTR_TO_BUF: 6548 case PTR_TO_BUF | MEM_RDONLY: 6549 case SCALAR_VALUE: 6550 return 0; 6551 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 6552 * fixed offset. 6553 */ 6554 case PTR_TO_BTF_ID: 6555 case PTR_TO_BTF_ID | MEM_ALLOC: 6556 case PTR_TO_BTF_ID | PTR_TRUSTED: 6557 case PTR_TO_BTF_ID | MEM_RCU: 6558 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED: 6559 /* When referenced PTR_TO_BTF_ID is passed to release function, 6560 * its fixed offset must be 0. In the other cases, fixed offset 6561 * can be non-zero. This was already checked above. So pass 6562 * fixed_off_ok as true to allow fixed offset for all other 6563 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 6564 * still need to do checks instead of returning. 6565 */ 6566 return __check_ptr_off_reg(env, reg, regno, true); 6567 default: 6568 return __check_ptr_off_reg(env, reg, regno, false); 6569 } 6570 } 6571 6572 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 6573 { 6574 struct bpf_func_state *state = func(env, reg); 6575 int spi; 6576 6577 if (reg->type == CONST_PTR_TO_DYNPTR) 6578 return reg->id; 6579 spi = dynptr_get_spi(env, reg); 6580 if (spi < 0) 6581 return spi; 6582 return state->stack[spi].spilled_ptr.id; 6583 } 6584 6585 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 6586 { 6587 struct bpf_func_state *state = func(env, reg); 6588 int spi; 6589 6590 if (reg->type == CONST_PTR_TO_DYNPTR) 6591 return reg->ref_obj_id; 6592 spi = dynptr_get_spi(env, reg); 6593 if (spi < 0) 6594 return spi; 6595 return state->stack[spi].spilled_ptr.ref_obj_id; 6596 } 6597 6598 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 6599 struct bpf_call_arg_meta *meta, 6600 const struct bpf_func_proto *fn) 6601 { 6602 u32 regno = BPF_REG_1 + arg; 6603 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6604 enum bpf_arg_type arg_type = fn->arg_type[arg]; 6605 enum bpf_reg_type type = reg->type; 6606 u32 *arg_btf_id = NULL; 6607 int err = 0; 6608 6609 if (arg_type == ARG_DONTCARE) 6610 return 0; 6611 6612 err = check_reg_arg(env, regno, SRC_OP); 6613 if (err) 6614 return err; 6615 6616 if (arg_type == ARG_ANYTHING) { 6617 if (is_pointer_value(env, regno)) { 6618 verbose(env, "R%d leaks addr into helper function\n", 6619 regno); 6620 return -EACCES; 6621 } 6622 return 0; 6623 } 6624 6625 if (type_is_pkt_pointer(type) && 6626 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 6627 verbose(env, "helper access to the packet is not allowed\n"); 6628 return -EACCES; 6629 } 6630 6631 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 6632 err = resolve_map_arg_type(env, meta, &arg_type); 6633 if (err) 6634 return err; 6635 } 6636 6637 if (register_is_null(reg) && type_may_be_null(arg_type)) 6638 /* A NULL register has a SCALAR_VALUE type, so skip 6639 * type checking. 6640 */ 6641 goto skip_type_check; 6642 6643 /* arg_btf_id and arg_size are in a union. */ 6644 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 6645 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 6646 arg_btf_id = fn->arg_btf_id[arg]; 6647 6648 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 6649 if (err) 6650 return err; 6651 6652 err = check_func_arg_reg_off(env, reg, regno, arg_type); 6653 if (err) 6654 return err; 6655 6656 skip_type_check: 6657 if (arg_type_is_release(arg_type)) { 6658 if (arg_type_is_dynptr(arg_type)) { 6659 struct bpf_func_state *state = func(env, reg); 6660 int spi; 6661 6662 /* Only dynptr created on stack can be released, thus 6663 * the get_spi and stack state checks for spilled_ptr 6664 * should only be done before process_dynptr_func for 6665 * PTR_TO_STACK. 6666 */ 6667 if (reg->type == PTR_TO_STACK) { 6668 spi = dynptr_get_spi(env, reg); 6669 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 6670 verbose(env, "arg %d is an unacquired reference\n", regno); 6671 return -EINVAL; 6672 } 6673 } else { 6674 verbose(env, "cannot release unowned const bpf_dynptr\n"); 6675 return -EINVAL; 6676 } 6677 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 6678 verbose(env, "R%d must be referenced when passed to release function\n", 6679 regno); 6680 return -EINVAL; 6681 } 6682 if (meta->release_regno) { 6683 verbose(env, "verifier internal error: more than one release argument\n"); 6684 return -EFAULT; 6685 } 6686 meta->release_regno = regno; 6687 } 6688 6689 if (reg->ref_obj_id) { 6690 if (meta->ref_obj_id) { 6691 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 6692 regno, reg->ref_obj_id, 6693 meta->ref_obj_id); 6694 return -EFAULT; 6695 } 6696 meta->ref_obj_id = reg->ref_obj_id; 6697 } 6698 6699 switch (base_type(arg_type)) { 6700 case ARG_CONST_MAP_PTR: 6701 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 6702 if (meta->map_ptr) { 6703 /* Use map_uid (which is unique id of inner map) to reject: 6704 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 6705 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 6706 * if (inner_map1 && inner_map2) { 6707 * timer = bpf_map_lookup_elem(inner_map1); 6708 * if (timer) 6709 * // mismatch would have been allowed 6710 * bpf_timer_init(timer, inner_map2); 6711 * } 6712 * 6713 * Comparing map_ptr is enough to distinguish normal and outer maps. 6714 */ 6715 if (meta->map_ptr != reg->map_ptr || 6716 meta->map_uid != reg->map_uid) { 6717 verbose(env, 6718 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 6719 meta->map_uid, reg->map_uid); 6720 return -EINVAL; 6721 } 6722 } 6723 meta->map_ptr = reg->map_ptr; 6724 meta->map_uid = reg->map_uid; 6725 break; 6726 case ARG_PTR_TO_MAP_KEY: 6727 /* bpf_map_xxx(..., map_ptr, ..., key) call: 6728 * check that [key, key + map->key_size) are within 6729 * stack limits and initialized 6730 */ 6731 if (!meta->map_ptr) { 6732 /* in function declaration map_ptr must come before 6733 * map_key, so that it's verified and known before 6734 * we have to check map_key here. Otherwise it means 6735 * that kernel subsystem misconfigured verifier 6736 */ 6737 verbose(env, "invalid map_ptr to access map->key\n"); 6738 return -EACCES; 6739 } 6740 err = check_helper_mem_access(env, regno, 6741 meta->map_ptr->key_size, false, 6742 NULL); 6743 break; 6744 case ARG_PTR_TO_MAP_VALUE: 6745 if (type_may_be_null(arg_type) && register_is_null(reg)) 6746 return 0; 6747 6748 /* bpf_map_xxx(..., map_ptr, ..., value) call: 6749 * check [value, value + map->value_size) validity 6750 */ 6751 if (!meta->map_ptr) { 6752 /* kernel subsystem misconfigured verifier */ 6753 verbose(env, "invalid map_ptr to access map->value\n"); 6754 return -EACCES; 6755 } 6756 meta->raw_mode = arg_type & MEM_UNINIT; 6757 err = check_helper_mem_access(env, regno, 6758 meta->map_ptr->value_size, false, 6759 meta); 6760 break; 6761 case ARG_PTR_TO_PERCPU_BTF_ID: 6762 if (!reg->btf_id) { 6763 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 6764 return -EACCES; 6765 } 6766 meta->ret_btf = reg->btf; 6767 meta->ret_btf_id = reg->btf_id; 6768 break; 6769 case ARG_PTR_TO_SPIN_LOCK: 6770 if (meta->func_id == BPF_FUNC_spin_lock) { 6771 err = process_spin_lock(env, regno, true); 6772 if (err) 6773 return err; 6774 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 6775 err = process_spin_lock(env, regno, false); 6776 if (err) 6777 return err; 6778 } else { 6779 verbose(env, "verifier internal error\n"); 6780 return -EFAULT; 6781 } 6782 break; 6783 case ARG_PTR_TO_TIMER: 6784 err = process_timer_func(env, regno, meta); 6785 if (err) 6786 return err; 6787 break; 6788 case ARG_PTR_TO_FUNC: 6789 meta->subprogno = reg->subprogno; 6790 break; 6791 case ARG_PTR_TO_MEM: 6792 /* The access to this pointer is only checked when we hit the 6793 * next is_mem_size argument below. 6794 */ 6795 meta->raw_mode = arg_type & MEM_UNINIT; 6796 if (arg_type & MEM_FIXED_SIZE) { 6797 err = check_helper_mem_access(env, regno, 6798 fn->arg_size[arg], false, 6799 meta); 6800 } 6801 break; 6802 case ARG_CONST_SIZE: 6803 err = check_mem_size_reg(env, reg, regno, false, meta); 6804 break; 6805 case ARG_CONST_SIZE_OR_ZERO: 6806 err = check_mem_size_reg(env, reg, regno, true, meta); 6807 break; 6808 case ARG_PTR_TO_DYNPTR: 6809 err = process_dynptr_func(env, regno, arg_type, meta); 6810 if (err) 6811 return err; 6812 break; 6813 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 6814 if (!tnum_is_const(reg->var_off)) { 6815 verbose(env, "R%d is not a known constant'\n", 6816 regno); 6817 return -EACCES; 6818 } 6819 meta->mem_size = reg->var_off.value; 6820 err = mark_chain_precision(env, regno); 6821 if (err) 6822 return err; 6823 break; 6824 case ARG_PTR_TO_INT: 6825 case ARG_PTR_TO_LONG: 6826 { 6827 int size = int_ptr_type_to_size(arg_type); 6828 6829 err = check_helper_mem_access(env, regno, size, false, meta); 6830 if (err) 6831 return err; 6832 err = check_ptr_alignment(env, reg, 0, size, true); 6833 break; 6834 } 6835 case ARG_PTR_TO_CONST_STR: 6836 { 6837 struct bpf_map *map = reg->map_ptr; 6838 int map_off; 6839 u64 map_addr; 6840 char *str_ptr; 6841 6842 if (!bpf_map_is_rdonly(map)) { 6843 verbose(env, "R%d does not point to a readonly map'\n", regno); 6844 return -EACCES; 6845 } 6846 6847 if (!tnum_is_const(reg->var_off)) { 6848 verbose(env, "R%d is not a constant address'\n", regno); 6849 return -EACCES; 6850 } 6851 6852 if (!map->ops->map_direct_value_addr) { 6853 verbose(env, "no direct value access support for this map type\n"); 6854 return -EACCES; 6855 } 6856 6857 err = check_map_access(env, regno, reg->off, 6858 map->value_size - reg->off, false, 6859 ACCESS_HELPER); 6860 if (err) 6861 return err; 6862 6863 map_off = reg->off + reg->var_off.value; 6864 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 6865 if (err) { 6866 verbose(env, "direct value access on string failed\n"); 6867 return err; 6868 } 6869 6870 str_ptr = (char *)(long)(map_addr); 6871 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 6872 verbose(env, "string is not zero-terminated\n"); 6873 return -EINVAL; 6874 } 6875 break; 6876 } 6877 case ARG_PTR_TO_KPTR: 6878 err = process_kptr_func(env, regno, meta); 6879 if (err) 6880 return err; 6881 break; 6882 } 6883 6884 return err; 6885 } 6886 6887 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 6888 { 6889 enum bpf_attach_type eatype = env->prog->expected_attach_type; 6890 enum bpf_prog_type type = resolve_prog_type(env->prog); 6891 6892 if (func_id != BPF_FUNC_map_update_elem) 6893 return false; 6894 6895 /* It's not possible to get access to a locked struct sock in these 6896 * contexts, so updating is safe. 6897 */ 6898 switch (type) { 6899 case BPF_PROG_TYPE_TRACING: 6900 if (eatype == BPF_TRACE_ITER) 6901 return true; 6902 break; 6903 case BPF_PROG_TYPE_SOCKET_FILTER: 6904 case BPF_PROG_TYPE_SCHED_CLS: 6905 case BPF_PROG_TYPE_SCHED_ACT: 6906 case BPF_PROG_TYPE_XDP: 6907 case BPF_PROG_TYPE_SK_REUSEPORT: 6908 case BPF_PROG_TYPE_FLOW_DISSECTOR: 6909 case BPF_PROG_TYPE_SK_LOOKUP: 6910 return true; 6911 default: 6912 break; 6913 } 6914 6915 verbose(env, "cannot update sockmap in this context\n"); 6916 return false; 6917 } 6918 6919 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 6920 { 6921 return env->prog->jit_requested && 6922 bpf_jit_supports_subprog_tailcalls(); 6923 } 6924 6925 static int check_map_func_compatibility(struct bpf_verifier_env *env, 6926 struct bpf_map *map, int func_id) 6927 { 6928 if (!map) 6929 return 0; 6930 6931 /* We need a two way check, first is from map perspective ... */ 6932 switch (map->map_type) { 6933 case BPF_MAP_TYPE_PROG_ARRAY: 6934 if (func_id != BPF_FUNC_tail_call) 6935 goto error; 6936 break; 6937 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 6938 if (func_id != BPF_FUNC_perf_event_read && 6939 func_id != BPF_FUNC_perf_event_output && 6940 func_id != BPF_FUNC_skb_output && 6941 func_id != BPF_FUNC_perf_event_read_value && 6942 func_id != BPF_FUNC_xdp_output) 6943 goto error; 6944 break; 6945 case BPF_MAP_TYPE_RINGBUF: 6946 if (func_id != BPF_FUNC_ringbuf_output && 6947 func_id != BPF_FUNC_ringbuf_reserve && 6948 func_id != BPF_FUNC_ringbuf_query && 6949 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 6950 func_id != BPF_FUNC_ringbuf_submit_dynptr && 6951 func_id != BPF_FUNC_ringbuf_discard_dynptr) 6952 goto error; 6953 break; 6954 case BPF_MAP_TYPE_USER_RINGBUF: 6955 if (func_id != BPF_FUNC_user_ringbuf_drain) 6956 goto error; 6957 break; 6958 case BPF_MAP_TYPE_STACK_TRACE: 6959 if (func_id != BPF_FUNC_get_stackid) 6960 goto error; 6961 break; 6962 case BPF_MAP_TYPE_CGROUP_ARRAY: 6963 if (func_id != BPF_FUNC_skb_under_cgroup && 6964 func_id != BPF_FUNC_current_task_under_cgroup) 6965 goto error; 6966 break; 6967 case BPF_MAP_TYPE_CGROUP_STORAGE: 6968 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 6969 if (func_id != BPF_FUNC_get_local_storage) 6970 goto error; 6971 break; 6972 case BPF_MAP_TYPE_DEVMAP: 6973 case BPF_MAP_TYPE_DEVMAP_HASH: 6974 if (func_id != BPF_FUNC_redirect_map && 6975 func_id != BPF_FUNC_map_lookup_elem) 6976 goto error; 6977 break; 6978 /* Restrict bpf side of cpumap and xskmap, open when use-cases 6979 * appear. 6980 */ 6981 case BPF_MAP_TYPE_CPUMAP: 6982 if (func_id != BPF_FUNC_redirect_map) 6983 goto error; 6984 break; 6985 case BPF_MAP_TYPE_XSKMAP: 6986 if (func_id != BPF_FUNC_redirect_map && 6987 func_id != BPF_FUNC_map_lookup_elem) 6988 goto error; 6989 break; 6990 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 6991 case BPF_MAP_TYPE_HASH_OF_MAPS: 6992 if (func_id != BPF_FUNC_map_lookup_elem) 6993 goto error; 6994 break; 6995 case BPF_MAP_TYPE_SOCKMAP: 6996 if (func_id != BPF_FUNC_sk_redirect_map && 6997 func_id != BPF_FUNC_sock_map_update && 6998 func_id != BPF_FUNC_map_delete_elem && 6999 func_id != BPF_FUNC_msg_redirect_map && 7000 func_id != BPF_FUNC_sk_select_reuseport && 7001 func_id != BPF_FUNC_map_lookup_elem && 7002 !may_update_sockmap(env, func_id)) 7003 goto error; 7004 break; 7005 case BPF_MAP_TYPE_SOCKHASH: 7006 if (func_id != BPF_FUNC_sk_redirect_hash && 7007 func_id != BPF_FUNC_sock_hash_update && 7008 func_id != BPF_FUNC_map_delete_elem && 7009 func_id != BPF_FUNC_msg_redirect_hash && 7010 func_id != BPF_FUNC_sk_select_reuseport && 7011 func_id != BPF_FUNC_map_lookup_elem && 7012 !may_update_sockmap(env, func_id)) 7013 goto error; 7014 break; 7015 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 7016 if (func_id != BPF_FUNC_sk_select_reuseport) 7017 goto error; 7018 break; 7019 case BPF_MAP_TYPE_QUEUE: 7020 case BPF_MAP_TYPE_STACK: 7021 if (func_id != BPF_FUNC_map_peek_elem && 7022 func_id != BPF_FUNC_map_pop_elem && 7023 func_id != BPF_FUNC_map_push_elem) 7024 goto error; 7025 break; 7026 case BPF_MAP_TYPE_SK_STORAGE: 7027 if (func_id != BPF_FUNC_sk_storage_get && 7028 func_id != BPF_FUNC_sk_storage_delete) 7029 goto error; 7030 break; 7031 case BPF_MAP_TYPE_INODE_STORAGE: 7032 if (func_id != BPF_FUNC_inode_storage_get && 7033 func_id != BPF_FUNC_inode_storage_delete) 7034 goto error; 7035 break; 7036 case BPF_MAP_TYPE_TASK_STORAGE: 7037 if (func_id != BPF_FUNC_task_storage_get && 7038 func_id != BPF_FUNC_task_storage_delete) 7039 goto error; 7040 break; 7041 case BPF_MAP_TYPE_CGRP_STORAGE: 7042 if (func_id != BPF_FUNC_cgrp_storage_get && 7043 func_id != BPF_FUNC_cgrp_storage_delete) 7044 goto error; 7045 break; 7046 case BPF_MAP_TYPE_BLOOM_FILTER: 7047 if (func_id != BPF_FUNC_map_peek_elem && 7048 func_id != BPF_FUNC_map_push_elem) 7049 goto error; 7050 break; 7051 default: 7052 break; 7053 } 7054 7055 /* ... and second from the function itself. */ 7056 switch (func_id) { 7057 case BPF_FUNC_tail_call: 7058 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 7059 goto error; 7060 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 7061 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 7062 return -EINVAL; 7063 } 7064 break; 7065 case BPF_FUNC_perf_event_read: 7066 case BPF_FUNC_perf_event_output: 7067 case BPF_FUNC_perf_event_read_value: 7068 case BPF_FUNC_skb_output: 7069 case BPF_FUNC_xdp_output: 7070 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 7071 goto error; 7072 break; 7073 case BPF_FUNC_ringbuf_output: 7074 case BPF_FUNC_ringbuf_reserve: 7075 case BPF_FUNC_ringbuf_query: 7076 case BPF_FUNC_ringbuf_reserve_dynptr: 7077 case BPF_FUNC_ringbuf_submit_dynptr: 7078 case BPF_FUNC_ringbuf_discard_dynptr: 7079 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 7080 goto error; 7081 break; 7082 case BPF_FUNC_user_ringbuf_drain: 7083 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 7084 goto error; 7085 break; 7086 case BPF_FUNC_get_stackid: 7087 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 7088 goto error; 7089 break; 7090 case BPF_FUNC_current_task_under_cgroup: 7091 case BPF_FUNC_skb_under_cgroup: 7092 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 7093 goto error; 7094 break; 7095 case BPF_FUNC_redirect_map: 7096 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 7097 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 7098 map->map_type != BPF_MAP_TYPE_CPUMAP && 7099 map->map_type != BPF_MAP_TYPE_XSKMAP) 7100 goto error; 7101 break; 7102 case BPF_FUNC_sk_redirect_map: 7103 case BPF_FUNC_msg_redirect_map: 7104 case BPF_FUNC_sock_map_update: 7105 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 7106 goto error; 7107 break; 7108 case BPF_FUNC_sk_redirect_hash: 7109 case BPF_FUNC_msg_redirect_hash: 7110 case BPF_FUNC_sock_hash_update: 7111 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 7112 goto error; 7113 break; 7114 case BPF_FUNC_get_local_storage: 7115 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 7116 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 7117 goto error; 7118 break; 7119 case BPF_FUNC_sk_select_reuseport: 7120 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 7121 map->map_type != BPF_MAP_TYPE_SOCKMAP && 7122 map->map_type != BPF_MAP_TYPE_SOCKHASH) 7123 goto error; 7124 break; 7125 case BPF_FUNC_map_pop_elem: 7126 if (map->map_type != BPF_MAP_TYPE_QUEUE && 7127 map->map_type != BPF_MAP_TYPE_STACK) 7128 goto error; 7129 break; 7130 case BPF_FUNC_map_peek_elem: 7131 case BPF_FUNC_map_push_elem: 7132 if (map->map_type != BPF_MAP_TYPE_QUEUE && 7133 map->map_type != BPF_MAP_TYPE_STACK && 7134 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 7135 goto error; 7136 break; 7137 case BPF_FUNC_map_lookup_percpu_elem: 7138 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 7139 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 7140 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 7141 goto error; 7142 break; 7143 case BPF_FUNC_sk_storage_get: 7144 case BPF_FUNC_sk_storage_delete: 7145 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 7146 goto error; 7147 break; 7148 case BPF_FUNC_inode_storage_get: 7149 case BPF_FUNC_inode_storage_delete: 7150 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 7151 goto error; 7152 break; 7153 case BPF_FUNC_task_storage_get: 7154 case BPF_FUNC_task_storage_delete: 7155 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 7156 goto error; 7157 break; 7158 case BPF_FUNC_cgrp_storage_get: 7159 case BPF_FUNC_cgrp_storage_delete: 7160 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 7161 goto error; 7162 break; 7163 default: 7164 break; 7165 } 7166 7167 return 0; 7168 error: 7169 verbose(env, "cannot pass map_type %d into func %s#%d\n", 7170 map->map_type, func_id_name(func_id), func_id); 7171 return -EINVAL; 7172 } 7173 7174 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 7175 { 7176 int count = 0; 7177 7178 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 7179 count++; 7180 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 7181 count++; 7182 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 7183 count++; 7184 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 7185 count++; 7186 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 7187 count++; 7188 7189 /* We only support one arg being in raw mode at the moment, 7190 * which is sufficient for the helper functions we have 7191 * right now. 7192 */ 7193 return count <= 1; 7194 } 7195 7196 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 7197 { 7198 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 7199 bool has_size = fn->arg_size[arg] != 0; 7200 bool is_next_size = false; 7201 7202 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 7203 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 7204 7205 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 7206 return is_next_size; 7207 7208 return has_size == is_next_size || is_next_size == is_fixed; 7209 } 7210 7211 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 7212 { 7213 /* bpf_xxx(..., buf, len) call will access 'len' 7214 * bytes from memory 'buf'. Both arg types need 7215 * to be paired, so make sure there's no buggy 7216 * helper function specification. 7217 */ 7218 if (arg_type_is_mem_size(fn->arg1_type) || 7219 check_args_pair_invalid(fn, 0) || 7220 check_args_pair_invalid(fn, 1) || 7221 check_args_pair_invalid(fn, 2) || 7222 check_args_pair_invalid(fn, 3) || 7223 check_args_pair_invalid(fn, 4)) 7224 return false; 7225 7226 return true; 7227 } 7228 7229 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 7230 { 7231 int i; 7232 7233 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 7234 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 7235 return !!fn->arg_btf_id[i]; 7236 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 7237 return fn->arg_btf_id[i] == BPF_PTR_POISON; 7238 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 7239 /* arg_btf_id and arg_size are in a union. */ 7240 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 7241 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 7242 return false; 7243 } 7244 7245 return true; 7246 } 7247 7248 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 7249 { 7250 return check_raw_mode_ok(fn) && 7251 check_arg_pair_ok(fn) && 7252 check_btf_id_ok(fn) ? 0 : -EINVAL; 7253 } 7254 7255 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 7256 * are now invalid, so turn them into unknown SCALAR_VALUE. 7257 */ 7258 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 7259 { 7260 struct bpf_func_state *state; 7261 struct bpf_reg_state *reg; 7262 7263 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 7264 if (reg_is_pkt_pointer_any(reg)) 7265 __mark_reg_unknown(env, reg); 7266 })); 7267 } 7268 7269 enum { 7270 AT_PKT_END = -1, 7271 BEYOND_PKT_END = -2, 7272 }; 7273 7274 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 7275 { 7276 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7277 struct bpf_reg_state *reg = &state->regs[regn]; 7278 7279 if (reg->type != PTR_TO_PACKET) 7280 /* PTR_TO_PACKET_META is not supported yet */ 7281 return; 7282 7283 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 7284 * How far beyond pkt_end it goes is unknown. 7285 * if (!range_open) it's the case of pkt >= pkt_end 7286 * if (range_open) it's the case of pkt > pkt_end 7287 * hence this pointer is at least 1 byte bigger than pkt_end 7288 */ 7289 if (range_open) 7290 reg->range = BEYOND_PKT_END; 7291 else 7292 reg->range = AT_PKT_END; 7293 } 7294 7295 /* The pointer with the specified id has released its reference to kernel 7296 * resources. Identify all copies of the same pointer and clear the reference. 7297 */ 7298 static int release_reference(struct bpf_verifier_env *env, 7299 int ref_obj_id) 7300 { 7301 struct bpf_func_state *state; 7302 struct bpf_reg_state *reg; 7303 int err; 7304 7305 err = release_reference_state(cur_func(env), ref_obj_id); 7306 if (err) 7307 return err; 7308 7309 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 7310 if (reg->ref_obj_id == ref_obj_id) { 7311 if (!env->allow_ptr_leaks) 7312 __mark_reg_not_init(env, reg); 7313 else 7314 __mark_reg_unknown(env, reg); 7315 } 7316 })); 7317 7318 return 0; 7319 } 7320 7321 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 7322 struct bpf_reg_state *regs) 7323 { 7324 int i; 7325 7326 /* after the call registers r0 - r5 were scratched */ 7327 for (i = 0; i < CALLER_SAVED_REGS; i++) { 7328 mark_reg_not_init(env, regs, caller_saved[i]); 7329 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 7330 } 7331 } 7332 7333 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 7334 struct bpf_func_state *caller, 7335 struct bpf_func_state *callee, 7336 int insn_idx); 7337 7338 static int set_callee_state(struct bpf_verifier_env *env, 7339 struct bpf_func_state *caller, 7340 struct bpf_func_state *callee, int insn_idx); 7341 7342 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7343 int *insn_idx, int subprog, 7344 set_callee_state_fn set_callee_state_cb) 7345 { 7346 struct bpf_verifier_state *state = env->cur_state; 7347 struct bpf_func_info_aux *func_info_aux; 7348 struct bpf_func_state *caller, *callee; 7349 int err; 7350 bool is_global = false; 7351 7352 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 7353 verbose(env, "the call stack of %d frames is too deep\n", 7354 state->curframe + 2); 7355 return -E2BIG; 7356 } 7357 7358 caller = state->frame[state->curframe]; 7359 if (state->frame[state->curframe + 1]) { 7360 verbose(env, "verifier bug. Frame %d already allocated\n", 7361 state->curframe + 1); 7362 return -EFAULT; 7363 } 7364 7365 func_info_aux = env->prog->aux->func_info_aux; 7366 if (func_info_aux) 7367 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 7368 err = btf_check_subprog_call(env, subprog, caller->regs); 7369 if (err == -EFAULT) 7370 return err; 7371 if (is_global) { 7372 if (err) { 7373 verbose(env, "Caller passes invalid args into func#%d\n", 7374 subprog); 7375 return err; 7376 } else { 7377 if (env->log.level & BPF_LOG_LEVEL) 7378 verbose(env, 7379 "Func#%d is global and valid. Skipping.\n", 7380 subprog); 7381 clear_caller_saved_regs(env, caller->regs); 7382 7383 /* All global functions return a 64-bit SCALAR_VALUE */ 7384 mark_reg_unknown(env, caller->regs, BPF_REG_0); 7385 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 7386 7387 /* continue with next insn after call */ 7388 return 0; 7389 } 7390 } 7391 7392 /* set_callee_state is used for direct subprog calls, but we are 7393 * interested in validating only BPF helpers that can call subprogs as 7394 * callbacks 7395 */ 7396 if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) { 7397 verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n", 7398 func_id_name(insn->imm), insn->imm); 7399 return -EFAULT; 7400 } 7401 7402 if (insn->code == (BPF_JMP | BPF_CALL) && 7403 insn->src_reg == 0 && 7404 insn->imm == BPF_FUNC_timer_set_callback) { 7405 struct bpf_verifier_state *async_cb; 7406 7407 /* there is no real recursion here. timer callbacks are async */ 7408 env->subprog_info[subprog].is_async_cb = true; 7409 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 7410 *insn_idx, subprog); 7411 if (!async_cb) 7412 return -EFAULT; 7413 callee = async_cb->frame[0]; 7414 callee->async_entry_cnt = caller->async_entry_cnt + 1; 7415 7416 /* Convert bpf_timer_set_callback() args into timer callback args */ 7417 err = set_callee_state_cb(env, caller, callee, *insn_idx); 7418 if (err) 7419 return err; 7420 7421 clear_caller_saved_regs(env, caller->regs); 7422 mark_reg_unknown(env, caller->regs, BPF_REG_0); 7423 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 7424 /* continue with next insn after call */ 7425 return 0; 7426 } 7427 7428 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 7429 if (!callee) 7430 return -ENOMEM; 7431 state->frame[state->curframe + 1] = callee; 7432 7433 /* callee cannot access r0, r6 - r9 for reading and has to write 7434 * into its own stack before reading from it. 7435 * callee can read/write into caller's stack 7436 */ 7437 init_func_state(env, callee, 7438 /* remember the callsite, it will be used by bpf_exit */ 7439 *insn_idx /* callsite */, 7440 state->curframe + 1 /* frameno within this callchain */, 7441 subprog /* subprog number within this prog */); 7442 7443 /* Transfer references to the callee */ 7444 err = copy_reference_state(callee, caller); 7445 if (err) 7446 goto err_out; 7447 7448 err = set_callee_state_cb(env, caller, callee, *insn_idx); 7449 if (err) 7450 goto err_out; 7451 7452 clear_caller_saved_regs(env, caller->regs); 7453 7454 /* only increment it after check_reg_arg() finished */ 7455 state->curframe++; 7456 7457 /* and go analyze first insn of the callee */ 7458 *insn_idx = env->subprog_info[subprog].start - 1; 7459 7460 if (env->log.level & BPF_LOG_LEVEL) { 7461 verbose(env, "caller:\n"); 7462 print_verifier_state(env, caller, true); 7463 verbose(env, "callee:\n"); 7464 print_verifier_state(env, callee, true); 7465 } 7466 return 0; 7467 7468 err_out: 7469 free_func_state(callee); 7470 state->frame[state->curframe + 1] = NULL; 7471 return err; 7472 } 7473 7474 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 7475 struct bpf_func_state *caller, 7476 struct bpf_func_state *callee) 7477 { 7478 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 7479 * void *callback_ctx, u64 flags); 7480 * callback_fn(struct bpf_map *map, void *key, void *value, 7481 * void *callback_ctx); 7482 */ 7483 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 7484 7485 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 7486 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7487 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 7488 7489 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 7490 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 7491 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 7492 7493 /* pointer to stack or null */ 7494 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 7495 7496 /* unused */ 7497 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7498 return 0; 7499 } 7500 7501 static int set_callee_state(struct bpf_verifier_env *env, 7502 struct bpf_func_state *caller, 7503 struct bpf_func_state *callee, int insn_idx) 7504 { 7505 int i; 7506 7507 /* copy r1 - r5 args that callee can access. The copy includes parent 7508 * pointers, which connects us up to the liveness chain 7509 */ 7510 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 7511 callee->regs[i] = caller->regs[i]; 7512 return 0; 7513 } 7514 7515 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7516 int *insn_idx) 7517 { 7518 int subprog, target_insn; 7519 7520 target_insn = *insn_idx + insn->imm + 1; 7521 subprog = find_subprog(env, target_insn); 7522 if (subprog < 0) { 7523 verbose(env, "verifier bug. No program starts at insn %d\n", 7524 target_insn); 7525 return -EFAULT; 7526 } 7527 7528 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 7529 } 7530 7531 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 7532 struct bpf_func_state *caller, 7533 struct bpf_func_state *callee, 7534 int insn_idx) 7535 { 7536 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 7537 struct bpf_map *map; 7538 int err; 7539 7540 if (bpf_map_ptr_poisoned(insn_aux)) { 7541 verbose(env, "tail_call abusing map_ptr\n"); 7542 return -EINVAL; 7543 } 7544 7545 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 7546 if (!map->ops->map_set_for_each_callback_args || 7547 !map->ops->map_for_each_callback) { 7548 verbose(env, "callback function not allowed for map\n"); 7549 return -ENOTSUPP; 7550 } 7551 7552 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 7553 if (err) 7554 return err; 7555 7556 callee->in_callback_fn = true; 7557 callee->callback_ret_range = tnum_range(0, 1); 7558 return 0; 7559 } 7560 7561 static int set_loop_callback_state(struct bpf_verifier_env *env, 7562 struct bpf_func_state *caller, 7563 struct bpf_func_state *callee, 7564 int insn_idx) 7565 { 7566 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 7567 * u64 flags); 7568 * callback_fn(u32 index, void *callback_ctx); 7569 */ 7570 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 7571 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 7572 7573 /* unused */ 7574 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 7575 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7576 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7577 7578 callee->in_callback_fn = true; 7579 callee->callback_ret_range = tnum_range(0, 1); 7580 return 0; 7581 } 7582 7583 static int set_timer_callback_state(struct bpf_verifier_env *env, 7584 struct bpf_func_state *caller, 7585 struct bpf_func_state *callee, 7586 int insn_idx) 7587 { 7588 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 7589 7590 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 7591 * callback_fn(struct bpf_map *map, void *key, void *value); 7592 */ 7593 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 7594 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 7595 callee->regs[BPF_REG_1].map_ptr = map_ptr; 7596 7597 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 7598 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7599 callee->regs[BPF_REG_2].map_ptr = map_ptr; 7600 7601 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 7602 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 7603 callee->regs[BPF_REG_3].map_ptr = map_ptr; 7604 7605 /* unused */ 7606 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7607 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7608 callee->in_async_callback_fn = true; 7609 callee->callback_ret_range = tnum_range(0, 1); 7610 return 0; 7611 } 7612 7613 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 7614 struct bpf_func_state *caller, 7615 struct bpf_func_state *callee, 7616 int insn_idx) 7617 { 7618 /* bpf_find_vma(struct task_struct *task, u64 addr, 7619 * void *callback_fn, void *callback_ctx, u64 flags) 7620 * (callback_fn)(struct task_struct *task, 7621 * struct vm_area_struct *vma, void *callback_ctx); 7622 */ 7623 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 7624 7625 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 7626 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7627 callee->regs[BPF_REG_2].btf = btf_vmlinux; 7628 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 7629 7630 /* pointer to stack or null */ 7631 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 7632 7633 /* unused */ 7634 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7635 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7636 callee->in_callback_fn = true; 7637 callee->callback_ret_range = tnum_range(0, 1); 7638 return 0; 7639 } 7640 7641 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 7642 struct bpf_func_state *caller, 7643 struct bpf_func_state *callee, 7644 int insn_idx) 7645 { 7646 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 7647 * callback_ctx, u64 flags); 7648 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 7649 */ 7650 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 7651 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 7652 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 7653 7654 /* unused */ 7655 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 7656 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7657 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7658 7659 callee->in_callback_fn = true; 7660 callee->callback_ret_range = tnum_range(0, 1); 7661 return 0; 7662 } 7663 7664 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 7665 { 7666 struct bpf_verifier_state *state = env->cur_state; 7667 struct bpf_func_state *caller, *callee; 7668 struct bpf_reg_state *r0; 7669 int err; 7670 7671 callee = state->frame[state->curframe]; 7672 r0 = &callee->regs[BPF_REG_0]; 7673 if (r0->type == PTR_TO_STACK) { 7674 /* technically it's ok to return caller's stack pointer 7675 * (or caller's caller's pointer) back to the caller, 7676 * since these pointers are valid. Only current stack 7677 * pointer will be invalid as soon as function exits, 7678 * but let's be conservative 7679 */ 7680 verbose(env, "cannot return stack pointer to the caller\n"); 7681 return -EINVAL; 7682 } 7683 7684 caller = state->frame[state->curframe - 1]; 7685 if (callee->in_callback_fn) { 7686 /* enforce R0 return value range [0, 1]. */ 7687 struct tnum range = callee->callback_ret_range; 7688 7689 if (r0->type != SCALAR_VALUE) { 7690 verbose(env, "R0 not a scalar value\n"); 7691 return -EACCES; 7692 } 7693 if (!tnum_in(range, r0->var_off)) { 7694 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 7695 return -EINVAL; 7696 } 7697 } else { 7698 /* return to the caller whatever r0 had in the callee */ 7699 caller->regs[BPF_REG_0] = *r0; 7700 } 7701 7702 /* callback_fn frame should have released its own additions to parent's 7703 * reference state at this point, or check_reference_leak would 7704 * complain, hence it must be the same as the caller. There is no need 7705 * to copy it back. 7706 */ 7707 if (!callee->in_callback_fn) { 7708 /* Transfer references to the caller */ 7709 err = copy_reference_state(caller, callee); 7710 if (err) 7711 return err; 7712 } 7713 7714 *insn_idx = callee->callsite + 1; 7715 if (env->log.level & BPF_LOG_LEVEL) { 7716 verbose(env, "returning from callee:\n"); 7717 print_verifier_state(env, callee, true); 7718 verbose(env, "to caller at %d:\n", *insn_idx); 7719 print_verifier_state(env, caller, true); 7720 } 7721 /* clear everything in the callee */ 7722 free_func_state(callee); 7723 state->frame[state->curframe--] = NULL; 7724 return 0; 7725 } 7726 7727 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 7728 int func_id, 7729 struct bpf_call_arg_meta *meta) 7730 { 7731 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 7732 7733 if (ret_type != RET_INTEGER || 7734 (func_id != BPF_FUNC_get_stack && 7735 func_id != BPF_FUNC_get_task_stack && 7736 func_id != BPF_FUNC_probe_read_str && 7737 func_id != BPF_FUNC_probe_read_kernel_str && 7738 func_id != BPF_FUNC_probe_read_user_str)) 7739 return; 7740 7741 ret_reg->smax_value = meta->msize_max_value; 7742 ret_reg->s32_max_value = meta->msize_max_value; 7743 ret_reg->smin_value = -MAX_ERRNO; 7744 ret_reg->s32_min_value = -MAX_ERRNO; 7745 reg_bounds_sync(ret_reg); 7746 } 7747 7748 static int 7749 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 7750 int func_id, int insn_idx) 7751 { 7752 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 7753 struct bpf_map *map = meta->map_ptr; 7754 7755 if (func_id != BPF_FUNC_tail_call && 7756 func_id != BPF_FUNC_map_lookup_elem && 7757 func_id != BPF_FUNC_map_update_elem && 7758 func_id != BPF_FUNC_map_delete_elem && 7759 func_id != BPF_FUNC_map_push_elem && 7760 func_id != BPF_FUNC_map_pop_elem && 7761 func_id != BPF_FUNC_map_peek_elem && 7762 func_id != BPF_FUNC_for_each_map_elem && 7763 func_id != BPF_FUNC_redirect_map && 7764 func_id != BPF_FUNC_map_lookup_percpu_elem) 7765 return 0; 7766 7767 if (map == NULL) { 7768 verbose(env, "kernel subsystem misconfigured verifier\n"); 7769 return -EINVAL; 7770 } 7771 7772 /* In case of read-only, some additional restrictions 7773 * need to be applied in order to prevent altering the 7774 * state of the map from program side. 7775 */ 7776 if ((map->map_flags & BPF_F_RDONLY_PROG) && 7777 (func_id == BPF_FUNC_map_delete_elem || 7778 func_id == BPF_FUNC_map_update_elem || 7779 func_id == BPF_FUNC_map_push_elem || 7780 func_id == BPF_FUNC_map_pop_elem)) { 7781 verbose(env, "write into map forbidden\n"); 7782 return -EACCES; 7783 } 7784 7785 if (!BPF_MAP_PTR(aux->map_ptr_state)) 7786 bpf_map_ptr_store(aux, meta->map_ptr, 7787 !meta->map_ptr->bypass_spec_v1); 7788 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 7789 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 7790 !meta->map_ptr->bypass_spec_v1); 7791 return 0; 7792 } 7793 7794 static int 7795 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 7796 int func_id, int insn_idx) 7797 { 7798 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 7799 struct bpf_reg_state *regs = cur_regs(env), *reg; 7800 struct bpf_map *map = meta->map_ptr; 7801 u64 val, max; 7802 int err; 7803 7804 if (func_id != BPF_FUNC_tail_call) 7805 return 0; 7806 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 7807 verbose(env, "kernel subsystem misconfigured verifier\n"); 7808 return -EINVAL; 7809 } 7810 7811 reg = ®s[BPF_REG_3]; 7812 val = reg->var_off.value; 7813 max = map->max_entries; 7814 7815 if (!(register_is_const(reg) && val < max)) { 7816 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 7817 return 0; 7818 } 7819 7820 err = mark_chain_precision(env, BPF_REG_3); 7821 if (err) 7822 return err; 7823 if (bpf_map_key_unseen(aux)) 7824 bpf_map_key_store(aux, val); 7825 else if (!bpf_map_key_poisoned(aux) && 7826 bpf_map_key_immediate(aux) != val) 7827 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 7828 return 0; 7829 } 7830 7831 static int check_reference_leak(struct bpf_verifier_env *env) 7832 { 7833 struct bpf_func_state *state = cur_func(env); 7834 bool refs_lingering = false; 7835 int i; 7836 7837 if (state->frameno && !state->in_callback_fn) 7838 return 0; 7839 7840 for (i = 0; i < state->acquired_refs; i++) { 7841 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 7842 continue; 7843 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 7844 state->refs[i].id, state->refs[i].insn_idx); 7845 refs_lingering = true; 7846 } 7847 return refs_lingering ? -EINVAL : 0; 7848 } 7849 7850 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 7851 struct bpf_reg_state *regs) 7852 { 7853 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 7854 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 7855 struct bpf_map *fmt_map = fmt_reg->map_ptr; 7856 struct bpf_bprintf_data data = {}; 7857 int err, fmt_map_off, num_args; 7858 u64 fmt_addr; 7859 char *fmt; 7860 7861 /* data must be an array of u64 */ 7862 if (data_len_reg->var_off.value % 8) 7863 return -EINVAL; 7864 num_args = data_len_reg->var_off.value / 8; 7865 7866 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 7867 * and map_direct_value_addr is set. 7868 */ 7869 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 7870 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 7871 fmt_map_off); 7872 if (err) { 7873 verbose(env, "verifier bug\n"); 7874 return -EFAULT; 7875 } 7876 fmt = (char *)(long)fmt_addr + fmt_map_off; 7877 7878 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 7879 * can focus on validating the format specifiers. 7880 */ 7881 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 7882 if (err < 0) 7883 verbose(env, "Invalid format string\n"); 7884 7885 return err; 7886 } 7887 7888 static int check_get_func_ip(struct bpf_verifier_env *env) 7889 { 7890 enum bpf_prog_type type = resolve_prog_type(env->prog); 7891 int func_id = BPF_FUNC_get_func_ip; 7892 7893 if (type == BPF_PROG_TYPE_TRACING) { 7894 if (!bpf_prog_has_trampoline(env->prog)) { 7895 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 7896 func_id_name(func_id), func_id); 7897 return -ENOTSUPP; 7898 } 7899 return 0; 7900 } else if (type == BPF_PROG_TYPE_KPROBE) { 7901 return 0; 7902 } 7903 7904 verbose(env, "func %s#%d not supported for program type %d\n", 7905 func_id_name(func_id), func_id, type); 7906 return -ENOTSUPP; 7907 } 7908 7909 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 7910 { 7911 return &env->insn_aux_data[env->insn_idx]; 7912 } 7913 7914 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 7915 { 7916 struct bpf_reg_state *regs = cur_regs(env); 7917 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 7918 bool reg_is_null = register_is_null(reg); 7919 7920 if (reg_is_null) 7921 mark_chain_precision(env, BPF_REG_4); 7922 7923 return reg_is_null; 7924 } 7925 7926 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 7927 { 7928 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 7929 7930 if (!state->initialized) { 7931 state->initialized = 1; 7932 state->fit_for_inline = loop_flag_is_zero(env); 7933 state->callback_subprogno = subprogno; 7934 return; 7935 } 7936 7937 if (!state->fit_for_inline) 7938 return; 7939 7940 state->fit_for_inline = (loop_flag_is_zero(env) && 7941 state->callback_subprogno == subprogno); 7942 } 7943 7944 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7945 int *insn_idx_p) 7946 { 7947 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 7948 const struct bpf_func_proto *fn = NULL; 7949 enum bpf_return_type ret_type; 7950 enum bpf_type_flag ret_flag; 7951 struct bpf_reg_state *regs; 7952 struct bpf_call_arg_meta meta; 7953 int insn_idx = *insn_idx_p; 7954 bool changes_data; 7955 int i, err, func_id; 7956 7957 /* find function prototype */ 7958 func_id = insn->imm; 7959 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 7960 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 7961 func_id); 7962 return -EINVAL; 7963 } 7964 7965 if (env->ops->get_func_proto) 7966 fn = env->ops->get_func_proto(func_id, env->prog); 7967 if (!fn) { 7968 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 7969 func_id); 7970 return -EINVAL; 7971 } 7972 7973 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 7974 if (!env->prog->gpl_compatible && fn->gpl_only) { 7975 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 7976 return -EINVAL; 7977 } 7978 7979 if (fn->allowed && !fn->allowed(env->prog)) { 7980 verbose(env, "helper call is not allowed in probe\n"); 7981 return -EINVAL; 7982 } 7983 7984 if (!env->prog->aux->sleepable && fn->might_sleep) { 7985 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 7986 return -EINVAL; 7987 } 7988 7989 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 7990 changes_data = bpf_helper_changes_pkt_data(fn->func); 7991 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 7992 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 7993 func_id_name(func_id), func_id); 7994 return -EINVAL; 7995 } 7996 7997 memset(&meta, 0, sizeof(meta)); 7998 meta.pkt_access = fn->pkt_access; 7999 8000 err = check_func_proto(fn, func_id); 8001 if (err) { 8002 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 8003 func_id_name(func_id), func_id); 8004 return err; 8005 } 8006 8007 if (env->cur_state->active_rcu_lock) { 8008 if (fn->might_sleep) { 8009 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 8010 func_id_name(func_id), func_id); 8011 return -EINVAL; 8012 } 8013 8014 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 8015 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 8016 } 8017 8018 meta.func_id = func_id; 8019 /* check args */ 8020 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 8021 err = check_func_arg(env, i, &meta, fn); 8022 if (err) 8023 return err; 8024 } 8025 8026 err = record_func_map(env, &meta, func_id, insn_idx); 8027 if (err) 8028 return err; 8029 8030 err = record_func_key(env, &meta, func_id, insn_idx); 8031 if (err) 8032 return err; 8033 8034 /* Mark slots with STACK_MISC in case of raw mode, stack offset 8035 * is inferred from register state. 8036 */ 8037 for (i = 0; i < meta.access_size; i++) { 8038 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 8039 BPF_WRITE, -1, false); 8040 if (err) 8041 return err; 8042 } 8043 8044 regs = cur_regs(env); 8045 8046 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 8047 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr 8048 * is safe to do directly. 8049 */ 8050 if (meta.uninit_dynptr_regno) { 8051 if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) { 8052 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n"); 8053 return -EFAULT; 8054 } 8055 /* we write BPF_DW bits (8 bytes) at a time */ 8056 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 8057 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno, 8058 i, BPF_DW, BPF_WRITE, -1, false); 8059 if (err) 8060 return err; 8061 } 8062 8063 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno], 8064 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1], 8065 insn_idx); 8066 if (err) 8067 return err; 8068 } 8069 8070 if (meta.release_regno) { 8071 err = -EINVAL; 8072 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 8073 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 8074 * is safe to do directly. 8075 */ 8076 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 8077 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 8078 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 8079 return -EFAULT; 8080 } 8081 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 8082 } else if (meta.ref_obj_id) { 8083 err = release_reference(env, meta.ref_obj_id); 8084 } else if (register_is_null(®s[meta.release_regno])) { 8085 /* meta.ref_obj_id can only be 0 if register that is meant to be 8086 * released is NULL, which must be > R0. 8087 */ 8088 err = 0; 8089 } 8090 if (err) { 8091 verbose(env, "func %s#%d reference has not been acquired before\n", 8092 func_id_name(func_id), func_id); 8093 return err; 8094 } 8095 } 8096 8097 switch (func_id) { 8098 case BPF_FUNC_tail_call: 8099 err = check_reference_leak(env); 8100 if (err) { 8101 verbose(env, "tail_call would lead to reference leak\n"); 8102 return err; 8103 } 8104 break; 8105 case BPF_FUNC_get_local_storage: 8106 /* check that flags argument in get_local_storage(map, flags) is 0, 8107 * this is required because get_local_storage() can't return an error. 8108 */ 8109 if (!register_is_null(®s[BPF_REG_2])) { 8110 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 8111 return -EINVAL; 8112 } 8113 break; 8114 case BPF_FUNC_for_each_map_elem: 8115 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8116 set_map_elem_callback_state); 8117 break; 8118 case BPF_FUNC_timer_set_callback: 8119 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8120 set_timer_callback_state); 8121 break; 8122 case BPF_FUNC_find_vma: 8123 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8124 set_find_vma_callback_state); 8125 break; 8126 case BPF_FUNC_snprintf: 8127 err = check_bpf_snprintf_call(env, regs); 8128 break; 8129 case BPF_FUNC_loop: 8130 update_loop_inline_state(env, meta.subprogno); 8131 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8132 set_loop_callback_state); 8133 break; 8134 case BPF_FUNC_dynptr_from_mem: 8135 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 8136 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 8137 reg_type_str(env, regs[BPF_REG_1].type)); 8138 return -EACCES; 8139 } 8140 break; 8141 case BPF_FUNC_set_retval: 8142 if (prog_type == BPF_PROG_TYPE_LSM && 8143 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 8144 if (!env->prog->aux->attach_func_proto->type) { 8145 /* Make sure programs that attach to void 8146 * hooks don't try to modify return value. 8147 */ 8148 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 8149 return -EINVAL; 8150 } 8151 } 8152 break; 8153 case BPF_FUNC_dynptr_data: 8154 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 8155 if (arg_type_is_dynptr(fn->arg_type[i])) { 8156 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i]; 8157 int id, ref_obj_id; 8158 8159 if (meta.dynptr_id) { 8160 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 8161 return -EFAULT; 8162 } 8163 8164 if (meta.ref_obj_id) { 8165 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 8166 return -EFAULT; 8167 } 8168 8169 id = dynptr_id(env, reg); 8170 if (id < 0) { 8171 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 8172 return id; 8173 } 8174 8175 ref_obj_id = dynptr_ref_obj_id(env, reg); 8176 if (ref_obj_id < 0) { 8177 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 8178 return ref_obj_id; 8179 } 8180 8181 meta.dynptr_id = id; 8182 meta.ref_obj_id = ref_obj_id; 8183 break; 8184 } 8185 } 8186 if (i == MAX_BPF_FUNC_REG_ARGS) { 8187 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n"); 8188 return -EFAULT; 8189 } 8190 break; 8191 case BPF_FUNC_user_ringbuf_drain: 8192 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8193 set_user_ringbuf_callback_state); 8194 break; 8195 } 8196 8197 if (err) 8198 return err; 8199 8200 /* reset caller saved regs */ 8201 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8202 mark_reg_not_init(env, regs, caller_saved[i]); 8203 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8204 } 8205 8206 /* helper call returns 64-bit value. */ 8207 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8208 8209 /* update return register (already marked as written above) */ 8210 ret_type = fn->ret_type; 8211 ret_flag = type_flag(ret_type); 8212 8213 switch (base_type(ret_type)) { 8214 case RET_INTEGER: 8215 /* sets type to SCALAR_VALUE */ 8216 mark_reg_unknown(env, regs, BPF_REG_0); 8217 break; 8218 case RET_VOID: 8219 regs[BPF_REG_0].type = NOT_INIT; 8220 break; 8221 case RET_PTR_TO_MAP_VALUE: 8222 /* There is no offset yet applied, variable or fixed */ 8223 mark_reg_known_zero(env, regs, BPF_REG_0); 8224 /* remember map_ptr, so that check_map_access() 8225 * can check 'value_size' boundary of memory access 8226 * to map element returned from bpf_map_lookup_elem() 8227 */ 8228 if (meta.map_ptr == NULL) { 8229 verbose(env, 8230 "kernel subsystem misconfigured verifier\n"); 8231 return -EINVAL; 8232 } 8233 regs[BPF_REG_0].map_ptr = meta.map_ptr; 8234 regs[BPF_REG_0].map_uid = meta.map_uid; 8235 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 8236 if (!type_may_be_null(ret_type) && 8237 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 8238 regs[BPF_REG_0].id = ++env->id_gen; 8239 } 8240 break; 8241 case RET_PTR_TO_SOCKET: 8242 mark_reg_known_zero(env, regs, BPF_REG_0); 8243 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 8244 break; 8245 case RET_PTR_TO_SOCK_COMMON: 8246 mark_reg_known_zero(env, regs, BPF_REG_0); 8247 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 8248 break; 8249 case RET_PTR_TO_TCP_SOCK: 8250 mark_reg_known_zero(env, regs, BPF_REG_0); 8251 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 8252 break; 8253 case RET_PTR_TO_MEM: 8254 mark_reg_known_zero(env, regs, BPF_REG_0); 8255 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 8256 regs[BPF_REG_0].mem_size = meta.mem_size; 8257 break; 8258 case RET_PTR_TO_MEM_OR_BTF_ID: 8259 { 8260 const struct btf_type *t; 8261 8262 mark_reg_known_zero(env, regs, BPF_REG_0); 8263 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 8264 if (!btf_type_is_struct(t)) { 8265 u32 tsize; 8266 const struct btf_type *ret; 8267 const char *tname; 8268 8269 /* resolve the type size of ksym. */ 8270 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 8271 if (IS_ERR(ret)) { 8272 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 8273 verbose(env, "unable to resolve the size of type '%s': %ld\n", 8274 tname, PTR_ERR(ret)); 8275 return -EINVAL; 8276 } 8277 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 8278 regs[BPF_REG_0].mem_size = tsize; 8279 } else { 8280 /* MEM_RDONLY may be carried from ret_flag, but it 8281 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 8282 * it will confuse the check of PTR_TO_BTF_ID in 8283 * check_mem_access(). 8284 */ 8285 ret_flag &= ~MEM_RDONLY; 8286 8287 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 8288 regs[BPF_REG_0].btf = meta.ret_btf; 8289 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 8290 } 8291 break; 8292 } 8293 case RET_PTR_TO_BTF_ID: 8294 { 8295 struct btf *ret_btf; 8296 int ret_btf_id; 8297 8298 mark_reg_known_zero(env, regs, BPF_REG_0); 8299 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 8300 if (func_id == BPF_FUNC_kptr_xchg) { 8301 ret_btf = meta.kptr_field->kptr.btf; 8302 ret_btf_id = meta.kptr_field->kptr.btf_id; 8303 } else { 8304 if (fn->ret_btf_id == BPF_PTR_POISON) { 8305 verbose(env, "verifier internal error:"); 8306 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 8307 func_id_name(func_id)); 8308 return -EINVAL; 8309 } 8310 ret_btf = btf_vmlinux; 8311 ret_btf_id = *fn->ret_btf_id; 8312 } 8313 if (ret_btf_id == 0) { 8314 verbose(env, "invalid return type %u of func %s#%d\n", 8315 base_type(ret_type), func_id_name(func_id), 8316 func_id); 8317 return -EINVAL; 8318 } 8319 regs[BPF_REG_0].btf = ret_btf; 8320 regs[BPF_REG_0].btf_id = ret_btf_id; 8321 break; 8322 } 8323 default: 8324 verbose(env, "unknown return type %u of func %s#%d\n", 8325 base_type(ret_type), func_id_name(func_id), func_id); 8326 return -EINVAL; 8327 } 8328 8329 if (type_may_be_null(regs[BPF_REG_0].type)) 8330 regs[BPF_REG_0].id = ++env->id_gen; 8331 8332 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 8333 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 8334 func_id_name(func_id), func_id); 8335 return -EFAULT; 8336 } 8337 8338 if (is_dynptr_ref_function(func_id)) 8339 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 8340 8341 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 8342 /* For release_reference() */ 8343 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 8344 } else if (is_acquire_function(func_id, meta.map_ptr)) { 8345 int id = acquire_reference_state(env, insn_idx); 8346 8347 if (id < 0) 8348 return id; 8349 /* For mark_ptr_or_null_reg() */ 8350 regs[BPF_REG_0].id = id; 8351 /* For release_reference() */ 8352 regs[BPF_REG_0].ref_obj_id = id; 8353 } 8354 8355 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 8356 8357 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 8358 if (err) 8359 return err; 8360 8361 if ((func_id == BPF_FUNC_get_stack || 8362 func_id == BPF_FUNC_get_task_stack) && 8363 !env->prog->has_callchain_buf) { 8364 const char *err_str; 8365 8366 #ifdef CONFIG_PERF_EVENTS 8367 err = get_callchain_buffers(sysctl_perf_event_max_stack); 8368 err_str = "cannot get callchain buffer for func %s#%d\n"; 8369 #else 8370 err = -ENOTSUPP; 8371 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 8372 #endif 8373 if (err) { 8374 verbose(env, err_str, func_id_name(func_id), func_id); 8375 return err; 8376 } 8377 8378 env->prog->has_callchain_buf = true; 8379 } 8380 8381 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 8382 env->prog->call_get_stack = true; 8383 8384 if (func_id == BPF_FUNC_get_func_ip) { 8385 if (check_get_func_ip(env)) 8386 return -ENOTSUPP; 8387 env->prog->call_get_func_ip = true; 8388 } 8389 8390 if (changes_data) 8391 clear_all_pkt_pointers(env); 8392 return 0; 8393 } 8394 8395 /* mark_btf_func_reg_size() is used when the reg size is determined by 8396 * the BTF func_proto's return value size and argument. 8397 */ 8398 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 8399 size_t reg_size) 8400 { 8401 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 8402 8403 if (regno == BPF_REG_0) { 8404 /* Function return value */ 8405 reg->live |= REG_LIVE_WRITTEN; 8406 reg->subreg_def = reg_size == sizeof(u64) ? 8407 DEF_NOT_SUBREG : env->insn_idx + 1; 8408 } else { 8409 /* Function argument */ 8410 if (reg_size == sizeof(u64)) { 8411 mark_insn_zext(env, reg); 8412 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 8413 } else { 8414 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 8415 } 8416 } 8417 } 8418 8419 struct bpf_kfunc_call_arg_meta { 8420 /* In parameters */ 8421 struct btf *btf; 8422 u32 func_id; 8423 u32 kfunc_flags; 8424 const struct btf_type *func_proto; 8425 const char *func_name; 8426 /* Out parameters */ 8427 u32 ref_obj_id; 8428 u8 release_regno; 8429 bool r0_rdonly; 8430 u32 ret_btf_id; 8431 u64 r0_size; 8432 struct { 8433 u64 value; 8434 bool found; 8435 } arg_constant; 8436 struct { 8437 struct btf *btf; 8438 u32 btf_id; 8439 } arg_obj_drop; 8440 struct { 8441 struct btf_field *field; 8442 } arg_list_head; 8443 }; 8444 8445 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 8446 { 8447 return meta->kfunc_flags & KF_ACQUIRE; 8448 } 8449 8450 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 8451 { 8452 return meta->kfunc_flags & KF_RET_NULL; 8453 } 8454 8455 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 8456 { 8457 return meta->kfunc_flags & KF_RELEASE; 8458 } 8459 8460 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 8461 { 8462 return meta->kfunc_flags & KF_TRUSTED_ARGS; 8463 } 8464 8465 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 8466 { 8467 return meta->kfunc_flags & KF_SLEEPABLE; 8468 } 8469 8470 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 8471 { 8472 return meta->kfunc_flags & KF_DESTRUCTIVE; 8473 } 8474 8475 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 8476 { 8477 return meta->kfunc_flags & KF_RCU; 8478 } 8479 8480 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg) 8481 { 8482 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET); 8483 } 8484 8485 static bool __kfunc_param_match_suffix(const struct btf *btf, 8486 const struct btf_param *arg, 8487 const char *suffix) 8488 { 8489 int suffix_len = strlen(suffix), len; 8490 const char *param_name; 8491 8492 /* In the future, this can be ported to use BTF tagging */ 8493 param_name = btf_name_by_offset(btf, arg->name_off); 8494 if (str_is_empty(param_name)) 8495 return false; 8496 len = strlen(param_name); 8497 if (len < suffix_len) 8498 return false; 8499 param_name += len - suffix_len; 8500 return !strncmp(param_name, suffix, suffix_len); 8501 } 8502 8503 static bool is_kfunc_arg_mem_size(const struct btf *btf, 8504 const struct btf_param *arg, 8505 const struct bpf_reg_state *reg) 8506 { 8507 const struct btf_type *t; 8508 8509 t = btf_type_skip_modifiers(btf, arg->type, NULL); 8510 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 8511 return false; 8512 8513 return __kfunc_param_match_suffix(btf, arg, "__sz"); 8514 } 8515 8516 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 8517 { 8518 return __kfunc_param_match_suffix(btf, arg, "__k"); 8519 } 8520 8521 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 8522 { 8523 return __kfunc_param_match_suffix(btf, arg, "__ign"); 8524 } 8525 8526 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 8527 { 8528 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 8529 } 8530 8531 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 8532 const struct btf_param *arg, 8533 const char *name) 8534 { 8535 int len, target_len = strlen(name); 8536 const char *param_name; 8537 8538 param_name = btf_name_by_offset(btf, arg->name_off); 8539 if (str_is_empty(param_name)) 8540 return false; 8541 len = strlen(param_name); 8542 if (len != target_len) 8543 return false; 8544 if (strcmp(param_name, name)) 8545 return false; 8546 8547 return true; 8548 } 8549 8550 enum { 8551 KF_ARG_DYNPTR_ID, 8552 KF_ARG_LIST_HEAD_ID, 8553 KF_ARG_LIST_NODE_ID, 8554 }; 8555 8556 BTF_ID_LIST(kf_arg_btf_ids) 8557 BTF_ID(struct, bpf_dynptr_kern) 8558 BTF_ID(struct, bpf_list_head) 8559 BTF_ID(struct, bpf_list_node) 8560 8561 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 8562 const struct btf_param *arg, int type) 8563 { 8564 const struct btf_type *t; 8565 u32 res_id; 8566 8567 t = btf_type_skip_modifiers(btf, arg->type, NULL); 8568 if (!t) 8569 return false; 8570 if (!btf_type_is_ptr(t)) 8571 return false; 8572 t = btf_type_skip_modifiers(btf, t->type, &res_id); 8573 if (!t) 8574 return false; 8575 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 8576 } 8577 8578 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 8579 { 8580 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 8581 } 8582 8583 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 8584 { 8585 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 8586 } 8587 8588 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 8589 { 8590 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 8591 } 8592 8593 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 8594 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 8595 const struct btf *btf, 8596 const struct btf_type *t, int rec) 8597 { 8598 const struct btf_type *member_type; 8599 const struct btf_member *member; 8600 u32 i; 8601 8602 if (!btf_type_is_struct(t)) 8603 return false; 8604 8605 for_each_member(i, t, member) { 8606 const struct btf_array *array; 8607 8608 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 8609 if (btf_type_is_struct(member_type)) { 8610 if (rec >= 3) { 8611 verbose(env, "max struct nesting depth exceeded\n"); 8612 return false; 8613 } 8614 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 8615 return false; 8616 continue; 8617 } 8618 if (btf_type_is_array(member_type)) { 8619 array = btf_array(member_type); 8620 if (!array->nelems) 8621 return false; 8622 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 8623 if (!btf_type_is_scalar(member_type)) 8624 return false; 8625 continue; 8626 } 8627 if (!btf_type_is_scalar(member_type)) 8628 return false; 8629 } 8630 return true; 8631 } 8632 8633 8634 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 8635 #ifdef CONFIG_NET 8636 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 8637 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8638 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 8639 #endif 8640 }; 8641 8642 enum kfunc_ptr_arg_type { 8643 KF_ARG_PTR_TO_CTX, 8644 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 8645 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */ 8646 KF_ARG_PTR_TO_DYNPTR, 8647 KF_ARG_PTR_TO_LIST_HEAD, 8648 KF_ARG_PTR_TO_LIST_NODE, 8649 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 8650 KF_ARG_PTR_TO_MEM, 8651 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 8652 }; 8653 8654 enum special_kfunc_type { 8655 KF_bpf_obj_new_impl, 8656 KF_bpf_obj_drop_impl, 8657 KF_bpf_list_push_front, 8658 KF_bpf_list_push_back, 8659 KF_bpf_list_pop_front, 8660 KF_bpf_list_pop_back, 8661 KF_bpf_cast_to_kern_ctx, 8662 KF_bpf_rdonly_cast, 8663 KF_bpf_rcu_read_lock, 8664 KF_bpf_rcu_read_unlock, 8665 }; 8666 8667 BTF_SET_START(special_kfunc_set) 8668 BTF_ID(func, bpf_obj_new_impl) 8669 BTF_ID(func, bpf_obj_drop_impl) 8670 BTF_ID(func, bpf_list_push_front) 8671 BTF_ID(func, bpf_list_push_back) 8672 BTF_ID(func, bpf_list_pop_front) 8673 BTF_ID(func, bpf_list_pop_back) 8674 BTF_ID(func, bpf_cast_to_kern_ctx) 8675 BTF_ID(func, bpf_rdonly_cast) 8676 BTF_SET_END(special_kfunc_set) 8677 8678 BTF_ID_LIST(special_kfunc_list) 8679 BTF_ID(func, bpf_obj_new_impl) 8680 BTF_ID(func, bpf_obj_drop_impl) 8681 BTF_ID(func, bpf_list_push_front) 8682 BTF_ID(func, bpf_list_push_back) 8683 BTF_ID(func, bpf_list_pop_front) 8684 BTF_ID(func, bpf_list_pop_back) 8685 BTF_ID(func, bpf_cast_to_kern_ctx) 8686 BTF_ID(func, bpf_rdonly_cast) 8687 BTF_ID(func, bpf_rcu_read_lock) 8688 BTF_ID(func, bpf_rcu_read_unlock) 8689 8690 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 8691 { 8692 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 8693 } 8694 8695 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 8696 { 8697 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 8698 } 8699 8700 static enum kfunc_ptr_arg_type 8701 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 8702 struct bpf_kfunc_call_arg_meta *meta, 8703 const struct btf_type *t, const struct btf_type *ref_t, 8704 const char *ref_tname, const struct btf_param *args, 8705 int argno, int nargs) 8706 { 8707 u32 regno = argno + 1; 8708 struct bpf_reg_state *regs = cur_regs(env); 8709 struct bpf_reg_state *reg = ®s[regno]; 8710 bool arg_mem_size = false; 8711 8712 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 8713 return KF_ARG_PTR_TO_CTX; 8714 8715 /* In this function, we verify the kfunc's BTF as per the argument type, 8716 * leaving the rest of the verification with respect to the register 8717 * type to our caller. When a set of conditions hold in the BTF type of 8718 * arguments, we resolve it to a known kfunc_ptr_arg_type. 8719 */ 8720 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 8721 return KF_ARG_PTR_TO_CTX; 8722 8723 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 8724 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 8725 8726 if (is_kfunc_arg_kptr_get(meta, argno)) { 8727 if (!btf_type_is_ptr(ref_t)) { 8728 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n"); 8729 return -EINVAL; 8730 } 8731 ref_t = btf_type_by_id(meta->btf, ref_t->type); 8732 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off); 8733 if (!btf_type_is_struct(ref_t)) { 8734 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n", 8735 meta->func_name, btf_type_str(ref_t), ref_tname); 8736 return -EINVAL; 8737 } 8738 return KF_ARG_PTR_TO_KPTR; 8739 } 8740 8741 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 8742 return KF_ARG_PTR_TO_DYNPTR; 8743 8744 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 8745 return KF_ARG_PTR_TO_LIST_HEAD; 8746 8747 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 8748 return KF_ARG_PTR_TO_LIST_NODE; 8749 8750 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 8751 if (!btf_type_is_struct(ref_t)) { 8752 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 8753 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 8754 return -EINVAL; 8755 } 8756 return KF_ARG_PTR_TO_BTF_ID; 8757 } 8758 8759 if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])) 8760 arg_mem_size = true; 8761 8762 /* This is the catch all argument type of register types supported by 8763 * check_helper_mem_access. However, we only allow when argument type is 8764 * pointer to scalar, or struct composed (recursively) of scalars. When 8765 * arg_mem_size is true, the pointer can be void *. 8766 */ 8767 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 8768 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 8769 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 8770 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 8771 return -EINVAL; 8772 } 8773 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 8774 } 8775 8776 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 8777 struct bpf_reg_state *reg, 8778 const struct btf_type *ref_t, 8779 const char *ref_tname, u32 ref_id, 8780 struct bpf_kfunc_call_arg_meta *meta, 8781 int argno) 8782 { 8783 const struct btf_type *reg_ref_t; 8784 bool strict_type_match = false; 8785 const struct btf *reg_btf; 8786 const char *reg_ref_tname; 8787 u32 reg_ref_id; 8788 8789 if (base_type(reg->type) == PTR_TO_BTF_ID) { 8790 reg_btf = reg->btf; 8791 reg_ref_id = reg->btf_id; 8792 } else { 8793 reg_btf = btf_vmlinux; 8794 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 8795 } 8796 8797 if (is_kfunc_trusted_args(meta) || (is_kfunc_release(meta) && reg->ref_obj_id)) 8798 strict_type_match = true; 8799 8800 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 8801 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 8802 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 8803 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 8804 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 8805 btf_type_str(reg_ref_t), reg_ref_tname); 8806 return -EINVAL; 8807 } 8808 return 0; 8809 } 8810 8811 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env, 8812 struct bpf_reg_state *reg, 8813 const struct btf_type *ref_t, 8814 const char *ref_tname, 8815 struct bpf_kfunc_call_arg_meta *meta, 8816 int argno) 8817 { 8818 struct btf_field *kptr_field; 8819 8820 /* check_func_arg_reg_off allows var_off for 8821 * PTR_TO_MAP_VALUE, but we need fixed offset to find 8822 * off_desc. 8823 */ 8824 if (!tnum_is_const(reg->var_off)) { 8825 verbose(env, "arg#0 must have constant offset\n"); 8826 return -EINVAL; 8827 } 8828 8829 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR); 8830 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) { 8831 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n", 8832 reg->off + reg->var_off.value); 8833 return -EINVAL; 8834 } 8835 8836 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf, 8837 kptr_field->kptr.btf_id, true)) { 8838 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n", 8839 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 8840 return -EINVAL; 8841 } 8842 return 0; 8843 } 8844 8845 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id) 8846 { 8847 struct bpf_func_state *state = cur_func(env); 8848 struct bpf_reg_state *reg; 8849 int i; 8850 8851 /* bpf_spin_lock only allows calling list_push and list_pop, no BPF 8852 * subprogs, no global functions. This means that the references would 8853 * not be released inside the critical section but they may be added to 8854 * the reference state, and the acquired_refs are never copied out for a 8855 * different frame as BPF to BPF calls don't work in bpf_spin_lock 8856 * critical sections. 8857 */ 8858 if (!ref_obj_id) { 8859 verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n"); 8860 return -EFAULT; 8861 } 8862 for (i = 0; i < state->acquired_refs; i++) { 8863 if (state->refs[i].id == ref_obj_id) { 8864 if (state->refs[i].release_on_unlock) { 8865 verbose(env, "verifier internal error: expected false release_on_unlock"); 8866 return -EFAULT; 8867 } 8868 state->refs[i].release_on_unlock = true; 8869 /* Now mark everyone sharing same ref_obj_id as untrusted */ 8870 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8871 if (reg->ref_obj_id == ref_obj_id) 8872 reg->type |= PTR_UNTRUSTED; 8873 })); 8874 return 0; 8875 } 8876 } 8877 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 8878 return -EFAULT; 8879 } 8880 8881 /* Implementation details: 8882 * 8883 * Each register points to some region of memory, which we define as an 8884 * allocation. Each allocation may embed a bpf_spin_lock which protects any 8885 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 8886 * allocation. The lock and the data it protects are colocated in the same 8887 * memory region. 8888 * 8889 * Hence, everytime a register holds a pointer value pointing to such 8890 * allocation, the verifier preserves a unique reg->id for it. 8891 * 8892 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 8893 * bpf_spin_lock is called. 8894 * 8895 * To enable this, lock state in the verifier captures two values: 8896 * active_lock.ptr = Register's type specific pointer 8897 * active_lock.id = A unique ID for each register pointer value 8898 * 8899 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 8900 * supported register types. 8901 * 8902 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 8903 * allocated objects is the reg->btf pointer. 8904 * 8905 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 8906 * can establish the provenance of the map value statically for each distinct 8907 * lookup into such maps. They always contain a single map value hence unique 8908 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 8909 * 8910 * So, in case of global variables, they use array maps with max_entries = 1, 8911 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 8912 * into the same map value as max_entries is 1, as described above). 8913 * 8914 * In case of inner map lookups, the inner map pointer has same map_ptr as the 8915 * outer map pointer (in verifier context), but each lookup into an inner map 8916 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 8917 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 8918 * will get different reg->id assigned to each lookup, hence different 8919 * active_lock.id. 8920 * 8921 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 8922 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 8923 * returned from bpf_obj_new. Each allocation receives a new reg->id. 8924 */ 8925 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8926 { 8927 void *ptr; 8928 u32 id; 8929 8930 switch ((int)reg->type) { 8931 case PTR_TO_MAP_VALUE: 8932 ptr = reg->map_ptr; 8933 break; 8934 case PTR_TO_BTF_ID | MEM_ALLOC: 8935 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED: 8936 ptr = reg->btf; 8937 break; 8938 default: 8939 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 8940 return -EFAULT; 8941 } 8942 id = reg->id; 8943 8944 if (!env->cur_state->active_lock.ptr) 8945 return -EINVAL; 8946 if (env->cur_state->active_lock.ptr != ptr || 8947 env->cur_state->active_lock.id != id) { 8948 verbose(env, "held lock and object are not in the same allocation\n"); 8949 return -EINVAL; 8950 } 8951 return 0; 8952 } 8953 8954 static bool is_bpf_list_api_kfunc(u32 btf_id) 8955 { 8956 return btf_id == special_kfunc_list[KF_bpf_list_push_front] || 8957 btf_id == special_kfunc_list[KF_bpf_list_push_back] || 8958 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 8959 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 8960 } 8961 8962 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 8963 struct bpf_reg_state *reg, u32 regno, 8964 struct bpf_kfunc_call_arg_meta *meta) 8965 { 8966 struct btf_field *field; 8967 struct btf_record *rec; 8968 u32 list_head_off; 8969 8970 if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) { 8971 verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n"); 8972 return -EFAULT; 8973 } 8974 8975 if (!tnum_is_const(reg->var_off)) { 8976 verbose(env, 8977 "R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n", 8978 regno); 8979 return -EINVAL; 8980 } 8981 8982 rec = reg_btf_record(reg); 8983 list_head_off = reg->off + reg->var_off.value; 8984 field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD); 8985 if (!field) { 8986 verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off); 8987 return -EINVAL; 8988 } 8989 8990 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 8991 if (check_reg_allocation_locked(env, reg)) { 8992 verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n", 8993 rec->spin_lock_off); 8994 return -EINVAL; 8995 } 8996 8997 if (meta->arg_list_head.field) { 8998 verbose(env, "verifier internal error: repeating bpf_list_head arg\n"); 8999 return -EFAULT; 9000 } 9001 meta->arg_list_head.field = field; 9002 return 0; 9003 } 9004 9005 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 9006 struct bpf_reg_state *reg, u32 regno, 9007 struct bpf_kfunc_call_arg_meta *meta) 9008 { 9009 const struct btf_type *et, *t; 9010 struct btf_field *field; 9011 struct btf_record *rec; 9012 u32 list_node_off; 9013 9014 if (meta->btf != btf_vmlinux || 9015 (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] && 9016 meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) { 9017 verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n"); 9018 return -EFAULT; 9019 } 9020 9021 if (!tnum_is_const(reg->var_off)) { 9022 verbose(env, 9023 "R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n", 9024 regno); 9025 return -EINVAL; 9026 } 9027 9028 rec = reg_btf_record(reg); 9029 list_node_off = reg->off + reg->var_off.value; 9030 field = btf_record_find(rec, list_node_off, BPF_LIST_NODE); 9031 if (!field || field->offset != list_node_off) { 9032 verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off); 9033 return -EINVAL; 9034 } 9035 9036 field = meta->arg_list_head.field; 9037 9038 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 9039 t = btf_type_by_id(reg->btf, reg->btf_id); 9040 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 9041 field->graph_root.value_btf_id, true)) { 9042 verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d " 9043 "in struct %s, but arg is at offset=%d in struct %s\n", 9044 field->graph_root.node_offset, 9045 btf_name_by_offset(field->graph_root.btf, et->name_off), 9046 list_node_off, btf_name_by_offset(reg->btf, t->name_off)); 9047 return -EINVAL; 9048 } 9049 9050 if (list_node_off != field->graph_root.node_offset) { 9051 verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n", 9052 list_node_off, field->graph_root.node_offset, 9053 btf_name_by_offset(field->graph_root.btf, et->name_off)); 9054 return -EINVAL; 9055 } 9056 /* Set arg#1 for expiration after unlock */ 9057 return ref_set_release_on_unlock(env, reg->ref_obj_id); 9058 } 9059 9060 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta) 9061 { 9062 const char *func_name = meta->func_name, *ref_tname; 9063 const struct btf *btf = meta->btf; 9064 const struct btf_param *args; 9065 u32 i, nargs; 9066 int ret; 9067 9068 args = (const struct btf_param *)(meta->func_proto + 1); 9069 nargs = btf_type_vlen(meta->func_proto); 9070 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 9071 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 9072 MAX_BPF_FUNC_REG_ARGS); 9073 return -EINVAL; 9074 } 9075 9076 /* Check that BTF function arguments match actual types that the 9077 * verifier sees. 9078 */ 9079 for (i = 0; i < nargs; i++) { 9080 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 9081 const struct btf_type *t, *ref_t, *resolve_ret; 9082 enum bpf_arg_type arg_type = ARG_DONTCARE; 9083 u32 regno = i + 1, ref_id, type_size; 9084 bool is_ret_buf_sz = false; 9085 int kf_arg_type; 9086 9087 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 9088 9089 if (is_kfunc_arg_ignore(btf, &args[i])) 9090 continue; 9091 9092 if (btf_type_is_scalar(t)) { 9093 if (reg->type != SCALAR_VALUE) { 9094 verbose(env, "R%d is not a scalar\n", regno); 9095 return -EINVAL; 9096 } 9097 9098 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 9099 if (meta->arg_constant.found) { 9100 verbose(env, "verifier internal error: only one constant argument permitted\n"); 9101 return -EFAULT; 9102 } 9103 if (!tnum_is_const(reg->var_off)) { 9104 verbose(env, "R%d must be a known constant\n", regno); 9105 return -EINVAL; 9106 } 9107 ret = mark_chain_precision(env, regno); 9108 if (ret < 0) 9109 return ret; 9110 meta->arg_constant.found = true; 9111 meta->arg_constant.value = reg->var_off.value; 9112 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 9113 meta->r0_rdonly = true; 9114 is_ret_buf_sz = true; 9115 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 9116 is_ret_buf_sz = true; 9117 } 9118 9119 if (is_ret_buf_sz) { 9120 if (meta->r0_size) { 9121 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 9122 return -EINVAL; 9123 } 9124 9125 if (!tnum_is_const(reg->var_off)) { 9126 verbose(env, "R%d is not a const\n", regno); 9127 return -EINVAL; 9128 } 9129 9130 meta->r0_size = reg->var_off.value; 9131 ret = mark_chain_precision(env, regno); 9132 if (ret) 9133 return ret; 9134 } 9135 continue; 9136 } 9137 9138 if (!btf_type_is_ptr(t)) { 9139 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 9140 return -EINVAL; 9141 } 9142 9143 if (reg->ref_obj_id) { 9144 if (is_kfunc_release(meta) && meta->ref_obj_id) { 9145 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 9146 regno, reg->ref_obj_id, 9147 meta->ref_obj_id); 9148 return -EFAULT; 9149 } 9150 meta->ref_obj_id = reg->ref_obj_id; 9151 if (is_kfunc_release(meta)) 9152 meta->release_regno = regno; 9153 } 9154 9155 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 9156 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 9157 9158 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 9159 if (kf_arg_type < 0) 9160 return kf_arg_type; 9161 9162 switch (kf_arg_type) { 9163 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 9164 case KF_ARG_PTR_TO_BTF_ID: 9165 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 9166 break; 9167 9168 if (!is_trusted_reg(reg)) { 9169 if (!is_kfunc_rcu(meta)) { 9170 verbose(env, "R%d must be referenced or trusted\n", regno); 9171 return -EINVAL; 9172 } 9173 if (!is_rcu_reg(reg)) { 9174 verbose(env, "R%d must be a rcu pointer\n", regno); 9175 return -EINVAL; 9176 } 9177 } 9178 9179 fallthrough; 9180 case KF_ARG_PTR_TO_CTX: 9181 /* Trusted arguments have the same offset checks as release arguments */ 9182 arg_type |= OBJ_RELEASE; 9183 break; 9184 case KF_ARG_PTR_TO_KPTR: 9185 case KF_ARG_PTR_TO_DYNPTR: 9186 case KF_ARG_PTR_TO_LIST_HEAD: 9187 case KF_ARG_PTR_TO_LIST_NODE: 9188 case KF_ARG_PTR_TO_MEM: 9189 case KF_ARG_PTR_TO_MEM_SIZE: 9190 /* Trusted by default */ 9191 break; 9192 default: 9193 WARN_ON_ONCE(1); 9194 return -EFAULT; 9195 } 9196 9197 if (is_kfunc_release(meta) && reg->ref_obj_id) 9198 arg_type |= OBJ_RELEASE; 9199 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 9200 if (ret < 0) 9201 return ret; 9202 9203 switch (kf_arg_type) { 9204 case KF_ARG_PTR_TO_CTX: 9205 if (reg->type != PTR_TO_CTX) { 9206 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 9207 return -EINVAL; 9208 } 9209 9210 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 9211 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 9212 if (ret < 0) 9213 return -EINVAL; 9214 meta->ret_btf_id = ret; 9215 } 9216 break; 9217 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 9218 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9219 verbose(env, "arg#%d expected pointer to allocated object\n", i); 9220 return -EINVAL; 9221 } 9222 if (!reg->ref_obj_id) { 9223 verbose(env, "allocated object must be referenced\n"); 9224 return -EINVAL; 9225 } 9226 if (meta->btf == btf_vmlinux && 9227 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 9228 meta->arg_obj_drop.btf = reg->btf; 9229 meta->arg_obj_drop.btf_id = reg->btf_id; 9230 } 9231 break; 9232 case KF_ARG_PTR_TO_KPTR: 9233 if (reg->type != PTR_TO_MAP_VALUE) { 9234 verbose(env, "arg#0 expected pointer to map value\n"); 9235 return -EINVAL; 9236 } 9237 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i); 9238 if (ret < 0) 9239 return ret; 9240 break; 9241 case KF_ARG_PTR_TO_DYNPTR: 9242 if (reg->type != PTR_TO_STACK && 9243 reg->type != CONST_PTR_TO_DYNPTR) { 9244 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 9245 return -EINVAL; 9246 } 9247 9248 ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL); 9249 if (ret < 0) 9250 return ret; 9251 break; 9252 case KF_ARG_PTR_TO_LIST_HEAD: 9253 if (reg->type != PTR_TO_MAP_VALUE && 9254 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9255 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 9256 return -EINVAL; 9257 } 9258 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 9259 verbose(env, "allocated object must be referenced\n"); 9260 return -EINVAL; 9261 } 9262 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 9263 if (ret < 0) 9264 return ret; 9265 break; 9266 case KF_ARG_PTR_TO_LIST_NODE: 9267 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9268 verbose(env, "arg#%d expected pointer to allocated object\n", i); 9269 return -EINVAL; 9270 } 9271 if (!reg->ref_obj_id) { 9272 verbose(env, "allocated object must be referenced\n"); 9273 return -EINVAL; 9274 } 9275 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 9276 if (ret < 0) 9277 return ret; 9278 break; 9279 case KF_ARG_PTR_TO_BTF_ID: 9280 /* Only base_type is checked, further checks are done here */ 9281 if ((base_type(reg->type) != PTR_TO_BTF_ID || 9282 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 9283 !reg2btf_ids[base_type(reg->type)]) { 9284 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 9285 verbose(env, "expected %s or socket\n", 9286 reg_type_str(env, base_type(reg->type) | 9287 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 9288 return -EINVAL; 9289 } 9290 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 9291 if (ret < 0) 9292 return ret; 9293 break; 9294 case KF_ARG_PTR_TO_MEM: 9295 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 9296 if (IS_ERR(resolve_ret)) { 9297 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 9298 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 9299 return -EINVAL; 9300 } 9301 ret = check_mem_reg(env, reg, regno, type_size); 9302 if (ret < 0) 9303 return ret; 9304 break; 9305 case KF_ARG_PTR_TO_MEM_SIZE: 9306 ret = check_kfunc_mem_size_reg(env, ®s[regno + 1], regno + 1); 9307 if (ret < 0) { 9308 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 9309 return ret; 9310 } 9311 /* Skip next '__sz' argument */ 9312 i++; 9313 break; 9314 } 9315 } 9316 9317 if (is_kfunc_release(meta) && !meta->release_regno) { 9318 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 9319 func_name); 9320 return -EINVAL; 9321 } 9322 9323 return 0; 9324 } 9325 9326 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9327 int *insn_idx_p) 9328 { 9329 const struct btf_type *t, *func, *func_proto, *ptr_type; 9330 struct bpf_reg_state *regs = cur_regs(env); 9331 const char *func_name, *ptr_type_name; 9332 bool sleepable, rcu_lock, rcu_unlock; 9333 struct bpf_kfunc_call_arg_meta meta; 9334 u32 i, nargs, func_id, ptr_type_id; 9335 int err, insn_idx = *insn_idx_p; 9336 const struct btf_param *args; 9337 const struct btf_type *ret_t; 9338 struct btf *desc_btf; 9339 u32 *kfunc_flags; 9340 9341 /* skip for now, but return error when we find this in fixup_kfunc_call */ 9342 if (!insn->imm) 9343 return 0; 9344 9345 desc_btf = find_kfunc_desc_btf(env, insn->off); 9346 if (IS_ERR(desc_btf)) 9347 return PTR_ERR(desc_btf); 9348 9349 func_id = insn->imm; 9350 func = btf_type_by_id(desc_btf, func_id); 9351 func_name = btf_name_by_offset(desc_btf, func->name_off); 9352 func_proto = btf_type_by_id(desc_btf, func->type); 9353 9354 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id); 9355 if (!kfunc_flags) { 9356 verbose(env, "calling kernel function %s is not allowed\n", 9357 func_name); 9358 return -EACCES; 9359 } 9360 9361 /* Prepare kfunc call metadata */ 9362 memset(&meta, 0, sizeof(meta)); 9363 meta.btf = desc_btf; 9364 meta.func_id = func_id; 9365 meta.kfunc_flags = *kfunc_flags; 9366 meta.func_proto = func_proto; 9367 meta.func_name = func_name; 9368 9369 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 9370 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 9371 return -EACCES; 9372 } 9373 9374 sleepable = is_kfunc_sleepable(&meta); 9375 if (sleepable && !env->prog->aux->sleepable) { 9376 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 9377 return -EACCES; 9378 } 9379 9380 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 9381 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 9382 if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) { 9383 verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name); 9384 return -EACCES; 9385 } 9386 9387 if (env->cur_state->active_rcu_lock) { 9388 struct bpf_func_state *state; 9389 struct bpf_reg_state *reg; 9390 9391 if (rcu_lock) { 9392 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 9393 return -EINVAL; 9394 } else if (rcu_unlock) { 9395 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9396 if (reg->type & MEM_RCU) { 9397 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 9398 reg->type |= PTR_UNTRUSTED; 9399 } 9400 })); 9401 env->cur_state->active_rcu_lock = false; 9402 } else if (sleepable) { 9403 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 9404 return -EACCES; 9405 } 9406 } else if (rcu_lock) { 9407 env->cur_state->active_rcu_lock = true; 9408 } else if (rcu_unlock) { 9409 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 9410 return -EINVAL; 9411 } 9412 9413 /* Check the arguments */ 9414 err = check_kfunc_args(env, &meta); 9415 if (err < 0) 9416 return err; 9417 /* In case of release function, we get register number of refcounted 9418 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 9419 */ 9420 if (meta.release_regno) { 9421 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 9422 if (err) { 9423 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 9424 func_name, func_id); 9425 return err; 9426 } 9427 } 9428 9429 for (i = 0; i < CALLER_SAVED_REGS; i++) 9430 mark_reg_not_init(env, regs, caller_saved[i]); 9431 9432 /* Check return type */ 9433 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL); 9434 9435 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 9436 /* Only exception is bpf_obj_new_impl */ 9437 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) { 9438 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 9439 return -EINVAL; 9440 } 9441 } 9442 9443 if (btf_type_is_scalar(t)) { 9444 mark_reg_unknown(env, regs, BPF_REG_0); 9445 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 9446 } else if (btf_type_is_ptr(t)) { 9447 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 9448 9449 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 9450 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 9451 struct btf *ret_btf; 9452 u32 ret_btf_id; 9453 9454 if (unlikely(!bpf_global_ma_set)) 9455 return -ENOMEM; 9456 9457 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 9458 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 9459 return -EINVAL; 9460 } 9461 9462 ret_btf = env->prog->aux->btf; 9463 ret_btf_id = meta.arg_constant.value; 9464 9465 /* This may be NULL due to user not supplying a BTF */ 9466 if (!ret_btf) { 9467 verbose(env, "bpf_obj_new requires prog BTF\n"); 9468 return -EINVAL; 9469 } 9470 9471 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 9472 if (!ret_t || !__btf_type_is_struct(ret_t)) { 9473 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 9474 return -EINVAL; 9475 } 9476 9477 mark_reg_known_zero(env, regs, BPF_REG_0); 9478 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 9479 regs[BPF_REG_0].btf = ret_btf; 9480 regs[BPF_REG_0].btf_id = ret_btf_id; 9481 9482 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size; 9483 env->insn_aux_data[insn_idx].kptr_struct_meta = 9484 btf_find_struct_meta(ret_btf, ret_btf_id); 9485 } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 9486 env->insn_aux_data[insn_idx].kptr_struct_meta = 9487 btf_find_struct_meta(meta.arg_obj_drop.btf, 9488 meta.arg_obj_drop.btf_id); 9489 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 9490 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 9491 struct btf_field *field = meta.arg_list_head.field; 9492 9493 mark_reg_known_zero(env, regs, BPF_REG_0); 9494 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 9495 regs[BPF_REG_0].btf = field->graph_root.btf; 9496 regs[BPF_REG_0].btf_id = field->graph_root.value_btf_id; 9497 regs[BPF_REG_0].off = field->graph_root.node_offset; 9498 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 9499 mark_reg_known_zero(env, regs, BPF_REG_0); 9500 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 9501 regs[BPF_REG_0].btf = desc_btf; 9502 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 9503 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 9504 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 9505 if (!ret_t || !btf_type_is_struct(ret_t)) { 9506 verbose(env, 9507 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 9508 return -EINVAL; 9509 } 9510 9511 mark_reg_known_zero(env, regs, BPF_REG_0); 9512 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 9513 regs[BPF_REG_0].btf = desc_btf; 9514 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 9515 } else { 9516 verbose(env, "kernel function %s unhandled dynamic return type\n", 9517 meta.func_name); 9518 return -EFAULT; 9519 } 9520 } else if (!__btf_type_is_struct(ptr_type)) { 9521 if (!meta.r0_size) { 9522 ptr_type_name = btf_name_by_offset(desc_btf, 9523 ptr_type->name_off); 9524 verbose(env, 9525 "kernel function %s returns pointer type %s %s is not supported\n", 9526 func_name, 9527 btf_type_str(ptr_type), 9528 ptr_type_name); 9529 return -EINVAL; 9530 } 9531 9532 mark_reg_known_zero(env, regs, BPF_REG_0); 9533 regs[BPF_REG_0].type = PTR_TO_MEM; 9534 regs[BPF_REG_0].mem_size = meta.r0_size; 9535 9536 if (meta.r0_rdonly) 9537 regs[BPF_REG_0].type |= MEM_RDONLY; 9538 9539 /* Ensures we don't access the memory after a release_reference() */ 9540 if (meta.ref_obj_id) 9541 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 9542 } else { 9543 mark_reg_known_zero(env, regs, BPF_REG_0); 9544 regs[BPF_REG_0].btf = desc_btf; 9545 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 9546 regs[BPF_REG_0].btf_id = ptr_type_id; 9547 } 9548 9549 if (is_kfunc_ret_null(&meta)) { 9550 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 9551 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 9552 regs[BPF_REG_0].id = ++env->id_gen; 9553 } 9554 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 9555 if (is_kfunc_acquire(&meta)) { 9556 int id = acquire_reference_state(env, insn_idx); 9557 9558 if (id < 0) 9559 return id; 9560 if (is_kfunc_ret_null(&meta)) 9561 regs[BPF_REG_0].id = id; 9562 regs[BPF_REG_0].ref_obj_id = id; 9563 } 9564 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 9565 regs[BPF_REG_0].id = ++env->id_gen; 9566 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */ 9567 9568 nargs = btf_type_vlen(func_proto); 9569 args = (const struct btf_param *)(func_proto + 1); 9570 for (i = 0; i < nargs; i++) { 9571 u32 regno = i + 1; 9572 9573 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 9574 if (btf_type_is_ptr(t)) 9575 mark_btf_func_reg_size(env, regno, sizeof(void *)); 9576 else 9577 /* scalar. ensured by btf_check_kfunc_arg_match() */ 9578 mark_btf_func_reg_size(env, regno, t->size); 9579 } 9580 9581 return 0; 9582 } 9583 9584 static bool signed_add_overflows(s64 a, s64 b) 9585 { 9586 /* Do the add in u64, where overflow is well-defined */ 9587 s64 res = (s64)((u64)a + (u64)b); 9588 9589 if (b < 0) 9590 return res > a; 9591 return res < a; 9592 } 9593 9594 static bool signed_add32_overflows(s32 a, s32 b) 9595 { 9596 /* Do the add in u32, where overflow is well-defined */ 9597 s32 res = (s32)((u32)a + (u32)b); 9598 9599 if (b < 0) 9600 return res > a; 9601 return res < a; 9602 } 9603 9604 static bool signed_sub_overflows(s64 a, s64 b) 9605 { 9606 /* Do the sub in u64, where overflow is well-defined */ 9607 s64 res = (s64)((u64)a - (u64)b); 9608 9609 if (b < 0) 9610 return res < a; 9611 return res > a; 9612 } 9613 9614 static bool signed_sub32_overflows(s32 a, s32 b) 9615 { 9616 /* Do the sub in u32, where overflow is well-defined */ 9617 s32 res = (s32)((u32)a - (u32)b); 9618 9619 if (b < 0) 9620 return res < a; 9621 return res > a; 9622 } 9623 9624 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 9625 const struct bpf_reg_state *reg, 9626 enum bpf_reg_type type) 9627 { 9628 bool known = tnum_is_const(reg->var_off); 9629 s64 val = reg->var_off.value; 9630 s64 smin = reg->smin_value; 9631 9632 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 9633 verbose(env, "math between %s pointer and %lld is not allowed\n", 9634 reg_type_str(env, type), val); 9635 return false; 9636 } 9637 9638 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 9639 verbose(env, "%s pointer offset %d is not allowed\n", 9640 reg_type_str(env, type), reg->off); 9641 return false; 9642 } 9643 9644 if (smin == S64_MIN) { 9645 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 9646 reg_type_str(env, type)); 9647 return false; 9648 } 9649 9650 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 9651 verbose(env, "value %lld makes %s pointer be out of bounds\n", 9652 smin, reg_type_str(env, type)); 9653 return false; 9654 } 9655 9656 return true; 9657 } 9658 9659 enum { 9660 REASON_BOUNDS = -1, 9661 REASON_TYPE = -2, 9662 REASON_PATHS = -3, 9663 REASON_LIMIT = -4, 9664 REASON_STACK = -5, 9665 }; 9666 9667 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 9668 u32 *alu_limit, bool mask_to_left) 9669 { 9670 u32 max = 0, ptr_limit = 0; 9671 9672 switch (ptr_reg->type) { 9673 case PTR_TO_STACK: 9674 /* Offset 0 is out-of-bounds, but acceptable start for the 9675 * left direction, see BPF_REG_FP. Also, unknown scalar 9676 * offset where we would need to deal with min/max bounds is 9677 * currently prohibited for unprivileged. 9678 */ 9679 max = MAX_BPF_STACK + mask_to_left; 9680 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 9681 break; 9682 case PTR_TO_MAP_VALUE: 9683 max = ptr_reg->map_ptr->value_size; 9684 ptr_limit = (mask_to_left ? 9685 ptr_reg->smin_value : 9686 ptr_reg->umax_value) + ptr_reg->off; 9687 break; 9688 default: 9689 return REASON_TYPE; 9690 } 9691 9692 if (ptr_limit >= max) 9693 return REASON_LIMIT; 9694 *alu_limit = ptr_limit; 9695 return 0; 9696 } 9697 9698 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 9699 const struct bpf_insn *insn) 9700 { 9701 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 9702 } 9703 9704 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 9705 u32 alu_state, u32 alu_limit) 9706 { 9707 /* If we arrived here from different branches with different 9708 * state or limits to sanitize, then this won't work. 9709 */ 9710 if (aux->alu_state && 9711 (aux->alu_state != alu_state || 9712 aux->alu_limit != alu_limit)) 9713 return REASON_PATHS; 9714 9715 /* Corresponding fixup done in do_misc_fixups(). */ 9716 aux->alu_state = alu_state; 9717 aux->alu_limit = alu_limit; 9718 return 0; 9719 } 9720 9721 static int sanitize_val_alu(struct bpf_verifier_env *env, 9722 struct bpf_insn *insn) 9723 { 9724 struct bpf_insn_aux_data *aux = cur_aux(env); 9725 9726 if (can_skip_alu_sanitation(env, insn)) 9727 return 0; 9728 9729 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 9730 } 9731 9732 static bool sanitize_needed(u8 opcode) 9733 { 9734 return opcode == BPF_ADD || opcode == BPF_SUB; 9735 } 9736 9737 struct bpf_sanitize_info { 9738 struct bpf_insn_aux_data aux; 9739 bool mask_to_left; 9740 }; 9741 9742 static struct bpf_verifier_state * 9743 sanitize_speculative_path(struct bpf_verifier_env *env, 9744 const struct bpf_insn *insn, 9745 u32 next_idx, u32 curr_idx) 9746 { 9747 struct bpf_verifier_state *branch; 9748 struct bpf_reg_state *regs; 9749 9750 branch = push_stack(env, next_idx, curr_idx, true); 9751 if (branch && insn) { 9752 regs = branch->frame[branch->curframe]->regs; 9753 if (BPF_SRC(insn->code) == BPF_K) { 9754 mark_reg_unknown(env, regs, insn->dst_reg); 9755 } else if (BPF_SRC(insn->code) == BPF_X) { 9756 mark_reg_unknown(env, regs, insn->dst_reg); 9757 mark_reg_unknown(env, regs, insn->src_reg); 9758 } 9759 } 9760 return branch; 9761 } 9762 9763 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 9764 struct bpf_insn *insn, 9765 const struct bpf_reg_state *ptr_reg, 9766 const struct bpf_reg_state *off_reg, 9767 struct bpf_reg_state *dst_reg, 9768 struct bpf_sanitize_info *info, 9769 const bool commit_window) 9770 { 9771 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 9772 struct bpf_verifier_state *vstate = env->cur_state; 9773 bool off_is_imm = tnum_is_const(off_reg->var_off); 9774 bool off_is_neg = off_reg->smin_value < 0; 9775 bool ptr_is_dst_reg = ptr_reg == dst_reg; 9776 u8 opcode = BPF_OP(insn->code); 9777 u32 alu_state, alu_limit; 9778 struct bpf_reg_state tmp; 9779 bool ret; 9780 int err; 9781 9782 if (can_skip_alu_sanitation(env, insn)) 9783 return 0; 9784 9785 /* We already marked aux for masking from non-speculative 9786 * paths, thus we got here in the first place. We only care 9787 * to explore bad access from here. 9788 */ 9789 if (vstate->speculative) 9790 goto do_sim; 9791 9792 if (!commit_window) { 9793 if (!tnum_is_const(off_reg->var_off) && 9794 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 9795 return REASON_BOUNDS; 9796 9797 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 9798 (opcode == BPF_SUB && !off_is_neg); 9799 } 9800 9801 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 9802 if (err < 0) 9803 return err; 9804 9805 if (commit_window) { 9806 /* In commit phase we narrow the masking window based on 9807 * the observed pointer move after the simulated operation. 9808 */ 9809 alu_state = info->aux.alu_state; 9810 alu_limit = abs(info->aux.alu_limit - alu_limit); 9811 } else { 9812 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 9813 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 9814 alu_state |= ptr_is_dst_reg ? 9815 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 9816 9817 /* Limit pruning on unknown scalars to enable deep search for 9818 * potential masking differences from other program paths. 9819 */ 9820 if (!off_is_imm) 9821 env->explore_alu_limits = true; 9822 } 9823 9824 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 9825 if (err < 0) 9826 return err; 9827 do_sim: 9828 /* If we're in commit phase, we're done here given we already 9829 * pushed the truncated dst_reg into the speculative verification 9830 * stack. 9831 * 9832 * Also, when register is a known constant, we rewrite register-based 9833 * operation to immediate-based, and thus do not need masking (and as 9834 * a consequence, do not need to simulate the zero-truncation either). 9835 */ 9836 if (commit_window || off_is_imm) 9837 return 0; 9838 9839 /* Simulate and find potential out-of-bounds access under 9840 * speculative execution from truncation as a result of 9841 * masking when off was not within expected range. If off 9842 * sits in dst, then we temporarily need to move ptr there 9843 * to simulate dst (== 0) +/-= ptr. Needed, for example, 9844 * for cases where we use K-based arithmetic in one direction 9845 * and truncated reg-based in the other in order to explore 9846 * bad access. 9847 */ 9848 if (!ptr_is_dst_reg) { 9849 tmp = *dst_reg; 9850 *dst_reg = *ptr_reg; 9851 } 9852 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 9853 env->insn_idx); 9854 if (!ptr_is_dst_reg && ret) 9855 *dst_reg = tmp; 9856 return !ret ? REASON_STACK : 0; 9857 } 9858 9859 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 9860 { 9861 struct bpf_verifier_state *vstate = env->cur_state; 9862 9863 /* If we simulate paths under speculation, we don't update the 9864 * insn as 'seen' such that when we verify unreachable paths in 9865 * the non-speculative domain, sanitize_dead_code() can still 9866 * rewrite/sanitize them. 9867 */ 9868 if (!vstate->speculative) 9869 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 9870 } 9871 9872 static int sanitize_err(struct bpf_verifier_env *env, 9873 const struct bpf_insn *insn, int reason, 9874 const struct bpf_reg_state *off_reg, 9875 const struct bpf_reg_state *dst_reg) 9876 { 9877 static const char *err = "pointer arithmetic with it prohibited for !root"; 9878 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 9879 u32 dst = insn->dst_reg, src = insn->src_reg; 9880 9881 switch (reason) { 9882 case REASON_BOUNDS: 9883 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 9884 off_reg == dst_reg ? dst : src, err); 9885 break; 9886 case REASON_TYPE: 9887 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 9888 off_reg == dst_reg ? src : dst, err); 9889 break; 9890 case REASON_PATHS: 9891 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 9892 dst, op, err); 9893 break; 9894 case REASON_LIMIT: 9895 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 9896 dst, op, err); 9897 break; 9898 case REASON_STACK: 9899 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 9900 dst, err); 9901 break; 9902 default: 9903 verbose(env, "verifier internal error: unknown reason (%d)\n", 9904 reason); 9905 break; 9906 } 9907 9908 return -EACCES; 9909 } 9910 9911 /* check that stack access falls within stack limits and that 'reg' doesn't 9912 * have a variable offset. 9913 * 9914 * Variable offset is prohibited for unprivileged mode for simplicity since it 9915 * requires corresponding support in Spectre masking for stack ALU. See also 9916 * retrieve_ptr_limit(). 9917 * 9918 * 9919 * 'off' includes 'reg->off'. 9920 */ 9921 static int check_stack_access_for_ptr_arithmetic( 9922 struct bpf_verifier_env *env, 9923 int regno, 9924 const struct bpf_reg_state *reg, 9925 int off) 9926 { 9927 if (!tnum_is_const(reg->var_off)) { 9928 char tn_buf[48]; 9929 9930 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 9931 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 9932 regno, tn_buf, off); 9933 return -EACCES; 9934 } 9935 9936 if (off >= 0 || off < -MAX_BPF_STACK) { 9937 verbose(env, "R%d stack pointer arithmetic goes out of range, " 9938 "prohibited for !root; off=%d\n", regno, off); 9939 return -EACCES; 9940 } 9941 9942 return 0; 9943 } 9944 9945 static int sanitize_check_bounds(struct bpf_verifier_env *env, 9946 const struct bpf_insn *insn, 9947 const struct bpf_reg_state *dst_reg) 9948 { 9949 u32 dst = insn->dst_reg; 9950 9951 /* For unprivileged we require that resulting offset must be in bounds 9952 * in order to be able to sanitize access later on. 9953 */ 9954 if (env->bypass_spec_v1) 9955 return 0; 9956 9957 switch (dst_reg->type) { 9958 case PTR_TO_STACK: 9959 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 9960 dst_reg->off + dst_reg->var_off.value)) 9961 return -EACCES; 9962 break; 9963 case PTR_TO_MAP_VALUE: 9964 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 9965 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 9966 "prohibited for !root\n", dst); 9967 return -EACCES; 9968 } 9969 break; 9970 default: 9971 break; 9972 } 9973 9974 return 0; 9975 } 9976 9977 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 9978 * Caller should also handle BPF_MOV case separately. 9979 * If we return -EACCES, caller may want to try again treating pointer as a 9980 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 9981 */ 9982 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 9983 struct bpf_insn *insn, 9984 const struct bpf_reg_state *ptr_reg, 9985 const struct bpf_reg_state *off_reg) 9986 { 9987 struct bpf_verifier_state *vstate = env->cur_state; 9988 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9989 struct bpf_reg_state *regs = state->regs, *dst_reg; 9990 bool known = tnum_is_const(off_reg->var_off); 9991 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 9992 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 9993 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 9994 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 9995 struct bpf_sanitize_info info = {}; 9996 u8 opcode = BPF_OP(insn->code); 9997 u32 dst = insn->dst_reg; 9998 int ret; 9999 10000 dst_reg = ®s[dst]; 10001 10002 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 10003 smin_val > smax_val || umin_val > umax_val) { 10004 /* Taint dst register if offset had invalid bounds derived from 10005 * e.g. dead branches. 10006 */ 10007 __mark_reg_unknown(env, dst_reg); 10008 return 0; 10009 } 10010 10011 if (BPF_CLASS(insn->code) != BPF_ALU64) { 10012 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 10013 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 10014 __mark_reg_unknown(env, dst_reg); 10015 return 0; 10016 } 10017 10018 verbose(env, 10019 "R%d 32-bit pointer arithmetic prohibited\n", 10020 dst); 10021 return -EACCES; 10022 } 10023 10024 if (ptr_reg->type & PTR_MAYBE_NULL) { 10025 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 10026 dst, reg_type_str(env, ptr_reg->type)); 10027 return -EACCES; 10028 } 10029 10030 switch (base_type(ptr_reg->type)) { 10031 case CONST_PTR_TO_MAP: 10032 /* smin_val represents the known value */ 10033 if (known && smin_val == 0 && opcode == BPF_ADD) 10034 break; 10035 fallthrough; 10036 case PTR_TO_PACKET_END: 10037 case PTR_TO_SOCKET: 10038 case PTR_TO_SOCK_COMMON: 10039 case PTR_TO_TCP_SOCK: 10040 case PTR_TO_XDP_SOCK: 10041 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 10042 dst, reg_type_str(env, ptr_reg->type)); 10043 return -EACCES; 10044 default: 10045 break; 10046 } 10047 10048 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 10049 * The id may be overwritten later if we create a new variable offset. 10050 */ 10051 dst_reg->type = ptr_reg->type; 10052 dst_reg->id = ptr_reg->id; 10053 10054 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 10055 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 10056 return -EINVAL; 10057 10058 /* pointer types do not carry 32-bit bounds at the moment. */ 10059 __mark_reg32_unbounded(dst_reg); 10060 10061 if (sanitize_needed(opcode)) { 10062 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 10063 &info, false); 10064 if (ret < 0) 10065 return sanitize_err(env, insn, ret, off_reg, dst_reg); 10066 } 10067 10068 switch (opcode) { 10069 case BPF_ADD: 10070 /* We can take a fixed offset as long as it doesn't overflow 10071 * the s32 'off' field 10072 */ 10073 if (known && (ptr_reg->off + smin_val == 10074 (s64)(s32)(ptr_reg->off + smin_val))) { 10075 /* pointer += K. Accumulate it into fixed offset */ 10076 dst_reg->smin_value = smin_ptr; 10077 dst_reg->smax_value = smax_ptr; 10078 dst_reg->umin_value = umin_ptr; 10079 dst_reg->umax_value = umax_ptr; 10080 dst_reg->var_off = ptr_reg->var_off; 10081 dst_reg->off = ptr_reg->off + smin_val; 10082 dst_reg->raw = ptr_reg->raw; 10083 break; 10084 } 10085 /* A new variable offset is created. Note that off_reg->off 10086 * == 0, since it's a scalar. 10087 * dst_reg gets the pointer type and since some positive 10088 * integer value was added to the pointer, give it a new 'id' 10089 * if it's a PTR_TO_PACKET. 10090 * this creates a new 'base' pointer, off_reg (variable) gets 10091 * added into the variable offset, and we copy the fixed offset 10092 * from ptr_reg. 10093 */ 10094 if (signed_add_overflows(smin_ptr, smin_val) || 10095 signed_add_overflows(smax_ptr, smax_val)) { 10096 dst_reg->smin_value = S64_MIN; 10097 dst_reg->smax_value = S64_MAX; 10098 } else { 10099 dst_reg->smin_value = smin_ptr + smin_val; 10100 dst_reg->smax_value = smax_ptr + smax_val; 10101 } 10102 if (umin_ptr + umin_val < umin_ptr || 10103 umax_ptr + umax_val < umax_ptr) { 10104 dst_reg->umin_value = 0; 10105 dst_reg->umax_value = U64_MAX; 10106 } else { 10107 dst_reg->umin_value = umin_ptr + umin_val; 10108 dst_reg->umax_value = umax_ptr + umax_val; 10109 } 10110 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 10111 dst_reg->off = ptr_reg->off; 10112 dst_reg->raw = ptr_reg->raw; 10113 if (reg_is_pkt_pointer(ptr_reg)) { 10114 dst_reg->id = ++env->id_gen; 10115 /* something was added to pkt_ptr, set range to zero */ 10116 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 10117 } 10118 break; 10119 case BPF_SUB: 10120 if (dst_reg == off_reg) { 10121 /* scalar -= pointer. Creates an unknown scalar */ 10122 verbose(env, "R%d tried to subtract pointer from scalar\n", 10123 dst); 10124 return -EACCES; 10125 } 10126 /* We don't allow subtraction from FP, because (according to 10127 * test_verifier.c test "invalid fp arithmetic", JITs might not 10128 * be able to deal with it. 10129 */ 10130 if (ptr_reg->type == PTR_TO_STACK) { 10131 verbose(env, "R%d subtraction from stack pointer prohibited\n", 10132 dst); 10133 return -EACCES; 10134 } 10135 if (known && (ptr_reg->off - smin_val == 10136 (s64)(s32)(ptr_reg->off - smin_val))) { 10137 /* pointer -= K. Subtract it from fixed offset */ 10138 dst_reg->smin_value = smin_ptr; 10139 dst_reg->smax_value = smax_ptr; 10140 dst_reg->umin_value = umin_ptr; 10141 dst_reg->umax_value = umax_ptr; 10142 dst_reg->var_off = ptr_reg->var_off; 10143 dst_reg->id = ptr_reg->id; 10144 dst_reg->off = ptr_reg->off - smin_val; 10145 dst_reg->raw = ptr_reg->raw; 10146 break; 10147 } 10148 /* A new variable offset is created. If the subtrahend is known 10149 * nonnegative, then any reg->range we had before is still good. 10150 */ 10151 if (signed_sub_overflows(smin_ptr, smax_val) || 10152 signed_sub_overflows(smax_ptr, smin_val)) { 10153 /* Overflow possible, we know nothing */ 10154 dst_reg->smin_value = S64_MIN; 10155 dst_reg->smax_value = S64_MAX; 10156 } else { 10157 dst_reg->smin_value = smin_ptr - smax_val; 10158 dst_reg->smax_value = smax_ptr - smin_val; 10159 } 10160 if (umin_ptr < umax_val) { 10161 /* Overflow possible, we know nothing */ 10162 dst_reg->umin_value = 0; 10163 dst_reg->umax_value = U64_MAX; 10164 } else { 10165 /* Cannot overflow (as long as bounds are consistent) */ 10166 dst_reg->umin_value = umin_ptr - umax_val; 10167 dst_reg->umax_value = umax_ptr - umin_val; 10168 } 10169 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 10170 dst_reg->off = ptr_reg->off; 10171 dst_reg->raw = ptr_reg->raw; 10172 if (reg_is_pkt_pointer(ptr_reg)) { 10173 dst_reg->id = ++env->id_gen; 10174 /* something was added to pkt_ptr, set range to zero */ 10175 if (smin_val < 0) 10176 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 10177 } 10178 break; 10179 case BPF_AND: 10180 case BPF_OR: 10181 case BPF_XOR: 10182 /* bitwise ops on pointers are troublesome, prohibit. */ 10183 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 10184 dst, bpf_alu_string[opcode >> 4]); 10185 return -EACCES; 10186 default: 10187 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 10188 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 10189 dst, bpf_alu_string[opcode >> 4]); 10190 return -EACCES; 10191 } 10192 10193 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 10194 return -EINVAL; 10195 reg_bounds_sync(dst_reg); 10196 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 10197 return -EACCES; 10198 if (sanitize_needed(opcode)) { 10199 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 10200 &info, true); 10201 if (ret < 0) 10202 return sanitize_err(env, insn, ret, off_reg, dst_reg); 10203 } 10204 10205 return 0; 10206 } 10207 10208 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 10209 struct bpf_reg_state *src_reg) 10210 { 10211 s32 smin_val = src_reg->s32_min_value; 10212 s32 smax_val = src_reg->s32_max_value; 10213 u32 umin_val = src_reg->u32_min_value; 10214 u32 umax_val = src_reg->u32_max_value; 10215 10216 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 10217 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 10218 dst_reg->s32_min_value = S32_MIN; 10219 dst_reg->s32_max_value = S32_MAX; 10220 } else { 10221 dst_reg->s32_min_value += smin_val; 10222 dst_reg->s32_max_value += smax_val; 10223 } 10224 if (dst_reg->u32_min_value + umin_val < umin_val || 10225 dst_reg->u32_max_value + umax_val < umax_val) { 10226 dst_reg->u32_min_value = 0; 10227 dst_reg->u32_max_value = U32_MAX; 10228 } else { 10229 dst_reg->u32_min_value += umin_val; 10230 dst_reg->u32_max_value += umax_val; 10231 } 10232 } 10233 10234 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 10235 struct bpf_reg_state *src_reg) 10236 { 10237 s64 smin_val = src_reg->smin_value; 10238 s64 smax_val = src_reg->smax_value; 10239 u64 umin_val = src_reg->umin_value; 10240 u64 umax_val = src_reg->umax_value; 10241 10242 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 10243 signed_add_overflows(dst_reg->smax_value, smax_val)) { 10244 dst_reg->smin_value = S64_MIN; 10245 dst_reg->smax_value = S64_MAX; 10246 } else { 10247 dst_reg->smin_value += smin_val; 10248 dst_reg->smax_value += smax_val; 10249 } 10250 if (dst_reg->umin_value + umin_val < umin_val || 10251 dst_reg->umax_value + umax_val < umax_val) { 10252 dst_reg->umin_value = 0; 10253 dst_reg->umax_value = U64_MAX; 10254 } else { 10255 dst_reg->umin_value += umin_val; 10256 dst_reg->umax_value += umax_val; 10257 } 10258 } 10259 10260 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 10261 struct bpf_reg_state *src_reg) 10262 { 10263 s32 smin_val = src_reg->s32_min_value; 10264 s32 smax_val = src_reg->s32_max_value; 10265 u32 umin_val = src_reg->u32_min_value; 10266 u32 umax_val = src_reg->u32_max_value; 10267 10268 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 10269 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 10270 /* Overflow possible, we know nothing */ 10271 dst_reg->s32_min_value = S32_MIN; 10272 dst_reg->s32_max_value = S32_MAX; 10273 } else { 10274 dst_reg->s32_min_value -= smax_val; 10275 dst_reg->s32_max_value -= smin_val; 10276 } 10277 if (dst_reg->u32_min_value < umax_val) { 10278 /* Overflow possible, we know nothing */ 10279 dst_reg->u32_min_value = 0; 10280 dst_reg->u32_max_value = U32_MAX; 10281 } else { 10282 /* Cannot overflow (as long as bounds are consistent) */ 10283 dst_reg->u32_min_value -= umax_val; 10284 dst_reg->u32_max_value -= umin_val; 10285 } 10286 } 10287 10288 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 10289 struct bpf_reg_state *src_reg) 10290 { 10291 s64 smin_val = src_reg->smin_value; 10292 s64 smax_val = src_reg->smax_value; 10293 u64 umin_val = src_reg->umin_value; 10294 u64 umax_val = src_reg->umax_value; 10295 10296 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 10297 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 10298 /* Overflow possible, we know nothing */ 10299 dst_reg->smin_value = S64_MIN; 10300 dst_reg->smax_value = S64_MAX; 10301 } else { 10302 dst_reg->smin_value -= smax_val; 10303 dst_reg->smax_value -= smin_val; 10304 } 10305 if (dst_reg->umin_value < umax_val) { 10306 /* Overflow possible, we know nothing */ 10307 dst_reg->umin_value = 0; 10308 dst_reg->umax_value = U64_MAX; 10309 } else { 10310 /* Cannot overflow (as long as bounds are consistent) */ 10311 dst_reg->umin_value -= umax_val; 10312 dst_reg->umax_value -= umin_val; 10313 } 10314 } 10315 10316 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 10317 struct bpf_reg_state *src_reg) 10318 { 10319 s32 smin_val = src_reg->s32_min_value; 10320 u32 umin_val = src_reg->u32_min_value; 10321 u32 umax_val = src_reg->u32_max_value; 10322 10323 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 10324 /* Ain't nobody got time to multiply that sign */ 10325 __mark_reg32_unbounded(dst_reg); 10326 return; 10327 } 10328 /* Both values are positive, so we can work with unsigned and 10329 * copy the result to signed (unless it exceeds S32_MAX). 10330 */ 10331 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 10332 /* Potential overflow, we know nothing */ 10333 __mark_reg32_unbounded(dst_reg); 10334 return; 10335 } 10336 dst_reg->u32_min_value *= umin_val; 10337 dst_reg->u32_max_value *= umax_val; 10338 if (dst_reg->u32_max_value > S32_MAX) { 10339 /* Overflow possible, we know nothing */ 10340 dst_reg->s32_min_value = S32_MIN; 10341 dst_reg->s32_max_value = S32_MAX; 10342 } else { 10343 dst_reg->s32_min_value = dst_reg->u32_min_value; 10344 dst_reg->s32_max_value = dst_reg->u32_max_value; 10345 } 10346 } 10347 10348 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 10349 struct bpf_reg_state *src_reg) 10350 { 10351 s64 smin_val = src_reg->smin_value; 10352 u64 umin_val = src_reg->umin_value; 10353 u64 umax_val = src_reg->umax_value; 10354 10355 if (smin_val < 0 || dst_reg->smin_value < 0) { 10356 /* Ain't nobody got time to multiply that sign */ 10357 __mark_reg64_unbounded(dst_reg); 10358 return; 10359 } 10360 /* Both values are positive, so we can work with unsigned and 10361 * copy the result to signed (unless it exceeds S64_MAX). 10362 */ 10363 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 10364 /* Potential overflow, we know nothing */ 10365 __mark_reg64_unbounded(dst_reg); 10366 return; 10367 } 10368 dst_reg->umin_value *= umin_val; 10369 dst_reg->umax_value *= umax_val; 10370 if (dst_reg->umax_value > S64_MAX) { 10371 /* Overflow possible, we know nothing */ 10372 dst_reg->smin_value = S64_MIN; 10373 dst_reg->smax_value = S64_MAX; 10374 } else { 10375 dst_reg->smin_value = dst_reg->umin_value; 10376 dst_reg->smax_value = dst_reg->umax_value; 10377 } 10378 } 10379 10380 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 10381 struct bpf_reg_state *src_reg) 10382 { 10383 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10384 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10385 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10386 s32 smin_val = src_reg->s32_min_value; 10387 u32 umax_val = src_reg->u32_max_value; 10388 10389 if (src_known && dst_known) { 10390 __mark_reg32_known(dst_reg, var32_off.value); 10391 return; 10392 } 10393 10394 /* We get our minimum from the var_off, since that's inherently 10395 * bitwise. Our maximum is the minimum of the operands' maxima. 10396 */ 10397 dst_reg->u32_min_value = var32_off.value; 10398 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 10399 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 10400 /* Lose signed bounds when ANDing negative numbers, 10401 * ain't nobody got time for that. 10402 */ 10403 dst_reg->s32_min_value = S32_MIN; 10404 dst_reg->s32_max_value = S32_MAX; 10405 } else { 10406 /* ANDing two positives gives a positive, so safe to 10407 * cast result into s64. 10408 */ 10409 dst_reg->s32_min_value = dst_reg->u32_min_value; 10410 dst_reg->s32_max_value = dst_reg->u32_max_value; 10411 } 10412 } 10413 10414 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 10415 struct bpf_reg_state *src_reg) 10416 { 10417 bool src_known = tnum_is_const(src_reg->var_off); 10418 bool dst_known = tnum_is_const(dst_reg->var_off); 10419 s64 smin_val = src_reg->smin_value; 10420 u64 umax_val = src_reg->umax_value; 10421 10422 if (src_known && dst_known) { 10423 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10424 return; 10425 } 10426 10427 /* We get our minimum from the var_off, since that's inherently 10428 * bitwise. Our maximum is the minimum of the operands' maxima. 10429 */ 10430 dst_reg->umin_value = dst_reg->var_off.value; 10431 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 10432 if (dst_reg->smin_value < 0 || smin_val < 0) { 10433 /* Lose signed bounds when ANDing negative numbers, 10434 * ain't nobody got time for that. 10435 */ 10436 dst_reg->smin_value = S64_MIN; 10437 dst_reg->smax_value = S64_MAX; 10438 } else { 10439 /* ANDing two positives gives a positive, so safe to 10440 * cast result into s64. 10441 */ 10442 dst_reg->smin_value = dst_reg->umin_value; 10443 dst_reg->smax_value = dst_reg->umax_value; 10444 } 10445 /* We may learn something more from the var_off */ 10446 __update_reg_bounds(dst_reg); 10447 } 10448 10449 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 10450 struct bpf_reg_state *src_reg) 10451 { 10452 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10453 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10454 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10455 s32 smin_val = src_reg->s32_min_value; 10456 u32 umin_val = src_reg->u32_min_value; 10457 10458 if (src_known && dst_known) { 10459 __mark_reg32_known(dst_reg, var32_off.value); 10460 return; 10461 } 10462 10463 /* We get our maximum from the var_off, and our minimum is the 10464 * maximum of the operands' minima 10465 */ 10466 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 10467 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 10468 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 10469 /* Lose signed bounds when ORing negative numbers, 10470 * ain't nobody got time for that. 10471 */ 10472 dst_reg->s32_min_value = S32_MIN; 10473 dst_reg->s32_max_value = S32_MAX; 10474 } else { 10475 /* ORing two positives gives a positive, so safe to 10476 * cast result into s64. 10477 */ 10478 dst_reg->s32_min_value = dst_reg->u32_min_value; 10479 dst_reg->s32_max_value = dst_reg->u32_max_value; 10480 } 10481 } 10482 10483 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 10484 struct bpf_reg_state *src_reg) 10485 { 10486 bool src_known = tnum_is_const(src_reg->var_off); 10487 bool dst_known = tnum_is_const(dst_reg->var_off); 10488 s64 smin_val = src_reg->smin_value; 10489 u64 umin_val = src_reg->umin_value; 10490 10491 if (src_known && dst_known) { 10492 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10493 return; 10494 } 10495 10496 /* We get our maximum from the var_off, and our minimum is the 10497 * maximum of the operands' minima 10498 */ 10499 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 10500 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 10501 if (dst_reg->smin_value < 0 || smin_val < 0) { 10502 /* Lose signed bounds when ORing negative numbers, 10503 * ain't nobody got time for that. 10504 */ 10505 dst_reg->smin_value = S64_MIN; 10506 dst_reg->smax_value = S64_MAX; 10507 } else { 10508 /* ORing two positives gives a positive, so safe to 10509 * cast result into s64. 10510 */ 10511 dst_reg->smin_value = dst_reg->umin_value; 10512 dst_reg->smax_value = dst_reg->umax_value; 10513 } 10514 /* We may learn something more from the var_off */ 10515 __update_reg_bounds(dst_reg); 10516 } 10517 10518 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 10519 struct bpf_reg_state *src_reg) 10520 { 10521 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10522 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10523 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10524 s32 smin_val = src_reg->s32_min_value; 10525 10526 if (src_known && dst_known) { 10527 __mark_reg32_known(dst_reg, var32_off.value); 10528 return; 10529 } 10530 10531 /* We get both minimum and maximum from the var32_off. */ 10532 dst_reg->u32_min_value = var32_off.value; 10533 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 10534 10535 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 10536 /* XORing two positive sign numbers gives a positive, 10537 * so safe to cast u32 result into s32. 10538 */ 10539 dst_reg->s32_min_value = dst_reg->u32_min_value; 10540 dst_reg->s32_max_value = dst_reg->u32_max_value; 10541 } else { 10542 dst_reg->s32_min_value = S32_MIN; 10543 dst_reg->s32_max_value = S32_MAX; 10544 } 10545 } 10546 10547 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 10548 struct bpf_reg_state *src_reg) 10549 { 10550 bool src_known = tnum_is_const(src_reg->var_off); 10551 bool dst_known = tnum_is_const(dst_reg->var_off); 10552 s64 smin_val = src_reg->smin_value; 10553 10554 if (src_known && dst_known) { 10555 /* dst_reg->var_off.value has been updated earlier */ 10556 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10557 return; 10558 } 10559 10560 /* We get both minimum and maximum from the var_off. */ 10561 dst_reg->umin_value = dst_reg->var_off.value; 10562 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 10563 10564 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 10565 /* XORing two positive sign numbers gives a positive, 10566 * so safe to cast u64 result into s64. 10567 */ 10568 dst_reg->smin_value = dst_reg->umin_value; 10569 dst_reg->smax_value = dst_reg->umax_value; 10570 } else { 10571 dst_reg->smin_value = S64_MIN; 10572 dst_reg->smax_value = S64_MAX; 10573 } 10574 10575 __update_reg_bounds(dst_reg); 10576 } 10577 10578 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 10579 u64 umin_val, u64 umax_val) 10580 { 10581 /* We lose all sign bit information (except what we can pick 10582 * up from var_off) 10583 */ 10584 dst_reg->s32_min_value = S32_MIN; 10585 dst_reg->s32_max_value = S32_MAX; 10586 /* If we might shift our top bit out, then we know nothing */ 10587 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 10588 dst_reg->u32_min_value = 0; 10589 dst_reg->u32_max_value = U32_MAX; 10590 } else { 10591 dst_reg->u32_min_value <<= umin_val; 10592 dst_reg->u32_max_value <<= umax_val; 10593 } 10594 } 10595 10596 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 10597 struct bpf_reg_state *src_reg) 10598 { 10599 u32 umax_val = src_reg->u32_max_value; 10600 u32 umin_val = src_reg->u32_min_value; 10601 /* u32 alu operation will zext upper bits */ 10602 struct tnum subreg = tnum_subreg(dst_reg->var_off); 10603 10604 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 10605 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 10606 /* Not required but being careful mark reg64 bounds as unknown so 10607 * that we are forced to pick them up from tnum and zext later and 10608 * if some path skips this step we are still safe. 10609 */ 10610 __mark_reg64_unbounded(dst_reg); 10611 __update_reg32_bounds(dst_reg); 10612 } 10613 10614 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 10615 u64 umin_val, u64 umax_val) 10616 { 10617 /* Special case <<32 because it is a common compiler pattern to sign 10618 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 10619 * positive we know this shift will also be positive so we can track 10620 * bounds correctly. Otherwise we lose all sign bit information except 10621 * what we can pick up from var_off. Perhaps we can generalize this 10622 * later to shifts of any length. 10623 */ 10624 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 10625 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 10626 else 10627 dst_reg->smax_value = S64_MAX; 10628 10629 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 10630 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 10631 else 10632 dst_reg->smin_value = S64_MIN; 10633 10634 /* If we might shift our top bit out, then we know nothing */ 10635 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 10636 dst_reg->umin_value = 0; 10637 dst_reg->umax_value = U64_MAX; 10638 } else { 10639 dst_reg->umin_value <<= umin_val; 10640 dst_reg->umax_value <<= umax_val; 10641 } 10642 } 10643 10644 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 10645 struct bpf_reg_state *src_reg) 10646 { 10647 u64 umax_val = src_reg->umax_value; 10648 u64 umin_val = src_reg->umin_value; 10649 10650 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 10651 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 10652 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 10653 10654 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 10655 /* We may learn something more from the var_off */ 10656 __update_reg_bounds(dst_reg); 10657 } 10658 10659 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 10660 struct bpf_reg_state *src_reg) 10661 { 10662 struct tnum subreg = tnum_subreg(dst_reg->var_off); 10663 u32 umax_val = src_reg->u32_max_value; 10664 u32 umin_val = src_reg->u32_min_value; 10665 10666 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 10667 * be negative, then either: 10668 * 1) src_reg might be zero, so the sign bit of the result is 10669 * unknown, so we lose our signed bounds 10670 * 2) it's known negative, thus the unsigned bounds capture the 10671 * signed bounds 10672 * 3) the signed bounds cross zero, so they tell us nothing 10673 * about the result 10674 * If the value in dst_reg is known nonnegative, then again the 10675 * unsigned bounds capture the signed bounds. 10676 * Thus, in all cases it suffices to blow away our signed bounds 10677 * and rely on inferring new ones from the unsigned bounds and 10678 * var_off of the result. 10679 */ 10680 dst_reg->s32_min_value = S32_MIN; 10681 dst_reg->s32_max_value = S32_MAX; 10682 10683 dst_reg->var_off = tnum_rshift(subreg, umin_val); 10684 dst_reg->u32_min_value >>= umax_val; 10685 dst_reg->u32_max_value >>= umin_val; 10686 10687 __mark_reg64_unbounded(dst_reg); 10688 __update_reg32_bounds(dst_reg); 10689 } 10690 10691 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 10692 struct bpf_reg_state *src_reg) 10693 { 10694 u64 umax_val = src_reg->umax_value; 10695 u64 umin_val = src_reg->umin_value; 10696 10697 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 10698 * be negative, then either: 10699 * 1) src_reg might be zero, so the sign bit of the result is 10700 * unknown, so we lose our signed bounds 10701 * 2) it's known negative, thus the unsigned bounds capture the 10702 * signed bounds 10703 * 3) the signed bounds cross zero, so they tell us nothing 10704 * about the result 10705 * If the value in dst_reg is known nonnegative, then again the 10706 * unsigned bounds capture the signed bounds. 10707 * Thus, in all cases it suffices to blow away our signed bounds 10708 * and rely on inferring new ones from the unsigned bounds and 10709 * var_off of the result. 10710 */ 10711 dst_reg->smin_value = S64_MIN; 10712 dst_reg->smax_value = S64_MAX; 10713 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 10714 dst_reg->umin_value >>= umax_val; 10715 dst_reg->umax_value >>= umin_val; 10716 10717 /* Its not easy to operate on alu32 bounds here because it depends 10718 * on bits being shifted in. Take easy way out and mark unbounded 10719 * so we can recalculate later from tnum. 10720 */ 10721 __mark_reg32_unbounded(dst_reg); 10722 __update_reg_bounds(dst_reg); 10723 } 10724 10725 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 10726 struct bpf_reg_state *src_reg) 10727 { 10728 u64 umin_val = src_reg->u32_min_value; 10729 10730 /* Upon reaching here, src_known is true and 10731 * umax_val is equal to umin_val. 10732 */ 10733 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 10734 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 10735 10736 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 10737 10738 /* blow away the dst_reg umin_value/umax_value and rely on 10739 * dst_reg var_off to refine the result. 10740 */ 10741 dst_reg->u32_min_value = 0; 10742 dst_reg->u32_max_value = U32_MAX; 10743 10744 __mark_reg64_unbounded(dst_reg); 10745 __update_reg32_bounds(dst_reg); 10746 } 10747 10748 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 10749 struct bpf_reg_state *src_reg) 10750 { 10751 u64 umin_val = src_reg->umin_value; 10752 10753 /* Upon reaching here, src_known is true and umax_val is equal 10754 * to umin_val. 10755 */ 10756 dst_reg->smin_value >>= umin_val; 10757 dst_reg->smax_value >>= umin_val; 10758 10759 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 10760 10761 /* blow away the dst_reg umin_value/umax_value and rely on 10762 * dst_reg var_off to refine the result. 10763 */ 10764 dst_reg->umin_value = 0; 10765 dst_reg->umax_value = U64_MAX; 10766 10767 /* Its not easy to operate on alu32 bounds here because it depends 10768 * on bits being shifted in from upper 32-bits. Take easy way out 10769 * and mark unbounded so we can recalculate later from tnum. 10770 */ 10771 __mark_reg32_unbounded(dst_reg); 10772 __update_reg_bounds(dst_reg); 10773 } 10774 10775 /* WARNING: This function does calculations on 64-bit values, but the actual 10776 * execution may occur on 32-bit values. Therefore, things like bitshifts 10777 * need extra checks in the 32-bit case. 10778 */ 10779 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 10780 struct bpf_insn *insn, 10781 struct bpf_reg_state *dst_reg, 10782 struct bpf_reg_state src_reg) 10783 { 10784 struct bpf_reg_state *regs = cur_regs(env); 10785 u8 opcode = BPF_OP(insn->code); 10786 bool src_known; 10787 s64 smin_val, smax_val; 10788 u64 umin_val, umax_val; 10789 s32 s32_min_val, s32_max_val; 10790 u32 u32_min_val, u32_max_val; 10791 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 10792 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 10793 int ret; 10794 10795 smin_val = src_reg.smin_value; 10796 smax_val = src_reg.smax_value; 10797 umin_val = src_reg.umin_value; 10798 umax_val = src_reg.umax_value; 10799 10800 s32_min_val = src_reg.s32_min_value; 10801 s32_max_val = src_reg.s32_max_value; 10802 u32_min_val = src_reg.u32_min_value; 10803 u32_max_val = src_reg.u32_max_value; 10804 10805 if (alu32) { 10806 src_known = tnum_subreg_is_const(src_reg.var_off); 10807 if ((src_known && 10808 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 10809 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 10810 /* Taint dst register if offset had invalid bounds 10811 * derived from e.g. dead branches. 10812 */ 10813 __mark_reg_unknown(env, dst_reg); 10814 return 0; 10815 } 10816 } else { 10817 src_known = tnum_is_const(src_reg.var_off); 10818 if ((src_known && 10819 (smin_val != smax_val || umin_val != umax_val)) || 10820 smin_val > smax_val || umin_val > umax_val) { 10821 /* Taint dst register if offset had invalid bounds 10822 * derived from e.g. dead branches. 10823 */ 10824 __mark_reg_unknown(env, dst_reg); 10825 return 0; 10826 } 10827 } 10828 10829 if (!src_known && 10830 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 10831 __mark_reg_unknown(env, dst_reg); 10832 return 0; 10833 } 10834 10835 if (sanitize_needed(opcode)) { 10836 ret = sanitize_val_alu(env, insn); 10837 if (ret < 0) 10838 return sanitize_err(env, insn, ret, NULL, NULL); 10839 } 10840 10841 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 10842 * There are two classes of instructions: The first class we track both 10843 * alu32 and alu64 sign/unsigned bounds independently this provides the 10844 * greatest amount of precision when alu operations are mixed with jmp32 10845 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 10846 * and BPF_OR. This is possible because these ops have fairly easy to 10847 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 10848 * See alu32 verifier tests for examples. The second class of 10849 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 10850 * with regards to tracking sign/unsigned bounds because the bits may 10851 * cross subreg boundaries in the alu64 case. When this happens we mark 10852 * the reg unbounded in the subreg bound space and use the resulting 10853 * tnum to calculate an approximation of the sign/unsigned bounds. 10854 */ 10855 switch (opcode) { 10856 case BPF_ADD: 10857 scalar32_min_max_add(dst_reg, &src_reg); 10858 scalar_min_max_add(dst_reg, &src_reg); 10859 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 10860 break; 10861 case BPF_SUB: 10862 scalar32_min_max_sub(dst_reg, &src_reg); 10863 scalar_min_max_sub(dst_reg, &src_reg); 10864 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 10865 break; 10866 case BPF_MUL: 10867 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 10868 scalar32_min_max_mul(dst_reg, &src_reg); 10869 scalar_min_max_mul(dst_reg, &src_reg); 10870 break; 10871 case BPF_AND: 10872 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 10873 scalar32_min_max_and(dst_reg, &src_reg); 10874 scalar_min_max_and(dst_reg, &src_reg); 10875 break; 10876 case BPF_OR: 10877 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 10878 scalar32_min_max_or(dst_reg, &src_reg); 10879 scalar_min_max_or(dst_reg, &src_reg); 10880 break; 10881 case BPF_XOR: 10882 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 10883 scalar32_min_max_xor(dst_reg, &src_reg); 10884 scalar_min_max_xor(dst_reg, &src_reg); 10885 break; 10886 case BPF_LSH: 10887 if (umax_val >= insn_bitness) { 10888 /* Shifts greater than 31 or 63 are undefined. 10889 * This includes shifts by a negative number. 10890 */ 10891 mark_reg_unknown(env, regs, insn->dst_reg); 10892 break; 10893 } 10894 if (alu32) 10895 scalar32_min_max_lsh(dst_reg, &src_reg); 10896 else 10897 scalar_min_max_lsh(dst_reg, &src_reg); 10898 break; 10899 case BPF_RSH: 10900 if (umax_val >= insn_bitness) { 10901 /* Shifts greater than 31 or 63 are undefined. 10902 * This includes shifts by a negative number. 10903 */ 10904 mark_reg_unknown(env, regs, insn->dst_reg); 10905 break; 10906 } 10907 if (alu32) 10908 scalar32_min_max_rsh(dst_reg, &src_reg); 10909 else 10910 scalar_min_max_rsh(dst_reg, &src_reg); 10911 break; 10912 case BPF_ARSH: 10913 if (umax_val >= insn_bitness) { 10914 /* Shifts greater than 31 or 63 are undefined. 10915 * This includes shifts by a negative number. 10916 */ 10917 mark_reg_unknown(env, regs, insn->dst_reg); 10918 break; 10919 } 10920 if (alu32) 10921 scalar32_min_max_arsh(dst_reg, &src_reg); 10922 else 10923 scalar_min_max_arsh(dst_reg, &src_reg); 10924 break; 10925 default: 10926 mark_reg_unknown(env, regs, insn->dst_reg); 10927 break; 10928 } 10929 10930 /* ALU32 ops are zero extended into 64bit register */ 10931 if (alu32) 10932 zext_32_to_64(dst_reg); 10933 reg_bounds_sync(dst_reg); 10934 return 0; 10935 } 10936 10937 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 10938 * and var_off. 10939 */ 10940 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 10941 struct bpf_insn *insn) 10942 { 10943 struct bpf_verifier_state *vstate = env->cur_state; 10944 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 10945 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 10946 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 10947 u8 opcode = BPF_OP(insn->code); 10948 int err; 10949 10950 dst_reg = ®s[insn->dst_reg]; 10951 src_reg = NULL; 10952 if (dst_reg->type != SCALAR_VALUE) 10953 ptr_reg = dst_reg; 10954 else 10955 /* Make sure ID is cleared otherwise dst_reg min/max could be 10956 * incorrectly propagated into other registers by find_equal_scalars() 10957 */ 10958 dst_reg->id = 0; 10959 if (BPF_SRC(insn->code) == BPF_X) { 10960 src_reg = ®s[insn->src_reg]; 10961 if (src_reg->type != SCALAR_VALUE) { 10962 if (dst_reg->type != SCALAR_VALUE) { 10963 /* Combining two pointers by any ALU op yields 10964 * an arbitrary scalar. Disallow all math except 10965 * pointer subtraction 10966 */ 10967 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 10968 mark_reg_unknown(env, regs, insn->dst_reg); 10969 return 0; 10970 } 10971 verbose(env, "R%d pointer %s pointer prohibited\n", 10972 insn->dst_reg, 10973 bpf_alu_string[opcode >> 4]); 10974 return -EACCES; 10975 } else { 10976 /* scalar += pointer 10977 * This is legal, but we have to reverse our 10978 * src/dest handling in computing the range 10979 */ 10980 err = mark_chain_precision(env, insn->dst_reg); 10981 if (err) 10982 return err; 10983 return adjust_ptr_min_max_vals(env, insn, 10984 src_reg, dst_reg); 10985 } 10986 } else if (ptr_reg) { 10987 /* pointer += scalar */ 10988 err = mark_chain_precision(env, insn->src_reg); 10989 if (err) 10990 return err; 10991 return adjust_ptr_min_max_vals(env, insn, 10992 dst_reg, src_reg); 10993 } else if (dst_reg->precise) { 10994 /* if dst_reg is precise, src_reg should be precise as well */ 10995 err = mark_chain_precision(env, insn->src_reg); 10996 if (err) 10997 return err; 10998 } 10999 } else { 11000 /* Pretend the src is a reg with a known value, since we only 11001 * need to be able to read from this state. 11002 */ 11003 off_reg.type = SCALAR_VALUE; 11004 __mark_reg_known(&off_reg, insn->imm); 11005 src_reg = &off_reg; 11006 if (ptr_reg) /* pointer += K */ 11007 return adjust_ptr_min_max_vals(env, insn, 11008 ptr_reg, src_reg); 11009 } 11010 11011 /* Got here implies adding two SCALAR_VALUEs */ 11012 if (WARN_ON_ONCE(ptr_reg)) { 11013 print_verifier_state(env, state, true); 11014 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 11015 return -EINVAL; 11016 } 11017 if (WARN_ON(!src_reg)) { 11018 print_verifier_state(env, state, true); 11019 verbose(env, "verifier internal error: no src_reg\n"); 11020 return -EINVAL; 11021 } 11022 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 11023 } 11024 11025 /* check validity of 32-bit and 64-bit arithmetic operations */ 11026 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 11027 { 11028 struct bpf_reg_state *regs = cur_regs(env); 11029 u8 opcode = BPF_OP(insn->code); 11030 int err; 11031 11032 if (opcode == BPF_END || opcode == BPF_NEG) { 11033 if (opcode == BPF_NEG) { 11034 if (BPF_SRC(insn->code) != BPF_K || 11035 insn->src_reg != BPF_REG_0 || 11036 insn->off != 0 || insn->imm != 0) { 11037 verbose(env, "BPF_NEG uses reserved fields\n"); 11038 return -EINVAL; 11039 } 11040 } else { 11041 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 11042 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 11043 BPF_CLASS(insn->code) == BPF_ALU64) { 11044 verbose(env, "BPF_END uses reserved fields\n"); 11045 return -EINVAL; 11046 } 11047 } 11048 11049 /* check src operand */ 11050 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11051 if (err) 11052 return err; 11053 11054 if (is_pointer_value(env, insn->dst_reg)) { 11055 verbose(env, "R%d pointer arithmetic prohibited\n", 11056 insn->dst_reg); 11057 return -EACCES; 11058 } 11059 11060 /* check dest operand */ 11061 err = check_reg_arg(env, insn->dst_reg, DST_OP); 11062 if (err) 11063 return err; 11064 11065 } else if (opcode == BPF_MOV) { 11066 11067 if (BPF_SRC(insn->code) == BPF_X) { 11068 if (insn->imm != 0 || insn->off != 0) { 11069 verbose(env, "BPF_MOV uses reserved fields\n"); 11070 return -EINVAL; 11071 } 11072 11073 /* check src operand */ 11074 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11075 if (err) 11076 return err; 11077 } else { 11078 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 11079 verbose(env, "BPF_MOV uses reserved fields\n"); 11080 return -EINVAL; 11081 } 11082 } 11083 11084 /* check dest operand, mark as required later */ 11085 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 11086 if (err) 11087 return err; 11088 11089 if (BPF_SRC(insn->code) == BPF_X) { 11090 struct bpf_reg_state *src_reg = regs + insn->src_reg; 11091 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 11092 11093 if (BPF_CLASS(insn->code) == BPF_ALU64) { 11094 /* case: R1 = R2 11095 * copy register state to dest reg 11096 */ 11097 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 11098 /* Assign src and dst registers the same ID 11099 * that will be used by find_equal_scalars() 11100 * to propagate min/max range. 11101 */ 11102 src_reg->id = ++env->id_gen; 11103 *dst_reg = *src_reg; 11104 dst_reg->live |= REG_LIVE_WRITTEN; 11105 dst_reg->subreg_def = DEF_NOT_SUBREG; 11106 } else { 11107 /* R1 = (u32) R2 */ 11108 if (is_pointer_value(env, insn->src_reg)) { 11109 verbose(env, 11110 "R%d partial copy of pointer\n", 11111 insn->src_reg); 11112 return -EACCES; 11113 } else if (src_reg->type == SCALAR_VALUE) { 11114 *dst_reg = *src_reg; 11115 /* Make sure ID is cleared otherwise 11116 * dst_reg min/max could be incorrectly 11117 * propagated into src_reg by find_equal_scalars() 11118 */ 11119 dst_reg->id = 0; 11120 dst_reg->live |= REG_LIVE_WRITTEN; 11121 dst_reg->subreg_def = env->insn_idx + 1; 11122 } else { 11123 mark_reg_unknown(env, regs, 11124 insn->dst_reg); 11125 } 11126 zext_32_to_64(dst_reg); 11127 reg_bounds_sync(dst_reg); 11128 } 11129 } else { 11130 /* case: R = imm 11131 * remember the value we stored into this reg 11132 */ 11133 /* clear any state __mark_reg_known doesn't set */ 11134 mark_reg_unknown(env, regs, insn->dst_reg); 11135 regs[insn->dst_reg].type = SCALAR_VALUE; 11136 if (BPF_CLASS(insn->code) == BPF_ALU64) { 11137 __mark_reg_known(regs + insn->dst_reg, 11138 insn->imm); 11139 } else { 11140 __mark_reg_known(regs + insn->dst_reg, 11141 (u32)insn->imm); 11142 } 11143 } 11144 11145 } else if (opcode > BPF_END) { 11146 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 11147 return -EINVAL; 11148 11149 } else { /* all other ALU ops: and, sub, xor, add, ... */ 11150 11151 if (BPF_SRC(insn->code) == BPF_X) { 11152 if (insn->imm != 0 || insn->off != 0) { 11153 verbose(env, "BPF_ALU uses reserved fields\n"); 11154 return -EINVAL; 11155 } 11156 /* check src1 operand */ 11157 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11158 if (err) 11159 return err; 11160 } else { 11161 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 11162 verbose(env, "BPF_ALU uses reserved fields\n"); 11163 return -EINVAL; 11164 } 11165 } 11166 11167 /* check src2 operand */ 11168 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11169 if (err) 11170 return err; 11171 11172 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 11173 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 11174 verbose(env, "div by zero\n"); 11175 return -EINVAL; 11176 } 11177 11178 if ((opcode == BPF_LSH || opcode == BPF_RSH || 11179 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 11180 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 11181 11182 if (insn->imm < 0 || insn->imm >= size) { 11183 verbose(env, "invalid shift %d\n", insn->imm); 11184 return -EINVAL; 11185 } 11186 } 11187 11188 /* check dest operand */ 11189 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 11190 if (err) 11191 return err; 11192 11193 return adjust_reg_min_max_vals(env, insn); 11194 } 11195 11196 return 0; 11197 } 11198 11199 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 11200 struct bpf_reg_state *dst_reg, 11201 enum bpf_reg_type type, 11202 bool range_right_open) 11203 { 11204 struct bpf_func_state *state; 11205 struct bpf_reg_state *reg; 11206 int new_range; 11207 11208 if (dst_reg->off < 0 || 11209 (dst_reg->off == 0 && range_right_open)) 11210 /* This doesn't give us any range */ 11211 return; 11212 11213 if (dst_reg->umax_value > MAX_PACKET_OFF || 11214 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 11215 /* Risk of overflow. For instance, ptr + (1<<63) may be less 11216 * than pkt_end, but that's because it's also less than pkt. 11217 */ 11218 return; 11219 11220 new_range = dst_reg->off; 11221 if (range_right_open) 11222 new_range++; 11223 11224 /* Examples for register markings: 11225 * 11226 * pkt_data in dst register: 11227 * 11228 * r2 = r3; 11229 * r2 += 8; 11230 * if (r2 > pkt_end) goto <handle exception> 11231 * <access okay> 11232 * 11233 * r2 = r3; 11234 * r2 += 8; 11235 * if (r2 < pkt_end) goto <access okay> 11236 * <handle exception> 11237 * 11238 * Where: 11239 * r2 == dst_reg, pkt_end == src_reg 11240 * r2=pkt(id=n,off=8,r=0) 11241 * r3=pkt(id=n,off=0,r=0) 11242 * 11243 * pkt_data in src register: 11244 * 11245 * r2 = r3; 11246 * r2 += 8; 11247 * if (pkt_end >= r2) goto <access okay> 11248 * <handle exception> 11249 * 11250 * r2 = r3; 11251 * r2 += 8; 11252 * if (pkt_end <= r2) goto <handle exception> 11253 * <access okay> 11254 * 11255 * Where: 11256 * pkt_end == dst_reg, r2 == src_reg 11257 * r2=pkt(id=n,off=8,r=0) 11258 * r3=pkt(id=n,off=0,r=0) 11259 * 11260 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 11261 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 11262 * and [r3, r3 + 8-1) respectively is safe to access depending on 11263 * the check. 11264 */ 11265 11266 /* If our ids match, then we must have the same max_value. And we 11267 * don't care about the other reg's fixed offset, since if it's too big 11268 * the range won't allow anything. 11269 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 11270 */ 11271 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 11272 if (reg->type == type && reg->id == dst_reg->id) 11273 /* keep the maximum range already checked */ 11274 reg->range = max(reg->range, new_range); 11275 })); 11276 } 11277 11278 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 11279 { 11280 struct tnum subreg = tnum_subreg(reg->var_off); 11281 s32 sval = (s32)val; 11282 11283 switch (opcode) { 11284 case BPF_JEQ: 11285 if (tnum_is_const(subreg)) 11286 return !!tnum_equals_const(subreg, val); 11287 break; 11288 case BPF_JNE: 11289 if (tnum_is_const(subreg)) 11290 return !tnum_equals_const(subreg, val); 11291 break; 11292 case BPF_JSET: 11293 if ((~subreg.mask & subreg.value) & val) 11294 return 1; 11295 if (!((subreg.mask | subreg.value) & val)) 11296 return 0; 11297 break; 11298 case BPF_JGT: 11299 if (reg->u32_min_value > val) 11300 return 1; 11301 else if (reg->u32_max_value <= val) 11302 return 0; 11303 break; 11304 case BPF_JSGT: 11305 if (reg->s32_min_value > sval) 11306 return 1; 11307 else if (reg->s32_max_value <= sval) 11308 return 0; 11309 break; 11310 case BPF_JLT: 11311 if (reg->u32_max_value < val) 11312 return 1; 11313 else if (reg->u32_min_value >= val) 11314 return 0; 11315 break; 11316 case BPF_JSLT: 11317 if (reg->s32_max_value < sval) 11318 return 1; 11319 else if (reg->s32_min_value >= sval) 11320 return 0; 11321 break; 11322 case BPF_JGE: 11323 if (reg->u32_min_value >= val) 11324 return 1; 11325 else if (reg->u32_max_value < val) 11326 return 0; 11327 break; 11328 case BPF_JSGE: 11329 if (reg->s32_min_value >= sval) 11330 return 1; 11331 else if (reg->s32_max_value < sval) 11332 return 0; 11333 break; 11334 case BPF_JLE: 11335 if (reg->u32_max_value <= val) 11336 return 1; 11337 else if (reg->u32_min_value > val) 11338 return 0; 11339 break; 11340 case BPF_JSLE: 11341 if (reg->s32_max_value <= sval) 11342 return 1; 11343 else if (reg->s32_min_value > sval) 11344 return 0; 11345 break; 11346 } 11347 11348 return -1; 11349 } 11350 11351 11352 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 11353 { 11354 s64 sval = (s64)val; 11355 11356 switch (opcode) { 11357 case BPF_JEQ: 11358 if (tnum_is_const(reg->var_off)) 11359 return !!tnum_equals_const(reg->var_off, val); 11360 break; 11361 case BPF_JNE: 11362 if (tnum_is_const(reg->var_off)) 11363 return !tnum_equals_const(reg->var_off, val); 11364 break; 11365 case BPF_JSET: 11366 if ((~reg->var_off.mask & reg->var_off.value) & val) 11367 return 1; 11368 if (!((reg->var_off.mask | reg->var_off.value) & val)) 11369 return 0; 11370 break; 11371 case BPF_JGT: 11372 if (reg->umin_value > val) 11373 return 1; 11374 else if (reg->umax_value <= val) 11375 return 0; 11376 break; 11377 case BPF_JSGT: 11378 if (reg->smin_value > sval) 11379 return 1; 11380 else if (reg->smax_value <= sval) 11381 return 0; 11382 break; 11383 case BPF_JLT: 11384 if (reg->umax_value < val) 11385 return 1; 11386 else if (reg->umin_value >= val) 11387 return 0; 11388 break; 11389 case BPF_JSLT: 11390 if (reg->smax_value < sval) 11391 return 1; 11392 else if (reg->smin_value >= sval) 11393 return 0; 11394 break; 11395 case BPF_JGE: 11396 if (reg->umin_value >= val) 11397 return 1; 11398 else if (reg->umax_value < val) 11399 return 0; 11400 break; 11401 case BPF_JSGE: 11402 if (reg->smin_value >= sval) 11403 return 1; 11404 else if (reg->smax_value < sval) 11405 return 0; 11406 break; 11407 case BPF_JLE: 11408 if (reg->umax_value <= val) 11409 return 1; 11410 else if (reg->umin_value > val) 11411 return 0; 11412 break; 11413 case BPF_JSLE: 11414 if (reg->smax_value <= sval) 11415 return 1; 11416 else if (reg->smin_value > sval) 11417 return 0; 11418 break; 11419 } 11420 11421 return -1; 11422 } 11423 11424 /* compute branch direction of the expression "if (reg opcode val) goto target;" 11425 * and return: 11426 * 1 - branch will be taken and "goto target" will be executed 11427 * 0 - branch will not be taken and fall-through to next insn 11428 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 11429 * range [0,10] 11430 */ 11431 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 11432 bool is_jmp32) 11433 { 11434 if (__is_pointer_value(false, reg)) { 11435 if (!reg_type_not_null(reg->type)) 11436 return -1; 11437 11438 /* If pointer is valid tests against zero will fail so we can 11439 * use this to direct branch taken. 11440 */ 11441 if (val != 0) 11442 return -1; 11443 11444 switch (opcode) { 11445 case BPF_JEQ: 11446 return 0; 11447 case BPF_JNE: 11448 return 1; 11449 default: 11450 return -1; 11451 } 11452 } 11453 11454 if (is_jmp32) 11455 return is_branch32_taken(reg, val, opcode); 11456 return is_branch64_taken(reg, val, opcode); 11457 } 11458 11459 static int flip_opcode(u32 opcode) 11460 { 11461 /* How can we transform "a <op> b" into "b <op> a"? */ 11462 static const u8 opcode_flip[16] = { 11463 /* these stay the same */ 11464 [BPF_JEQ >> 4] = BPF_JEQ, 11465 [BPF_JNE >> 4] = BPF_JNE, 11466 [BPF_JSET >> 4] = BPF_JSET, 11467 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 11468 [BPF_JGE >> 4] = BPF_JLE, 11469 [BPF_JGT >> 4] = BPF_JLT, 11470 [BPF_JLE >> 4] = BPF_JGE, 11471 [BPF_JLT >> 4] = BPF_JGT, 11472 [BPF_JSGE >> 4] = BPF_JSLE, 11473 [BPF_JSGT >> 4] = BPF_JSLT, 11474 [BPF_JSLE >> 4] = BPF_JSGE, 11475 [BPF_JSLT >> 4] = BPF_JSGT 11476 }; 11477 return opcode_flip[opcode >> 4]; 11478 } 11479 11480 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 11481 struct bpf_reg_state *src_reg, 11482 u8 opcode) 11483 { 11484 struct bpf_reg_state *pkt; 11485 11486 if (src_reg->type == PTR_TO_PACKET_END) { 11487 pkt = dst_reg; 11488 } else if (dst_reg->type == PTR_TO_PACKET_END) { 11489 pkt = src_reg; 11490 opcode = flip_opcode(opcode); 11491 } else { 11492 return -1; 11493 } 11494 11495 if (pkt->range >= 0) 11496 return -1; 11497 11498 switch (opcode) { 11499 case BPF_JLE: 11500 /* pkt <= pkt_end */ 11501 fallthrough; 11502 case BPF_JGT: 11503 /* pkt > pkt_end */ 11504 if (pkt->range == BEYOND_PKT_END) 11505 /* pkt has at last one extra byte beyond pkt_end */ 11506 return opcode == BPF_JGT; 11507 break; 11508 case BPF_JLT: 11509 /* pkt < pkt_end */ 11510 fallthrough; 11511 case BPF_JGE: 11512 /* pkt >= pkt_end */ 11513 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 11514 return opcode == BPF_JGE; 11515 break; 11516 } 11517 return -1; 11518 } 11519 11520 /* Adjusts the register min/max values in the case that the dst_reg is the 11521 * variable register that we are working on, and src_reg is a constant or we're 11522 * simply doing a BPF_K check. 11523 * In JEQ/JNE cases we also adjust the var_off values. 11524 */ 11525 static void reg_set_min_max(struct bpf_reg_state *true_reg, 11526 struct bpf_reg_state *false_reg, 11527 u64 val, u32 val32, 11528 u8 opcode, bool is_jmp32) 11529 { 11530 struct tnum false_32off = tnum_subreg(false_reg->var_off); 11531 struct tnum false_64off = false_reg->var_off; 11532 struct tnum true_32off = tnum_subreg(true_reg->var_off); 11533 struct tnum true_64off = true_reg->var_off; 11534 s64 sval = (s64)val; 11535 s32 sval32 = (s32)val32; 11536 11537 /* If the dst_reg is a pointer, we can't learn anything about its 11538 * variable offset from the compare (unless src_reg were a pointer into 11539 * the same object, but we don't bother with that. 11540 * Since false_reg and true_reg have the same type by construction, we 11541 * only need to check one of them for pointerness. 11542 */ 11543 if (__is_pointer_value(false, false_reg)) 11544 return; 11545 11546 switch (opcode) { 11547 /* JEQ/JNE comparison doesn't change the register equivalence. 11548 * 11549 * r1 = r2; 11550 * if (r1 == 42) goto label; 11551 * ... 11552 * label: // here both r1 and r2 are known to be 42. 11553 * 11554 * Hence when marking register as known preserve it's ID. 11555 */ 11556 case BPF_JEQ: 11557 if (is_jmp32) { 11558 __mark_reg32_known(true_reg, val32); 11559 true_32off = tnum_subreg(true_reg->var_off); 11560 } else { 11561 ___mark_reg_known(true_reg, val); 11562 true_64off = true_reg->var_off; 11563 } 11564 break; 11565 case BPF_JNE: 11566 if (is_jmp32) { 11567 __mark_reg32_known(false_reg, val32); 11568 false_32off = tnum_subreg(false_reg->var_off); 11569 } else { 11570 ___mark_reg_known(false_reg, val); 11571 false_64off = false_reg->var_off; 11572 } 11573 break; 11574 case BPF_JSET: 11575 if (is_jmp32) { 11576 false_32off = tnum_and(false_32off, tnum_const(~val32)); 11577 if (is_power_of_2(val32)) 11578 true_32off = tnum_or(true_32off, 11579 tnum_const(val32)); 11580 } else { 11581 false_64off = tnum_and(false_64off, tnum_const(~val)); 11582 if (is_power_of_2(val)) 11583 true_64off = tnum_or(true_64off, 11584 tnum_const(val)); 11585 } 11586 break; 11587 case BPF_JGE: 11588 case BPF_JGT: 11589 { 11590 if (is_jmp32) { 11591 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 11592 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 11593 11594 false_reg->u32_max_value = min(false_reg->u32_max_value, 11595 false_umax); 11596 true_reg->u32_min_value = max(true_reg->u32_min_value, 11597 true_umin); 11598 } else { 11599 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 11600 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 11601 11602 false_reg->umax_value = min(false_reg->umax_value, false_umax); 11603 true_reg->umin_value = max(true_reg->umin_value, true_umin); 11604 } 11605 break; 11606 } 11607 case BPF_JSGE: 11608 case BPF_JSGT: 11609 { 11610 if (is_jmp32) { 11611 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 11612 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 11613 11614 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 11615 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 11616 } else { 11617 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 11618 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 11619 11620 false_reg->smax_value = min(false_reg->smax_value, false_smax); 11621 true_reg->smin_value = max(true_reg->smin_value, true_smin); 11622 } 11623 break; 11624 } 11625 case BPF_JLE: 11626 case BPF_JLT: 11627 { 11628 if (is_jmp32) { 11629 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 11630 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 11631 11632 false_reg->u32_min_value = max(false_reg->u32_min_value, 11633 false_umin); 11634 true_reg->u32_max_value = min(true_reg->u32_max_value, 11635 true_umax); 11636 } else { 11637 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 11638 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 11639 11640 false_reg->umin_value = max(false_reg->umin_value, false_umin); 11641 true_reg->umax_value = min(true_reg->umax_value, true_umax); 11642 } 11643 break; 11644 } 11645 case BPF_JSLE: 11646 case BPF_JSLT: 11647 { 11648 if (is_jmp32) { 11649 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 11650 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 11651 11652 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 11653 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 11654 } else { 11655 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 11656 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 11657 11658 false_reg->smin_value = max(false_reg->smin_value, false_smin); 11659 true_reg->smax_value = min(true_reg->smax_value, true_smax); 11660 } 11661 break; 11662 } 11663 default: 11664 return; 11665 } 11666 11667 if (is_jmp32) { 11668 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 11669 tnum_subreg(false_32off)); 11670 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 11671 tnum_subreg(true_32off)); 11672 __reg_combine_32_into_64(false_reg); 11673 __reg_combine_32_into_64(true_reg); 11674 } else { 11675 false_reg->var_off = false_64off; 11676 true_reg->var_off = true_64off; 11677 __reg_combine_64_into_32(false_reg); 11678 __reg_combine_64_into_32(true_reg); 11679 } 11680 } 11681 11682 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 11683 * the variable reg. 11684 */ 11685 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 11686 struct bpf_reg_state *false_reg, 11687 u64 val, u32 val32, 11688 u8 opcode, bool is_jmp32) 11689 { 11690 opcode = flip_opcode(opcode); 11691 /* This uses zero as "not present in table"; luckily the zero opcode, 11692 * BPF_JA, can't get here. 11693 */ 11694 if (opcode) 11695 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 11696 } 11697 11698 /* Regs are known to be equal, so intersect their min/max/var_off */ 11699 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 11700 struct bpf_reg_state *dst_reg) 11701 { 11702 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 11703 dst_reg->umin_value); 11704 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 11705 dst_reg->umax_value); 11706 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 11707 dst_reg->smin_value); 11708 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 11709 dst_reg->smax_value); 11710 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 11711 dst_reg->var_off); 11712 reg_bounds_sync(src_reg); 11713 reg_bounds_sync(dst_reg); 11714 } 11715 11716 static void reg_combine_min_max(struct bpf_reg_state *true_src, 11717 struct bpf_reg_state *true_dst, 11718 struct bpf_reg_state *false_src, 11719 struct bpf_reg_state *false_dst, 11720 u8 opcode) 11721 { 11722 switch (opcode) { 11723 case BPF_JEQ: 11724 __reg_combine_min_max(true_src, true_dst); 11725 break; 11726 case BPF_JNE: 11727 __reg_combine_min_max(false_src, false_dst); 11728 break; 11729 } 11730 } 11731 11732 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 11733 struct bpf_reg_state *reg, u32 id, 11734 bool is_null) 11735 { 11736 if (type_may_be_null(reg->type) && reg->id == id && 11737 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 11738 /* Old offset (both fixed and variable parts) should have been 11739 * known-zero, because we don't allow pointer arithmetic on 11740 * pointers that might be NULL. If we see this happening, don't 11741 * convert the register. 11742 * 11743 * But in some cases, some helpers that return local kptrs 11744 * advance offset for the returned pointer. In those cases, it 11745 * is fine to expect to see reg->off. 11746 */ 11747 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 11748 return; 11749 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off)) 11750 return; 11751 if (is_null) { 11752 reg->type = SCALAR_VALUE; 11753 /* We don't need id and ref_obj_id from this point 11754 * onwards anymore, thus we should better reset it, 11755 * so that state pruning has chances to take effect. 11756 */ 11757 reg->id = 0; 11758 reg->ref_obj_id = 0; 11759 11760 return; 11761 } 11762 11763 mark_ptr_not_null_reg(reg); 11764 11765 if (!reg_may_point_to_spin_lock(reg)) { 11766 /* For not-NULL ptr, reg->ref_obj_id will be reset 11767 * in release_reference(). 11768 * 11769 * reg->id is still used by spin_lock ptr. Other 11770 * than spin_lock ptr type, reg->id can be reset. 11771 */ 11772 reg->id = 0; 11773 } 11774 } 11775 } 11776 11777 /* The logic is similar to find_good_pkt_pointers(), both could eventually 11778 * be folded together at some point. 11779 */ 11780 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 11781 bool is_null) 11782 { 11783 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 11784 struct bpf_reg_state *regs = state->regs, *reg; 11785 u32 ref_obj_id = regs[regno].ref_obj_id; 11786 u32 id = regs[regno].id; 11787 11788 if (ref_obj_id && ref_obj_id == id && is_null) 11789 /* regs[regno] is in the " == NULL" branch. 11790 * No one could have freed the reference state before 11791 * doing the NULL check. 11792 */ 11793 WARN_ON_ONCE(release_reference_state(state, id)); 11794 11795 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 11796 mark_ptr_or_null_reg(state, reg, id, is_null); 11797 })); 11798 } 11799 11800 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 11801 struct bpf_reg_state *dst_reg, 11802 struct bpf_reg_state *src_reg, 11803 struct bpf_verifier_state *this_branch, 11804 struct bpf_verifier_state *other_branch) 11805 { 11806 if (BPF_SRC(insn->code) != BPF_X) 11807 return false; 11808 11809 /* Pointers are always 64-bit. */ 11810 if (BPF_CLASS(insn->code) == BPF_JMP32) 11811 return false; 11812 11813 switch (BPF_OP(insn->code)) { 11814 case BPF_JGT: 11815 if ((dst_reg->type == PTR_TO_PACKET && 11816 src_reg->type == PTR_TO_PACKET_END) || 11817 (dst_reg->type == PTR_TO_PACKET_META && 11818 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11819 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 11820 find_good_pkt_pointers(this_branch, dst_reg, 11821 dst_reg->type, false); 11822 mark_pkt_end(other_branch, insn->dst_reg, true); 11823 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11824 src_reg->type == PTR_TO_PACKET) || 11825 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11826 src_reg->type == PTR_TO_PACKET_META)) { 11827 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 11828 find_good_pkt_pointers(other_branch, src_reg, 11829 src_reg->type, true); 11830 mark_pkt_end(this_branch, insn->src_reg, false); 11831 } else { 11832 return false; 11833 } 11834 break; 11835 case BPF_JLT: 11836 if ((dst_reg->type == PTR_TO_PACKET && 11837 src_reg->type == PTR_TO_PACKET_END) || 11838 (dst_reg->type == PTR_TO_PACKET_META && 11839 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11840 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 11841 find_good_pkt_pointers(other_branch, dst_reg, 11842 dst_reg->type, true); 11843 mark_pkt_end(this_branch, insn->dst_reg, false); 11844 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11845 src_reg->type == PTR_TO_PACKET) || 11846 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11847 src_reg->type == PTR_TO_PACKET_META)) { 11848 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 11849 find_good_pkt_pointers(this_branch, src_reg, 11850 src_reg->type, false); 11851 mark_pkt_end(other_branch, insn->src_reg, true); 11852 } else { 11853 return false; 11854 } 11855 break; 11856 case BPF_JGE: 11857 if ((dst_reg->type == PTR_TO_PACKET && 11858 src_reg->type == PTR_TO_PACKET_END) || 11859 (dst_reg->type == PTR_TO_PACKET_META && 11860 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11861 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 11862 find_good_pkt_pointers(this_branch, dst_reg, 11863 dst_reg->type, true); 11864 mark_pkt_end(other_branch, insn->dst_reg, false); 11865 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11866 src_reg->type == PTR_TO_PACKET) || 11867 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11868 src_reg->type == PTR_TO_PACKET_META)) { 11869 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 11870 find_good_pkt_pointers(other_branch, src_reg, 11871 src_reg->type, false); 11872 mark_pkt_end(this_branch, insn->src_reg, true); 11873 } else { 11874 return false; 11875 } 11876 break; 11877 case BPF_JLE: 11878 if ((dst_reg->type == PTR_TO_PACKET && 11879 src_reg->type == PTR_TO_PACKET_END) || 11880 (dst_reg->type == PTR_TO_PACKET_META && 11881 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11882 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 11883 find_good_pkt_pointers(other_branch, dst_reg, 11884 dst_reg->type, false); 11885 mark_pkt_end(this_branch, insn->dst_reg, true); 11886 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11887 src_reg->type == PTR_TO_PACKET) || 11888 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11889 src_reg->type == PTR_TO_PACKET_META)) { 11890 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 11891 find_good_pkt_pointers(this_branch, src_reg, 11892 src_reg->type, true); 11893 mark_pkt_end(other_branch, insn->src_reg, false); 11894 } else { 11895 return false; 11896 } 11897 break; 11898 default: 11899 return false; 11900 } 11901 11902 return true; 11903 } 11904 11905 static void find_equal_scalars(struct bpf_verifier_state *vstate, 11906 struct bpf_reg_state *known_reg) 11907 { 11908 struct bpf_func_state *state; 11909 struct bpf_reg_state *reg; 11910 11911 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 11912 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 11913 *reg = *known_reg; 11914 })); 11915 } 11916 11917 static int check_cond_jmp_op(struct bpf_verifier_env *env, 11918 struct bpf_insn *insn, int *insn_idx) 11919 { 11920 struct bpf_verifier_state *this_branch = env->cur_state; 11921 struct bpf_verifier_state *other_branch; 11922 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 11923 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 11924 struct bpf_reg_state *eq_branch_regs; 11925 u8 opcode = BPF_OP(insn->code); 11926 bool is_jmp32; 11927 int pred = -1; 11928 int err; 11929 11930 /* Only conditional jumps are expected to reach here. */ 11931 if (opcode == BPF_JA || opcode > BPF_JSLE) { 11932 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 11933 return -EINVAL; 11934 } 11935 11936 if (BPF_SRC(insn->code) == BPF_X) { 11937 if (insn->imm != 0) { 11938 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 11939 return -EINVAL; 11940 } 11941 11942 /* check src1 operand */ 11943 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11944 if (err) 11945 return err; 11946 11947 if (is_pointer_value(env, insn->src_reg)) { 11948 verbose(env, "R%d pointer comparison prohibited\n", 11949 insn->src_reg); 11950 return -EACCES; 11951 } 11952 src_reg = ®s[insn->src_reg]; 11953 } else { 11954 if (insn->src_reg != BPF_REG_0) { 11955 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 11956 return -EINVAL; 11957 } 11958 } 11959 11960 /* check src2 operand */ 11961 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11962 if (err) 11963 return err; 11964 11965 dst_reg = ®s[insn->dst_reg]; 11966 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 11967 11968 if (BPF_SRC(insn->code) == BPF_K) { 11969 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 11970 } else if (src_reg->type == SCALAR_VALUE && 11971 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 11972 pred = is_branch_taken(dst_reg, 11973 tnum_subreg(src_reg->var_off).value, 11974 opcode, 11975 is_jmp32); 11976 } else if (src_reg->type == SCALAR_VALUE && 11977 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 11978 pred = is_branch_taken(dst_reg, 11979 src_reg->var_off.value, 11980 opcode, 11981 is_jmp32); 11982 } else if (reg_is_pkt_pointer_any(dst_reg) && 11983 reg_is_pkt_pointer_any(src_reg) && 11984 !is_jmp32) { 11985 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 11986 } 11987 11988 if (pred >= 0) { 11989 /* If we get here with a dst_reg pointer type it is because 11990 * above is_branch_taken() special cased the 0 comparison. 11991 */ 11992 if (!__is_pointer_value(false, dst_reg)) 11993 err = mark_chain_precision(env, insn->dst_reg); 11994 if (BPF_SRC(insn->code) == BPF_X && !err && 11995 !__is_pointer_value(false, src_reg)) 11996 err = mark_chain_precision(env, insn->src_reg); 11997 if (err) 11998 return err; 11999 } 12000 12001 if (pred == 1) { 12002 /* Only follow the goto, ignore fall-through. If needed, push 12003 * the fall-through branch for simulation under speculative 12004 * execution. 12005 */ 12006 if (!env->bypass_spec_v1 && 12007 !sanitize_speculative_path(env, insn, *insn_idx + 1, 12008 *insn_idx)) 12009 return -EFAULT; 12010 *insn_idx += insn->off; 12011 return 0; 12012 } else if (pred == 0) { 12013 /* Only follow the fall-through branch, since that's where the 12014 * program will go. If needed, push the goto branch for 12015 * simulation under speculative execution. 12016 */ 12017 if (!env->bypass_spec_v1 && 12018 !sanitize_speculative_path(env, insn, 12019 *insn_idx + insn->off + 1, 12020 *insn_idx)) 12021 return -EFAULT; 12022 return 0; 12023 } 12024 12025 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 12026 false); 12027 if (!other_branch) 12028 return -EFAULT; 12029 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 12030 12031 /* detect if we are comparing against a constant value so we can adjust 12032 * our min/max values for our dst register. 12033 * this is only legit if both are scalars (or pointers to the same 12034 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 12035 * because otherwise the different base pointers mean the offsets aren't 12036 * comparable. 12037 */ 12038 if (BPF_SRC(insn->code) == BPF_X) { 12039 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 12040 12041 if (dst_reg->type == SCALAR_VALUE && 12042 src_reg->type == SCALAR_VALUE) { 12043 if (tnum_is_const(src_reg->var_off) || 12044 (is_jmp32 && 12045 tnum_is_const(tnum_subreg(src_reg->var_off)))) 12046 reg_set_min_max(&other_branch_regs[insn->dst_reg], 12047 dst_reg, 12048 src_reg->var_off.value, 12049 tnum_subreg(src_reg->var_off).value, 12050 opcode, is_jmp32); 12051 else if (tnum_is_const(dst_reg->var_off) || 12052 (is_jmp32 && 12053 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 12054 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 12055 src_reg, 12056 dst_reg->var_off.value, 12057 tnum_subreg(dst_reg->var_off).value, 12058 opcode, is_jmp32); 12059 else if (!is_jmp32 && 12060 (opcode == BPF_JEQ || opcode == BPF_JNE)) 12061 /* Comparing for equality, we can combine knowledge */ 12062 reg_combine_min_max(&other_branch_regs[insn->src_reg], 12063 &other_branch_regs[insn->dst_reg], 12064 src_reg, dst_reg, opcode); 12065 if (src_reg->id && 12066 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 12067 find_equal_scalars(this_branch, src_reg); 12068 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 12069 } 12070 12071 } 12072 } else if (dst_reg->type == SCALAR_VALUE) { 12073 reg_set_min_max(&other_branch_regs[insn->dst_reg], 12074 dst_reg, insn->imm, (u32)insn->imm, 12075 opcode, is_jmp32); 12076 } 12077 12078 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 12079 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 12080 find_equal_scalars(this_branch, dst_reg); 12081 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 12082 } 12083 12084 /* if one pointer register is compared to another pointer 12085 * register check if PTR_MAYBE_NULL could be lifted. 12086 * E.g. register A - maybe null 12087 * register B - not null 12088 * for JNE A, B, ... - A is not null in the false branch; 12089 * for JEQ A, B, ... - A is not null in the true branch. 12090 * 12091 * Since PTR_TO_BTF_ID points to a kernel struct that does 12092 * not need to be null checked by the BPF program, i.e., 12093 * could be null even without PTR_MAYBE_NULL marking, so 12094 * only propagate nullness when neither reg is that type. 12095 */ 12096 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 12097 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 12098 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 12099 base_type(src_reg->type) != PTR_TO_BTF_ID && 12100 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 12101 eq_branch_regs = NULL; 12102 switch (opcode) { 12103 case BPF_JEQ: 12104 eq_branch_regs = other_branch_regs; 12105 break; 12106 case BPF_JNE: 12107 eq_branch_regs = regs; 12108 break; 12109 default: 12110 /* do nothing */ 12111 break; 12112 } 12113 if (eq_branch_regs) { 12114 if (type_may_be_null(src_reg->type)) 12115 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 12116 else 12117 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 12118 } 12119 } 12120 12121 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 12122 * NOTE: these optimizations below are related with pointer comparison 12123 * which will never be JMP32. 12124 */ 12125 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 12126 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 12127 type_may_be_null(dst_reg->type)) { 12128 /* Mark all identical registers in each branch as either 12129 * safe or unknown depending R == 0 or R != 0 conditional. 12130 */ 12131 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 12132 opcode == BPF_JNE); 12133 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 12134 opcode == BPF_JEQ); 12135 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 12136 this_branch, other_branch) && 12137 is_pointer_value(env, insn->dst_reg)) { 12138 verbose(env, "R%d pointer comparison prohibited\n", 12139 insn->dst_reg); 12140 return -EACCES; 12141 } 12142 if (env->log.level & BPF_LOG_LEVEL) 12143 print_insn_state(env, this_branch->frame[this_branch->curframe]); 12144 return 0; 12145 } 12146 12147 /* verify BPF_LD_IMM64 instruction */ 12148 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 12149 { 12150 struct bpf_insn_aux_data *aux = cur_aux(env); 12151 struct bpf_reg_state *regs = cur_regs(env); 12152 struct bpf_reg_state *dst_reg; 12153 struct bpf_map *map; 12154 int err; 12155 12156 if (BPF_SIZE(insn->code) != BPF_DW) { 12157 verbose(env, "invalid BPF_LD_IMM insn\n"); 12158 return -EINVAL; 12159 } 12160 if (insn->off != 0) { 12161 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 12162 return -EINVAL; 12163 } 12164 12165 err = check_reg_arg(env, insn->dst_reg, DST_OP); 12166 if (err) 12167 return err; 12168 12169 dst_reg = ®s[insn->dst_reg]; 12170 if (insn->src_reg == 0) { 12171 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 12172 12173 dst_reg->type = SCALAR_VALUE; 12174 __mark_reg_known(®s[insn->dst_reg], imm); 12175 return 0; 12176 } 12177 12178 /* All special src_reg cases are listed below. From this point onwards 12179 * we either succeed and assign a corresponding dst_reg->type after 12180 * zeroing the offset, or fail and reject the program. 12181 */ 12182 mark_reg_known_zero(env, regs, insn->dst_reg); 12183 12184 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 12185 dst_reg->type = aux->btf_var.reg_type; 12186 switch (base_type(dst_reg->type)) { 12187 case PTR_TO_MEM: 12188 dst_reg->mem_size = aux->btf_var.mem_size; 12189 break; 12190 case PTR_TO_BTF_ID: 12191 dst_reg->btf = aux->btf_var.btf; 12192 dst_reg->btf_id = aux->btf_var.btf_id; 12193 break; 12194 default: 12195 verbose(env, "bpf verifier is misconfigured\n"); 12196 return -EFAULT; 12197 } 12198 return 0; 12199 } 12200 12201 if (insn->src_reg == BPF_PSEUDO_FUNC) { 12202 struct bpf_prog_aux *aux = env->prog->aux; 12203 u32 subprogno = find_subprog(env, 12204 env->insn_idx + insn->imm + 1); 12205 12206 if (!aux->func_info) { 12207 verbose(env, "missing btf func_info\n"); 12208 return -EINVAL; 12209 } 12210 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 12211 verbose(env, "callback function not static\n"); 12212 return -EINVAL; 12213 } 12214 12215 dst_reg->type = PTR_TO_FUNC; 12216 dst_reg->subprogno = subprogno; 12217 return 0; 12218 } 12219 12220 map = env->used_maps[aux->map_index]; 12221 dst_reg->map_ptr = map; 12222 12223 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 12224 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 12225 dst_reg->type = PTR_TO_MAP_VALUE; 12226 dst_reg->off = aux->map_off; 12227 WARN_ON_ONCE(map->max_entries != 1); 12228 /* We want reg->id to be same (0) as map_value is not distinct */ 12229 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 12230 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 12231 dst_reg->type = CONST_PTR_TO_MAP; 12232 } else { 12233 verbose(env, "bpf verifier is misconfigured\n"); 12234 return -EINVAL; 12235 } 12236 12237 return 0; 12238 } 12239 12240 static bool may_access_skb(enum bpf_prog_type type) 12241 { 12242 switch (type) { 12243 case BPF_PROG_TYPE_SOCKET_FILTER: 12244 case BPF_PROG_TYPE_SCHED_CLS: 12245 case BPF_PROG_TYPE_SCHED_ACT: 12246 return true; 12247 default: 12248 return false; 12249 } 12250 } 12251 12252 /* verify safety of LD_ABS|LD_IND instructions: 12253 * - they can only appear in the programs where ctx == skb 12254 * - since they are wrappers of function calls, they scratch R1-R5 registers, 12255 * preserve R6-R9, and store return value into R0 12256 * 12257 * Implicit input: 12258 * ctx == skb == R6 == CTX 12259 * 12260 * Explicit input: 12261 * SRC == any register 12262 * IMM == 32-bit immediate 12263 * 12264 * Output: 12265 * R0 - 8/16/32-bit skb data converted to cpu endianness 12266 */ 12267 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 12268 { 12269 struct bpf_reg_state *regs = cur_regs(env); 12270 static const int ctx_reg = BPF_REG_6; 12271 u8 mode = BPF_MODE(insn->code); 12272 int i, err; 12273 12274 if (!may_access_skb(resolve_prog_type(env->prog))) { 12275 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 12276 return -EINVAL; 12277 } 12278 12279 if (!env->ops->gen_ld_abs) { 12280 verbose(env, "bpf verifier is misconfigured\n"); 12281 return -EINVAL; 12282 } 12283 12284 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 12285 BPF_SIZE(insn->code) == BPF_DW || 12286 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 12287 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 12288 return -EINVAL; 12289 } 12290 12291 /* check whether implicit source operand (register R6) is readable */ 12292 err = check_reg_arg(env, ctx_reg, SRC_OP); 12293 if (err) 12294 return err; 12295 12296 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 12297 * gen_ld_abs() may terminate the program at runtime, leading to 12298 * reference leak. 12299 */ 12300 err = check_reference_leak(env); 12301 if (err) { 12302 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 12303 return err; 12304 } 12305 12306 if (env->cur_state->active_lock.ptr) { 12307 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 12308 return -EINVAL; 12309 } 12310 12311 if (env->cur_state->active_rcu_lock) { 12312 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 12313 return -EINVAL; 12314 } 12315 12316 if (regs[ctx_reg].type != PTR_TO_CTX) { 12317 verbose(env, 12318 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 12319 return -EINVAL; 12320 } 12321 12322 if (mode == BPF_IND) { 12323 /* check explicit source operand */ 12324 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12325 if (err) 12326 return err; 12327 } 12328 12329 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 12330 if (err < 0) 12331 return err; 12332 12333 /* reset caller saved regs to unreadable */ 12334 for (i = 0; i < CALLER_SAVED_REGS; i++) { 12335 mark_reg_not_init(env, regs, caller_saved[i]); 12336 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 12337 } 12338 12339 /* mark destination R0 register as readable, since it contains 12340 * the value fetched from the packet. 12341 * Already marked as written above. 12342 */ 12343 mark_reg_unknown(env, regs, BPF_REG_0); 12344 /* ld_abs load up to 32-bit skb data. */ 12345 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 12346 return 0; 12347 } 12348 12349 static int check_return_code(struct bpf_verifier_env *env) 12350 { 12351 struct tnum enforce_attach_type_range = tnum_unknown; 12352 const struct bpf_prog *prog = env->prog; 12353 struct bpf_reg_state *reg; 12354 struct tnum range = tnum_range(0, 1); 12355 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12356 int err; 12357 struct bpf_func_state *frame = env->cur_state->frame[0]; 12358 const bool is_subprog = frame->subprogno; 12359 12360 /* LSM and struct_ops func-ptr's return type could be "void" */ 12361 if (!is_subprog) { 12362 switch (prog_type) { 12363 case BPF_PROG_TYPE_LSM: 12364 if (prog->expected_attach_type == BPF_LSM_CGROUP) 12365 /* See below, can be 0 or 0-1 depending on hook. */ 12366 break; 12367 fallthrough; 12368 case BPF_PROG_TYPE_STRUCT_OPS: 12369 if (!prog->aux->attach_func_proto->type) 12370 return 0; 12371 break; 12372 default: 12373 break; 12374 } 12375 } 12376 12377 /* eBPF calling convention is such that R0 is used 12378 * to return the value from eBPF program. 12379 * Make sure that it's readable at this time 12380 * of bpf_exit, which means that program wrote 12381 * something into it earlier 12382 */ 12383 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 12384 if (err) 12385 return err; 12386 12387 if (is_pointer_value(env, BPF_REG_0)) { 12388 verbose(env, "R0 leaks addr as return value\n"); 12389 return -EACCES; 12390 } 12391 12392 reg = cur_regs(env) + BPF_REG_0; 12393 12394 if (frame->in_async_callback_fn) { 12395 /* enforce return zero from async callbacks like timer */ 12396 if (reg->type != SCALAR_VALUE) { 12397 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 12398 reg_type_str(env, reg->type)); 12399 return -EINVAL; 12400 } 12401 12402 if (!tnum_in(tnum_const(0), reg->var_off)) { 12403 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 12404 return -EINVAL; 12405 } 12406 return 0; 12407 } 12408 12409 if (is_subprog) { 12410 if (reg->type != SCALAR_VALUE) { 12411 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 12412 reg_type_str(env, reg->type)); 12413 return -EINVAL; 12414 } 12415 return 0; 12416 } 12417 12418 switch (prog_type) { 12419 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 12420 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 12421 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 12422 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 12423 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 12424 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 12425 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 12426 range = tnum_range(1, 1); 12427 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 12428 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 12429 range = tnum_range(0, 3); 12430 break; 12431 case BPF_PROG_TYPE_CGROUP_SKB: 12432 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 12433 range = tnum_range(0, 3); 12434 enforce_attach_type_range = tnum_range(2, 3); 12435 } 12436 break; 12437 case BPF_PROG_TYPE_CGROUP_SOCK: 12438 case BPF_PROG_TYPE_SOCK_OPS: 12439 case BPF_PROG_TYPE_CGROUP_DEVICE: 12440 case BPF_PROG_TYPE_CGROUP_SYSCTL: 12441 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 12442 break; 12443 case BPF_PROG_TYPE_RAW_TRACEPOINT: 12444 if (!env->prog->aux->attach_btf_id) 12445 return 0; 12446 range = tnum_const(0); 12447 break; 12448 case BPF_PROG_TYPE_TRACING: 12449 switch (env->prog->expected_attach_type) { 12450 case BPF_TRACE_FENTRY: 12451 case BPF_TRACE_FEXIT: 12452 range = tnum_const(0); 12453 break; 12454 case BPF_TRACE_RAW_TP: 12455 case BPF_MODIFY_RETURN: 12456 return 0; 12457 case BPF_TRACE_ITER: 12458 break; 12459 default: 12460 return -ENOTSUPP; 12461 } 12462 break; 12463 case BPF_PROG_TYPE_SK_LOOKUP: 12464 range = tnum_range(SK_DROP, SK_PASS); 12465 break; 12466 12467 case BPF_PROG_TYPE_LSM: 12468 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 12469 /* Regular BPF_PROG_TYPE_LSM programs can return 12470 * any value. 12471 */ 12472 return 0; 12473 } 12474 if (!env->prog->aux->attach_func_proto->type) { 12475 /* Make sure programs that attach to void 12476 * hooks don't try to modify return value. 12477 */ 12478 range = tnum_range(1, 1); 12479 } 12480 break; 12481 12482 case BPF_PROG_TYPE_EXT: 12483 /* freplace program can return anything as its return value 12484 * depends on the to-be-replaced kernel func or bpf program. 12485 */ 12486 default: 12487 return 0; 12488 } 12489 12490 if (reg->type != SCALAR_VALUE) { 12491 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 12492 reg_type_str(env, reg->type)); 12493 return -EINVAL; 12494 } 12495 12496 if (!tnum_in(range, reg->var_off)) { 12497 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 12498 if (prog->expected_attach_type == BPF_LSM_CGROUP && 12499 prog_type == BPF_PROG_TYPE_LSM && 12500 !prog->aux->attach_func_proto->type) 12501 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 12502 return -EINVAL; 12503 } 12504 12505 if (!tnum_is_unknown(enforce_attach_type_range) && 12506 tnum_in(enforce_attach_type_range, reg->var_off)) 12507 env->prog->enforce_expected_attach_type = 1; 12508 return 0; 12509 } 12510 12511 /* non-recursive DFS pseudo code 12512 * 1 procedure DFS-iterative(G,v): 12513 * 2 label v as discovered 12514 * 3 let S be a stack 12515 * 4 S.push(v) 12516 * 5 while S is not empty 12517 * 6 t <- S.peek() 12518 * 7 if t is what we're looking for: 12519 * 8 return t 12520 * 9 for all edges e in G.adjacentEdges(t) do 12521 * 10 if edge e is already labelled 12522 * 11 continue with the next edge 12523 * 12 w <- G.adjacentVertex(t,e) 12524 * 13 if vertex w is not discovered and not explored 12525 * 14 label e as tree-edge 12526 * 15 label w as discovered 12527 * 16 S.push(w) 12528 * 17 continue at 5 12529 * 18 else if vertex w is discovered 12530 * 19 label e as back-edge 12531 * 20 else 12532 * 21 // vertex w is explored 12533 * 22 label e as forward- or cross-edge 12534 * 23 label t as explored 12535 * 24 S.pop() 12536 * 12537 * convention: 12538 * 0x10 - discovered 12539 * 0x11 - discovered and fall-through edge labelled 12540 * 0x12 - discovered and fall-through and branch edges labelled 12541 * 0x20 - explored 12542 */ 12543 12544 enum { 12545 DISCOVERED = 0x10, 12546 EXPLORED = 0x20, 12547 FALLTHROUGH = 1, 12548 BRANCH = 2, 12549 }; 12550 12551 static u32 state_htab_size(struct bpf_verifier_env *env) 12552 { 12553 return env->prog->len; 12554 } 12555 12556 static struct bpf_verifier_state_list **explored_state( 12557 struct bpf_verifier_env *env, 12558 int idx) 12559 { 12560 struct bpf_verifier_state *cur = env->cur_state; 12561 struct bpf_func_state *state = cur->frame[cur->curframe]; 12562 12563 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 12564 } 12565 12566 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 12567 { 12568 env->insn_aux_data[idx].prune_point = true; 12569 } 12570 12571 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 12572 { 12573 return env->insn_aux_data[insn_idx].prune_point; 12574 } 12575 12576 enum { 12577 DONE_EXPLORING = 0, 12578 KEEP_EXPLORING = 1, 12579 }; 12580 12581 /* t, w, e - match pseudo-code above: 12582 * t - index of current instruction 12583 * w - next instruction 12584 * e - edge 12585 */ 12586 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 12587 bool loop_ok) 12588 { 12589 int *insn_stack = env->cfg.insn_stack; 12590 int *insn_state = env->cfg.insn_state; 12591 12592 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 12593 return DONE_EXPLORING; 12594 12595 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 12596 return DONE_EXPLORING; 12597 12598 if (w < 0 || w >= env->prog->len) { 12599 verbose_linfo(env, t, "%d: ", t); 12600 verbose(env, "jump out of range from insn %d to %d\n", t, w); 12601 return -EINVAL; 12602 } 12603 12604 if (e == BRANCH) { 12605 /* mark branch target for state pruning */ 12606 mark_prune_point(env, w); 12607 mark_jmp_point(env, w); 12608 } 12609 12610 if (insn_state[w] == 0) { 12611 /* tree-edge */ 12612 insn_state[t] = DISCOVERED | e; 12613 insn_state[w] = DISCOVERED; 12614 if (env->cfg.cur_stack >= env->prog->len) 12615 return -E2BIG; 12616 insn_stack[env->cfg.cur_stack++] = w; 12617 return KEEP_EXPLORING; 12618 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 12619 if (loop_ok && env->bpf_capable) 12620 return DONE_EXPLORING; 12621 verbose_linfo(env, t, "%d: ", t); 12622 verbose_linfo(env, w, "%d: ", w); 12623 verbose(env, "back-edge from insn %d to %d\n", t, w); 12624 return -EINVAL; 12625 } else if (insn_state[w] == EXPLORED) { 12626 /* forward- or cross-edge */ 12627 insn_state[t] = DISCOVERED | e; 12628 } else { 12629 verbose(env, "insn state internal bug\n"); 12630 return -EFAULT; 12631 } 12632 return DONE_EXPLORING; 12633 } 12634 12635 static int visit_func_call_insn(int t, struct bpf_insn *insns, 12636 struct bpf_verifier_env *env, 12637 bool visit_callee) 12638 { 12639 int ret; 12640 12641 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 12642 if (ret) 12643 return ret; 12644 12645 mark_prune_point(env, t + 1); 12646 /* when we exit from subprog, we need to record non-linear history */ 12647 mark_jmp_point(env, t + 1); 12648 12649 if (visit_callee) { 12650 mark_prune_point(env, t); 12651 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 12652 /* It's ok to allow recursion from CFG point of 12653 * view. __check_func_call() will do the actual 12654 * check. 12655 */ 12656 bpf_pseudo_func(insns + t)); 12657 } 12658 return ret; 12659 } 12660 12661 /* Visits the instruction at index t and returns one of the following: 12662 * < 0 - an error occurred 12663 * DONE_EXPLORING - the instruction was fully explored 12664 * KEEP_EXPLORING - there is still work to be done before it is fully explored 12665 */ 12666 static int visit_insn(int t, struct bpf_verifier_env *env) 12667 { 12668 struct bpf_insn *insns = env->prog->insnsi; 12669 int ret; 12670 12671 if (bpf_pseudo_func(insns + t)) 12672 return visit_func_call_insn(t, insns, env, true); 12673 12674 /* All non-branch instructions have a single fall-through edge. */ 12675 if (BPF_CLASS(insns[t].code) != BPF_JMP && 12676 BPF_CLASS(insns[t].code) != BPF_JMP32) 12677 return push_insn(t, t + 1, FALLTHROUGH, env, false); 12678 12679 switch (BPF_OP(insns[t].code)) { 12680 case BPF_EXIT: 12681 return DONE_EXPLORING; 12682 12683 case BPF_CALL: 12684 if (insns[t].imm == BPF_FUNC_timer_set_callback) 12685 /* Mark this call insn as a prune point to trigger 12686 * is_state_visited() check before call itself is 12687 * processed by __check_func_call(). Otherwise new 12688 * async state will be pushed for further exploration. 12689 */ 12690 mark_prune_point(env, t); 12691 return visit_func_call_insn(t, insns, env, 12692 insns[t].src_reg == BPF_PSEUDO_CALL); 12693 12694 case BPF_JA: 12695 if (BPF_SRC(insns[t].code) != BPF_K) 12696 return -EINVAL; 12697 12698 /* unconditional jump with single edge */ 12699 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env, 12700 true); 12701 if (ret) 12702 return ret; 12703 12704 mark_prune_point(env, t + insns[t].off + 1); 12705 mark_jmp_point(env, t + insns[t].off + 1); 12706 12707 return ret; 12708 12709 default: 12710 /* conditional jump with two edges */ 12711 mark_prune_point(env, t); 12712 12713 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 12714 if (ret) 12715 return ret; 12716 12717 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true); 12718 } 12719 } 12720 12721 /* non-recursive depth-first-search to detect loops in BPF program 12722 * loop == back-edge in directed graph 12723 */ 12724 static int check_cfg(struct bpf_verifier_env *env) 12725 { 12726 int insn_cnt = env->prog->len; 12727 int *insn_stack, *insn_state; 12728 int ret = 0; 12729 int i; 12730 12731 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 12732 if (!insn_state) 12733 return -ENOMEM; 12734 12735 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 12736 if (!insn_stack) { 12737 kvfree(insn_state); 12738 return -ENOMEM; 12739 } 12740 12741 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 12742 insn_stack[0] = 0; /* 0 is the first instruction */ 12743 env->cfg.cur_stack = 1; 12744 12745 while (env->cfg.cur_stack > 0) { 12746 int t = insn_stack[env->cfg.cur_stack - 1]; 12747 12748 ret = visit_insn(t, env); 12749 switch (ret) { 12750 case DONE_EXPLORING: 12751 insn_state[t] = EXPLORED; 12752 env->cfg.cur_stack--; 12753 break; 12754 case KEEP_EXPLORING: 12755 break; 12756 default: 12757 if (ret > 0) { 12758 verbose(env, "visit_insn internal bug\n"); 12759 ret = -EFAULT; 12760 } 12761 goto err_free; 12762 } 12763 } 12764 12765 if (env->cfg.cur_stack < 0) { 12766 verbose(env, "pop stack internal bug\n"); 12767 ret = -EFAULT; 12768 goto err_free; 12769 } 12770 12771 for (i = 0; i < insn_cnt; i++) { 12772 if (insn_state[i] != EXPLORED) { 12773 verbose(env, "unreachable insn %d\n", i); 12774 ret = -EINVAL; 12775 goto err_free; 12776 } 12777 } 12778 ret = 0; /* cfg looks good */ 12779 12780 err_free: 12781 kvfree(insn_state); 12782 kvfree(insn_stack); 12783 env->cfg.insn_state = env->cfg.insn_stack = NULL; 12784 return ret; 12785 } 12786 12787 static int check_abnormal_return(struct bpf_verifier_env *env) 12788 { 12789 int i; 12790 12791 for (i = 1; i < env->subprog_cnt; i++) { 12792 if (env->subprog_info[i].has_ld_abs) { 12793 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 12794 return -EINVAL; 12795 } 12796 if (env->subprog_info[i].has_tail_call) { 12797 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 12798 return -EINVAL; 12799 } 12800 } 12801 return 0; 12802 } 12803 12804 /* The minimum supported BTF func info size */ 12805 #define MIN_BPF_FUNCINFO_SIZE 8 12806 #define MAX_FUNCINFO_REC_SIZE 252 12807 12808 static int check_btf_func(struct bpf_verifier_env *env, 12809 const union bpf_attr *attr, 12810 bpfptr_t uattr) 12811 { 12812 const struct btf_type *type, *func_proto, *ret_type; 12813 u32 i, nfuncs, urec_size, min_size; 12814 u32 krec_size = sizeof(struct bpf_func_info); 12815 struct bpf_func_info *krecord; 12816 struct bpf_func_info_aux *info_aux = NULL; 12817 struct bpf_prog *prog; 12818 const struct btf *btf; 12819 bpfptr_t urecord; 12820 u32 prev_offset = 0; 12821 bool scalar_return; 12822 int ret = -ENOMEM; 12823 12824 nfuncs = attr->func_info_cnt; 12825 if (!nfuncs) { 12826 if (check_abnormal_return(env)) 12827 return -EINVAL; 12828 return 0; 12829 } 12830 12831 if (nfuncs != env->subprog_cnt) { 12832 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 12833 return -EINVAL; 12834 } 12835 12836 urec_size = attr->func_info_rec_size; 12837 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 12838 urec_size > MAX_FUNCINFO_REC_SIZE || 12839 urec_size % sizeof(u32)) { 12840 verbose(env, "invalid func info rec size %u\n", urec_size); 12841 return -EINVAL; 12842 } 12843 12844 prog = env->prog; 12845 btf = prog->aux->btf; 12846 12847 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 12848 min_size = min_t(u32, krec_size, urec_size); 12849 12850 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 12851 if (!krecord) 12852 return -ENOMEM; 12853 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 12854 if (!info_aux) 12855 goto err_free; 12856 12857 for (i = 0; i < nfuncs; i++) { 12858 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 12859 if (ret) { 12860 if (ret == -E2BIG) { 12861 verbose(env, "nonzero tailing record in func info"); 12862 /* set the size kernel expects so loader can zero 12863 * out the rest of the record. 12864 */ 12865 if (copy_to_bpfptr_offset(uattr, 12866 offsetof(union bpf_attr, func_info_rec_size), 12867 &min_size, sizeof(min_size))) 12868 ret = -EFAULT; 12869 } 12870 goto err_free; 12871 } 12872 12873 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 12874 ret = -EFAULT; 12875 goto err_free; 12876 } 12877 12878 /* check insn_off */ 12879 ret = -EINVAL; 12880 if (i == 0) { 12881 if (krecord[i].insn_off) { 12882 verbose(env, 12883 "nonzero insn_off %u for the first func info record", 12884 krecord[i].insn_off); 12885 goto err_free; 12886 } 12887 } else if (krecord[i].insn_off <= prev_offset) { 12888 verbose(env, 12889 "same or smaller insn offset (%u) than previous func info record (%u)", 12890 krecord[i].insn_off, prev_offset); 12891 goto err_free; 12892 } 12893 12894 if (env->subprog_info[i].start != krecord[i].insn_off) { 12895 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 12896 goto err_free; 12897 } 12898 12899 /* check type_id */ 12900 type = btf_type_by_id(btf, krecord[i].type_id); 12901 if (!type || !btf_type_is_func(type)) { 12902 verbose(env, "invalid type id %d in func info", 12903 krecord[i].type_id); 12904 goto err_free; 12905 } 12906 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 12907 12908 func_proto = btf_type_by_id(btf, type->type); 12909 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 12910 /* btf_func_check() already verified it during BTF load */ 12911 goto err_free; 12912 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 12913 scalar_return = 12914 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 12915 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 12916 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 12917 goto err_free; 12918 } 12919 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 12920 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 12921 goto err_free; 12922 } 12923 12924 prev_offset = krecord[i].insn_off; 12925 bpfptr_add(&urecord, urec_size); 12926 } 12927 12928 prog->aux->func_info = krecord; 12929 prog->aux->func_info_cnt = nfuncs; 12930 prog->aux->func_info_aux = info_aux; 12931 return 0; 12932 12933 err_free: 12934 kvfree(krecord); 12935 kfree(info_aux); 12936 return ret; 12937 } 12938 12939 static void adjust_btf_func(struct bpf_verifier_env *env) 12940 { 12941 struct bpf_prog_aux *aux = env->prog->aux; 12942 int i; 12943 12944 if (!aux->func_info) 12945 return; 12946 12947 for (i = 0; i < env->subprog_cnt; i++) 12948 aux->func_info[i].insn_off = env->subprog_info[i].start; 12949 } 12950 12951 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 12952 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 12953 12954 static int check_btf_line(struct bpf_verifier_env *env, 12955 const union bpf_attr *attr, 12956 bpfptr_t uattr) 12957 { 12958 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 12959 struct bpf_subprog_info *sub; 12960 struct bpf_line_info *linfo; 12961 struct bpf_prog *prog; 12962 const struct btf *btf; 12963 bpfptr_t ulinfo; 12964 int err; 12965 12966 nr_linfo = attr->line_info_cnt; 12967 if (!nr_linfo) 12968 return 0; 12969 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 12970 return -EINVAL; 12971 12972 rec_size = attr->line_info_rec_size; 12973 if (rec_size < MIN_BPF_LINEINFO_SIZE || 12974 rec_size > MAX_LINEINFO_REC_SIZE || 12975 rec_size & (sizeof(u32) - 1)) 12976 return -EINVAL; 12977 12978 /* Need to zero it in case the userspace may 12979 * pass in a smaller bpf_line_info object. 12980 */ 12981 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 12982 GFP_KERNEL | __GFP_NOWARN); 12983 if (!linfo) 12984 return -ENOMEM; 12985 12986 prog = env->prog; 12987 btf = prog->aux->btf; 12988 12989 s = 0; 12990 sub = env->subprog_info; 12991 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 12992 expected_size = sizeof(struct bpf_line_info); 12993 ncopy = min_t(u32, expected_size, rec_size); 12994 for (i = 0; i < nr_linfo; i++) { 12995 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 12996 if (err) { 12997 if (err == -E2BIG) { 12998 verbose(env, "nonzero tailing record in line_info"); 12999 if (copy_to_bpfptr_offset(uattr, 13000 offsetof(union bpf_attr, line_info_rec_size), 13001 &expected_size, sizeof(expected_size))) 13002 err = -EFAULT; 13003 } 13004 goto err_free; 13005 } 13006 13007 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 13008 err = -EFAULT; 13009 goto err_free; 13010 } 13011 13012 /* 13013 * Check insn_off to ensure 13014 * 1) strictly increasing AND 13015 * 2) bounded by prog->len 13016 * 13017 * The linfo[0].insn_off == 0 check logically falls into 13018 * the later "missing bpf_line_info for func..." case 13019 * because the first linfo[0].insn_off must be the 13020 * first sub also and the first sub must have 13021 * subprog_info[0].start == 0. 13022 */ 13023 if ((i && linfo[i].insn_off <= prev_offset) || 13024 linfo[i].insn_off >= prog->len) { 13025 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 13026 i, linfo[i].insn_off, prev_offset, 13027 prog->len); 13028 err = -EINVAL; 13029 goto err_free; 13030 } 13031 13032 if (!prog->insnsi[linfo[i].insn_off].code) { 13033 verbose(env, 13034 "Invalid insn code at line_info[%u].insn_off\n", 13035 i); 13036 err = -EINVAL; 13037 goto err_free; 13038 } 13039 13040 if (!btf_name_by_offset(btf, linfo[i].line_off) || 13041 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 13042 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 13043 err = -EINVAL; 13044 goto err_free; 13045 } 13046 13047 if (s != env->subprog_cnt) { 13048 if (linfo[i].insn_off == sub[s].start) { 13049 sub[s].linfo_idx = i; 13050 s++; 13051 } else if (sub[s].start < linfo[i].insn_off) { 13052 verbose(env, "missing bpf_line_info for func#%u\n", s); 13053 err = -EINVAL; 13054 goto err_free; 13055 } 13056 } 13057 13058 prev_offset = linfo[i].insn_off; 13059 bpfptr_add(&ulinfo, rec_size); 13060 } 13061 13062 if (s != env->subprog_cnt) { 13063 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 13064 env->subprog_cnt - s, s); 13065 err = -EINVAL; 13066 goto err_free; 13067 } 13068 13069 prog->aux->linfo = linfo; 13070 prog->aux->nr_linfo = nr_linfo; 13071 13072 return 0; 13073 13074 err_free: 13075 kvfree(linfo); 13076 return err; 13077 } 13078 13079 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 13080 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 13081 13082 static int check_core_relo(struct bpf_verifier_env *env, 13083 const union bpf_attr *attr, 13084 bpfptr_t uattr) 13085 { 13086 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 13087 struct bpf_core_relo core_relo = {}; 13088 struct bpf_prog *prog = env->prog; 13089 const struct btf *btf = prog->aux->btf; 13090 struct bpf_core_ctx ctx = { 13091 .log = &env->log, 13092 .btf = btf, 13093 }; 13094 bpfptr_t u_core_relo; 13095 int err; 13096 13097 nr_core_relo = attr->core_relo_cnt; 13098 if (!nr_core_relo) 13099 return 0; 13100 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 13101 return -EINVAL; 13102 13103 rec_size = attr->core_relo_rec_size; 13104 if (rec_size < MIN_CORE_RELO_SIZE || 13105 rec_size > MAX_CORE_RELO_SIZE || 13106 rec_size % sizeof(u32)) 13107 return -EINVAL; 13108 13109 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 13110 expected_size = sizeof(struct bpf_core_relo); 13111 ncopy = min_t(u32, expected_size, rec_size); 13112 13113 /* Unlike func_info and line_info, copy and apply each CO-RE 13114 * relocation record one at a time. 13115 */ 13116 for (i = 0; i < nr_core_relo; i++) { 13117 /* future proofing when sizeof(bpf_core_relo) changes */ 13118 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 13119 if (err) { 13120 if (err == -E2BIG) { 13121 verbose(env, "nonzero tailing record in core_relo"); 13122 if (copy_to_bpfptr_offset(uattr, 13123 offsetof(union bpf_attr, core_relo_rec_size), 13124 &expected_size, sizeof(expected_size))) 13125 err = -EFAULT; 13126 } 13127 break; 13128 } 13129 13130 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 13131 err = -EFAULT; 13132 break; 13133 } 13134 13135 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 13136 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 13137 i, core_relo.insn_off, prog->len); 13138 err = -EINVAL; 13139 break; 13140 } 13141 13142 err = bpf_core_apply(&ctx, &core_relo, i, 13143 &prog->insnsi[core_relo.insn_off / 8]); 13144 if (err) 13145 break; 13146 bpfptr_add(&u_core_relo, rec_size); 13147 } 13148 return err; 13149 } 13150 13151 static int check_btf_info(struct bpf_verifier_env *env, 13152 const union bpf_attr *attr, 13153 bpfptr_t uattr) 13154 { 13155 struct btf *btf; 13156 int err; 13157 13158 if (!attr->func_info_cnt && !attr->line_info_cnt) { 13159 if (check_abnormal_return(env)) 13160 return -EINVAL; 13161 return 0; 13162 } 13163 13164 btf = btf_get_by_fd(attr->prog_btf_fd); 13165 if (IS_ERR(btf)) 13166 return PTR_ERR(btf); 13167 if (btf_is_kernel(btf)) { 13168 btf_put(btf); 13169 return -EACCES; 13170 } 13171 env->prog->aux->btf = btf; 13172 13173 err = check_btf_func(env, attr, uattr); 13174 if (err) 13175 return err; 13176 13177 err = check_btf_line(env, attr, uattr); 13178 if (err) 13179 return err; 13180 13181 err = check_core_relo(env, attr, uattr); 13182 if (err) 13183 return err; 13184 13185 return 0; 13186 } 13187 13188 /* check %cur's range satisfies %old's */ 13189 static bool range_within(struct bpf_reg_state *old, 13190 struct bpf_reg_state *cur) 13191 { 13192 return old->umin_value <= cur->umin_value && 13193 old->umax_value >= cur->umax_value && 13194 old->smin_value <= cur->smin_value && 13195 old->smax_value >= cur->smax_value && 13196 old->u32_min_value <= cur->u32_min_value && 13197 old->u32_max_value >= cur->u32_max_value && 13198 old->s32_min_value <= cur->s32_min_value && 13199 old->s32_max_value >= cur->s32_max_value; 13200 } 13201 13202 /* If in the old state two registers had the same id, then they need to have 13203 * the same id in the new state as well. But that id could be different from 13204 * the old state, so we need to track the mapping from old to new ids. 13205 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 13206 * regs with old id 5 must also have new id 9 for the new state to be safe. But 13207 * regs with a different old id could still have new id 9, we don't care about 13208 * that. 13209 * So we look through our idmap to see if this old id has been seen before. If 13210 * so, we require the new id to match; otherwise, we add the id pair to the map. 13211 */ 13212 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap) 13213 { 13214 unsigned int i; 13215 13216 /* either both IDs should be set or both should be zero */ 13217 if (!!old_id != !!cur_id) 13218 return false; 13219 13220 if (old_id == 0) /* cur_id == 0 as well */ 13221 return true; 13222 13223 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 13224 if (!idmap[i].old) { 13225 /* Reached an empty slot; haven't seen this id before */ 13226 idmap[i].old = old_id; 13227 idmap[i].cur = cur_id; 13228 return true; 13229 } 13230 if (idmap[i].old == old_id) 13231 return idmap[i].cur == cur_id; 13232 } 13233 /* We ran out of idmap slots, which should be impossible */ 13234 WARN_ON_ONCE(1); 13235 return false; 13236 } 13237 13238 static void clean_func_state(struct bpf_verifier_env *env, 13239 struct bpf_func_state *st) 13240 { 13241 enum bpf_reg_liveness live; 13242 int i, j; 13243 13244 for (i = 0; i < BPF_REG_FP; i++) { 13245 live = st->regs[i].live; 13246 /* liveness must not touch this register anymore */ 13247 st->regs[i].live |= REG_LIVE_DONE; 13248 if (!(live & REG_LIVE_READ)) 13249 /* since the register is unused, clear its state 13250 * to make further comparison simpler 13251 */ 13252 __mark_reg_not_init(env, &st->regs[i]); 13253 } 13254 13255 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 13256 live = st->stack[i].spilled_ptr.live; 13257 /* liveness must not touch this stack slot anymore */ 13258 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 13259 if (!(live & REG_LIVE_READ)) { 13260 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 13261 for (j = 0; j < BPF_REG_SIZE; j++) 13262 st->stack[i].slot_type[j] = STACK_INVALID; 13263 } 13264 } 13265 } 13266 13267 static void clean_verifier_state(struct bpf_verifier_env *env, 13268 struct bpf_verifier_state *st) 13269 { 13270 int i; 13271 13272 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 13273 /* all regs in this state in all frames were already marked */ 13274 return; 13275 13276 for (i = 0; i <= st->curframe; i++) 13277 clean_func_state(env, st->frame[i]); 13278 } 13279 13280 /* the parentage chains form a tree. 13281 * the verifier states are added to state lists at given insn and 13282 * pushed into state stack for future exploration. 13283 * when the verifier reaches bpf_exit insn some of the verifer states 13284 * stored in the state lists have their final liveness state already, 13285 * but a lot of states will get revised from liveness point of view when 13286 * the verifier explores other branches. 13287 * Example: 13288 * 1: r0 = 1 13289 * 2: if r1 == 100 goto pc+1 13290 * 3: r0 = 2 13291 * 4: exit 13292 * when the verifier reaches exit insn the register r0 in the state list of 13293 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 13294 * of insn 2 and goes exploring further. At the insn 4 it will walk the 13295 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 13296 * 13297 * Since the verifier pushes the branch states as it sees them while exploring 13298 * the program the condition of walking the branch instruction for the second 13299 * time means that all states below this branch were already explored and 13300 * their final liveness marks are already propagated. 13301 * Hence when the verifier completes the search of state list in is_state_visited() 13302 * we can call this clean_live_states() function to mark all liveness states 13303 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 13304 * will not be used. 13305 * This function also clears the registers and stack for states that !READ 13306 * to simplify state merging. 13307 * 13308 * Important note here that walking the same branch instruction in the callee 13309 * doesn't meant that the states are DONE. The verifier has to compare 13310 * the callsites 13311 */ 13312 static void clean_live_states(struct bpf_verifier_env *env, int insn, 13313 struct bpf_verifier_state *cur) 13314 { 13315 struct bpf_verifier_state_list *sl; 13316 int i; 13317 13318 sl = *explored_state(env, insn); 13319 while (sl) { 13320 if (sl->state.branches) 13321 goto next; 13322 if (sl->state.insn_idx != insn || 13323 sl->state.curframe != cur->curframe) 13324 goto next; 13325 for (i = 0; i <= cur->curframe; i++) 13326 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 13327 goto next; 13328 clean_verifier_state(env, &sl->state); 13329 next: 13330 sl = sl->next; 13331 } 13332 } 13333 13334 static bool regs_exact(const struct bpf_reg_state *rold, 13335 const struct bpf_reg_state *rcur, 13336 struct bpf_id_pair *idmap) 13337 { 13338 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 13339 check_ids(rold->id, rcur->id, idmap) && 13340 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 13341 } 13342 13343 /* Returns true if (rold safe implies rcur safe) */ 13344 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 13345 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap) 13346 { 13347 if (!(rold->live & REG_LIVE_READ)) 13348 /* explored state didn't use this */ 13349 return true; 13350 if (rold->type == NOT_INIT) 13351 /* explored state can't have used this */ 13352 return true; 13353 if (rcur->type == NOT_INIT) 13354 return false; 13355 13356 /* Enforce that register types have to match exactly, including their 13357 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 13358 * rule. 13359 * 13360 * One can make a point that using a pointer register as unbounded 13361 * SCALAR would be technically acceptable, but this could lead to 13362 * pointer leaks because scalars are allowed to leak while pointers 13363 * are not. We could make this safe in special cases if root is 13364 * calling us, but it's probably not worth the hassle. 13365 * 13366 * Also, register types that are *not* MAYBE_NULL could technically be 13367 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 13368 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 13369 * to the same map). 13370 * However, if the old MAYBE_NULL register then got NULL checked, 13371 * doing so could have affected others with the same id, and we can't 13372 * check for that because we lost the id when we converted to 13373 * a non-MAYBE_NULL variant. 13374 * So, as a general rule we don't allow mixing MAYBE_NULL and 13375 * non-MAYBE_NULL registers as well. 13376 */ 13377 if (rold->type != rcur->type) 13378 return false; 13379 13380 switch (base_type(rold->type)) { 13381 case SCALAR_VALUE: 13382 if (regs_exact(rold, rcur, idmap)) 13383 return true; 13384 if (env->explore_alu_limits) 13385 return false; 13386 if (!rold->precise) 13387 return true; 13388 /* new val must satisfy old val knowledge */ 13389 return range_within(rold, rcur) && 13390 tnum_in(rold->var_off, rcur->var_off); 13391 case PTR_TO_MAP_KEY: 13392 case PTR_TO_MAP_VALUE: 13393 /* If the new min/max/var_off satisfy the old ones and 13394 * everything else matches, we are OK. 13395 */ 13396 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 13397 range_within(rold, rcur) && 13398 tnum_in(rold->var_off, rcur->var_off) && 13399 check_ids(rold->id, rcur->id, idmap); 13400 case PTR_TO_PACKET_META: 13401 case PTR_TO_PACKET: 13402 /* We must have at least as much range as the old ptr 13403 * did, so that any accesses which were safe before are 13404 * still safe. This is true even if old range < old off, 13405 * since someone could have accessed through (ptr - k), or 13406 * even done ptr -= k in a register, to get a safe access. 13407 */ 13408 if (rold->range > rcur->range) 13409 return false; 13410 /* If the offsets don't match, we can't trust our alignment; 13411 * nor can we be sure that we won't fall out of range. 13412 */ 13413 if (rold->off != rcur->off) 13414 return false; 13415 /* id relations must be preserved */ 13416 if (!check_ids(rold->id, rcur->id, idmap)) 13417 return false; 13418 /* new val must satisfy old val knowledge */ 13419 return range_within(rold, rcur) && 13420 tnum_in(rold->var_off, rcur->var_off); 13421 case PTR_TO_STACK: 13422 /* two stack pointers are equal only if they're pointing to 13423 * the same stack frame, since fp-8 in foo != fp-8 in bar 13424 */ 13425 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 13426 default: 13427 return regs_exact(rold, rcur, idmap); 13428 } 13429 } 13430 13431 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 13432 struct bpf_func_state *cur, struct bpf_id_pair *idmap) 13433 { 13434 int i, spi; 13435 13436 /* walk slots of the explored stack and ignore any additional 13437 * slots in the current stack, since explored(safe) state 13438 * didn't use them 13439 */ 13440 for (i = 0; i < old->allocated_stack; i++) { 13441 spi = i / BPF_REG_SIZE; 13442 13443 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 13444 i += BPF_REG_SIZE - 1; 13445 /* explored state didn't use this */ 13446 continue; 13447 } 13448 13449 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 13450 continue; 13451 13452 /* explored stack has more populated slots than current stack 13453 * and these slots were used 13454 */ 13455 if (i >= cur->allocated_stack) 13456 return false; 13457 13458 /* if old state was safe with misc data in the stack 13459 * it will be safe with zero-initialized stack. 13460 * The opposite is not true 13461 */ 13462 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 13463 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 13464 continue; 13465 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 13466 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 13467 /* Ex: old explored (safe) state has STACK_SPILL in 13468 * this stack slot, but current has STACK_MISC -> 13469 * this verifier states are not equivalent, 13470 * return false to continue verification of this path 13471 */ 13472 return false; 13473 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 13474 continue; 13475 /* Both old and cur are having same slot_type */ 13476 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 13477 case STACK_SPILL: 13478 /* when explored and current stack slot are both storing 13479 * spilled registers, check that stored pointers types 13480 * are the same as well. 13481 * Ex: explored safe path could have stored 13482 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 13483 * but current path has stored: 13484 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 13485 * such verifier states are not equivalent. 13486 * return false to continue verification of this path 13487 */ 13488 if (!regsafe(env, &old->stack[spi].spilled_ptr, 13489 &cur->stack[spi].spilled_ptr, idmap)) 13490 return false; 13491 break; 13492 case STACK_DYNPTR: 13493 { 13494 const struct bpf_reg_state *old_reg, *cur_reg; 13495 13496 old_reg = &old->stack[spi].spilled_ptr; 13497 cur_reg = &cur->stack[spi].spilled_ptr; 13498 if (old_reg->dynptr.type != cur_reg->dynptr.type || 13499 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 13500 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 13501 return false; 13502 break; 13503 } 13504 case STACK_MISC: 13505 case STACK_ZERO: 13506 case STACK_INVALID: 13507 continue; 13508 /* Ensure that new unhandled slot types return false by default */ 13509 default: 13510 return false; 13511 } 13512 } 13513 return true; 13514 } 13515 13516 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 13517 struct bpf_id_pair *idmap) 13518 { 13519 int i; 13520 13521 if (old->acquired_refs != cur->acquired_refs) 13522 return false; 13523 13524 for (i = 0; i < old->acquired_refs; i++) { 13525 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 13526 return false; 13527 } 13528 13529 return true; 13530 } 13531 13532 /* compare two verifier states 13533 * 13534 * all states stored in state_list are known to be valid, since 13535 * verifier reached 'bpf_exit' instruction through them 13536 * 13537 * this function is called when verifier exploring different branches of 13538 * execution popped from the state stack. If it sees an old state that has 13539 * more strict register state and more strict stack state then this execution 13540 * branch doesn't need to be explored further, since verifier already 13541 * concluded that more strict state leads to valid finish. 13542 * 13543 * Therefore two states are equivalent if register state is more conservative 13544 * and explored stack state is more conservative than the current one. 13545 * Example: 13546 * explored current 13547 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 13548 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 13549 * 13550 * In other words if current stack state (one being explored) has more 13551 * valid slots than old one that already passed validation, it means 13552 * the verifier can stop exploring and conclude that current state is valid too 13553 * 13554 * Similarly with registers. If explored state has register type as invalid 13555 * whereas register type in current state is meaningful, it means that 13556 * the current state will reach 'bpf_exit' instruction safely 13557 */ 13558 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 13559 struct bpf_func_state *cur) 13560 { 13561 int i; 13562 13563 for (i = 0; i < MAX_BPF_REG; i++) 13564 if (!regsafe(env, &old->regs[i], &cur->regs[i], 13565 env->idmap_scratch)) 13566 return false; 13567 13568 if (!stacksafe(env, old, cur, env->idmap_scratch)) 13569 return false; 13570 13571 if (!refsafe(old, cur, env->idmap_scratch)) 13572 return false; 13573 13574 return true; 13575 } 13576 13577 static bool states_equal(struct bpf_verifier_env *env, 13578 struct bpf_verifier_state *old, 13579 struct bpf_verifier_state *cur) 13580 { 13581 int i; 13582 13583 if (old->curframe != cur->curframe) 13584 return false; 13585 13586 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch)); 13587 13588 /* Verification state from speculative execution simulation 13589 * must never prune a non-speculative execution one. 13590 */ 13591 if (old->speculative && !cur->speculative) 13592 return false; 13593 13594 if (old->active_lock.ptr != cur->active_lock.ptr) 13595 return false; 13596 13597 /* Old and cur active_lock's have to be either both present 13598 * or both absent. 13599 */ 13600 if (!!old->active_lock.id != !!cur->active_lock.id) 13601 return false; 13602 13603 if (old->active_lock.id && 13604 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch)) 13605 return false; 13606 13607 if (old->active_rcu_lock != cur->active_rcu_lock) 13608 return false; 13609 13610 /* for states to be equal callsites have to be the same 13611 * and all frame states need to be equivalent 13612 */ 13613 for (i = 0; i <= old->curframe; i++) { 13614 if (old->frame[i]->callsite != cur->frame[i]->callsite) 13615 return false; 13616 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 13617 return false; 13618 } 13619 return true; 13620 } 13621 13622 /* Return 0 if no propagation happened. Return negative error code if error 13623 * happened. Otherwise, return the propagated bit. 13624 */ 13625 static int propagate_liveness_reg(struct bpf_verifier_env *env, 13626 struct bpf_reg_state *reg, 13627 struct bpf_reg_state *parent_reg) 13628 { 13629 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 13630 u8 flag = reg->live & REG_LIVE_READ; 13631 int err; 13632 13633 /* When comes here, read flags of PARENT_REG or REG could be any of 13634 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 13635 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 13636 */ 13637 if (parent_flag == REG_LIVE_READ64 || 13638 /* Or if there is no read flag from REG. */ 13639 !flag || 13640 /* Or if the read flag from REG is the same as PARENT_REG. */ 13641 parent_flag == flag) 13642 return 0; 13643 13644 err = mark_reg_read(env, reg, parent_reg, flag); 13645 if (err) 13646 return err; 13647 13648 return flag; 13649 } 13650 13651 /* A write screens off any subsequent reads; but write marks come from the 13652 * straight-line code between a state and its parent. When we arrive at an 13653 * equivalent state (jump target or such) we didn't arrive by the straight-line 13654 * code, so read marks in the state must propagate to the parent regardless 13655 * of the state's write marks. That's what 'parent == state->parent' comparison 13656 * in mark_reg_read() is for. 13657 */ 13658 static int propagate_liveness(struct bpf_verifier_env *env, 13659 const struct bpf_verifier_state *vstate, 13660 struct bpf_verifier_state *vparent) 13661 { 13662 struct bpf_reg_state *state_reg, *parent_reg; 13663 struct bpf_func_state *state, *parent; 13664 int i, frame, err = 0; 13665 13666 if (vparent->curframe != vstate->curframe) { 13667 WARN(1, "propagate_live: parent frame %d current frame %d\n", 13668 vparent->curframe, vstate->curframe); 13669 return -EFAULT; 13670 } 13671 /* Propagate read liveness of registers... */ 13672 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 13673 for (frame = 0; frame <= vstate->curframe; frame++) { 13674 parent = vparent->frame[frame]; 13675 state = vstate->frame[frame]; 13676 parent_reg = parent->regs; 13677 state_reg = state->regs; 13678 /* We don't need to worry about FP liveness, it's read-only */ 13679 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 13680 err = propagate_liveness_reg(env, &state_reg[i], 13681 &parent_reg[i]); 13682 if (err < 0) 13683 return err; 13684 if (err == REG_LIVE_READ64) 13685 mark_insn_zext(env, &parent_reg[i]); 13686 } 13687 13688 /* Propagate stack slots. */ 13689 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 13690 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 13691 parent_reg = &parent->stack[i].spilled_ptr; 13692 state_reg = &state->stack[i].spilled_ptr; 13693 err = propagate_liveness_reg(env, state_reg, 13694 parent_reg); 13695 if (err < 0) 13696 return err; 13697 } 13698 } 13699 return 0; 13700 } 13701 13702 /* find precise scalars in the previous equivalent state and 13703 * propagate them into the current state 13704 */ 13705 static int propagate_precision(struct bpf_verifier_env *env, 13706 const struct bpf_verifier_state *old) 13707 { 13708 struct bpf_reg_state *state_reg; 13709 struct bpf_func_state *state; 13710 int i, err = 0, fr; 13711 13712 for (fr = old->curframe; fr >= 0; fr--) { 13713 state = old->frame[fr]; 13714 state_reg = state->regs; 13715 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 13716 if (state_reg->type != SCALAR_VALUE || 13717 !state_reg->precise) 13718 continue; 13719 if (env->log.level & BPF_LOG_LEVEL2) 13720 verbose(env, "frame %d: propagating r%d\n", i, fr); 13721 err = mark_chain_precision_frame(env, fr, i); 13722 if (err < 0) 13723 return err; 13724 } 13725 13726 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 13727 if (!is_spilled_reg(&state->stack[i])) 13728 continue; 13729 state_reg = &state->stack[i].spilled_ptr; 13730 if (state_reg->type != SCALAR_VALUE || 13731 !state_reg->precise) 13732 continue; 13733 if (env->log.level & BPF_LOG_LEVEL2) 13734 verbose(env, "frame %d: propagating fp%d\n", 13735 (-i - 1) * BPF_REG_SIZE, fr); 13736 err = mark_chain_precision_stack_frame(env, fr, i); 13737 if (err < 0) 13738 return err; 13739 } 13740 } 13741 return 0; 13742 } 13743 13744 static bool states_maybe_looping(struct bpf_verifier_state *old, 13745 struct bpf_verifier_state *cur) 13746 { 13747 struct bpf_func_state *fold, *fcur; 13748 int i, fr = cur->curframe; 13749 13750 if (old->curframe != fr) 13751 return false; 13752 13753 fold = old->frame[fr]; 13754 fcur = cur->frame[fr]; 13755 for (i = 0; i < MAX_BPF_REG; i++) 13756 if (memcmp(&fold->regs[i], &fcur->regs[i], 13757 offsetof(struct bpf_reg_state, parent))) 13758 return false; 13759 return true; 13760 } 13761 13762 13763 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 13764 { 13765 struct bpf_verifier_state_list *new_sl; 13766 struct bpf_verifier_state_list *sl, **pprev; 13767 struct bpf_verifier_state *cur = env->cur_state, *new; 13768 int i, j, err, states_cnt = 0; 13769 bool add_new_state = env->test_state_freq ? true : false; 13770 13771 /* bpf progs typically have pruning point every 4 instructions 13772 * http://vger.kernel.org/bpfconf2019.html#session-1 13773 * Do not add new state for future pruning if the verifier hasn't seen 13774 * at least 2 jumps and at least 8 instructions. 13775 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 13776 * In tests that amounts to up to 50% reduction into total verifier 13777 * memory consumption and 20% verifier time speedup. 13778 */ 13779 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 13780 env->insn_processed - env->prev_insn_processed >= 8) 13781 add_new_state = true; 13782 13783 pprev = explored_state(env, insn_idx); 13784 sl = *pprev; 13785 13786 clean_live_states(env, insn_idx, cur); 13787 13788 while (sl) { 13789 states_cnt++; 13790 if (sl->state.insn_idx != insn_idx) 13791 goto next; 13792 13793 if (sl->state.branches) { 13794 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 13795 13796 if (frame->in_async_callback_fn && 13797 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 13798 /* Different async_entry_cnt means that the verifier is 13799 * processing another entry into async callback. 13800 * Seeing the same state is not an indication of infinite 13801 * loop or infinite recursion. 13802 * But finding the same state doesn't mean that it's safe 13803 * to stop processing the current state. The previous state 13804 * hasn't yet reached bpf_exit, since state.branches > 0. 13805 * Checking in_async_callback_fn alone is not enough either. 13806 * Since the verifier still needs to catch infinite loops 13807 * inside async callbacks. 13808 */ 13809 } else if (states_maybe_looping(&sl->state, cur) && 13810 states_equal(env, &sl->state, cur)) { 13811 verbose_linfo(env, insn_idx, "; "); 13812 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 13813 return -EINVAL; 13814 } 13815 /* if the verifier is processing a loop, avoid adding new state 13816 * too often, since different loop iterations have distinct 13817 * states and may not help future pruning. 13818 * This threshold shouldn't be too low to make sure that 13819 * a loop with large bound will be rejected quickly. 13820 * The most abusive loop will be: 13821 * r1 += 1 13822 * if r1 < 1000000 goto pc-2 13823 * 1M insn_procssed limit / 100 == 10k peak states. 13824 * This threshold shouldn't be too high either, since states 13825 * at the end of the loop are likely to be useful in pruning. 13826 */ 13827 if (env->jmps_processed - env->prev_jmps_processed < 20 && 13828 env->insn_processed - env->prev_insn_processed < 100) 13829 add_new_state = false; 13830 goto miss; 13831 } 13832 if (states_equal(env, &sl->state, cur)) { 13833 sl->hit_cnt++; 13834 /* reached equivalent register/stack state, 13835 * prune the search. 13836 * Registers read by the continuation are read by us. 13837 * If we have any write marks in env->cur_state, they 13838 * will prevent corresponding reads in the continuation 13839 * from reaching our parent (an explored_state). Our 13840 * own state will get the read marks recorded, but 13841 * they'll be immediately forgotten as we're pruning 13842 * this state and will pop a new one. 13843 */ 13844 err = propagate_liveness(env, &sl->state, cur); 13845 13846 /* if previous state reached the exit with precision and 13847 * current state is equivalent to it (except precsion marks) 13848 * the precision needs to be propagated back in 13849 * the current state. 13850 */ 13851 err = err ? : push_jmp_history(env, cur); 13852 err = err ? : propagate_precision(env, &sl->state); 13853 if (err) 13854 return err; 13855 return 1; 13856 } 13857 miss: 13858 /* when new state is not going to be added do not increase miss count. 13859 * Otherwise several loop iterations will remove the state 13860 * recorded earlier. The goal of these heuristics is to have 13861 * states from some iterations of the loop (some in the beginning 13862 * and some at the end) to help pruning. 13863 */ 13864 if (add_new_state) 13865 sl->miss_cnt++; 13866 /* heuristic to determine whether this state is beneficial 13867 * to keep checking from state equivalence point of view. 13868 * Higher numbers increase max_states_per_insn and verification time, 13869 * but do not meaningfully decrease insn_processed. 13870 */ 13871 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 13872 /* the state is unlikely to be useful. Remove it to 13873 * speed up verification 13874 */ 13875 *pprev = sl->next; 13876 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 13877 u32 br = sl->state.branches; 13878 13879 WARN_ONCE(br, 13880 "BUG live_done but branches_to_explore %d\n", 13881 br); 13882 free_verifier_state(&sl->state, false); 13883 kfree(sl); 13884 env->peak_states--; 13885 } else { 13886 /* cannot free this state, since parentage chain may 13887 * walk it later. Add it for free_list instead to 13888 * be freed at the end of verification 13889 */ 13890 sl->next = env->free_list; 13891 env->free_list = sl; 13892 } 13893 sl = *pprev; 13894 continue; 13895 } 13896 next: 13897 pprev = &sl->next; 13898 sl = *pprev; 13899 } 13900 13901 if (env->max_states_per_insn < states_cnt) 13902 env->max_states_per_insn = states_cnt; 13903 13904 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 13905 return 0; 13906 13907 if (!add_new_state) 13908 return 0; 13909 13910 /* There were no equivalent states, remember the current one. 13911 * Technically the current state is not proven to be safe yet, 13912 * but it will either reach outer most bpf_exit (which means it's safe) 13913 * or it will be rejected. When there are no loops the verifier won't be 13914 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 13915 * again on the way to bpf_exit. 13916 * When looping the sl->state.branches will be > 0 and this state 13917 * will not be considered for equivalence until branches == 0. 13918 */ 13919 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 13920 if (!new_sl) 13921 return -ENOMEM; 13922 env->total_states++; 13923 env->peak_states++; 13924 env->prev_jmps_processed = env->jmps_processed; 13925 env->prev_insn_processed = env->insn_processed; 13926 13927 /* forget precise markings we inherited, see __mark_chain_precision */ 13928 if (env->bpf_capable) 13929 mark_all_scalars_imprecise(env, cur); 13930 13931 /* add new state to the head of linked list */ 13932 new = &new_sl->state; 13933 err = copy_verifier_state(new, cur); 13934 if (err) { 13935 free_verifier_state(new, false); 13936 kfree(new_sl); 13937 return err; 13938 } 13939 new->insn_idx = insn_idx; 13940 WARN_ONCE(new->branches != 1, 13941 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 13942 13943 cur->parent = new; 13944 cur->first_insn_idx = insn_idx; 13945 clear_jmp_history(cur); 13946 new_sl->next = *explored_state(env, insn_idx); 13947 *explored_state(env, insn_idx) = new_sl; 13948 /* connect new state to parentage chain. Current frame needs all 13949 * registers connected. Only r6 - r9 of the callers are alive (pushed 13950 * to the stack implicitly by JITs) so in callers' frames connect just 13951 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 13952 * the state of the call instruction (with WRITTEN set), and r0 comes 13953 * from callee with its full parentage chain, anyway. 13954 */ 13955 /* clear write marks in current state: the writes we did are not writes 13956 * our child did, so they don't screen off its reads from us. 13957 * (There are no read marks in current state, because reads always mark 13958 * their parent and current state never has children yet. Only 13959 * explored_states can get read marks.) 13960 */ 13961 for (j = 0; j <= cur->curframe; j++) { 13962 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 13963 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 13964 for (i = 0; i < BPF_REG_FP; i++) 13965 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 13966 } 13967 13968 /* all stack frames are accessible from callee, clear them all */ 13969 for (j = 0; j <= cur->curframe; j++) { 13970 struct bpf_func_state *frame = cur->frame[j]; 13971 struct bpf_func_state *newframe = new->frame[j]; 13972 13973 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 13974 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 13975 frame->stack[i].spilled_ptr.parent = 13976 &newframe->stack[i].spilled_ptr; 13977 } 13978 } 13979 return 0; 13980 } 13981 13982 /* Return true if it's OK to have the same insn return a different type. */ 13983 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 13984 { 13985 switch (base_type(type)) { 13986 case PTR_TO_CTX: 13987 case PTR_TO_SOCKET: 13988 case PTR_TO_SOCK_COMMON: 13989 case PTR_TO_TCP_SOCK: 13990 case PTR_TO_XDP_SOCK: 13991 case PTR_TO_BTF_ID: 13992 return false; 13993 default: 13994 return true; 13995 } 13996 } 13997 13998 /* If an instruction was previously used with particular pointer types, then we 13999 * need to be careful to avoid cases such as the below, where it may be ok 14000 * for one branch accessing the pointer, but not ok for the other branch: 14001 * 14002 * R1 = sock_ptr 14003 * goto X; 14004 * ... 14005 * R1 = some_other_valid_ptr; 14006 * goto X; 14007 * ... 14008 * R2 = *(u32 *)(R1 + 0); 14009 */ 14010 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 14011 { 14012 return src != prev && (!reg_type_mismatch_ok(src) || 14013 !reg_type_mismatch_ok(prev)); 14014 } 14015 14016 static int do_check(struct bpf_verifier_env *env) 14017 { 14018 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 14019 struct bpf_verifier_state *state = env->cur_state; 14020 struct bpf_insn *insns = env->prog->insnsi; 14021 struct bpf_reg_state *regs; 14022 int insn_cnt = env->prog->len; 14023 bool do_print_state = false; 14024 int prev_insn_idx = -1; 14025 14026 for (;;) { 14027 struct bpf_insn *insn; 14028 u8 class; 14029 int err; 14030 14031 env->prev_insn_idx = prev_insn_idx; 14032 if (env->insn_idx >= insn_cnt) { 14033 verbose(env, "invalid insn idx %d insn_cnt %d\n", 14034 env->insn_idx, insn_cnt); 14035 return -EFAULT; 14036 } 14037 14038 insn = &insns[env->insn_idx]; 14039 class = BPF_CLASS(insn->code); 14040 14041 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 14042 verbose(env, 14043 "BPF program is too large. Processed %d insn\n", 14044 env->insn_processed); 14045 return -E2BIG; 14046 } 14047 14048 state->last_insn_idx = env->prev_insn_idx; 14049 14050 if (is_prune_point(env, env->insn_idx)) { 14051 err = is_state_visited(env, env->insn_idx); 14052 if (err < 0) 14053 return err; 14054 if (err == 1) { 14055 /* found equivalent state, can prune the search */ 14056 if (env->log.level & BPF_LOG_LEVEL) { 14057 if (do_print_state) 14058 verbose(env, "\nfrom %d to %d%s: safe\n", 14059 env->prev_insn_idx, env->insn_idx, 14060 env->cur_state->speculative ? 14061 " (speculative execution)" : ""); 14062 else 14063 verbose(env, "%d: safe\n", env->insn_idx); 14064 } 14065 goto process_bpf_exit; 14066 } 14067 } 14068 14069 if (is_jmp_point(env, env->insn_idx)) { 14070 err = push_jmp_history(env, state); 14071 if (err) 14072 return err; 14073 } 14074 14075 if (signal_pending(current)) 14076 return -EAGAIN; 14077 14078 if (need_resched()) 14079 cond_resched(); 14080 14081 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 14082 verbose(env, "\nfrom %d to %d%s:", 14083 env->prev_insn_idx, env->insn_idx, 14084 env->cur_state->speculative ? 14085 " (speculative execution)" : ""); 14086 print_verifier_state(env, state->frame[state->curframe], true); 14087 do_print_state = false; 14088 } 14089 14090 if (env->log.level & BPF_LOG_LEVEL) { 14091 const struct bpf_insn_cbs cbs = { 14092 .cb_call = disasm_kfunc_name, 14093 .cb_print = verbose, 14094 .private_data = env, 14095 }; 14096 14097 if (verifier_state_scratched(env)) 14098 print_insn_state(env, state->frame[state->curframe]); 14099 14100 verbose_linfo(env, env->insn_idx, "; "); 14101 env->prev_log_len = env->log.len_used; 14102 verbose(env, "%d: ", env->insn_idx); 14103 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 14104 env->prev_insn_print_len = env->log.len_used - env->prev_log_len; 14105 env->prev_log_len = env->log.len_used; 14106 } 14107 14108 if (bpf_prog_is_offloaded(env->prog->aux)) { 14109 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 14110 env->prev_insn_idx); 14111 if (err) 14112 return err; 14113 } 14114 14115 regs = cur_regs(env); 14116 sanitize_mark_insn_seen(env); 14117 prev_insn_idx = env->insn_idx; 14118 14119 if (class == BPF_ALU || class == BPF_ALU64) { 14120 err = check_alu_op(env, insn); 14121 if (err) 14122 return err; 14123 14124 } else if (class == BPF_LDX) { 14125 enum bpf_reg_type *prev_src_type, src_reg_type; 14126 14127 /* check for reserved fields is already done */ 14128 14129 /* check src operand */ 14130 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14131 if (err) 14132 return err; 14133 14134 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14135 if (err) 14136 return err; 14137 14138 src_reg_type = regs[insn->src_reg].type; 14139 14140 /* check that memory (src_reg + off) is readable, 14141 * the state of dst_reg will be updated by this func 14142 */ 14143 err = check_mem_access(env, env->insn_idx, insn->src_reg, 14144 insn->off, BPF_SIZE(insn->code), 14145 BPF_READ, insn->dst_reg, false); 14146 if (err) 14147 return err; 14148 14149 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 14150 14151 if (*prev_src_type == NOT_INIT) { 14152 /* saw a valid insn 14153 * dst_reg = *(u32 *)(src_reg + off) 14154 * save type to validate intersecting paths 14155 */ 14156 *prev_src_type = src_reg_type; 14157 14158 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 14159 /* ABuser program is trying to use the same insn 14160 * dst_reg = *(u32*) (src_reg + off) 14161 * with different pointer types: 14162 * src_reg == ctx in one branch and 14163 * src_reg == stack|map in some other branch. 14164 * Reject it. 14165 */ 14166 verbose(env, "same insn cannot be used with different pointers\n"); 14167 return -EINVAL; 14168 } 14169 14170 } else if (class == BPF_STX) { 14171 enum bpf_reg_type *prev_dst_type, dst_reg_type; 14172 14173 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 14174 err = check_atomic(env, env->insn_idx, insn); 14175 if (err) 14176 return err; 14177 env->insn_idx++; 14178 continue; 14179 } 14180 14181 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 14182 verbose(env, "BPF_STX uses reserved fields\n"); 14183 return -EINVAL; 14184 } 14185 14186 /* check src1 operand */ 14187 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14188 if (err) 14189 return err; 14190 /* check src2 operand */ 14191 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14192 if (err) 14193 return err; 14194 14195 dst_reg_type = regs[insn->dst_reg].type; 14196 14197 /* check that memory (dst_reg + off) is writeable */ 14198 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 14199 insn->off, BPF_SIZE(insn->code), 14200 BPF_WRITE, insn->src_reg, false); 14201 if (err) 14202 return err; 14203 14204 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 14205 14206 if (*prev_dst_type == NOT_INIT) { 14207 *prev_dst_type = dst_reg_type; 14208 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 14209 verbose(env, "same insn cannot be used with different pointers\n"); 14210 return -EINVAL; 14211 } 14212 14213 } else if (class == BPF_ST) { 14214 if (BPF_MODE(insn->code) != BPF_MEM || 14215 insn->src_reg != BPF_REG_0) { 14216 verbose(env, "BPF_ST uses reserved fields\n"); 14217 return -EINVAL; 14218 } 14219 /* check src operand */ 14220 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14221 if (err) 14222 return err; 14223 14224 if (is_ctx_reg(env, insn->dst_reg)) { 14225 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 14226 insn->dst_reg, 14227 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 14228 return -EACCES; 14229 } 14230 14231 /* check that memory (dst_reg + off) is writeable */ 14232 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 14233 insn->off, BPF_SIZE(insn->code), 14234 BPF_WRITE, -1, false); 14235 if (err) 14236 return err; 14237 14238 } else if (class == BPF_JMP || class == BPF_JMP32) { 14239 u8 opcode = BPF_OP(insn->code); 14240 14241 env->jmps_processed++; 14242 if (opcode == BPF_CALL) { 14243 if (BPF_SRC(insn->code) != BPF_K || 14244 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 14245 && insn->off != 0) || 14246 (insn->src_reg != BPF_REG_0 && 14247 insn->src_reg != BPF_PSEUDO_CALL && 14248 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 14249 insn->dst_reg != BPF_REG_0 || 14250 class == BPF_JMP32) { 14251 verbose(env, "BPF_CALL uses reserved fields\n"); 14252 return -EINVAL; 14253 } 14254 14255 if (env->cur_state->active_lock.ptr) { 14256 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 14257 (insn->src_reg == BPF_PSEUDO_CALL) || 14258 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 14259 (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) { 14260 verbose(env, "function calls are not allowed while holding a lock\n"); 14261 return -EINVAL; 14262 } 14263 } 14264 if (insn->src_reg == BPF_PSEUDO_CALL) 14265 err = check_func_call(env, insn, &env->insn_idx); 14266 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 14267 err = check_kfunc_call(env, insn, &env->insn_idx); 14268 else 14269 err = check_helper_call(env, insn, &env->insn_idx); 14270 if (err) 14271 return err; 14272 } else if (opcode == BPF_JA) { 14273 if (BPF_SRC(insn->code) != BPF_K || 14274 insn->imm != 0 || 14275 insn->src_reg != BPF_REG_0 || 14276 insn->dst_reg != BPF_REG_0 || 14277 class == BPF_JMP32) { 14278 verbose(env, "BPF_JA uses reserved fields\n"); 14279 return -EINVAL; 14280 } 14281 14282 env->insn_idx += insn->off + 1; 14283 continue; 14284 14285 } else if (opcode == BPF_EXIT) { 14286 if (BPF_SRC(insn->code) != BPF_K || 14287 insn->imm != 0 || 14288 insn->src_reg != BPF_REG_0 || 14289 insn->dst_reg != BPF_REG_0 || 14290 class == BPF_JMP32) { 14291 verbose(env, "BPF_EXIT uses reserved fields\n"); 14292 return -EINVAL; 14293 } 14294 14295 if (env->cur_state->active_lock.ptr) { 14296 verbose(env, "bpf_spin_unlock is missing\n"); 14297 return -EINVAL; 14298 } 14299 14300 if (env->cur_state->active_rcu_lock) { 14301 verbose(env, "bpf_rcu_read_unlock is missing\n"); 14302 return -EINVAL; 14303 } 14304 14305 /* We must do check_reference_leak here before 14306 * prepare_func_exit to handle the case when 14307 * state->curframe > 0, it may be a callback 14308 * function, for which reference_state must 14309 * match caller reference state when it exits. 14310 */ 14311 err = check_reference_leak(env); 14312 if (err) 14313 return err; 14314 14315 if (state->curframe) { 14316 /* exit from nested function */ 14317 err = prepare_func_exit(env, &env->insn_idx); 14318 if (err) 14319 return err; 14320 do_print_state = true; 14321 continue; 14322 } 14323 14324 err = check_return_code(env); 14325 if (err) 14326 return err; 14327 process_bpf_exit: 14328 mark_verifier_state_scratched(env); 14329 update_branch_counts(env, env->cur_state); 14330 err = pop_stack(env, &prev_insn_idx, 14331 &env->insn_idx, pop_log); 14332 if (err < 0) { 14333 if (err != -ENOENT) 14334 return err; 14335 break; 14336 } else { 14337 do_print_state = true; 14338 continue; 14339 } 14340 } else { 14341 err = check_cond_jmp_op(env, insn, &env->insn_idx); 14342 if (err) 14343 return err; 14344 } 14345 } else if (class == BPF_LD) { 14346 u8 mode = BPF_MODE(insn->code); 14347 14348 if (mode == BPF_ABS || mode == BPF_IND) { 14349 err = check_ld_abs(env, insn); 14350 if (err) 14351 return err; 14352 14353 } else if (mode == BPF_IMM) { 14354 err = check_ld_imm(env, insn); 14355 if (err) 14356 return err; 14357 14358 env->insn_idx++; 14359 sanitize_mark_insn_seen(env); 14360 } else { 14361 verbose(env, "invalid BPF_LD mode\n"); 14362 return -EINVAL; 14363 } 14364 } else { 14365 verbose(env, "unknown insn class %d\n", class); 14366 return -EINVAL; 14367 } 14368 14369 env->insn_idx++; 14370 } 14371 14372 return 0; 14373 } 14374 14375 static int find_btf_percpu_datasec(struct btf *btf) 14376 { 14377 const struct btf_type *t; 14378 const char *tname; 14379 int i, n; 14380 14381 /* 14382 * Both vmlinux and module each have their own ".data..percpu" 14383 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 14384 * types to look at only module's own BTF types. 14385 */ 14386 n = btf_nr_types(btf); 14387 if (btf_is_module(btf)) 14388 i = btf_nr_types(btf_vmlinux); 14389 else 14390 i = 1; 14391 14392 for(; i < n; i++) { 14393 t = btf_type_by_id(btf, i); 14394 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 14395 continue; 14396 14397 tname = btf_name_by_offset(btf, t->name_off); 14398 if (!strcmp(tname, ".data..percpu")) 14399 return i; 14400 } 14401 14402 return -ENOENT; 14403 } 14404 14405 /* replace pseudo btf_id with kernel symbol address */ 14406 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 14407 struct bpf_insn *insn, 14408 struct bpf_insn_aux_data *aux) 14409 { 14410 const struct btf_var_secinfo *vsi; 14411 const struct btf_type *datasec; 14412 struct btf_mod_pair *btf_mod; 14413 const struct btf_type *t; 14414 const char *sym_name; 14415 bool percpu = false; 14416 u32 type, id = insn->imm; 14417 struct btf *btf; 14418 s32 datasec_id; 14419 u64 addr; 14420 int i, btf_fd, err; 14421 14422 btf_fd = insn[1].imm; 14423 if (btf_fd) { 14424 btf = btf_get_by_fd(btf_fd); 14425 if (IS_ERR(btf)) { 14426 verbose(env, "invalid module BTF object FD specified.\n"); 14427 return -EINVAL; 14428 } 14429 } else { 14430 if (!btf_vmlinux) { 14431 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 14432 return -EINVAL; 14433 } 14434 btf = btf_vmlinux; 14435 btf_get(btf); 14436 } 14437 14438 t = btf_type_by_id(btf, id); 14439 if (!t) { 14440 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 14441 err = -ENOENT; 14442 goto err_put; 14443 } 14444 14445 if (!btf_type_is_var(t)) { 14446 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id); 14447 err = -EINVAL; 14448 goto err_put; 14449 } 14450 14451 sym_name = btf_name_by_offset(btf, t->name_off); 14452 addr = kallsyms_lookup_name(sym_name); 14453 if (!addr) { 14454 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 14455 sym_name); 14456 err = -ENOENT; 14457 goto err_put; 14458 } 14459 14460 datasec_id = find_btf_percpu_datasec(btf); 14461 if (datasec_id > 0) { 14462 datasec = btf_type_by_id(btf, datasec_id); 14463 for_each_vsi(i, datasec, vsi) { 14464 if (vsi->type == id) { 14465 percpu = true; 14466 break; 14467 } 14468 } 14469 } 14470 14471 insn[0].imm = (u32)addr; 14472 insn[1].imm = addr >> 32; 14473 14474 type = t->type; 14475 t = btf_type_skip_modifiers(btf, type, NULL); 14476 if (percpu) { 14477 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 14478 aux->btf_var.btf = btf; 14479 aux->btf_var.btf_id = type; 14480 } else if (!btf_type_is_struct(t)) { 14481 const struct btf_type *ret; 14482 const char *tname; 14483 u32 tsize; 14484 14485 /* resolve the type size of ksym. */ 14486 ret = btf_resolve_size(btf, t, &tsize); 14487 if (IS_ERR(ret)) { 14488 tname = btf_name_by_offset(btf, t->name_off); 14489 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 14490 tname, PTR_ERR(ret)); 14491 err = -EINVAL; 14492 goto err_put; 14493 } 14494 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 14495 aux->btf_var.mem_size = tsize; 14496 } else { 14497 aux->btf_var.reg_type = PTR_TO_BTF_ID; 14498 aux->btf_var.btf = btf; 14499 aux->btf_var.btf_id = type; 14500 } 14501 14502 /* check whether we recorded this BTF (and maybe module) already */ 14503 for (i = 0; i < env->used_btf_cnt; i++) { 14504 if (env->used_btfs[i].btf == btf) { 14505 btf_put(btf); 14506 return 0; 14507 } 14508 } 14509 14510 if (env->used_btf_cnt >= MAX_USED_BTFS) { 14511 err = -E2BIG; 14512 goto err_put; 14513 } 14514 14515 btf_mod = &env->used_btfs[env->used_btf_cnt]; 14516 btf_mod->btf = btf; 14517 btf_mod->module = NULL; 14518 14519 /* if we reference variables from kernel module, bump its refcount */ 14520 if (btf_is_module(btf)) { 14521 btf_mod->module = btf_try_get_module(btf); 14522 if (!btf_mod->module) { 14523 err = -ENXIO; 14524 goto err_put; 14525 } 14526 } 14527 14528 env->used_btf_cnt++; 14529 14530 return 0; 14531 err_put: 14532 btf_put(btf); 14533 return err; 14534 } 14535 14536 static bool is_tracing_prog_type(enum bpf_prog_type type) 14537 { 14538 switch (type) { 14539 case BPF_PROG_TYPE_KPROBE: 14540 case BPF_PROG_TYPE_TRACEPOINT: 14541 case BPF_PROG_TYPE_PERF_EVENT: 14542 case BPF_PROG_TYPE_RAW_TRACEPOINT: 14543 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 14544 return true; 14545 default: 14546 return false; 14547 } 14548 } 14549 14550 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 14551 struct bpf_map *map, 14552 struct bpf_prog *prog) 14553 14554 { 14555 enum bpf_prog_type prog_type = resolve_prog_type(prog); 14556 14557 if (btf_record_has_field(map->record, BPF_LIST_HEAD)) { 14558 if (is_tracing_prog_type(prog_type)) { 14559 verbose(env, "tracing progs cannot use bpf_list_head yet\n"); 14560 return -EINVAL; 14561 } 14562 } 14563 14564 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 14565 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 14566 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 14567 return -EINVAL; 14568 } 14569 14570 if (is_tracing_prog_type(prog_type)) { 14571 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 14572 return -EINVAL; 14573 } 14574 14575 if (prog->aux->sleepable) { 14576 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 14577 return -EINVAL; 14578 } 14579 } 14580 14581 if (btf_record_has_field(map->record, BPF_TIMER)) { 14582 if (is_tracing_prog_type(prog_type)) { 14583 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 14584 return -EINVAL; 14585 } 14586 } 14587 14588 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 14589 !bpf_offload_prog_map_match(prog, map)) { 14590 verbose(env, "offload device mismatch between prog and map\n"); 14591 return -EINVAL; 14592 } 14593 14594 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 14595 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 14596 return -EINVAL; 14597 } 14598 14599 if (prog->aux->sleepable) 14600 switch (map->map_type) { 14601 case BPF_MAP_TYPE_HASH: 14602 case BPF_MAP_TYPE_LRU_HASH: 14603 case BPF_MAP_TYPE_ARRAY: 14604 case BPF_MAP_TYPE_PERCPU_HASH: 14605 case BPF_MAP_TYPE_PERCPU_ARRAY: 14606 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 14607 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 14608 case BPF_MAP_TYPE_HASH_OF_MAPS: 14609 case BPF_MAP_TYPE_RINGBUF: 14610 case BPF_MAP_TYPE_USER_RINGBUF: 14611 case BPF_MAP_TYPE_INODE_STORAGE: 14612 case BPF_MAP_TYPE_SK_STORAGE: 14613 case BPF_MAP_TYPE_TASK_STORAGE: 14614 case BPF_MAP_TYPE_CGRP_STORAGE: 14615 break; 14616 default: 14617 verbose(env, 14618 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 14619 return -EINVAL; 14620 } 14621 14622 return 0; 14623 } 14624 14625 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 14626 { 14627 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 14628 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 14629 } 14630 14631 /* find and rewrite pseudo imm in ld_imm64 instructions: 14632 * 14633 * 1. if it accesses map FD, replace it with actual map pointer. 14634 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 14635 * 14636 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 14637 */ 14638 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 14639 { 14640 struct bpf_insn *insn = env->prog->insnsi; 14641 int insn_cnt = env->prog->len; 14642 int i, j, err; 14643 14644 err = bpf_prog_calc_tag(env->prog); 14645 if (err) 14646 return err; 14647 14648 for (i = 0; i < insn_cnt; i++, insn++) { 14649 if (BPF_CLASS(insn->code) == BPF_LDX && 14650 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 14651 verbose(env, "BPF_LDX uses reserved fields\n"); 14652 return -EINVAL; 14653 } 14654 14655 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 14656 struct bpf_insn_aux_data *aux; 14657 struct bpf_map *map; 14658 struct fd f; 14659 u64 addr; 14660 u32 fd; 14661 14662 if (i == insn_cnt - 1 || insn[1].code != 0 || 14663 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 14664 insn[1].off != 0) { 14665 verbose(env, "invalid bpf_ld_imm64 insn\n"); 14666 return -EINVAL; 14667 } 14668 14669 if (insn[0].src_reg == 0) 14670 /* valid generic load 64-bit imm */ 14671 goto next_insn; 14672 14673 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 14674 aux = &env->insn_aux_data[i]; 14675 err = check_pseudo_btf_id(env, insn, aux); 14676 if (err) 14677 return err; 14678 goto next_insn; 14679 } 14680 14681 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 14682 aux = &env->insn_aux_data[i]; 14683 aux->ptr_type = PTR_TO_FUNC; 14684 goto next_insn; 14685 } 14686 14687 /* In final convert_pseudo_ld_imm64() step, this is 14688 * converted into regular 64-bit imm load insn. 14689 */ 14690 switch (insn[0].src_reg) { 14691 case BPF_PSEUDO_MAP_VALUE: 14692 case BPF_PSEUDO_MAP_IDX_VALUE: 14693 break; 14694 case BPF_PSEUDO_MAP_FD: 14695 case BPF_PSEUDO_MAP_IDX: 14696 if (insn[1].imm == 0) 14697 break; 14698 fallthrough; 14699 default: 14700 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 14701 return -EINVAL; 14702 } 14703 14704 switch (insn[0].src_reg) { 14705 case BPF_PSEUDO_MAP_IDX_VALUE: 14706 case BPF_PSEUDO_MAP_IDX: 14707 if (bpfptr_is_null(env->fd_array)) { 14708 verbose(env, "fd_idx without fd_array is invalid\n"); 14709 return -EPROTO; 14710 } 14711 if (copy_from_bpfptr_offset(&fd, env->fd_array, 14712 insn[0].imm * sizeof(fd), 14713 sizeof(fd))) 14714 return -EFAULT; 14715 break; 14716 default: 14717 fd = insn[0].imm; 14718 break; 14719 } 14720 14721 f = fdget(fd); 14722 map = __bpf_map_get(f); 14723 if (IS_ERR(map)) { 14724 verbose(env, "fd %d is not pointing to valid bpf_map\n", 14725 insn[0].imm); 14726 return PTR_ERR(map); 14727 } 14728 14729 err = check_map_prog_compatibility(env, map, env->prog); 14730 if (err) { 14731 fdput(f); 14732 return err; 14733 } 14734 14735 aux = &env->insn_aux_data[i]; 14736 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 14737 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 14738 addr = (unsigned long)map; 14739 } else { 14740 u32 off = insn[1].imm; 14741 14742 if (off >= BPF_MAX_VAR_OFF) { 14743 verbose(env, "direct value offset of %u is not allowed\n", off); 14744 fdput(f); 14745 return -EINVAL; 14746 } 14747 14748 if (!map->ops->map_direct_value_addr) { 14749 verbose(env, "no direct value access support for this map type\n"); 14750 fdput(f); 14751 return -EINVAL; 14752 } 14753 14754 err = map->ops->map_direct_value_addr(map, &addr, off); 14755 if (err) { 14756 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 14757 map->value_size, off); 14758 fdput(f); 14759 return err; 14760 } 14761 14762 aux->map_off = off; 14763 addr += off; 14764 } 14765 14766 insn[0].imm = (u32)addr; 14767 insn[1].imm = addr >> 32; 14768 14769 /* check whether we recorded this map already */ 14770 for (j = 0; j < env->used_map_cnt; j++) { 14771 if (env->used_maps[j] == map) { 14772 aux->map_index = j; 14773 fdput(f); 14774 goto next_insn; 14775 } 14776 } 14777 14778 if (env->used_map_cnt >= MAX_USED_MAPS) { 14779 fdput(f); 14780 return -E2BIG; 14781 } 14782 14783 /* hold the map. If the program is rejected by verifier, 14784 * the map will be released by release_maps() or it 14785 * will be used by the valid program until it's unloaded 14786 * and all maps are released in free_used_maps() 14787 */ 14788 bpf_map_inc(map); 14789 14790 aux->map_index = env->used_map_cnt; 14791 env->used_maps[env->used_map_cnt++] = map; 14792 14793 if (bpf_map_is_cgroup_storage(map) && 14794 bpf_cgroup_storage_assign(env->prog->aux, map)) { 14795 verbose(env, "only one cgroup storage of each type is allowed\n"); 14796 fdput(f); 14797 return -EBUSY; 14798 } 14799 14800 fdput(f); 14801 next_insn: 14802 insn++; 14803 i++; 14804 continue; 14805 } 14806 14807 /* Basic sanity check before we invest more work here. */ 14808 if (!bpf_opcode_in_insntable(insn->code)) { 14809 verbose(env, "unknown opcode %02x\n", insn->code); 14810 return -EINVAL; 14811 } 14812 } 14813 14814 /* now all pseudo BPF_LD_IMM64 instructions load valid 14815 * 'struct bpf_map *' into a register instead of user map_fd. 14816 * These pointers will be used later by verifier to validate map access. 14817 */ 14818 return 0; 14819 } 14820 14821 /* drop refcnt of maps used by the rejected program */ 14822 static void release_maps(struct bpf_verifier_env *env) 14823 { 14824 __bpf_free_used_maps(env->prog->aux, env->used_maps, 14825 env->used_map_cnt); 14826 } 14827 14828 /* drop refcnt of maps used by the rejected program */ 14829 static void release_btfs(struct bpf_verifier_env *env) 14830 { 14831 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 14832 env->used_btf_cnt); 14833 } 14834 14835 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 14836 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 14837 { 14838 struct bpf_insn *insn = env->prog->insnsi; 14839 int insn_cnt = env->prog->len; 14840 int i; 14841 14842 for (i = 0; i < insn_cnt; i++, insn++) { 14843 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 14844 continue; 14845 if (insn->src_reg == BPF_PSEUDO_FUNC) 14846 continue; 14847 insn->src_reg = 0; 14848 } 14849 } 14850 14851 /* single env->prog->insni[off] instruction was replaced with the range 14852 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 14853 * [0, off) and [off, end) to new locations, so the patched range stays zero 14854 */ 14855 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 14856 struct bpf_insn_aux_data *new_data, 14857 struct bpf_prog *new_prog, u32 off, u32 cnt) 14858 { 14859 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 14860 struct bpf_insn *insn = new_prog->insnsi; 14861 u32 old_seen = old_data[off].seen; 14862 u32 prog_len; 14863 int i; 14864 14865 /* aux info at OFF always needs adjustment, no matter fast path 14866 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 14867 * original insn at old prog. 14868 */ 14869 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 14870 14871 if (cnt == 1) 14872 return; 14873 prog_len = new_prog->len; 14874 14875 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 14876 memcpy(new_data + off + cnt - 1, old_data + off, 14877 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 14878 for (i = off; i < off + cnt - 1; i++) { 14879 /* Expand insni[off]'s seen count to the patched range. */ 14880 new_data[i].seen = old_seen; 14881 new_data[i].zext_dst = insn_has_def32(env, insn + i); 14882 } 14883 env->insn_aux_data = new_data; 14884 vfree(old_data); 14885 } 14886 14887 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 14888 { 14889 int i; 14890 14891 if (len == 1) 14892 return; 14893 /* NOTE: fake 'exit' subprog should be updated as well. */ 14894 for (i = 0; i <= env->subprog_cnt; i++) { 14895 if (env->subprog_info[i].start <= off) 14896 continue; 14897 env->subprog_info[i].start += len - 1; 14898 } 14899 } 14900 14901 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 14902 { 14903 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 14904 int i, sz = prog->aux->size_poke_tab; 14905 struct bpf_jit_poke_descriptor *desc; 14906 14907 for (i = 0; i < sz; i++) { 14908 desc = &tab[i]; 14909 if (desc->insn_idx <= off) 14910 continue; 14911 desc->insn_idx += len - 1; 14912 } 14913 } 14914 14915 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 14916 const struct bpf_insn *patch, u32 len) 14917 { 14918 struct bpf_prog *new_prog; 14919 struct bpf_insn_aux_data *new_data = NULL; 14920 14921 if (len > 1) { 14922 new_data = vzalloc(array_size(env->prog->len + len - 1, 14923 sizeof(struct bpf_insn_aux_data))); 14924 if (!new_data) 14925 return NULL; 14926 } 14927 14928 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 14929 if (IS_ERR(new_prog)) { 14930 if (PTR_ERR(new_prog) == -ERANGE) 14931 verbose(env, 14932 "insn %d cannot be patched due to 16-bit range\n", 14933 env->insn_aux_data[off].orig_idx); 14934 vfree(new_data); 14935 return NULL; 14936 } 14937 adjust_insn_aux_data(env, new_data, new_prog, off, len); 14938 adjust_subprog_starts(env, off, len); 14939 adjust_poke_descs(new_prog, off, len); 14940 return new_prog; 14941 } 14942 14943 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 14944 u32 off, u32 cnt) 14945 { 14946 int i, j; 14947 14948 /* find first prog starting at or after off (first to remove) */ 14949 for (i = 0; i < env->subprog_cnt; i++) 14950 if (env->subprog_info[i].start >= off) 14951 break; 14952 /* find first prog starting at or after off + cnt (first to stay) */ 14953 for (j = i; j < env->subprog_cnt; j++) 14954 if (env->subprog_info[j].start >= off + cnt) 14955 break; 14956 /* if j doesn't start exactly at off + cnt, we are just removing 14957 * the front of previous prog 14958 */ 14959 if (env->subprog_info[j].start != off + cnt) 14960 j--; 14961 14962 if (j > i) { 14963 struct bpf_prog_aux *aux = env->prog->aux; 14964 int move; 14965 14966 /* move fake 'exit' subprog as well */ 14967 move = env->subprog_cnt + 1 - j; 14968 14969 memmove(env->subprog_info + i, 14970 env->subprog_info + j, 14971 sizeof(*env->subprog_info) * move); 14972 env->subprog_cnt -= j - i; 14973 14974 /* remove func_info */ 14975 if (aux->func_info) { 14976 move = aux->func_info_cnt - j; 14977 14978 memmove(aux->func_info + i, 14979 aux->func_info + j, 14980 sizeof(*aux->func_info) * move); 14981 aux->func_info_cnt -= j - i; 14982 /* func_info->insn_off is set after all code rewrites, 14983 * in adjust_btf_func() - no need to adjust 14984 */ 14985 } 14986 } else { 14987 /* convert i from "first prog to remove" to "first to adjust" */ 14988 if (env->subprog_info[i].start == off) 14989 i++; 14990 } 14991 14992 /* update fake 'exit' subprog as well */ 14993 for (; i <= env->subprog_cnt; i++) 14994 env->subprog_info[i].start -= cnt; 14995 14996 return 0; 14997 } 14998 14999 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 15000 u32 cnt) 15001 { 15002 struct bpf_prog *prog = env->prog; 15003 u32 i, l_off, l_cnt, nr_linfo; 15004 struct bpf_line_info *linfo; 15005 15006 nr_linfo = prog->aux->nr_linfo; 15007 if (!nr_linfo) 15008 return 0; 15009 15010 linfo = prog->aux->linfo; 15011 15012 /* find first line info to remove, count lines to be removed */ 15013 for (i = 0; i < nr_linfo; i++) 15014 if (linfo[i].insn_off >= off) 15015 break; 15016 15017 l_off = i; 15018 l_cnt = 0; 15019 for (; i < nr_linfo; i++) 15020 if (linfo[i].insn_off < off + cnt) 15021 l_cnt++; 15022 else 15023 break; 15024 15025 /* First live insn doesn't match first live linfo, it needs to "inherit" 15026 * last removed linfo. prog is already modified, so prog->len == off 15027 * means no live instructions after (tail of the program was removed). 15028 */ 15029 if (prog->len != off && l_cnt && 15030 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 15031 l_cnt--; 15032 linfo[--i].insn_off = off + cnt; 15033 } 15034 15035 /* remove the line info which refer to the removed instructions */ 15036 if (l_cnt) { 15037 memmove(linfo + l_off, linfo + i, 15038 sizeof(*linfo) * (nr_linfo - i)); 15039 15040 prog->aux->nr_linfo -= l_cnt; 15041 nr_linfo = prog->aux->nr_linfo; 15042 } 15043 15044 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 15045 for (i = l_off; i < nr_linfo; i++) 15046 linfo[i].insn_off -= cnt; 15047 15048 /* fix up all subprogs (incl. 'exit') which start >= off */ 15049 for (i = 0; i <= env->subprog_cnt; i++) 15050 if (env->subprog_info[i].linfo_idx > l_off) { 15051 /* program may have started in the removed region but 15052 * may not be fully removed 15053 */ 15054 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 15055 env->subprog_info[i].linfo_idx -= l_cnt; 15056 else 15057 env->subprog_info[i].linfo_idx = l_off; 15058 } 15059 15060 return 0; 15061 } 15062 15063 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 15064 { 15065 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15066 unsigned int orig_prog_len = env->prog->len; 15067 int err; 15068 15069 if (bpf_prog_is_offloaded(env->prog->aux)) 15070 bpf_prog_offload_remove_insns(env, off, cnt); 15071 15072 err = bpf_remove_insns(env->prog, off, cnt); 15073 if (err) 15074 return err; 15075 15076 err = adjust_subprog_starts_after_remove(env, off, cnt); 15077 if (err) 15078 return err; 15079 15080 err = bpf_adj_linfo_after_remove(env, off, cnt); 15081 if (err) 15082 return err; 15083 15084 memmove(aux_data + off, aux_data + off + cnt, 15085 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 15086 15087 return 0; 15088 } 15089 15090 /* The verifier does more data flow analysis than llvm and will not 15091 * explore branches that are dead at run time. Malicious programs can 15092 * have dead code too. Therefore replace all dead at-run-time code 15093 * with 'ja -1'. 15094 * 15095 * Just nops are not optimal, e.g. if they would sit at the end of the 15096 * program and through another bug we would manage to jump there, then 15097 * we'd execute beyond program memory otherwise. Returning exception 15098 * code also wouldn't work since we can have subprogs where the dead 15099 * code could be located. 15100 */ 15101 static void sanitize_dead_code(struct bpf_verifier_env *env) 15102 { 15103 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15104 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 15105 struct bpf_insn *insn = env->prog->insnsi; 15106 const int insn_cnt = env->prog->len; 15107 int i; 15108 15109 for (i = 0; i < insn_cnt; i++) { 15110 if (aux_data[i].seen) 15111 continue; 15112 memcpy(insn + i, &trap, sizeof(trap)); 15113 aux_data[i].zext_dst = false; 15114 } 15115 } 15116 15117 static bool insn_is_cond_jump(u8 code) 15118 { 15119 u8 op; 15120 15121 if (BPF_CLASS(code) == BPF_JMP32) 15122 return true; 15123 15124 if (BPF_CLASS(code) != BPF_JMP) 15125 return false; 15126 15127 op = BPF_OP(code); 15128 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 15129 } 15130 15131 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 15132 { 15133 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15134 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 15135 struct bpf_insn *insn = env->prog->insnsi; 15136 const int insn_cnt = env->prog->len; 15137 int i; 15138 15139 for (i = 0; i < insn_cnt; i++, insn++) { 15140 if (!insn_is_cond_jump(insn->code)) 15141 continue; 15142 15143 if (!aux_data[i + 1].seen) 15144 ja.off = insn->off; 15145 else if (!aux_data[i + 1 + insn->off].seen) 15146 ja.off = 0; 15147 else 15148 continue; 15149 15150 if (bpf_prog_is_offloaded(env->prog->aux)) 15151 bpf_prog_offload_replace_insn(env, i, &ja); 15152 15153 memcpy(insn, &ja, sizeof(ja)); 15154 } 15155 } 15156 15157 static int opt_remove_dead_code(struct bpf_verifier_env *env) 15158 { 15159 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15160 int insn_cnt = env->prog->len; 15161 int i, err; 15162 15163 for (i = 0; i < insn_cnt; i++) { 15164 int j; 15165 15166 j = 0; 15167 while (i + j < insn_cnt && !aux_data[i + j].seen) 15168 j++; 15169 if (!j) 15170 continue; 15171 15172 err = verifier_remove_insns(env, i, j); 15173 if (err) 15174 return err; 15175 insn_cnt = env->prog->len; 15176 } 15177 15178 return 0; 15179 } 15180 15181 static int opt_remove_nops(struct bpf_verifier_env *env) 15182 { 15183 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 15184 struct bpf_insn *insn = env->prog->insnsi; 15185 int insn_cnt = env->prog->len; 15186 int i, err; 15187 15188 for (i = 0; i < insn_cnt; i++) { 15189 if (memcmp(&insn[i], &ja, sizeof(ja))) 15190 continue; 15191 15192 err = verifier_remove_insns(env, i, 1); 15193 if (err) 15194 return err; 15195 insn_cnt--; 15196 i--; 15197 } 15198 15199 return 0; 15200 } 15201 15202 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 15203 const union bpf_attr *attr) 15204 { 15205 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 15206 struct bpf_insn_aux_data *aux = env->insn_aux_data; 15207 int i, patch_len, delta = 0, len = env->prog->len; 15208 struct bpf_insn *insns = env->prog->insnsi; 15209 struct bpf_prog *new_prog; 15210 bool rnd_hi32; 15211 15212 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 15213 zext_patch[1] = BPF_ZEXT_REG(0); 15214 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 15215 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 15216 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 15217 for (i = 0; i < len; i++) { 15218 int adj_idx = i + delta; 15219 struct bpf_insn insn; 15220 int load_reg; 15221 15222 insn = insns[adj_idx]; 15223 load_reg = insn_def_regno(&insn); 15224 if (!aux[adj_idx].zext_dst) { 15225 u8 code, class; 15226 u32 imm_rnd; 15227 15228 if (!rnd_hi32) 15229 continue; 15230 15231 code = insn.code; 15232 class = BPF_CLASS(code); 15233 if (load_reg == -1) 15234 continue; 15235 15236 /* NOTE: arg "reg" (the fourth one) is only used for 15237 * BPF_STX + SRC_OP, so it is safe to pass NULL 15238 * here. 15239 */ 15240 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 15241 if (class == BPF_LD && 15242 BPF_MODE(code) == BPF_IMM) 15243 i++; 15244 continue; 15245 } 15246 15247 /* ctx load could be transformed into wider load. */ 15248 if (class == BPF_LDX && 15249 aux[adj_idx].ptr_type == PTR_TO_CTX) 15250 continue; 15251 15252 imm_rnd = get_random_u32(); 15253 rnd_hi32_patch[0] = insn; 15254 rnd_hi32_patch[1].imm = imm_rnd; 15255 rnd_hi32_patch[3].dst_reg = load_reg; 15256 patch = rnd_hi32_patch; 15257 patch_len = 4; 15258 goto apply_patch_buffer; 15259 } 15260 15261 /* Add in an zero-extend instruction if a) the JIT has requested 15262 * it or b) it's a CMPXCHG. 15263 * 15264 * The latter is because: BPF_CMPXCHG always loads a value into 15265 * R0, therefore always zero-extends. However some archs' 15266 * equivalent instruction only does this load when the 15267 * comparison is successful. This detail of CMPXCHG is 15268 * orthogonal to the general zero-extension behaviour of the 15269 * CPU, so it's treated independently of bpf_jit_needs_zext. 15270 */ 15271 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 15272 continue; 15273 15274 /* Zero-extension is done by the caller. */ 15275 if (bpf_pseudo_kfunc_call(&insn)) 15276 continue; 15277 15278 if (WARN_ON(load_reg == -1)) { 15279 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 15280 return -EFAULT; 15281 } 15282 15283 zext_patch[0] = insn; 15284 zext_patch[1].dst_reg = load_reg; 15285 zext_patch[1].src_reg = load_reg; 15286 patch = zext_patch; 15287 patch_len = 2; 15288 apply_patch_buffer: 15289 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 15290 if (!new_prog) 15291 return -ENOMEM; 15292 env->prog = new_prog; 15293 insns = new_prog->insnsi; 15294 aux = env->insn_aux_data; 15295 delta += patch_len - 1; 15296 } 15297 15298 return 0; 15299 } 15300 15301 /* convert load instructions that access fields of a context type into a 15302 * sequence of instructions that access fields of the underlying structure: 15303 * struct __sk_buff -> struct sk_buff 15304 * struct bpf_sock_ops -> struct sock 15305 */ 15306 static int convert_ctx_accesses(struct bpf_verifier_env *env) 15307 { 15308 const struct bpf_verifier_ops *ops = env->ops; 15309 int i, cnt, size, ctx_field_size, delta = 0; 15310 const int insn_cnt = env->prog->len; 15311 struct bpf_insn insn_buf[16], *insn; 15312 u32 target_size, size_default, off; 15313 struct bpf_prog *new_prog; 15314 enum bpf_access_type type; 15315 bool is_narrower_load; 15316 15317 if (ops->gen_prologue || env->seen_direct_write) { 15318 if (!ops->gen_prologue) { 15319 verbose(env, "bpf verifier is misconfigured\n"); 15320 return -EINVAL; 15321 } 15322 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 15323 env->prog); 15324 if (cnt >= ARRAY_SIZE(insn_buf)) { 15325 verbose(env, "bpf verifier is misconfigured\n"); 15326 return -EINVAL; 15327 } else if (cnt) { 15328 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 15329 if (!new_prog) 15330 return -ENOMEM; 15331 15332 env->prog = new_prog; 15333 delta += cnt - 1; 15334 } 15335 } 15336 15337 if (bpf_prog_is_offloaded(env->prog->aux)) 15338 return 0; 15339 15340 insn = env->prog->insnsi + delta; 15341 15342 for (i = 0; i < insn_cnt; i++, insn++) { 15343 bpf_convert_ctx_access_t convert_ctx_access; 15344 bool ctx_access; 15345 15346 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 15347 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 15348 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 15349 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) { 15350 type = BPF_READ; 15351 ctx_access = true; 15352 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 15353 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 15354 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 15355 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 15356 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 15357 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 15358 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 15359 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 15360 type = BPF_WRITE; 15361 ctx_access = BPF_CLASS(insn->code) == BPF_STX; 15362 } else { 15363 continue; 15364 } 15365 15366 if (type == BPF_WRITE && 15367 env->insn_aux_data[i + delta].sanitize_stack_spill) { 15368 struct bpf_insn patch[] = { 15369 *insn, 15370 BPF_ST_NOSPEC(), 15371 }; 15372 15373 cnt = ARRAY_SIZE(patch); 15374 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 15375 if (!new_prog) 15376 return -ENOMEM; 15377 15378 delta += cnt - 1; 15379 env->prog = new_prog; 15380 insn = new_prog->insnsi + i + delta; 15381 continue; 15382 } 15383 15384 if (!ctx_access) 15385 continue; 15386 15387 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 15388 case PTR_TO_CTX: 15389 if (!ops->convert_ctx_access) 15390 continue; 15391 convert_ctx_access = ops->convert_ctx_access; 15392 break; 15393 case PTR_TO_SOCKET: 15394 case PTR_TO_SOCK_COMMON: 15395 convert_ctx_access = bpf_sock_convert_ctx_access; 15396 break; 15397 case PTR_TO_TCP_SOCK: 15398 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 15399 break; 15400 case PTR_TO_XDP_SOCK: 15401 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 15402 break; 15403 case PTR_TO_BTF_ID: 15404 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 15405 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 15406 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 15407 * be said once it is marked PTR_UNTRUSTED, hence we must handle 15408 * any faults for loads into such types. BPF_WRITE is disallowed 15409 * for this case. 15410 */ 15411 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 15412 if (type == BPF_READ) { 15413 insn->code = BPF_LDX | BPF_PROBE_MEM | 15414 BPF_SIZE((insn)->code); 15415 env->prog->aux->num_exentries++; 15416 } 15417 continue; 15418 default: 15419 continue; 15420 } 15421 15422 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 15423 size = BPF_LDST_BYTES(insn); 15424 15425 /* If the read access is a narrower load of the field, 15426 * convert to a 4/8-byte load, to minimum program type specific 15427 * convert_ctx_access changes. If conversion is successful, 15428 * we will apply proper mask to the result. 15429 */ 15430 is_narrower_load = size < ctx_field_size; 15431 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 15432 off = insn->off; 15433 if (is_narrower_load) { 15434 u8 size_code; 15435 15436 if (type == BPF_WRITE) { 15437 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 15438 return -EINVAL; 15439 } 15440 15441 size_code = BPF_H; 15442 if (ctx_field_size == 4) 15443 size_code = BPF_W; 15444 else if (ctx_field_size == 8) 15445 size_code = BPF_DW; 15446 15447 insn->off = off & ~(size_default - 1); 15448 insn->code = BPF_LDX | BPF_MEM | size_code; 15449 } 15450 15451 target_size = 0; 15452 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 15453 &target_size); 15454 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 15455 (ctx_field_size && !target_size)) { 15456 verbose(env, "bpf verifier is misconfigured\n"); 15457 return -EINVAL; 15458 } 15459 15460 if (is_narrower_load && size < target_size) { 15461 u8 shift = bpf_ctx_narrow_access_offset( 15462 off, size, size_default) * 8; 15463 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 15464 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 15465 return -EINVAL; 15466 } 15467 if (ctx_field_size <= 4) { 15468 if (shift) 15469 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 15470 insn->dst_reg, 15471 shift); 15472 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 15473 (1 << size * 8) - 1); 15474 } else { 15475 if (shift) 15476 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 15477 insn->dst_reg, 15478 shift); 15479 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 15480 (1ULL << size * 8) - 1); 15481 } 15482 } 15483 15484 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15485 if (!new_prog) 15486 return -ENOMEM; 15487 15488 delta += cnt - 1; 15489 15490 /* keep walking new program and skip insns we just inserted */ 15491 env->prog = new_prog; 15492 insn = new_prog->insnsi + i + delta; 15493 } 15494 15495 return 0; 15496 } 15497 15498 static int jit_subprogs(struct bpf_verifier_env *env) 15499 { 15500 struct bpf_prog *prog = env->prog, **func, *tmp; 15501 int i, j, subprog_start, subprog_end = 0, len, subprog; 15502 struct bpf_map *map_ptr; 15503 struct bpf_insn *insn; 15504 void *old_bpf_func; 15505 int err, num_exentries; 15506 15507 if (env->subprog_cnt <= 1) 15508 return 0; 15509 15510 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 15511 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 15512 continue; 15513 15514 /* Upon error here we cannot fall back to interpreter but 15515 * need a hard reject of the program. Thus -EFAULT is 15516 * propagated in any case. 15517 */ 15518 subprog = find_subprog(env, i + insn->imm + 1); 15519 if (subprog < 0) { 15520 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 15521 i + insn->imm + 1); 15522 return -EFAULT; 15523 } 15524 /* temporarily remember subprog id inside insn instead of 15525 * aux_data, since next loop will split up all insns into funcs 15526 */ 15527 insn->off = subprog; 15528 /* remember original imm in case JIT fails and fallback 15529 * to interpreter will be needed 15530 */ 15531 env->insn_aux_data[i].call_imm = insn->imm; 15532 /* point imm to __bpf_call_base+1 from JITs point of view */ 15533 insn->imm = 1; 15534 if (bpf_pseudo_func(insn)) 15535 /* jit (e.g. x86_64) may emit fewer instructions 15536 * if it learns a u32 imm is the same as a u64 imm. 15537 * Force a non zero here. 15538 */ 15539 insn[1].imm = 1; 15540 } 15541 15542 err = bpf_prog_alloc_jited_linfo(prog); 15543 if (err) 15544 goto out_undo_insn; 15545 15546 err = -ENOMEM; 15547 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 15548 if (!func) 15549 goto out_undo_insn; 15550 15551 for (i = 0; i < env->subprog_cnt; i++) { 15552 subprog_start = subprog_end; 15553 subprog_end = env->subprog_info[i + 1].start; 15554 15555 len = subprog_end - subprog_start; 15556 /* bpf_prog_run() doesn't call subprogs directly, 15557 * hence main prog stats include the runtime of subprogs. 15558 * subprogs don't have IDs and not reachable via prog_get_next_id 15559 * func[i]->stats will never be accessed and stays NULL 15560 */ 15561 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 15562 if (!func[i]) 15563 goto out_free; 15564 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 15565 len * sizeof(struct bpf_insn)); 15566 func[i]->type = prog->type; 15567 func[i]->len = len; 15568 if (bpf_prog_calc_tag(func[i])) 15569 goto out_free; 15570 func[i]->is_func = 1; 15571 func[i]->aux->func_idx = i; 15572 /* Below members will be freed only at prog->aux */ 15573 func[i]->aux->btf = prog->aux->btf; 15574 func[i]->aux->func_info = prog->aux->func_info; 15575 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 15576 func[i]->aux->poke_tab = prog->aux->poke_tab; 15577 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 15578 15579 for (j = 0; j < prog->aux->size_poke_tab; j++) { 15580 struct bpf_jit_poke_descriptor *poke; 15581 15582 poke = &prog->aux->poke_tab[j]; 15583 if (poke->insn_idx < subprog_end && 15584 poke->insn_idx >= subprog_start) 15585 poke->aux = func[i]->aux; 15586 } 15587 15588 func[i]->aux->name[0] = 'F'; 15589 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 15590 func[i]->jit_requested = 1; 15591 func[i]->blinding_requested = prog->blinding_requested; 15592 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 15593 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 15594 func[i]->aux->linfo = prog->aux->linfo; 15595 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 15596 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 15597 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 15598 num_exentries = 0; 15599 insn = func[i]->insnsi; 15600 for (j = 0; j < func[i]->len; j++, insn++) { 15601 if (BPF_CLASS(insn->code) == BPF_LDX && 15602 BPF_MODE(insn->code) == BPF_PROBE_MEM) 15603 num_exentries++; 15604 } 15605 func[i]->aux->num_exentries = num_exentries; 15606 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 15607 func[i] = bpf_int_jit_compile(func[i]); 15608 if (!func[i]->jited) { 15609 err = -ENOTSUPP; 15610 goto out_free; 15611 } 15612 cond_resched(); 15613 } 15614 15615 /* at this point all bpf functions were successfully JITed 15616 * now populate all bpf_calls with correct addresses and 15617 * run last pass of JIT 15618 */ 15619 for (i = 0; i < env->subprog_cnt; i++) { 15620 insn = func[i]->insnsi; 15621 for (j = 0; j < func[i]->len; j++, insn++) { 15622 if (bpf_pseudo_func(insn)) { 15623 subprog = insn->off; 15624 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 15625 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 15626 continue; 15627 } 15628 if (!bpf_pseudo_call(insn)) 15629 continue; 15630 subprog = insn->off; 15631 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 15632 } 15633 15634 /* we use the aux data to keep a list of the start addresses 15635 * of the JITed images for each function in the program 15636 * 15637 * for some architectures, such as powerpc64, the imm field 15638 * might not be large enough to hold the offset of the start 15639 * address of the callee's JITed image from __bpf_call_base 15640 * 15641 * in such cases, we can lookup the start address of a callee 15642 * by using its subprog id, available from the off field of 15643 * the call instruction, as an index for this list 15644 */ 15645 func[i]->aux->func = func; 15646 func[i]->aux->func_cnt = env->subprog_cnt; 15647 } 15648 for (i = 0; i < env->subprog_cnt; i++) { 15649 old_bpf_func = func[i]->bpf_func; 15650 tmp = bpf_int_jit_compile(func[i]); 15651 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 15652 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 15653 err = -ENOTSUPP; 15654 goto out_free; 15655 } 15656 cond_resched(); 15657 } 15658 15659 /* finally lock prog and jit images for all functions and 15660 * populate kallsysm 15661 */ 15662 for (i = 0; i < env->subprog_cnt; i++) { 15663 bpf_prog_lock_ro(func[i]); 15664 bpf_prog_kallsyms_add(func[i]); 15665 } 15666 15667 /* Last step: make now unused interpreter insns from main 15668 * prog consistent for later dump requests, so they can 15669 * later look the same as if they were interpreted only. 15670 */ 15671 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 15672 if (bpf_pseudo_func(insn)) { 15673 insn[0].imm = env->insn_aux_data[i].call_imm; 15674 insn[1].imm = insn->off; 15675 insn->off = 0; 15676 continue; 15677 } 15678 if (!bpf_pseudo_call(insn)) 15679 continue; 15680 insn->off = env->insn_aux_data[i].call_imm; 15681 subprog = find_subprog(env, i + insn->off + 1); 15682 insn->imm = subprog; 15683 } 15684 15685 prog->jited = 1; 15686 prog->bpf_func = func[0]->bpf_func; 15687 prog->jited_len = func[0]->jited_len; 15688 prog->aux->func = func; 15689 prog->aux->func_cnt = env->subprog_cnt; 15690 bpf_prog_jit_attempt_done(prog); 15691 return 0; 15692 out_free: 15693 /* We failed JIT'ing, so at this point we need to unregister poke 15694 * descriptors from subprogs, so that kernel is not attempting to 15695 * patch it anymore as we're freeing the subprog JIT memory. 15696 */ 15697 for (i = 0; i < prog->aux->size_poke_tab; i++) { 15698 map_ptr = prog->aux->poke_tab[i].tail_call.map; 15699 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 15700 } 15701 /* At this point we're guaranteed that poke descriptors are not 15702 * live anymore. We can just unlink its descriptor table as it's 15703 * released with the main prog. 15704 */ 15705 for (i = 0; i < env->subprog_cnt; i++) { 15706 if (!func[i]) 15707 continue; 15708 func[i]->aux->poke_tab = NULL; 15709 bpf_jit_free(func[i]); 15710 } 15711 kfree(func); 15712 out_undo_insn: 15713 /* cleanup main prog to be interpreted */ 15714 prog->jit_requested = 0; 15715 prog->blinding_requested = 0; 15716 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 15717 if (!bpf_pseudo_call(insn)) 15718 continue; 15719 insn->off = 0; 15720 insn->imm = env->insn_aux_data[i].call_imm; 15721 } 15722 bpf_prog_jit_attempt_done(prog); 15723 return err; 15724 } 15725 15726 static int fixup_call_args(struct bpf_verifier_env *env) 15727 { 15728 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 15729 struct bpf_prog *prog = env->prog; 15730 struct bpf_insn *insn = prog->insnsi; 15731 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 15732 int i, depth; 15733 #endif 15734 int err = 0; 15735 15736 if (env->prog->jit_requested && 15737 !bpf_prog_is_offloaded(env->prog->aux)) { 15738 err = jit_subprogs(env); 15739 if (err == 0) 15740 return 0; 15741 if (err == -EFAULT) 15742 return err; 15743 } 15744 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 15745 if (has_kfunc_call) { 15746 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 15747 return -EINVAL; 15748 } 15749 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 15750 /* When JIT fails the progs with bpf2bpf calls and tail_calls 15751 * have to be rejected, since interpreter doesn't support them yet. 15752 */ 15753 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 15754 return -EINVAL; 15755 } 15756 for (i = 0; i < prog->len; i++, insn++) { 15757 if (bpf_pseudo_func(insn)) { 15758 /* When JIT fails the progs with callback calls 15759 * have to be rejected, since interpreter doesn't support them yet. 15760 */ 15761 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 15762 return -EINVAL; 15763 } 15764 15765 if (!bpf_pseudo_call(insn)) 15766 continue; 15767 depth = get_callee_stack_depth(env, insn, i); 15768 if (depth < 0) 15769 return depth; 15770 bpf_patch_call_args(insn, depth); 15771 } 15772 err = 0; 15773 #endif 15774 return err; 15775 } 15776 15777 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 15778 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 15779 { 15780 const struct bpf_kfunc_desc *desc; 15781 void *xdp_kfunc; 15782 15783 if (!insn->imm) { 15784 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 15785 return -EINVAL; 15786 } 15787 15788 *cnt = 0; 15789 15790 if (bpf_dev_bound_kfunc_id(insn->imm)) { 15791 xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm); 15792 if (xdp_kfunc) { 15793 insn->imm = BPF_CALL_IMM(xdp_kfunc); 15794 return 0; 15795 } 15796 15797 /* fallback to default kfunc when not supported by netdev */ 15798 } 15799 15800 /* insn->imm has the btf func_id. Replace it with 15801 * an address (relative to __bpf_call_base). 15802 */ 15803 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 15804 if (!desc) { 15805 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 15806 insn->imm); 15807 return -EFAULT; 15808 } 15809 15810 insn->imm = desc->imm; 15811 if (insn->off) 15812 return 0; 15813 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 15814 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 15815 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 15816 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 15817 15818 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 15819 insn_buf[1] = addr[0]; 15820 insn_buf[2] = addr[1]; 15821 insn_buf[3] = *insn; 15822 *cnt = 4; 15823 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 15824 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 15825 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 15826 15827 insn_buf[0] = addr[0]; 15828 insn_buf[1] = addr[1]; 15829 insn_buf[2] = *insn; 15830 *cnt = 3; 15831 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 15832 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 15833 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 15834 *cnt = 1; 15835 } 15836 return 0; 15837 } 15838 15839 /* Do various post-verification rewrites in a single program pass. 15840 * These rewrites simplify JIT and interpreter implementations. 15841 */ 15842 static int do_misc_fixups(struct bpf_verifier_env *env) 15843 { 15844 struct bpf_prog *prog = env->prog; 15845 enum bpf_attach_type eatype = prog->expected_attach_type; 15846 enum bpf_prog_type prog_type = resolve_prog_type(prog); 15847 struct bpf_insn *insn = prog->insnsi; 15848 const struct bpf_func_proto *fn; 15849 const int insn_cnt = prog->len; 15850 const struct bpf_map_ops *ops; 15851 struct bpf_insn_aux_data *aux; 15852 struct bpf_insn insn_buf[16]; 15853 struct bpf_prog *new_prog; 15854 struct bpf_map *map_ptr; 15855 int i, ret, cnt, delta = 0; 15856 15857 for (i = 0; i < insn_cnt; i++, insn++) { 15858 /* Make divide-by-zero exceptions impossible. */ 15859 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 15860 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 15861 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 15862 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 15863 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 15864 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 15865 struct bpf_insn *patchlet; 15866 struct bpf_insn chk_and_div[] = { 15867 /* [R,W]x div 0 -> 0 */ 15868 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 15869 BPF_JNE | BPF_K, insn->src_reg, 15870 0, 2, 0), 15871 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 15872 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 15873 *insn, 15874 }; 15875 struct bpf_insn chk_and_mod[] = { 15876 /* [R,W]x mod 0 -> [R,W]x */ 15877 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 15878 BPF_JEQ | BPF_K, insn->src_reg, 15879 0, 1 + (is64 ? 0 : 1), 0), 15880 *insn, 15881 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 15882 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 15883 }; 15884 15885 patchlet = isdiv ? chk_and_div : chk_and_mod; 15886 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 15887 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 15888 15889 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 15890 if (!new_prog) 15891 return -ENOMEM; 15892 15893 delta += cnt - 1; 15894 env->prog = prog = new_prog; 15895 insn = new_prog->insnsi + i + delta; 15896 continue; 15897 } 15898 15899 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 15900 if (BPF_CLASS(insn->code) == BPF_LD && 15901 (BPF_MODE(insn->code) == BPF_ABS || 15902 BPF_MODE(insn->code) == BPF_IND)) { 15903 cnt = env->ops->gen_ld_abs(insn, insn_buf); 15904 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 15905 verbose(env, "bpf verifier is misconfigured\n"); 15906 return -EINVAL; 15907 } 15908 15909 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15910 if (!new_prog) 15911 return -ENOMEM; 15912 15913 delta += cnt - 1; 15914 env->prog = prog = new_prog; 15915 insn = new_prog->insnsi + i + delta; 15916 continue; 15917 } 15918 15919 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 15920 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 15921 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 15922 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 15923 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 15924 struct bpf_insn *patch = &insn_buf[0]; 15925 bool issrc, isneg, isimm; 15926 u32 off_reg; 15927 15928 aux = &env->insn_aux_data[i + delta]; 15929 if (!aux->alu_state || 15930 aux->alu_state == BPF_ALU_NON_POINTER) 15931 continue; 15932 15933 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 15934 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 15935 BPF_ALU_SANITIZE_SRC; 15936 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 15937 15938 off_reg = issrc ? insn->src_reg : insn->dst_reg; 15939 if (isimm) { 15940 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 15941 } else { 15942 if (isneg) 15943 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 15944 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 15945 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 15946 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 15947 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 15948 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 15949 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 15950 } 15951 if (!issrc) 15952 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 15953 insn->src_reg = BPF_REG_AX; 15954 if (isneg) 15955 insn->code = insn->code == code_add ? 15956 code_sub : code_add; 15957 *patch++ = *insn; 15958 if (issrc && isneg && !isimm) 15959 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 15960 cnt = patch - insn_buf; 15961 15962 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15963 if (!new_prog) 15964 return -ENOMEM; 15965 15966 delta += cnt - 1; 15967 env->prog = prog = new_prog; 15968 insn = new_prog->insnsi + i + delta; 15969 continue; 15970 } 15971 15972 if (insn->code != (BPF_JMP | BPF_CALL)) 15973 continue; 15974 if (insn->src_reg == BPF_PSEUDO_CALL) 15975 continue; 15976 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 15977 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 15978 if (ret) 15979 return ret; 15980 if (cnt == 0) 15981 continue; 15982 15983 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15984 if (!new_prog) 15985 return -ENOMEM; 15986 15987 delta += cnt - 1; 15988 env->prog = prog = new_prog; 15989 insn = new_prog->insnsi + i + delta; 15990 continue; 15991 } 15992 15993 if (insn->imm == BPF_FUNC_get_route_realm) 15994 prog->dst_needed = 1; 15995 if (insn->imm == BPF_FUNC_get_prandom_u32) 15996 bpf_user_rnd_init_once(); 15997 if (insn->imm == BPF_FUNC_override_return) 15998 prog->kprobe_override = 1; 15999 if (insn->imm == BPF_FUNC_tail_call) { 16000 /* If we tail call into other programs, we 16001 * cannot make any assumptions since they can 16002 * be replaced dynamically during runtime in 16003 * the program array. 16004 */ 16005 prog->cb_access = 1; 16006 if (!allow_tail_call_in_subprogs(env)) 16007 prog->aux->stack_depth = MAX_BPF_STACK; 16008 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 16009 16010 /* mark bpf_tail_call as different opcode to avoid 16011 * conditional branch in the interpreter for every normal 16012 * call and to prevent accidental JITing by JIT compiler 16013 * that doesn't support bpf_tail_call yet 16014 */ 16015 insn->imm = 0; 16016 insn->code = BPF_JMP | BPF_TAIL_CALL; 16017 16018 aux = &env->insn_aux_data[i + delta]; 16019 if (env->bpf_capable && !prog->blinding_requested && 16020 prog->jit_requested && 16021 !bpf_map_key_poisoned(aux) && 16022 !bpf_map_ptr_poisoned(aux) && 16023 !bpf_map_ptr_unpriv(aux)) { 16024 struct bpf_jit_poke_descriptor desc = { 16025 .reason = BPF_POKE_REASON_TAIL_CALL, 16026 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 16027 .tail_call.key = bpf_map_key_immediate(aux), 16028 .insn_idx = i + delta, 16029 }; 16030 16031 ret = bpf_jit_add_poke_descriptor(prog, &desc); 16032 if (ret < 0) { 16033 verbose(env, "adding tail call poke descriptor failed\n"); 16034 return ret; 16035 } 16036 16037 insn->imm = ret + 1; 16038 continue; 16039 } 16040 16041 if (!bpf_map_ptr_unpriv(aux)) 16042 continue; 16043 16044 /* instead of changing every JIT dealing with tail_call 16045 * emit two extra insns: 16046 * if (index >= max_entries) goto out; 16047 * index &= array->index_mask; 16048 * to avoid out-of-bounds cpu speculation 16049 */ 16050 if (bpf_map_ptr_poisoned(aux)) { 16051 verbose(env, "tail_call abusing map_ptr\n"); 16052 return -EINVAL; 16053 } 16054 16055 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 16056 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 16057 map_ptr->max_entries, 2); 16058 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 16059 container_of(map_ptr, 16060 struct bpf_array, 16061 map)->index_mask); 16062 insn_buf[2] = *insn; 16063 cnt = 3; 16064 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16065 if (!new_prog) 16066 return -ENOMEM; 16067 16068 delta += cnt - 1; 16069 env->prog = prog = new_prog; 16070 insn = new_prog->insnsi + i + delta; 16071 continue; 16072 } 16073 16074 if (insn->imm == BPF_FUNC_timer_set_callback) { 16075 /* The verifier will process callback_fn as many times as necessary 16076 * with different maps and the register states prepared by 16077 * set_timer_callback_state will be accurate. 16078 * 16079 * The following use case is valid: 16080 * map1 is shared by prog1, prog2, prog3. 16081 * prog1 calls bpf_timer_init for some map1 elements 16082 * prog2 calls bpf_timer_set_callback for some map1 elements. 16083 * Those that were not bpf_timer_init-ed will return -EINVAL. 16084 * prog3 calls bpf_timer_start for some map1 elements. 16085 * Those that were not both bpf_timer_init-ed and 16086 * bpf_timer_set_callback-ed will return -EINVAL. 16087 */ 16088 struct bpf_insn ld_addrs[2] = { 16089 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 16090 }; 16091 16092 insn_buf[0] = ld_addrs[0]; 16093 insn_buf[1] = ld_addrs[1]; 16094 insn_buf[2] = *insn; 16095 cnt = 3; 16096 16097 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16098 if (!new_prog) 16099 return -ENOMEM; 16100 16101 delta += cnt - 1; 16102 env->prog = prog = new_prog; 16103 insn = new_prog->insnsi + i + delta; 16104 goto patch_call_imm; 16105 } 16106 16107 if (is_storage_get_function(insn->imm)) { 16108 if (!env->prog->aux->sleepable || 16109 env->insn_aux_data[i + delta].storage_get_func_atomic) 16110 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 16111 else 16112 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 16113 insn_buf[1] = *insn; 16114 cnt = 2; 16115 16116 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16117 if (!new_prog) 16118 return -ENOMEM; 16119 16120 delta += cnt - 1; 16121 env->prog = prog = new_prog; 16122 insn = new_prog->insnsi + i + delta; 16123 goto patch_call_imm; 16124 } 16125 16126 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 16127 * and other inlining handlers are currently limited to 64 bit 16128 * only. 16129 */ 16130 if (prog->jit_requested && BITS_PER_LONG == 64 && 16131 (insn->imm == BPF_FUNC_map_lookup_elem || 16132 insn->imm == BPF_FUNC_map_update_elem || 16133 insn->imm == BPF_FUNC_map_delete_elem || 16134 insn->imm == BPF_FUNC_map_push_elem || 16135 insn->imm == BPF_FUNC_map_pop_elem || 16136 insn->imm == BPF_FUNC_map_peek_elem || 16137 insn->imm == BPF_FUNC_redirect_map || 16138 insn->imm == BPF_FUNC_for_each_map_elem || 16139 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 16140 aux = &env->insn_aux_data[i + delta]; 16141 if (bpf_map_ptr_poisoned(aux)) 16142 goto patch_call_imm; 16143 16144 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 16145 ops = map_ptr->ops; 16146 if (insn->imm == BPF_FUNC_map_lookup_elem && 16147 ops->map_gen_lookup) { 16148 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 16149 if (cnt == -EOPNOTSUPP) 16150 goto patch_map_ops_generic; 16151 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 16152 verbose(env, "bpf verifier is misconfigured\n"); 16153 return -EINVAL; 16154 } 16155 16156 new_prog = bpf_patch_insn_data(env, i + delta, 16157 insn_buf, cnt); 16158 if (!new_prog) 16159 return -ENOMEM; 16160 16161 delta += cnt - 1; 16162 env->prog = prog = new_prog; 16163 insn = new_prog->insnsi + i + delta; 16164 continue; 16165 } 16166 16167 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 16168 (void *(*)(struct bpf_map *map, void *key))NULL)); 16169 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 16170 (int (*)(struct bpf_map *map, void *key))NULL)); 16171 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 16172 (int (*)(struct bpf_map *map, void *key, void *value, 16173 u64 flags))NULL)); 16174 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 16175 (int (*)(struct bpf_map *map, void *value, 16176 u64 flags))NULL)); 16177 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 16178 (int (*)(struct bpf_map *map, void *value))NULL)); 16179 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 16180 (int (*)(struct bpf_map *map, void *value))NULL)); 16181 BUILD_BUG_ON(!__same_type(ops->map_redirect, 16182 (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 16183 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 16184 (int (*)(struct bpf_map *map, 16185 bpf_callback_t callback_fn, 16186 void *callback_ctx, 16187 u64 flags))NULL)); 16188 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 16189 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 16190 16191 patch_map_ops_generic: 16192 switch (insn->imm) { 16193 case BPF_FUNC_map_lookup_elem: 16194 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 16195 continue; 16196 case BPF_FUNC_map_update_elem: 16197 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 16198 continue; 16199 case BPF_FUNC_map_delete_elem: 16200 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 16201 continue; 16202 case BPF_FUNC_map_push_elem: 16203 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 16204 continue; 16205 case BPF_FUNC_map_pop_elem: 16206 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 16207 continue; 16208 case BPF_FUNC_map_peek_elem: 16209 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 16210 continue; 16211 case BPF_FUNC_redirect_map: 16212 insn->imm = BPF_CALL_IMM(ops->map_redirect); 16213 continue; 16214 case BPF_FUNC_for_each_map_elem: 16215 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 16216 continue; 16217 case BPF_FUNC_map_lookup_percpu_elem: 16218 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 16219 continue; 16220 } 16221 16222 goto patch_call_imm; 16223 } 16224 16225 /* Implement bpf_jiffies64 inline. */ 16226 if (prog->jit_requested && BITS_PER_LONG == 64 && 16227 insn->imm == BPF_FUNC_jiffies64) { 16228 struct bpf_insn ld_jiffies_addr[2] = { 16229 BPF_LD_IMM64(BPF_REG_0, 16230 (unsigned long)&jiffies), 16231 }; 16232 16233 insn_buf[0] = ld_jiffies_addr[0]; 16234 insn_buf[1] = ld_jiffies_addr[1]; 16235 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 16236 BPF_REG_0, 0); 16237 cnt = 3; 16238 16239 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 16240 cnt); 16241 if (!new_prog) 16242 return -ENOMEM; 16243 16244 delta += cnt - 1; 16245 env->prog = prog = new_prog; 16246 insn = new_prog->insnsi + i + delta; 16247 continue; 16248 } 16249 16250 /* Implement bpf_get_func_arg inline. */ 16251 if (prog_type == BPF_PROG_TYPE_TRACING && 16252 insn->imm == BPF_FUNC_get_func_arg) { 16253 /* Load nr_args from ctx - 8 */ 16254 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 16255 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 16256 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 16257 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 16258 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 16259 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 16260 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 16261 insn_buf[7] = BPF_JMP_A(1); 16262 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 16263 cnt = 9; 16264 16265 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16266 if (!new_prog) 16267 return -ENOMEM; 16268 16269 delta += cnt - 1; 16270 env->prog = prog = new_prog; 16271 insn = new_prog->insnsi + i + delta; 16272 continue; 16273 } 16274 16275 /* Implement bpf_get_func_ret inline. */ 16276 if (prog_type == BPF_PROG_TYPE_TRACING && 16277 insn->imm == BPF_FUNC_get_func_ret) { 16278 if (eatype == BPF_TRACE_FEXIT || 16279 eatype == BPF_MODIFY_RETURN) { 16280 /* Load nr_args from ctx - 8 */ 16281 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 16282 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 16283 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 16284 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 16285 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 16286 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 16287 cnt = 6; 16288 } else { 16289 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 16290 cnt = 1; 16291 } 16292 16293 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16294 if (!new_prog) 16295 return -ENOMEM; 16296 16297 delta += cnt - 1; 16298 env->prog = prog = new_prog; 16299 insn = new_prog->insnsi + i + delta; 16300 continue; 16301 } 16302 16303 /* Implement get_func_arg_cnt inline. */ 16304 if (prog_type == BPF_PROG_TYPE_TRACING && 16305 insn->imm == BPF_FUNC_get_func_arg_cnt) { 16306 /* Load nr_args from ctx - 8 */ 16307 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 16308 16309 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 16310 if (!new_prog) 16311 return -ENOMEM; 16312 16313 env->prog = prog = new_prog; 16314 insn = new_prog->insnsi + i + delta; 16315 continue; 16316 } 16317 16318 /* Implement bpf_get_func_ip inline. */ 16319 if (prog_type == BPF_PROG_TYPE_TRACING && 16320 insn->imm == BPF_FUNC_get_func_ip) { 16321 /* Load IP address from ctx - 16 */ 16322 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 16323 16324 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 16325 if (!new_prog) 16326 return -ENOMEM; 16327 16328 env->prog = prog = new_prog; 16329 insn = new_prog->insnsi + i + delta; 16330 continue; 16331 } 16332 16333 patch_call_imm: 16334 fn = env->ops->get_func_proto(insn->imm, env->prog); 16335 /* all functions that have prototype and verifier allowed 16336 * programs to call them, must be real in-kernel functions 16337 */ 16338 if (!fn->func) { 16339 verbose(env, 16340 "kernel subsystem misconfigured func %s#%d\n", 16341 func_id_name(insn->imm), insn->imm); 16342 return -EFAULT; 16343 } 16344 insn->imm = fn->func - __bpf_call_base; 16345 } 16346 16347 /* Since poke tab is now finalized, publish aux to tracker. */ 16348 for (i = 0; i < prog->aux->size_poke_tab; i++) { 16349 map_ptr = prog->aux->poke_tab[i].tail_call.map; 16350 if (!map_ptr->ops->map_poke_track || 16351 !map_ptr->ops->map_poke_untrack || 16352 !map_ptr->ops->map_poke_run) { 16353 verbose(env, "bpf verifier is misconfigured\n"); 16354 return -EINVAL; 16355 } 16356 16357 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 16358 if (ret < 0) { 16359 verbose(env, "tracking tail call prog failed\n"); 16360 return ret; 16361 } 16362 } 16363 16364 sort_kfunc_descs_by_imm(env->prog); 16365 16366 return 0; 16367 } 16368 16369 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 16370 int position, 16371 s32 stack_base, 16372 u32 callback_subprogno, 16373 u32 *cnt) 16374 { 16375 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 16376 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 16377 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 16378 int reg_loop_max = BPF_REG_6; 16379 int reg_loop_cnt = BPF_REG_7; 16380 int reg_loop_ctx = BPF_REG_8; 16381 16382 struct bpf_prog *new_prog; 16383 u32 callback_start; 16384 u32 call_insn_offset; 16385 s32 callback_offset; 16386 16387 /* This represents an inlined version of bpf_iter.c:bpf_loop, 16388 * be careful to modify this code in sync. 16389 */ 16390 struct bpf_insn insn_buf[] = { 16391 /* Return error and jump to the end of the patch if 16392 * expected number of iterations is too big. 16393 */ 16394 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 16395 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 16396 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 16397 /* spill R6, R7, R8 to use these as loop vars */ 16398 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 16399 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 16400 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 16401 /* initialize loop vars */ 16402 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 16403 BPF_MOV32_IMM(reg_loop_cnt, 0), 16404 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 16405 /* loop header, 16406 * if reg_loop_cnt >= reg_loop_max skip the loop body 16407 */ 16408 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 16409 /* callback call, 16410 * correct callback offset would be set after patching 16411 */ 16412 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 16413 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 16414 BPF_CALL_REL(0), 16415 /* increment loop counter */ 16416 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 16417 /* jump to loop header if callback returned 0 */ 16418 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 16419 /* return value of bpf_loop, 16420 * set R0 to the number of iterations 16421 */ 16422 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 16423 /* restore original values of R6, R7, R8 */ 16424 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 16425 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 16426 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 16427 }; 16428 16429 *cnt = ARRAY_SIZE(insn_buf); 16430 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 16431 if (!new_prog) 16432 return new_prog; 16433 16434 /* callback start is known only after patching */ 16435 callback_start = env->subprog_info[callback_subprogno].start; 16436 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 16437 call_insn_offset = position + 12; 16438 callback_offset = callback_start - call_insn_offset - 1; 16439 new_prog->insnsi[call_insn_offset].imm = callback_offset; 16440 16441 return new_prog; 16442 } 16443 16444 static bool is_bpf_loop_call(struct bpf_insn *insn) 16445 { 16446 return insn->code == (BPF_JMP | BPF_CALL) && 16447 insn->src_reg == 0 && 16448 insn->imm == BPF_FUNC_loop; 16449 } 16450 16451 /* For all sub-programs in the program (including main) check 16452 * insn_aux_data to see if there are bpf_loop calls that require 16453 * inlining. If such calls are found the calls are replaced with a 16454 * sequence of instructions produced by `inline_bpf_loop` function and 16455 * subprog stack_depth is increased by the size of 3 registers. 16456 * This stack space is used to spill values of the R6, R7, R8. These 16457 * registers are used to store the loop bound, counter and context 16458 * variables. 16459 */ 16460 static int optimize_bpf_loop(struct bpf_verifier_env *env) 16461 { 16462 struct bpf_subprog_info *subprogs = env->subprog_info; 16463 int i, cur_subprog = 0, cnt, delta = 0; 16464 struct bpf_insn *insn = env->prog->insnsi; 16465 int insn_cnt = env->prog->len; 16466 u16 stack_depth = subprogs[cur_subprog].stack_depth; 16467 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 16468 u16 stack_depth_extra = 0; 16469 16470 for (i = 0; i < insn_cnt; i++, insn++) { 16471 struct bpf_loop_inline_state *inline_state = 16472 &env->insn_aux_data[i + delta].loop_inline_state; 16473 16474 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 16475 struct bpf_prog *new_prog; 16476 16477 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 16478 new_prog = inline_bpf_loop(env, 16479 i + delta, 16480 -(stack_depth + stack_depth_extra), 16481 inline_state->callback_subprogno, 16482 &cnt); 16483 if (!new_prog) 16484 return -ENOMEM; 16485 16486 delta += cnt - 1; 16487 env->prog = new_prog; 16488 insn = new_prog->insnsi + i + delta; 16489 } 16490 16491 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 16492 subprogs[cur_subprog].stack_depth += stack_depth_extra; 16493 cur_subprog++; 16494 stack_depth = subprogs[cur_subprog].stack_depth; 16495 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 16496 stack_depth_extra = 0; 16497 } 16498 } 16499 16500 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 16501 16502 return 0; 16503 } 16504 16505 static void free_states(struct bpf_verifier_env *env) 16506 { 16507 struct bpf_verifier_state_list *sl, *sln; 16508 int i; 16509 16510 sl = env->free_list; 16511 while (sl) { 16512 sln = sl->next; 16513 free_verifier_state(&sl->state, false); 16514 kfree(sl); 16515 sl = sln; 16516 } 16517 env->free_list = NULL; 16518 16519 if (!env->explored_states) 16520 return; 16521 16522 for (i = 0; i < state_htab_size(env); i++) { 16523 sl = env->explored_states[i]; 16524 16525 while (sl) { 16526 sln = sl->next; 16527 free_verifier_state(&sl->state, false); 16528 kfree(sl); 16529 sl = sln; 16530 } 16531 env->explored_states[i] = NULL; 16532 } 16533 } 16534 16535 static int do_check_common(struct bpf_verifier_env *env, int subprog) 16536 { 16537 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 16538 struct bpf_verifier_state *state; 16539 struct bpf_reg_state *regs; 16540 int ret, i; 16541 16542 env->prev_linfo = NULL; 16543 env->pass_cnt++; 16544 16545 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 16546 if (!state) 16547 return -ENOMEM; 16548 state->curframe = 0; 16549 state->speculative = false; 16550 state->branches = 1; 16551 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 16552 if (!state->frame[0]) { 16553 kfree(state); 16554 return -ENOMEM; 16555 } 16556 env->cur_state = state; 16557 init_func_state(env, state->frame[0], 16558 BPF_MAIN_FUNC /* callsite */, 16559 0 /* frameno */, 16560 subprog); 16561 state->first_insn_idx = env->subprog_info[subprog].start; 16562 state->last_insn_idx = -1; 16563 16564 regs = state->frame[state->curframe]->regs; 16565 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 16566 ret = btf_prepare_func_args(env, subprog, regs); 16567 if (ret) 16568 goto out; 16569 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 16570 if (regs[i].type == PTR_TO_CTX) 16571 mark_reg_known_zero(env, regs, i); 16572 else if (regs[i].type == SCALAR_VALUE) 16573 mark_reg_unknown(env, regs, i); 16574 else if (base_type(regs[i].type) == PTR_TO_MEM) { 16575 const u32 mem_size = regs[i].mem_size; 16576 16577 mark_reg_known_zero(env, regs, i); 16578 regs[i].mem_size = mem_size; 16579 regs[i].id = ++env->id_gen; 16580 } 16581 } 16582 } else { 16583 /* 1st arg to a function */ 16584 regs[BPF_REG_1].type = PTR_TO_CTX; 16585 mark_reg_known_zero(env, regs, BPF_REG_1); 16586 ret = btf_check_subprog_arg_match(env, subprog, regs); 16587 if (ret == -EFAULT) 16588 /* unlikely verifier bug. abort. 16589 * ret == 0 and ret < 0 are sadly acceptable for 16590 * main() function due to backward compatibility. 16591 * Like socket filter program may be written as: 16592 * int bpf_prog(struct pt_regs *ctx) 16593 * and never dereference that ctx in the program. 16594 * 'struct pt_regs' is a type mismatch for socket 16595 * filter that should be using 'struct __sk_buff'. 16596 */ 16597 goto out; 16598 } 16599 16600 ret = do_check(env); 16601 out: 16602 /* check for NULL is necessary, since cur_state can be freed inside 16603 * do_check() under memory pressure. 16604 */ 16605 if (env->cur_state) { 16606 free_verifier_state(env->cur_state, true); 16607 env->cur_state = NULL; 16608 } 16609 while (!pop_stack(env, NULL, NULL, false)); 16610 if (!ret && pop_log) 16611 bpf_vlog_reset(&env->log, 0); 16612 free_states(env); 16613 return ret; 16614 } 16615 16616 /* Verify all global functions in a BPF program one by one based on their BTF. 16617 * All global functions must pass verification. Otherwise the whole program is rejected. 16618 * Consider: 16619 * int bar(int); 16620 * int foo(int f) 16621 * { 16622 * return bar(f); 16623 * } 16624 * int bar(int b) 16625 * { 16626 * ... 16627 * } 16628 * foo() will be verified first for R1=any_scalar_value. During verification it 16629 * will be assumed that bar() already verified successfully and call to bar() 16630 * from foo() will be checked for type match only. Later bar() will be verified 16631 * independently to check that it's safe for R1=any_scalar_value. 16632 */ 16633 static int do_check_subprogs(struct bpf_verifier_env *env) 16634 { 16635 struct bpf_prog_aux *aux = env->prog->aux; 16636 int i, ret; 16637 16638 if (!aux->func_info) 16639 return 0; 16640 16641 for (i = 1; i < env->subprog_cnt; i++) { 16642 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 16643 continue; 16644 env->insn_idx = env->subprog_info[i].start; 16645 WARN_ON_ONCE(env->insn_idx == 0); 16646 ret = do_check_common(env, i); 16647 if (ret) { 16648 return ret; 16649 } else if (env->log.level & BPF_LOG_LEVEL) { 16650 verbose(env, 16651 "Func#%d is safe for any args that match its prototype\n", 16652 i); 16653 } 16654 } 16655 return 0; 16656 } 16657 16658 static int do_check_main(struct bpf_verifier_env *env) 16659 { 16660 int ret; 16661 16662 env->insn_idx = 0; 16663 ret = do_check_common(env, 0); 16664 if (!ret) 16665 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 16666 return ret; 16667 } 16668 16669 16670 static void print_verification_stats(struct bpf_verifier_env *env) 16671 { 16672 int i; 16673 16674 if (env->log.level & BPF_LOG_STATS) { 16675 verbose(env, "verification time %lld usec\n", 16676 div_u64(env->verification_time, 1000)); 16677 verbose(env, "stack depth "); 16678 for (i = 0; i < env->subprog_cnt; i++) { 16679 u32 depth = env->subprog_info[i].stack_depth; 16680 16681 verbose(env, "%d", depth); 16682 if (i + 1 < env->subprog_cnt) 16683 verbose(env, "+"); 16684 } 16685 verbose(env, "\n"); 16686 } 16687 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 16688 "total_states %d peak_states %d mark_read %d\n", 16689 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 16690 env->max_states_per_insn, env->total_states, 16691 env->peak_states, env->longest_mark_read_walk); 16692 } 16693 16694 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 16695 { 16696 const struct btf_type *t, *func_proto; 16697 const struct bpf_struct_ops *st_ops; 16698 const struct btf_member *member; 16699 struct bpf_prog *prog = env->prog; 16700 u32 btf_id, member_idx; 16701 const char *mname; 16702 16703 if (!prog->gpl_compatible) { 16704 verbose(env, "struct ops programs must have a GPL compatible license\n"); 16705 return -EINVAL; 16706 } 16707 16708 btf_id = prog->aux->attach_btf_id; 16709 st_ops = bpf_struct_ops_find(btf_id); 16710 if (!st_ops) { 16711 verbose(env, "attach_btf_id %u is not a supported struct\n", 16712 btf_id); 16713 return -ENOTSUPP; 16714 } 16715 16716 t = st_ops->type; 16717 member_idx = prog->expected_attach_type; 16718 if (member_idx >= btf_type_vlen(t)) { 16719 verbose(env, "attach to invalid member idx %u of struct %s\n", 16720 member_idx, st_ops->name); 16721 return -EINVAL; 16722 } 16723 16724 member = &btf_type_member(t)[member_idx]; 16725 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 16726 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 16727 NULL); 16728 if (!func_proto) { 16729 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 16730 mname, member_idx, st_ops->name); 16731 return -EINVAL; 16732 } 16733 16734 if (st_ops->check_member) { 16735 int err = st_ops->check_member(t, member); 16736 16737 if (err) { 16738 verbose(env, "attach to unsupported member %s of struct %s\n", 16739 mname, st_ops->name); 16740 return err; 16741 } 16742 } 16743 16744 prog->aux->attach_func_proto = func_proto; 16745 prog->aux->attach_func_name = mname; 16746 env->ops = st_ops->verifier_ops; 16747 16748 return 0; 16749 } 16750 #define SECURITY_PREFIX "security_" 16751 16752 static int check_attach_modify_return(unsigned long addr, const char *func_name) 16753 { 16754 if (within_error_injection_list(addr) || 16755 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 16756 return 0; 16757 16758 return -EINVAL; 16759 } 16760 16761 /* list of non-sleepable functions that are otherwise on 16762 * ALLOW_ERROR_INJECTION list 16763 */ 16764 BTF_SET_START(btf_non_sleepable_error_inject) 16765 /* Three functions below can be called from sleepable and non-sleepable context. 16766 * Assume non-sleepable from bpf safety point of view. 16767 */ 16768 BTF_ID(func, __filemap_add_folio) 16769 BTF_ID(func, should_fail_alloc_page) 16770 BTF_ID(func, should_failslab) 16771 BTF_SET_END(btf_non_sleepable_error_inject) 16772 16773 static int check_non_sleepable_error_inject(u32 btf_id) 16774 { 16775 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 16776 } 16777 16778 int bpf_check_attach_target(struct bpf_verifier_log *log, 16779 const struct bpf_prog *prog, 16780 const struct bpf_prog *tgt_prog, 16781 u32 btf_id, 16782 struct bpf_attach_target_info *tgt_info) 16783 { 16784 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 16785 const char prefix[] = "btf_trace_"; 16786 int ret = 0, subprog = -1, i; 16787 const struct btf_type *t; 16788 bool conservative = true; 16789 const char *tname; 16790 struct btf *btf; 16791 long addr = 0; 16792 16793 if (!btf_id) { 16794 bpf_log(log, "Tracing programs must provide btf_id\n"); 16795 return -EINVAL; 16796 } 16797 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 16798 if (!btf) { 16799 bpf_log(log, 16800 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 16801 return -EINVAL; 16802 } 16803 t = btf_type_by_id(btf, btf_id); 16804 if (!t) { 16805 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 16806 return -EINVAL; 16807 } 16808 tname = btf_name_by_offset(btf, t->name_off); 16809 if (!tname) { 16810 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 16811 return -EINVAL; 16812 } 16813 if (tgt_prog) { 16814 struct bpf_prog_aux *aux = tgt_prog->aux; 16815 16816 if (bpf_prog_is_dev_bound(prog->aux) && 16817 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 16818 bpf_log(log, "Target program bound device mismatch"); 16819 return -EINVAL; 16820 } 16821 16822 for (i = 0; i < aux->func_info_cnt; i++) 16823 if (aux->func_info[i].type_id == btf_id) { 16824 subprog = i; 16825 break; 16826 } 16827 if (subprog == -1) { 16828 bpf_log(log, "Subprog %s doesn't exist\n", tname); 16829 return -EINVAL; 16830 } 16831 conservative = aux->func_info_aux[subprog].unreliable; 16832 if (prog_extension) { 16833 if (conservative) { 16834 bpf_log(log, 16835 "Cannot replace static functions\n"); 16836 return -EINVAL; 16837 } 16838 if (!prog->jit_requested) { 16839 bpf_log(log, 16840 "Extension programs should be JITed\n"); 16841 return -EINVAL; 16842 } 16843 } 16844 if (!tgt_prog->jited) { 16845 bpf_log(log, "Can attach to only JITed progs\n"); 16846 return -EINVAL; 16847 } 16848 if (tgt_prog->type == prog->type) { 16849 /* Cannot fentry/fexit another fentry/fexit program. 16850 * Cannot attach program extension to another extension. 16851 * It's ok to attach fentry/fexit to extension program. 16852 */ 16853 bpf_log(log, "Cannot recursively attach\n"); 16854 return -EINVAL; 16855 } 16856 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 16857 prog_extension && 16858 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 16859 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 16860 /* Program extensions can extend all program types 16861 * except fentry/fexit. The reason is the following. 16862 * The fentry/fexit programs are used for performance 16863 * analysis, stats and can be attached to any program 16864 * type except themselves. When extension program is 16865 * replacing XDP function it is necessary to allow 16866 * performance analysis of all functions. Both original 16867 * XDP program and its program extension. Hence 16868 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 16869 * allowed. If extending of fentry/fexit was allowed it 16870 * would be possible to create long call chain 16871 * fentry->extension->fentry->extension beyond 16872 * reasonable stack size. Hence extending fentry is not 16873 * allowed. 16874 */ 16875 bpf_log(log, "Cannot extend fentry/fexit\n"); 16876 return -EINVAL; 16877 } 16878 } else { 16879 if (prog_extension) { 16880 bpf_log(log, "Cannot replace kernel functions\n"); 16881 return -EINVAL; 16882 } 16883 } 16884 16885 switch (prog->expected_attach_type) { 16886 case BPF_TRACE_RAW_TP: 16887 if (tgt_prog) { 16888 bpf_log(log, 16889 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 16890 return -EINVAL; 16891 } 16892 if (!btf_type_is_typedef(t)) { 16893 bpf_log(log, "attach_btf_id %u is not a typedef\n", 16894 btf_id); 16895 return -EINVAL; 16896 } 16897 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 16898 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 16899 btf_id, tname); 16900 return -EINVAL; 16901 } 16902 tname += sizeof(prefix) - 1; 16903 t = btf_type_by_id(btf, t->type); 16904 if (!btf_type_is_ptr(t)) 16905 /* should never happen in valid vmlinux build */ 16906 return -EINVAL; 16907 t = btf_type_by_id(btf, t->type); 16908 if (!btf_type_is_func_proto(t)) 16909 /* should never happen in valid vmlinux build */ 16910 return -EINVAL; 16911 16912 break; 16913 case BPF_TRACE_ITER: 16914 if (!btf_type_is_func(t)) { 16915 bpf_log(log, "attach_btf_id %u is not a function\n", 16916 btf_id); 16917 return -EINVAL; 16918 } 16919 t = btf_type_by_id(btf, t->type); 16920 if (!btf_type_is_func_proto(t)) 16921 return -EINVAL; 16922 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 16923 if (ret) 16924 return ret; 16925 break; 16926 default: 16927 if (!prog_extension) 16928 return -EINVAL; 16929 fallthrough; 16930 case BPF_MODIFY_RETURN: 16931 case BPF_LSM_MAC: 16932 case BPF_LSM_CGROUP: 16933 case BPF_TRACE_FENTRY: 16934 case BPF_TRACE_FEXIT: 16935 if (!btf_type_is_func(t)) { 16936 bpf_log(log, "attach_btf_id %u is not a function\n", 16937 btf_id); 16938 return -EINVAL; 16939 } 16940 if (prog_extension && 16941 btf_check_type_match(log, prog, btf, t)) 16942 return -EINVAL; 16943 t = btf_type_by_id(btf, t->type); 16944 if (!btf_type_is_func_proto(t)) 16945 return -EINVAL; 16946 16947 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 16948 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 16949 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 16950 return -EINVAL; 16951 16952 if (tgt_prog && conservative) 16953 t = NULL; 16954 16955 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 16956 if (ret < 0) 16957 return ret; 16958 16959 if (tgt_prog) { 16960 if (subprog == 0) 16961 addr = (long) tgt_prog->bpf_func; 16962 else 16963 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 16964 } else { 16965 addr = kallsyms_lookup_name(tname); 16966 if (!addr) { 16967 bpf_log(log, 16968 "The address of function %s cannot be found\n", 16969 tname); 16970 return -ENOENT; 16971 } 16972 } 16973 16974 if (prog->aux->sleepable) { 16975 ret = -EINVAL; 16976 switch (prog->type) { 16977 case BPF_PROG_TYPE_TRACING: 16978 16979 /* fentry/fexit/fmod_ret progs can be sleepable if they are 16980 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 16981 */ 16982 if (!check_non_sleepable_error_inject(btf_id) && 16983 within_error_injection_list(addr)) 16984 ret = 0; 16985 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 16986 * in the fmodret id set with the KF_SLEEPABLE flag. 16987 */ 16988 else { 16989 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id); 16990 16991 if (flags && (*flags & KF_SLEEPABLE)) 16992 ret = 0; 16993 } 16994 break; 16995 case BPF_PROG_TYPE_LSM: 16996 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 16997 * Only some of them are sleepable. 16998 */ 16999 if (bpf_lsm_is_sleepable_hook(btf_id)) 17000 ret = 0; 17001 break; 17002 default: 17003 break; 17004 } 17005 if (ret) { 17006 bpf_log(log, "%s is not sleepable\n", tname); 17007 return ret; 17008 } 17009 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 17010 if (tgt_prog) { 17011 bpf_log(log, "can't modify return codes of BPF programs\n"); 17012 return -EINVAL; 17013 } 17014 ret = -EINVAL; 17015 if (btf_kfunc_is_modify_return(btf, btf_id) || 17016 !check_attach_modify_return(addr, tname)) 17017 ret = 0; 17018 if (ret) { 17019 bpf_log(log, "%s() is not modifiable\n", tname); 17020 return ret; 17021 } 17022 } 17023 17024 break; 17025 } 17026 tgt_info->tgt_addr = addr; 17027 tgt_info->tgt_name = tname; 17028 tgt_info->tgt_type = t; 17029 return 0; 17030 } 17031 17032 BTF_SET_START(btf_id_deny) 17033 BTF_ID_UNUSED 17034 #ifdef CONFIG_SMP 17035 BTF_ID(func, migrate_disable) 17036 BTF_ID(func, migrate_enable) 17037 #endif 17038 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 17039 BTF_ID(func, rcu_read_unlock_strict) 17040 #endif 17041 BTF_SET_END(btf_id_deny) 17042 17043 static bool can_be_sleepable(struct bpf_prog *prog) 17044 { 17045 if (prog->type == BPF_PROG_TYPE_TRACING) { 17046 switch (prog->expected_attach_type) { 17047 case BPF_TRACE_FENTRY: 17048 case BPF_TRACE_FEXIT: 17049 case BPF_MODIFY_RETURN: 17050 case BPF_TRACE_ITER: 17051 return true; 17052 default: 17053 return false; 17054 } 17055 } 17056 return prog->type == BPF_PROG_TYPE_LSM || 17057 prog->type == BPF_PROG_TYPE_KPROBE; /* only for uprobes */ 17058 } 17059 17060 static int check_attach_btf_id(struct bpf_verifier_env *env) 17061 { 17062 struct bpf_prog *prog = env->prog; 17063 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 17064 struct bpf_attach_target_info tgt_info = {}; 17065 u32 btf_id = prog->aux->attach_btf_id; 17066 struct bpf_trampoline *tr; 17067 int ret; 17068 u64 key; 17069 17070 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 17071 if (prog->aux->sleepable) 17072 /* attach_btf_id checked to be zero already */ 17073 return 0; 17074 verbose(env, "Syscall programs can only be sleepable\n"); 17075 return -EINVAL; 17076 } 17077 17078 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 17079 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter and uprobe programs can be sleepable\n"); 17080 return -EINVAL; 17081 } 17082 17083 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 17084 return check_struct_ops_btf_id(env); 17085 17086 if (prog->type != BPF_PROG_TYPE_TRACING && 17087 prog->type != BPF_PROG_TYPE_LSM && 17088 prog->type != BPF_PROG_TYPE_EXT) 17089 return 0; 17090 17091 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 17092 if (ret) 17093 return ret; 17094 17095 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 17096 /* to make freplace equivalent to their targets, they need to 17097 * inherit env->ops and expected_attach_type for the rest of the 17098 * verification 17099 */ 17100 env->ops = bpf_verifier_ops[tgt_prog->type]; 17101 prog->expected_attach_type = tgt_prog->expected_attach_type; 17102 } 17103 17104 /* store info about the attachment target that will be used later */ 17105 prog->aux->attach_func_proto = tgt_info.tgt_type; 17106 prog->aux->attach_func_name = tgt_info.tgt_name; 17107 17108 if (tgt_prog) { 17109 prog->aux->saved_dst_prog_type = tgt_prog->type; 17110 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 17111 } 17112 17113 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 17114 prog->aux->attach_btf_trace = true; 17115 return 0; 17116 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 17117 if (!bpf_iter_prog_supported(prog)) 17118 return -EINVAL; 17119 return 0; 17120 } 17121 17122 if (prog->type == BPF_PROG_TYPE_LSM) { 17123 ret = bpf_lsm_verify_prog(&env->log, prog); 17124 if (ret < 0) 17125 return ret; 17126 } else if (prog->type == BPF_PROG_TYPE_TRACING && 17127 btf_id_set_contains(&btf_id_deny, btf_id)) { 17128 return -EINVAL; 17129 } 17130 17131 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 17132 tr = bpf_trampoline_get(key, &tgt_info); 17133 if (!tr) 17134 return -ENOMEM; 17135 17136 prog->aux->dst_trampoline = tr; 17137 return 0; 17138 } 17139 17140 struct btf *bpf_get_btf_vmlinux(void) 17141 { 17142 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 17143 mutex_lock(&bpf_verifier_lock); 17144 if (!btf_vmlinux) 17145 btf_vmlinux = btf_parse_vmlinux(); 17146 mutex_unlock(&bpf_verifier_lock); 17147 } 17148 return btf_vmlinux; 17149 } 17150 17151 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr) 17152 { 17153 u64 start_time = ktime_get_ns(); 17154 struct bpf_verifier_env *env; 17155 struct bpf_verifier_log *log; 17156 int i, len, ret = -EINVAL; 17157 bool is_priv; 17158 17159 /* no program is valid */ 17160 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 17161 return -EINVAL; 17162 17163 /* 'struct bpf_verifier_env' can be global, but since it's not small, 17164 * allocate/free it every time bpf_check() is called 17165 */ 17166 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 17167 if (!env) 17168 return -ENOMEM; 17169 log = &env->log; 17170 17171 len = (*prog)->len; 17172 env->insn_aux_data = 17173 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 17174 ret = -ENOMEM; 17175 if (!env->insn_aux_data) 17176 goto err_free_env; 17177 for (i = 0; i < len; i++) 17178 env->insn_aux_data[i].orig_idx = i; 17179 env->prog = *prog; 17180 env->ops = bpf_verifier_ops[env->prog->type]; 17181 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 17182 is_priv = bpf_capable(); 17183 17184 bpf_get_btf_vmlinux(); 17185 17186 /* grab the mutex to protect few globals used by verifier */ 17187 if (!is_priv) 17188 mutex_lock(&bpf_verifier_lock); 17189 17190 if (attr->log_level || attr->log_buf || attr->log_size) { 17191 /* user requested verbose verifier output 17192 * and supplied buffer to store the verification trace 17193 */ 17194 log->level = attr->log_level; 17195 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 17196 log->len_total = attr->log_size; 17197 17198 /* log attributes have to be sane */ 17199 if (!bpf_verifier_log_attr_valid(log)) { 17200 ret = -EINVAL; 17201 goto err_unlock; 17202 } 17203 } 17204 17205 mark_verifier_state_clean(env); 17206 17207 if (IS_ERR(btf_vmlinux)) { 17208 /* Either gcc or pahole or kernel are broken. */ 17209 verbose(env, "in-kernel BTF is malformed\n"); 17210 ret = PTR_ERR(btf_vmlinux); 17211 goto skip_full_check; 17212 } 17213 17214 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 17215 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 17216 env->strict_alignment = true; 17217 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 17218 env->strict_alignment = false; 17219 17220 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 17221 env->allow_uninit_stack = bpf_allow_uninit_stack(); 17222 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 17223 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 17224 env->bpf_capable = bpf_capable(); 17225 env->rcu_tag_supported = btf_vmlinux && 17226 btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0; 17227 17228 if (is_priv) 17229 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 17230 17231 env->explored_states = kvcalloc(state_htab_size(env), 17232 sizeof(struct bpf_verifier_state_list *), 17233 GFP_USER); 17234 ret = -ENOMEM; 17235 if (!env->explored_states) 17236 goto skip_full_check; 17237 17238 ret = add_subprog_and_kfunc(env); 17239 if (ret < 0) 17240 goto skip_full_check; 17241 17242 ret = check_subprogs(env); 17243 if (ret < 0) 17244 goto skip_full_check; 17245 17246 ret = check_btf_info(env, attr, uattr); 17247 if (ret < 0) 17248 goto skip_full_check; 17249 17250 ret = check_attach_btf_id(env); 17251 if (ret) 17252 goto skip_full_check; 17253 17254 ret = resolve_pseudo_ldimm64(env); 17255 if (ret < 0) 17256 goto skip_full_check; 17257 17258 if (bpf_prog_is_offloaded(env->prog->aux)) { 17259 ret = bpf_prog_offload_verifier_prep(env->prog); 17260 if (ret) 17261 goto skip_full_check; 17262 } 17263 17264 ret = check_cfg(env); 17265 if (ret < 0) 17266 goto skip_full_check; 17267 17268 ret = do_check_subprogs(env); 17269 ret = ret ?: do_check_main(env); 17270 17271 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 17272 ret = bpf_prog_offload_finalize(env); 17273 17274 skip_full_check: 17275 kvfree(env->explored_states); 17276 17277 if (ret == 0) 17278 ret = check_max_stack_depth(env); 17279 17280 /* instruction rewrites happen after this point */ 17281 if (ret == 0) 17282 ret = optimize_bpf_loop(env); 17283 17284 if (is_priv) { 17285 if (ret == 0) 17286 opt_hard_wire_dead_code_branches(env); 17287 if (ret == 0) 17288 ret = opt_remove_dead_code(env); 17289 if (ret == 0) 17290 ret = opt_remove_nops(env); 17291 } else { 17292 if (ret == 0) 17293 sanitize_dead_code(env); 17294 } 17295 17296 if (ret == 0) 17297 /* program is valid, convert *(u32*)(ctx + off) accesses */ 17298 ret = convert_ctx_accesses(env); 17299 17300 if (ret == 0) 17301 ret = do_misc_fixups(env); 17302 17303 /* do 32-bit optimization after insn patching has done so those patched 17304 * insns could be handled correctly. 17305 */ 17306 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 17307 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 17308 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 17309 : false; 17310 } 17311 17312 if (ret == 0) 17313 ret = fixup_call_args(env); 17314 17315 env->verification_time = ktime_get_ns() - start_time; 17316 print_verification_stats(env); 17317 env->prog->aux->verified_insns = env->insn_processed; 17318 17319 if (log->level && bpf_verifier_log_full(log)) 17320 ret = -ENOSPC; 17321 if (log->level && !log->ubuf) { 17322 ret = -EFAULT; 17323 goto err_release_maps; 17324 } 17325 17326 if (ret) 17327 goto err_release_maps; 17328 17329 if (env->used_map_cnt) { 17330 /* if program passed verifier, update used_maps in bpf_prog_info */ 17331 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 17332 sizeof(env->used_maps[0]), 17333 GFP_KERNEL); 17334 17335 if (!env->prog->aux->used_maps) { 17336 ret = -ENOMEM; 17337 goto err_release_maps; 17338 } 17339 17340 memcpy(env->prog->aux->used_maps, env->used_maps, 17341 sizeof(env->used_maps[0]) * env->used_map_cnt); 17342 env->prog->aux->used_map_cnt = env->used_map_cnt; 17343 } 17344 if (env->used_btf_cnt) { 17345 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 17346 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 17347 sizeof(env->used_btfs[0]), 17348 GFP_KERNEL); 17349 if (!env->prog->aux->used_btfs) { 17350 ret = -ENOMEM; 17351 goto err_release_maps; 17352 } 17353 17354 memcpy(env->prog->aux->used_btfs, env->used_btfs, 17355 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 17356 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 17357 } 17358 if (env->used_map_cnt || env->used_btf_cnt) { 17359 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 17360 * bpf_ld_imm64 instructions 17361 */ 17362 convert_pseudo_ld_imm64(env); 17363 } 17364 17365 adjust_btf_func(env); 17366 17367 err_release_maps: 17368 if (!env->prog->aux->used_maps) 17369 /* if we didn't copy map pointers into bpf_prog_info, release 17370 * them now. Otherwise free_used_maps() will release them. 17371 */ 17372 release_maps(env); 17373 if (!env->prog->aux->used_btfs) 17374 release_btfs(env); 17375 17376 /* extension progs temporarily inherit the attach_type of their targets 17377 for verification purposes, so set it back to zero before returning 17378 */ 17379 if (env->prog->type == BPF_PROG_TYPE_EXT) 17380 env->prog->expected_attach_type = 0; 17381 17382 *prog = env->prog; 17383 err_unlock: 17384 if (!is_priv) 17385 mutex_unlock(&bpf_verifier_lock); 17386 vfree(env->insn_aux_data); 17387 err_free_env: 17388 kfree(env); 17389 return ret; 17390 } 17391