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 #define BTF_TYPE_SAFE_NESTED(__type) __PASTE(__type, __safe_fields) 4947 4948 BTF_TYPE_SAFE_NESTED(struct task_struct) { 4949 const cpumask_t *cpus_ptr; 4950 }; 4951 4952 static bool nested_ptr_is_trusted(struct bpf_verifier_env *env, 4953 struct bpf_reg_state *reg, 4954 int off) 4955 { 4956 /* If its parent is not trusted, it can't regain its trusted status. */ 4957 if (!is_trusted_reg(reg)) 4958 return false; 4959 4960 BTF_TYPE_EMIT(BTF_TYPE_SAFE_NESTED(struct task_struct)); 4961 4962 return btf_nested_type_is_trusted(&env->log, reg, off); 4963 } 4964 4965 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 4966 struct bpf_reg_state *regs, 4967 int regno, int off, int size, 4968 enum bpf_access_type atype, 4969 int value_regno) 4970 { 4971 struct bpf_reg_state *reg = regs + regno; 4972 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 4973 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 4974 enum bpf_type_flag flag = 0; 4975 u32 btf_id; 4976 int ret; 4977 4978 if (!env->allow_ptr_leaks) { 4979 verbose(env, 4980 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 4981 tname); 4982 return -EPERM; 4983 } 4984 if (!env->prog->gpl_compatible && btf_is_kernel(reg->btf)) { 4985 verbose(env, 4986 "Cannot access kernel 'struct %s' from non-GPL compatible program\n", 4987 tname); 4988 return -EINVAL; 4989 } 4990 if (off < 0) { 4991 verbose(env, 4992 "R%d is ptr_%s invalid negative access: off=%d\n", 4993 regno, tname, off); 4994 return -EACCES; 4995 } 4996 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4997 char tn_buf[48]; 4998 4999 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5000 verbose(env, 5001 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 5002 regno, tname, off, tn_buf); 5003 return -EACCES; 5004 } 5005 5006 if (reg->type & MEM_USER) { 5007 verbose(env, 5008 "R%d is ptr_%s access user memory: off=%d\n", 5009 regno, tname, off); 5010 return -EACCES; 5011 } 5012 5013 if (reg->type & MEM_PERCPU) { 5014 verbose(env, 5015 "R%d is ptr_%s access percpu memory: off=%d\n", 5016 regno, tname, off); 5017 return -EACCES; 5018 } 5019 5020 if (env->ops->btf_struct_access && !type_is_alloc(reg->type)) { 5021 if (!btf_is_kernel(reg->btf)) { 5022 verbose(env, "verifier internal error: reg->btf must be kernel btf\n"); 5023 return -EFAULT; 5024 } 5025 ret = env->ops->btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag); 5026 } else { 5027 /* Writes are permitted with default btf_struct_access for 5028 * program allocated objects (which always have ref_obj_id > 0), 5029 * but not for untrusted PTR_TO_BTF_ID | MEM_ALLOC. 5030 */ 5031 if (atype != BPF_READ && reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 5032 verbose(env, "only read is supported\n"); 5033 return -EACCES; 5034 } 5035 5036 if (type_is_alloc(reg->type) && !reg->ref_obj_id) { 5037 verbose(env, "verifier internal error: ref_obj_id for allocated object must be non-zero\n"); 5038 return -EFAULT; 5039 } 5040 5041 ret = btf_struct_access(&env->log, reg, off, size, atype, &btf_id, &flag); 5042 } 5043 5044 if (ret < 0) 5045 return ret; 5046 5047 /* If this is an untrusted pointer, all pointers formed by walking it 5048 * also inherit the untrusted flag. 5049 */ 5050 if (type_flag(reg->type) & PTR_UNTRUSTED) 5051 flag |= PTR_UNTRUSTED; 5052 5053 /* By default any pointer obtained from walking a trusted pointer is no 5054 * longer trusted, unless the field being accessed has explicitly been 5055 * marked as inheriting its parent's state of trust. 5056 * 5057 * An RCU-protected pointer can also be deemed trusted if we are in an 5058 * RCU read region. This case is handled below. 5059 */ 5060 if (nested_ptr_is_trusted(env, reg, off)) 5061 flag |= PTR_TRUSTED; 5062 else 5063 flag &= ~PTR_TRUSTED; 5064 5065 if (flag & MEM_RCU) { 5066 /* Mark value register as MEM_RCU only if it is protected by 5067 * bpf_rcu_read_lock() and the ptr reg is rcu or trusted. MEM_RCU 5068 * itself can already indicate trustedness inside the rcu 5069 * read lock region. Also mark rcu pointer as PTR_MAYBE_NULL since 5070 * it could be null in some cases. 5071 */ 5072 if (!env->cur_state->active_rcu_lock || 5073 !(is_trusted_reg(reg) || is_rcu_reg(reg))) 5074 flag &= ~MEM_RCU; 5075 else 5076 flag |= PTR_MAYBE_NULL; 5077 } else if (reg->type & MEM_RCU) { 5078 /* ptr (reg) is marked as MEM_RCU, but the struct field is not tagged 5079 * with __rcu. Mark the flag as PTR_UNTRUSTED conservatively. 5080 */ 5081 flag |= PTR_UNTRUSTED; 5082 } 5083 5084 if (atype == BPF_READ && value_regno >= 0) 5085 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id, flag); 5086 5087 return 0; 5088 } 5089 5090 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 5091 struct bpf_reg_state *regs, 5092 int regno, int off, int size, 5093 enum bpf_access_type atype, 5094 int value_regno) 5095 { 5096 struct bpf_reg_state *reg = regs + regno; 5097 struct bpf_map *map = reg->map_ptr; 5098 struct bpf_reg_state map_reg; 5099 enum bpf_type_flag flag = 0; 5100 const struct btf_type *t; 5101 const char *tname; 5102 u32 btf_id; 5103 int ret; 5104 5105 if (!btf_vmlinux) { 5106 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 5107 return -ENOTSUPP; 5108 } 5109 5110 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 5111 verbose(env, "map_ptr access not supported for map type %d\n", 5112 map->map_type); 5113 return -ENOTSUPP; 5114 } 5115 5116 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 5117 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 5118 5119 if (!env->allow_ptr_leaks) { 5120 verbose(env, 5121 "'struct %s' access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 5122 tname); 5123 return -EPERM; 5124 } 5125 5126 if (off < 0) { 5127 verbose(env, "R%d is %s invalid negative access: off=%d\n", 5128 regno, tname, off); 5129 return -EACCES; 5130 } 5131 5132 if (atype != BPF_READ) { 5133 verbose(env, "only read from %s is supported\n", tname); 5134 return -EACCES; 5135 } 5136 5137 /* Simulate access to a PTR_TO_BTF_ID */ 5138 memset(&map_reg, 0, sizeof(map_reg)); 5139 mark_btf_ld_reg(env, &map_reg, 0, PTR_TO_BTF_ID, btf_vmlinux, *map->ops->map_btf_id, 0); 5140 ret = btf_struct_access(&env->log, &map_reg, off, size, atype, &btf_id, &flag); 5141 if (ret < 0) 5142 return ret; 5143 5144 if (value_regno >= 0) 5145 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id, flag); 5146 5147 return 0; 5148 } 5149 5150 /* Check that the stack access at the given offset is within bounds. The 5151 * maximum valid offset is -1. 5152 * 5153 * The minimum valid offset is -MAX_BPF_STACK for writes, and 5154 * -state->allocated_stack for reads. 5155 */ 5156 static int check_stack_slot_within_bounds(int off, 5157 struct bpf_func_state *state, 5158 enum bpf_access_type t) 5159 { 5160 int min_valid_off; 5161 5162 if (t == BPF_WRITE) 5163 min_valid_off = -MAX_BPF_STACK; 5164 else 5165 min_valid_off = -state->allocated_stack; 5166 5167 if (off < min_valid_off || off > -1) 5168 return -EACCES; 5169 return 0; 5170 } 5171 5172 /* Check that the stack access at 'regno + off' falls within the maximum stack 5173 * bounds. 5174 * 5175 * 'off' includes `regno->offset`, but not its dynamic part (if any). 5176 */ 5177 static int check_stack_access_within_bounds( 5178 struct bpf_verifier_env *env, 5179 int regno, int off, int access_size, 5180 enum bpf_access_src src, enum bpf_access_type type) 5181 { 5182 struct bpf_reg_state *regs = cur_regs(env); 5183 struct bpf_reg_state *reg = regs + regno; 5184 struct bpf_func_state *state = func(env, reg); 5185 int min_off, max_off; 5186 int err; 5187 char *err_extra; 5188 5189 if (src == ACCESS_HELPER) 5190 /* We don't know if helpers are reading or writing (or both). */ 5191 err_extra = " indirect access to"; 5192 else if (type == BPF_READ) 5193 err_extra = " read from"; 5194 else 5195 err_extra = " write to"; 5196 5197 if (tnum_is_const(reg->var_off)) { 5198 min_off = reg->var_off.value + off; 5199 if (access_size > 0) 5200 max_off = min_off + access_size - 1; 5201 else 5202 max_off = min_off; 5203 } else { 5204 if (reg->smax_value >= BPF_MAX_VAR_OFF || 5205 reg->smin_value <= -BPF_MAX_VAR_OFF) { 5206 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 5207 err_extra, regno); 5208 return -EACCES; 5209 } 5210 min_off = reg->smin_value + off; 5211 if (access_size > 0) 5212 max_off = reg->smax_value + off + access_size - 1; 5213 else 5214 max_off = min_off; 5215 } 5216 5217 err = check_stack_slot_within_bounds(min_off, state, type); 5218 if (!err) 5219 err = check_stack_slot_within_bounds(max_off, state, type); 5220 5221 if (err) { 5222 if (tnum_is_const(reg->var_off)) { 5223 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 5224 err_extra, regno, off, access_size); 5225 } else { 5226 char tn_buf[48]; 5227 5228 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5229 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 5230 err_extra, regno, tn_buf, access_size); 5231 } 5232 } 5233 return err; 5234 } 5235 5236 /* check whether memory at (regno + off) is accessible for t = (read | write) 5237 * if t==write, value_regno is a register which value is stored into memory 5238 * if t==read, value_regno is a register which will receive the value from memory 5239 * if t==write && value_regno==-1, some unknown value is stored into memory 5240 * if t==read && value_regno==-1, don't care what we read from memory 5241 */ 5242 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 5243 int off, int bpf_size, enum bpf_access_type t, 5244 int value_regno, bool strict_alignment_once) 5245 { 5246 struct bpf_reg_state *regs = cur_regs(env); 5247 struct bpf_reg_state *reg = regs + regno; 5248 struct bpf_func_state *state; 5249 int size, err = 0; 5250 5251 size = bpf_size_to_bytes(bpf_size); 5252 if (size < 0) 5253 return size; 5254 5255 /* alignment checks will add in reg->off themselves */ 5256 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 5257 if (err) 5258 return err; 5259 5260 /* for access checks, reg->off is just part of off */ 5261 off += reg->off; 5262 5263 if (reg->type == PTR_TO_MAP_KEY) { 5264 if (t == BPF_WRITE) { 5265 verbose(env, "write to change key R%d not allowed\n", regno); 5266 return -EACCES; 5267 } 5268 5269 err = check_mem_region_access(env, regno, off, size, 5270 reg->map_ptr->key_size, false); 5271 if (err) 5272 return err; 5273 if (value_regno >= 0) 5274 mark_reg_unknown(env, regs, value_regno); 5275 } else if (reg->type == PTR_TO_MAP_VALUE) { 5276 struct btf_field *kptr_field = NULL; 5277 5278 if (t == BPF_WRITE && value_regno >= 0 && 5279 is_pointer_value(env, value_regno)) { 5280 verbose(env, "R%d leaks addr into map\n", value_regno); 5281 return -EACCES; 5282 } 5283 err = check_map_access_type(env, regno, off, size, t); 5284 if (err) 5285 return err; 5286 err = check_map_access(env, regno, off, size, false, ACCESS_DIRECT); 5287 if (err) 5288 return err; 5289 if (tnum_is_const(reg->var_off)) 5290 kptr_field = btf_record_find(reg->map_ptr->record, 5291 off + reg->var_off.value, BPF_KPTR); 5292 if (kptr_field) { 5293 err = check_map_kptr_access(env, regno, value_regno, insn_idx, kptr_field); 5294 } else if (t == BPF_READ && value_regno >= 0) { 5295 struct bpf_map *map = reg->map_ptr; 5296 5297 /* if map is read-only, track its contents as scalars */ 5298 if (tnum_is_const(reg->var_off) && 5299 bpf_map_is_rdonly(map) && 5300 map->ops->map_direct_value_addr) { 5301 int map_off = off + reg->var_off.value; 5302 u64 val = 0; 5303 5304 err = bpf_map_direct_read(map, map_off, size, 5305 &val); 5306 if (err) 5307 return err; 5308 5309 regs[value_regno].type = SCALAR_VALUE; 5310 __mark_reg_known(®s[value_regno], val); 5311 } else { 5312 mark_reg_unknown(env, regs, value_regno); 5313 } 5314 } 5315 } else if (base_type(reg->type) == PTR_TO_MEM) { 5316 bool rdonly_mem = type_is_rdonly_mem(reg->type); 5317 5318 if (type_may_be_null(reg->type)) { 5319 verbose(env, "R%d invalid mem access '%s'\n", regno, 5320 reg_type_str(env, reg->type)); 5321 return -EACCES; 5322 } 5323 5324 if (t == BPF_WRITE && rdonly_mem) { 5325 verbose(env, "R%d cannot write into %s\n", 5326 regno, reg_type_str(env, reg->type)); 5327 return -EACCES; 5328 } 5329 5330 if (t == BPF_WRITE && value_regno >= 0 && 5331 is_pointer_value(env, value_regno)) { 5332 verbose(env, "R%d leaks addr into mem\n", value_regno); 5333 return -EACCES; 5334 } 5335 5336 err = check_mem_region_access(env, regno, off, size, 5337 reg->mem_size, false); 5338 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 5339 mark_reg_unknown(env, regs, value_regno); 5340 } else if (reg->type == PTR_TO_CTX) { 5341 enum bpf_reg_type reg_type = SCALAR_VALUE; 5342 struct btf *btf = NULL; 5343 u32 btf_id = 0; 5344 5345 if (t == BPF_WRITE && value_regno >= 0 && 5346 is_pointer_value(env, value_regno)) { 5347 verbose(env, "R%d leaks addr into ctx\n", value_regno); 5348 return -EACCES; 5349 } 5350 5351 err = check_ptr_off_reg(env, reg, regno); 5352 if (err < 0) 5353 return err; 5354 5355 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, 5356 &btf_id); 5357 if (err) 5358 verbose_linfo(env, insn_idx, "; "); 5359 if (!err && t == BPF_READ && value_regno >= 0) { 5360 /* ctx access returns either a scalar, or a 5361 * PTR_TO_PACKET[_META,_END]. In the latter 5362 * case, we know the offset is zero. 5363 */ 5364 if (reg_type == SCALAR_VALUE) { 5365 mark_reg_unknown(env, regs, value_regno); 5366 } else { 5367 mark_reg_known_zero(env, regs, 5368 value_regno); 5369 if (type_may_be_null(reg_type)) 5370 regs[value_regno].id = ++env->id_gen; 5371 /* A load of ctx field could have different 5372 * actual load size with the one encoded in the 5373 * insn. When the dst is PTR, it is for sure not 5374 * a sub-register. 5375 */ 5376 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 5377 if (base_type(reg_type) == PTR_TO_BTF_ID) { 5378 regs[value_regno].btf = btf; 5379 regs[value_regno].btf_id = btf_id; 5380 } 5381 } 5382 regs[value_regno].type = reg_type; 5383 } 5384 5385 } else if (reg->type == PTR_TO_STACK) { 5386 /* Basic bounds checks. */ 5387 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 5388 if (err) 5389 return err; 5390 5391 state = func(env, reg); 5392 err = update_stack_depth(env, state, off); 5393 if (err) 5394 return err; 5395 5396 if (t == BPF_READ) 5397 err = check_stack_read(env, regno, off, size, 5398 value_regno); 5399 else 5400 err = check_stack_write(env, regno, off, size, 5401 value_regno, insn_idx); 5402 } else if (reg_is_pkt_pointer(reg)) { 5403 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 5404 verbose(env, "cannot write into packet\n"); 5405 return -EACCES; 5406 } 5407 if (t == BPF_WRITE && value_regno >= 0 && 5408 is_pointer_value(env, value_regno)) { 5409 verbose(env, "R%d leaks addr into packet\n", 5410 value_regno); 5411 return -EACCES; 5412 } 5413 err = check_packet_access(env, regno, off, size, false); 5414 if (!err && t == BPF_READ && value_regno >= 0) 5415 mark_reg_unknown(env, regs, value_regno); 5416 } else if (reg->type == PTR_TO_FLOW_KEYS) { 5417 if (t == BPF_WRITE && value_regno >= 0 && 5418 is_pointer_value(env, value_regno)) { 5419 verbose(env, "R%d leaks addr into flow keys\n", 5420 value_regno); 5421 return -EACCES; 5422 } 5423 5424 err = check_flow_keys_access(env, off, size); 5425 if (!err && t == BPF_READ && value_regno >= 0) 5426 mark_reg_unknown(env, regs, value_regno); 5427 } else if (type_is_sk_pointer(reg->type)) { 5428 if (t == BPF_WRITE) { 5429 verbose(env, "R%d cannot write into %s\n", 5430 regno, reg_type_str(env, reg->type)); 5431 return -EACCES; 5432 } 5433 err = check_sock_access(env, insn_idx, regno, off, size, t); 5434 if (!err && value_regno >= 0) 5435 mark_reg_unknown(env, regs, value_regno); 5436 } else if (reg->type == PTR_TO_TP_BUFFER) { 5437 err = check_tp_buffer_access(env, reg, regno, off, size); 5438 if (!err && t == BPF_READ && value_regno >= 0) 5439 mark_reg_unknown(env, regs, value_regno); 5440 } else if (base_type(reg->type) == PTR_TO_BTF_ID && 5441 !type_may_be_null(reg->type)) { 5442 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 5443 value_regno); 5444 } else if (reg->type == CONST_PTR_TO_MAP) { 5445 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 5446 value_regno); 5447 } else if (base_type(reg->type) == PTR_TO_BUF) { 5448 bool rdonly_mem = type_is_rdonly_mem(reg->type); 5449 u32 *max_access; 5450 5451 if (rdonly_mem) { 5452 if (t == BPF_WRITE) { 5453 verbose(env, "R%d cannot write into %s\n", 5454 regno, reg_type_str(env, reg->type)); 5455 return -EACCES; 5456 } 5457 max_access = &env->prog->aux->max_rdonly_access; 5458 } else { 5459 max_access = &env->prog->aux->max_rdwr_access; 5460 } 5461 5462 err = check_buffer_access(env, reg, regno, off, size, false, 5463 max_access); 5464 5465 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 5466 mark_reg_unknown(env, regs, value_regno); 5467 } else { 5468 verbose(env, "R%d invalid mem access '%s'\n", regno, 5469 reg_type_str(env, reg->type)); 5470 return -EACCES; 5471 } 5472 5473 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 5474 regs[value_regno].type == SCALAR_VALUE) { 5475 /* b/h/w load zero-extends, mark upper bits as known 0 */ 5476 coerce_reg_to_size(®s[value_regno], size); 5477 } 5478 return err; 5479 } 5480 5481 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 5482 { 5483 int load_reg; 5484 int err; 5485 5486 switch (insn->imm) { 5487 case BPF_ADD: 5488 case BPF_ADD | BPF_FETCH: 5489 case BPF_AND: 5490 case BPF_AND | BPF_FETCH: 5491 case BPF_OR: 5492 case BPF_OR | BPF_FETCH: 5493 case BPF_XOR: 5494 case BPF_XOR | BPF_FETCH: 5495 case BPF_XCHG: 5496 case BPF_CMPXCHG: 5497 break; 5498 default: 5499 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 5500 return -EINVAL; 5501 } 5502 5503 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 5504 verbose(env, "invalid atomic operand size\n"); 5505 return -EINVAL; 5506 } 5507 5508 /* check src1 operand */ 5509 err = check_reg_arg(env, insn->src_reg, SRC_OP); 5510 if (err) 5511 return err; 5512 5513 /* check src2 operand */ 5514 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 5515 if (err) 5516 return err; 5517 5518 if (insn->imm == BPF_CMPXCHG) { 5519 /* Check comparison of R0 with memory location */ 5520 const u32 aux_reg = BPF_REG_0; 5521 5522 err = check_reg_arg(env, aux_reg, SRC_OP); 5523 if (err) 5524 return err; 5525 5526 if (is_pointer_value(env, aux_reg)) { 5527 verbose(env, "R%d leaks addr into mem\n", aux_reg); 5528 return -EACCES; 5529 } 5530 } 5531 5532 if (is_pointer_value(env, insn->src_reg)) { 5533 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 5534 return -EACCES; 5535 } 5536 5537 if (is_ctx_reg(env, insn->dst_reg) || 5538 is_pkt_reg(env, insn->dst_reg) || 5539 is_flow_key_reg(env, insn->dst_reg) || 5540 is_sk_reg(env, insn->dst_reg)) { 5541 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 5542 insn->dst_reg, 5543 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 5544 return -EACCES; 5545 } 5546 5547 if (insn->imm & BPF_FETCH) { 5548 if (insn->imm == BPF_CMPXCHG) 5549 load_reg = BPF_REG_0; 5550 else 5551 load_reg = insn->src_reg; 5552 5553 /* check and record load of old value */ 5554 err = check_reg_arg(env, load_reg, DST_OP); 5555 if (err) 5556 return err; 5557 } else { 5558 /* This instruction accesses a memory location but doesn't 5559 * actually load it into a register. 5560 */ 5561 load_reg = -1; 5562 } 5563 5564 /* Check whether we can read the memory, with second call for fetch 5565 * case to simulate the register fill. 5566 */ 5567 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5568 BPF_SIZE(insn->code), BPF_READ, -1, true); 5569 if (!err && load_reg >= 0) 5570 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5571 BPF_SIZE(insn->code), BPF_READ, load_reg, 5572 true); 5573 if (err) 5574 return err; 5575 5576 /* Check whether we can write into the same memory. */ 5577 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5578 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 5579 if (err) 5580 return err; 5581 5582 return 0; 5583 } 5584 5585 /* When register 'regno' is used to read the stack (either directly or through 5586 * a helper function) make sure that it's within stack boundary and, depending 5587 * on the access type, that all elements of the stack are initialized. 5588 * 5589 * 'off' includes 'regno->off', but not its dynamic part (if any). 5590 * 5591 * All registers that have been spilled on the stack in the slots within the 5592 * read offsets are marked as read. 5593 */ 5594 static int check_stack_range_initialized( 5595 struct bpf_verifier_env *env, int regno, int off, 5596 int access_size, bool zero_size_allowed, 5597 enum bpf_access_src type, struct bpf_call_arg_meta *meta) 5598 { 5599 struct bpf_reg_state *reg = reg_state(env, regno); 5600 struct bpf_func_state *state = func(env, reg); 5601 int err, min_off, max_off, i, j, slot, spi; 5602 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 5603 enum bpf_access_type bounds_check_type; 5604 /* Some accesses can write anything into the stack, others are 5605 * read-only. 5606 */ 5607 bool clobber = false; 5608 5609 if (access_size == 0 && !zero_size_allowed) { 5610 verbose(env, "invalid zero-sized read\n"); 5611 return -EACCES; 5612 } 5613 5614 if (type == ACCESS_HELPER) { 5615 /* The bounds checks for writes are more permissive than for 5616 * reads. However, if raw_mode is not set, we'll do extra 5617 * checks below. 5618 */ 5619 bounds_check_type = BPF_WRITE; 5620 clobber = true; 5621 } else { 5622 bounds_check_type = BPF_READ; 5623 } 5624 err = check_stack_access_within_bounds(env, regno, off, access_size, 5625 type, bounds_check_type); 5626 if (err) 5627 return err; 5628 5629 5630 if (tnum_is_const(reg->var_off)) { 5631 min_off = max_off = reg->var_off.value + off; 5632 } else { 5633 /* Variable offset is prohibited for unprivileged mode for 5634 * simplicity since it requires corresponding support in 5635 * Spectre masking for stack ALU. 5636 * See also retrieve_ptr_limit(). 5637 */ 5638 if (!env->bypass_spec_v1) { 5639 char tn_buf[48]; 5640 5641 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5642 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 5643 regno, err_extra, tn_buf); 5644 return -EACCES; 5645 } 5646 /* Only initialized buffer on stack is allowed to be accessed 5647 * with variable offset. With uninitialized buffer it's hard to 5648 * guarantee that whole memory is marked as initialized on 5649 * helper return since specific bounds are unknown what may 5650 * cause uninitialized stack leaking. 5651 */ 5652 if (meta && meta->raw_mode) 5653 meta = NULL; 5654 5655 min_off = reg->smin_value + off; 5656 max_off = reg->smax_value + off; 5657 } 5658 5659 if (meta && meta->raw_mode) { 5660 /* Ensure we won't be overwriting dynptrs when simulating byte 5661 * by byte access in check_helper_call using meta.access_size. 5662 * This would be a problem if we have a helper in the future 5663 * which takes: 5664 * 5665 * helper(uninit_mem, len, dynptr) 5666 * 5667 * Now, uninint_mem may overlap with dynptr pointer. Hence, it 5668 * may end up writing to dynptr itself when touching memory from 5669 * arg 1. This can be relaxed on a case by case basis for known 5670 * safe cases, but reject due to the possibilitiy of aliasing by 5671 * default. 5672 */ 5673 for (i = min_off; i < max_off + access_size; i++) { 5674 int stack_off = -i - 1; 5675 5676 spi = __get_spi(i); 5677 /* raw_mode may write past allocated_stack */ 5678 if (state->allocated_stack <= stack_off) 5679 continue; 5680 if (state->stack[spi].slot_type[stack_off % BPF_REG_SIZE] == STACK_DYNPTR) { 5681 verbose(env, "potential write to dynptr at off=%d disallowed\n", i); 5682 return -EACCES; 5683 } 5684 } 5685 meta->access_size = access_size; 5686 meta->regno = regno; 5687 return 0; 5688 } 5689 5690 for (i = min_off; i < max_off + access_size; i++) { 5691 u8 *stype; 5692 5693 slot = -i - 1; 5694 spi = slot / BPF_REG_SIZE; 5695 if (state->allocated_stack <= slot) 5696 goto err; 5697 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 5698 if (*stype == STACK_MISC) 5699 goto mark; 5700 if (*stype == STACK_ZERO) { 5701 if (clobber) { 5702 /* helper can write anything into the stack */ 5703 *stype = STACK_MISC; 5704 } 5705 goto mark; 5706 } 5707 5708 if (is_spilled_reg(&state->stack[spi]) && 5709 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 5710 env->allow_ptr_leaks)) { 5711 if (clobber) { 5712 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 5713 for (j = 0; j < BPF_REG_SIZE; j++) 5714 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 5715 } 5716 goto mark; 5717 } 5718 5719 err: 5720 if (tnum_is_const(reg->var_off)) { 5721 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 5722 err_extra, regno, min_off, i - min_off, access_size); 5723 } else { 5724 char tn_buf[48]; 5725 5726 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5727 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 5728 err_extra, regno, tn_buf, i - min_off, access_size); 5729 } 5730 return -EACCES; 5731 mark: 5732 /* reading any byte out of 8-byte 'spill_slot' will cause 5733 * the whole slot to be marked as 'read' 5734 */ 5735 mark_reg_read(env, &state->stack[spi].spilled_ptr, 5736 state->stack[spi].spilled_ptr.parent, 5737 REG_LIVE_READ64); 5738 /* We do not set REG_LIVE_WRITTEN for stack slot, as we can not 5739 * be sure that whether stack slot is written to or not. Hence, 5740 * we must still conservatively propagate reads upwards even if 5741 * helper may write to the entire memory range. 5742 */ 5743 } 5744 return update_stack_depth(env, state, min_off); 5745 } 5746 5747 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 5748 int access_size, bool zero_size_allowed, 5749 struct bpf_call_arg_meta *meta) 5750 { 5751 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5752 u32 *max_access; 5753 5754 switch (base_type(reg->type)) { 5755 case PTR_TO_PACKET: 5756 case PTR_TO_PACKET_META: 5757 return check_packet_access(env, regno, reg->off, access_size, 5758 zero_size_allowed); 5759 case PTR_TO_MAP_KEY: 5760 if (meta && meta->raw_mode) { 5761 verbose(env, "R%d cannot write into %s\n", regno, 5762 reg_type_str(env, reg->type)); 5763 return -EACCES; 5764 } 5765 return check_mem_region_access(env, regno, reg->off, access_size, 5766 reg->map_ptr->key_size, false); 5767 case PTR_TO_MAP_VALUE: 5768 if (check_map_access_type(env, regno, reg->off, access_size, 5769 meta && meta->raw_mode ? BPF_WRITE : 5770 BPF_READ)) 5771 return -EACCES; 5772 return check_map_access(env, regno, reg->off, access_size, 5773 zero_size_allowed, ACCESS_HELPER); 5774 case PTR_TO_MEM: 5775 if (type_is_rdonly_mem(reg->type)) { 5776 if (meta && meta->raw_mode) { 5777 verbose(env, "R%d cannot write into %s\n", regno, 5778 reg_type_str(env, reg->type)); 5779 return -EACCES; 5780 } 5781 } 5782 return check_mem_region_access(env, regno, reg->off, 5783 access_size, reg->mem_size, 5784 zero_size_allowed); 5785 case PTR_TO_BUF: 5786 if (type_is_rdonly_mem(reg->type)) { 5787 if (meta && meta->raw_mode) { 5788 verbose(env, "R%d cannot write into %s\n", regno, 5789 reg_type_str(env, reg->type)); 5790 return -EACCES; 5791 } 5792 5793 max_access = &env->prog->aux->max_rdonly_access; 5794 } else { 5795 max_access = &env->prog->aux->max_rdwr_access; 5796 } 5797 return check_buffer_access(env, reg, regno, reg->off, 5798 access_size, zero_size_allowed, 5799 max_access); 5800 case PTR_TO_STACK: 5801 return check_stack_range_initialized( 5802 env, 5803 regno, reg->off, access_size, 5804 zero_size_allowed, ACCESS_HELPER, meta); 5805 case PTR_TO_CTX: 5806 /* in case the function doesn't know how to access the context, 5807 * (because we are in a program of type SYSCALL for example), we 5808 * can not statically check its size. 5809 * Dynamically check it now. 5810 */ 5811 if (!env->ops->convert_ctx_access) { 5812 enum bpf_access_type atype = meta && meta->raw_mode ? BPF_WRITE : BPF_READ; 5813 int offset = access_size - 1; 5814 5815 /* Allow zero-byte read from PTR_TO_CTX */ 5816 if (access_size == 0) 5817 return zero_size_allowed ? 0 : -EACCES; 5818 5819 return check_mem_access(env, env->insn_idx, regno, offset, BPF_B, 5820 atype, -1, false); 5821 } 5822 5823 fallthrough; 5824 default: /* scalar_value or invalid ptr */ 5825 /* Allow zero-byte read from NULL, regardless of pointer type */ 5826 if (zero_size_allowed && access_size == 0 && 5827 register_is_null(reg)) 5828 return 0; 5829 5830 verbose(env, "R%d type=%s ", regno, 5831 reg_type_str(env, reg->type)); 5832 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 5833 return -EACCES; 5834 } 5835 } 5836 5837 static int check_mem_size_reg(struct bpf_verifier_env *env, 5838 struct bpf_reg_state *reg, u32 regno, 5839 bool zero_size_allowed, 5840 struct bpf_call_arg_meta *meta) 5841 { 5842 int err; 5843 5844 /* This is used to refine r0 return value bounds for helpers 5845 * that enforce this value as an upper bound on return values. 5846 * See do_refine_retval_range() for helpers that can refine 5847 * the return value. C type of helper is u32 so we pull register 5848 * bound from umax_value however, if negative verifier errors 5849 * out. Only upper bounds can be learned because retval is an 5850 * int type and negative retvals are allowed. 5851 */ 5852 meta->msize_max_value = reg->umax_value; 5853 5854 /* The register is SCALAR_VALUE; the access check 5855 * happens using its boundaries. 5856 */ 5857 if (!tnum_is_const(reg->var_off)) 5858 /* For unprivileged variable accesses, disable raw 5859 * mode so that the program is required to 5860 * initialize all the memory that the helper could 5861 * just partially fill up. 5862 */ 5863 meta = NULL; 5864 5865 if (reg->smin_value < 0) { 5866 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 5867 regno); 5868 return -EACCES; 5869 } 5870 5871 if (reg->umin_value == 0) { 5872 err = check_helper_mem_access(env, regno - 1, 0, 5873 zero_size_allowed, 5874 meta); 5875 if (err) 5876 return err; 5877 } 5878 5879 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 5880 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 5881 regno); 5882 return -EACCES; 5883 } 5884 err = check_helper_mem_access(env, regno - 1, 5885 reg->umax_value, 5886 zero_size_allowed, meta); 5887 if (!err) 5888 err = mark_chain_precision(env, regno); 5889 return err; 5890 } 5891 5892 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5893 u32 regno, u32 mem_size) 5894 { 5895 bool may_be_null = type_may_be_null(reg->type); 5896 struct bpf_reg_state saved_reg; 5897 struct bpf_call_arg_meta meta; 5898 int err; 5899 5900 if (register_is_null(reg)) 5901 return 0; 5902 5903 memset(&meta, 0, sizeof(meta)); 5904 /* Assuming that the register contains a value check if the memory 5905 * access is safe. Temporarily save and restore the register's state as 5906 * the conversion shouldn't be visible to a caller. 5907 */ 5908 if (may_be_null) { 5909 saved_reg = *reg; 5910 mark_ptr_not_null_reg(reg); 5911 } 5912 5913 err = check_helper_mem_access(env, regno, mem_size, true, &meta); 5914 /* Check access for BPF_WRITE */ 5915 meta.raw_mode = true; 5916 err = err ?: check_helper_mem_access(env, regno, mem_size, true, &meta); 5917 5918 if (may_be_null) 5919 *reg = saved_reg; 5920 5921 return err; 5922 } 5923 5924 static int check_kfunc_mem_size_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 5925 u32 regno) 5926 { 5927 struct bpf_reg_state *mem_reg = &cur_regs(env)[regno - 1]; 5928 bool may_be_null = type_may_be_null(mem_reg->type); 5929 struct bpf_reg_state saved_reg; 5930 struct bpf_call_arg_meta meta; 5931 int err; 5932 5933 WARN_ON_ONCE(regno < BPF_REG_2 || regno > BPF_REG_5); 5934 5935 memset(&meta, 0, sizeof(meta)); 5936 5937 if (may_be_null) { 5938 saved_reg = *mem_reg; 5939 mark_ptr_not_null_reg(mem_reg); 5940 } 5941 5942 err = check_mem_size_reg(env, reg, regno, true, &meta); 5943 /* Check access for BPF_WRITE */ 5944 meta.raw_mode = true; 5945 err = err ?: check_mem_size_reg(env, reg, regno, true, &meta); 5946 5947 if (may_be_null) 5948 *mem_reg = saved_reg; 5949 return err; 5950 } 5951 5952 /* Implementation details: 5953 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL. 5954 * bpf_obj_new returns PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL. 5955 * Two bpf_map_lookups (even with the same key) will have different reg->id. 5956 * Two separate bpf_obj_new will also have different reg->id. 5957 * For traditional PTR_TO_MAP_VALUE or PTR_TO_BTF_ID | MEM_ALLOC, the verifier 5958 * clears reg->id after value_or_null->value transition, since the verifier only 5959 * cares about the range of access to valid map value pointer and doesn't care 5960 * about actual address of the map element. 5961 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 5962 * reg->id > 0 after value_or_null->value transition. By doing so 5963 * two bpf_map_lookups will be considered two different pointers that 5964 * point to different bpf_spin_locks. Likewise for pointers to allocated objects 5965 * returned from bpf_obj_new. 5966 * The verifier allows taking only one bpf_spin_lock at a time to avoid 5967 * dead-locks. 5968 * Since only one bpf_spin_lock is allowed the checks are simpler than 5969 * reg_is_refcounted() logic. The verifier needs to remember only 5970 * one spin_lock instead of array of acquired_refs. 5971 * cur_state->active_lock remembers which map value element or allocated 5972 * object got locked and clears it after bpf_spin_unlock. 5973 */ 5974 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 5975 bool is_lock) 5976 { 5977 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5978 struct bpf_verifier_state *cur = env->cur_state; 5979 bool is_const = tnum_is_const(reg->var_off); 5980 u64 val = reg->var_off.value; 5981 struct bpf_map *map = NULL; 5982 struct btf *btf = NULL; 5983 struct btf_record *rec; 5984 5985 if (!is_const) { 5986 verbose(env, 5987 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 5988 regno); 5989 return -EINVAL; 5990 } 5991 if (reg->type == PTR_TO_MAP_VALUE) { 5992 map = reg->map_ptr; 5993 if (!map->btf) { 5994 verbose(env, 5995 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 5996 map->name); 5997 return -EINVAL; 5998 } 5999 } else { 6000 btf = reg->btf; 6001 } 6002 6003 rec = reg_btf_record(reg); 6004 if (!btf_record_has_field(rec, BPF_SPIN_LOCK)) { 6005 verbose(env, "%s '%s' has no valid bpf_spin_lock\n", map ? "map" : "local", 6006 map ? map->name : "kptr"); 6007 return -EINVAL; 6008 } 6009 if (rec->spin_lock_off != val + reg->off) { 6010 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock' that is at %d\n", 6011 val + reg->off, rec->spin_lock_off); 6012 return -EINVAL; 6013 } 6014 if (is_lock) { 6015 if (cur->active_lock.ptr) { 6016 verbose(env, 6017 "Locking two bpf_spin_locks are not allowed\n"); 6018 return -EINVAL; 6019 } 6020 if (map) 6021 cur->active_lock.ptr = map; 6022 else 6023 cur->active_lock.ptr = btf; 6024 cur->active_lock.id = reg->id; 6025 } else { 6026 struct bpf_func_state *fstate = cur_func(env); 6027 void *ptr; 6028 int i; 6029 6030 if (map) 6031 ptr = map; 6032 else 6033 ptr = btf; 6034 6035 if (!cur->active_lock.ptr) { 6036 verbose(env, "bpf_spin_unlock without taking a lock\n"); 6037 return -EINVAL; 6038 } 6039 if (cur->active_lock.ptr != ptr || 6040 cur->active_lock.id != reg->id) { 6041 verbose(env, "bpf_spin_unlock of different lock\n"); 6042 return -EINVAL; 6043 } 6044 cur->active_lock.ptr = NULL; 6045 cur->active_lock.id = 0; 6046 6047 for (i = fstate->acquired_refs - 1; i >= 0; i--) { 6048 int err; 6049 6050 /* Complain on error because this reference state cannot 6051 * be freed before this point, as bpf_spin_lock critical 6052 * section does not allow functions that release the 6053 * allocated object immediately. 6054 */ 6055 if (!fstate->refs[i].release_on_unlock) 6056 continue; 6057 err = release_reference(env, fstate->refs[i].id); 6058 if (err) { 6059 verbose(env, "failed to release release_on_unlock reference"); 6060 return err; 6061 } 6062 } 6063 } 6064 return 0; 6065 } 6066 6067 static int process_timer_func(struct bpf_verifier_env *env, int regno, 6068 struct bpf_call_arg_meta *meta) 6069 { 6070 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6071 bool is_const = tnum_is_const(reg->var_off); 6072 struct bpf_map *map = reg->map_ptr; 6073 u64 val = reg->var_off.value; 6074 6075 if (!is_const) { 6076 verbose(env, 6077 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 6078 regno); 6079 return -EINVAL; 6080 } 6081 if (!map->btf) { 6082 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 6083 map->name); 6084 return -EINVAL; 6085 } 6086 if (!btf_record_has_field(map->record, BPF_TIMER)) { 6087 verbose(env, "map '%s' has no valid bpf_timer\n", map->name); 6088 return -EINVAL; 6089 } 6090 if (map->record->timer_off != val + reg->off) { 6091 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 6092 val + reg->off, map->record->timer_off); 6093 return -EINVAL; 6094 } 6095 if (meta->map_ptr) { 6096 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 6097 return -EFAULT; 6098 } 6099 meta->map_uid = reg->map_uid; 6100 meta->map_ptr = map; 6101 return 0; 6102 } 6103 6104 static int process_kptr_func(struct bpf_verifier_env *env, int regno, 6105 struct bpf_call_arg_meta *meta) 6106 { 6107 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6108 struct bpf_map *map_ptr = reg->map_ptr; 6109 struct btf_field *kptr_field; 6110 u32 kptr_off; 6111 6112 if (!tnum_is_const(reg->var_off)) { 6113 verbose(env, 6114 "R%d doesn't have constant offset. kptr has to be at the constant offset\n", 6115 regno); 6116 return -EINVAL; 6117 } 6118 if (!map_ptr->btf) { 6119 verbose(env, "map '%s' has to have BTF in order to use bpf_kptr_xchg\n", 6120 map_ptr->name); 6121 return -EINVAL; 6122 } 6123 if (!btf_record_has_field(map_ptr->record, BPF_KPTR)) { 6124 verbose(env, "map '%s' has no valid kptr\n", map_ptr->name); 6125 return -EINVAL; 6126 } 6127 6128 meta->map_ptr = map_ptr; 6129 kptr_off = reg->off + reg->var_off.value; 6130 kptr_field = btf_record_find(map_ptr->record, kptr_off, BPF_KPTR); 6131 if (!kptr_field) { 6132 verbose(env, "off=%d doesn't point to kptr\n", kptr_off); 6133 return -EACCES; 6134 } 6135 if (kptr_field->type != BPF_KPTR_REF) { 6136 verbose(env, "off=%d kptr isn't referenced kptr\n", kptr_off); 6137 return -EACCES; 6138 } 6139 meta->kptr_field = kptr_field; 6140 return 0; 6141 } 6142 6143 /* There are two register types representing a bpf_dynptr, one is PTR_TO_STACK 6144 * which points to a stack slot, and the other is CONST_PTR_TO_DYNPTR. 6145 * 6146 * In both cases we deal with the first 8 bytes, but need to mark the next 8 6147 * bytes as STACK_DYNPTR in case of PTR_TO_STACK. In case of 6148 * CONST_PTR_TO_DYNPTR, we are guaranteed to get the beginning of the object. 6149 * 6150 * Mutability of bpf_dynptr is at two levels, one is at the level of struct 6151 * bpf_dynptr itself, i.e. whether the helper is receiving a pointer to struct 6152 * bpf_dynptr or pointer to const struct bpf_dynptr. In the former case, it can 6153 * mutate the view of the dynptr and also possibly destroy it. In the latter 6154 * case, it cannot mutate the bpf_dynptr itself but it can still mutate the 6155 * memory that dynptr points to. 6156 * 6157 * The verifier will keep track both levels of mutation (bpf_dynptr's in 6158 * reg->type and the memory's in reg->dynptr.type), but there is no support for 6159 * readonly dynptr view yet, hence only the first case is tracked and checked. 6160 * 6161 * This is consistent with how C applies the const modifier to a struct object, 6162 * where the pointer itself inside bpf_dynptr becomes const but not what it 6163 * points to. 6164 * 6165 * Helpers which do not mutate the bpf_dynptr set MEM_RDONLY in their argument 6166 * type, and declare it as 'const struct bpf_dynptr *' in their prototype. 6167 */ 6168 int process_dynptr_func(struct bpf_verifier_env *env, int regno, 6169 enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) 6170 { 6171 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6172 int spi = 0; 6173 6174 /* MEM_UNINIT and MEM_RDONLY are exclusive, when applied to an 6175 * ARG_PTR_TO_DYNPTR (or ARG_PTR_TO_DYNPTR | DYNPTR_TYPE_*): 6176 */ 6177 if ((arg_type & (MEM_UNINIT | MEM_RDONLY)) == (MEM_UNINIT | MEM_RDONLY)) { 6178 verbose(env, "verifier internal error: misconfigured dynptr helper type flags\n"); 6179 return -EFAULT; 6180 } 6181 /* CONST_PTR_TO_DYNPTR already has fixed and var_off as 0 due to 6182 * check_func_arg_reg_off's logic. We only need to check offset 6183 * and its alignment for PTR_TO_STACK. 6184 */ 6185 if (reg->type == PTR_TO_STACK) { 6186 spi = dynptr_get_spi(env, reg); 6187 if (spi < 0 && spi != -ERANGE) 6188 return spi; 6189 } 6190 6191 /* MEM_UNINIT - Points to memory that is an appropriate candidate for 6192 * constructing a mutable bpf_dynptr object. 6193 * 6194 * Currently, this is only possible with PTR_TO_STACK 6195 * pointing to a region of at least 16 bytes which doesn't 6196 * contain an existing bpf_dynptr. 6197 * 6198 * MEM_RDONLY - Points to a initialized bpf_dynptr that will not be 6199 * mutated or destroyed. However, the memory it points to 6200 * may be mutated. 6201 * 6202 * None - Points to a initialized dynptr that can be mutated and 6203 * destroyed, including mutation of the memory it points 6204 * to. 6205 */ 6206 if (arg_type & MEM_UNINIT) { 6207 if (!is_dynptr_reg_valid_uninit(env, reg, spi)) { 6208 verbose(env, "Dynptr has to be an uninitialized dynptr\n"); 6209 return -EINVAL; 6210 } 6211 6212 /* We only support one dynptr being uninitialized at the moment, 6213 * which is sufficient for the helper functions we have right now. 6214 */ 6215 if (meta->uninit_dynptr_regno) { 6216 verbose(env, "verifier internal error: multiple uninitialized dynptr args\n"); 6217 return -EFAULT; 6218 } 6219 6220 meta->uninit_dynptr_regno = regno; 6221 } else /* MEM_RDONLY and None case from above */ { 6222 int err; 6223 6224 /* For the reg->type == PTR_TO_STACK case, bpf_dynptr is never const */ 6225 if (reg->type == CONST_PTR_TO_DYNPTR && !(arg_type & MEM_RDONLY)) { 6226 verbose(env, "cannot pass pointer to const bpf_dynptr, the helper mutates it\n"); 6227 return -EINVAL; 6228 } 6229 6230 if (!is_dynptr_reg_valid_init(env, reg, spi)) { 6231 verbose(env, 6232 "Expected an initialized dynptr as arg #%d\n", 6233 regno); 6234 return -EINVAL; 6235 } 6236 6237 /* Fold modifiers (in this case, MEM_RDONLY) when checking expected type */ 6238 if (!is_dynptr_type_expected(env, reg, arg_type & ~MEM_RDONLY)) { 6239 const char *err_extra = ""; 6240 6241 switch (arg_type & DYNPTR_TYPE_FLAG_MASK) { 6242 case DYNPTR_TYPE_LOCAL: 6243 err_extra = "local"; 6244 break; 6245 case DYNPTR_TYPE_RINGBUF: 6246 err_extra = "ringbuf"; 6247 break; 6248 default: 6249 err_extra = "<unknown>"; 6250 break; 6251 } 6252 verbose(env, 6253 "Expected a dynptr of type %s as arg #%d\n", 6254 err_extra, regno); 6255 return -EINVAL; 6256 } 6257 6258 err = mark_dynptr_read(env, reg); 6259 if (err) 6260 return err; 6261 } 6262 return 0; 6263 } 6264 6265 static bool arg_type_is_mem_size(enum bpf_arg_type type) 6266 { 6267 return type == ARG_CONST_SIZE || 6268 type == ARG_CONST_SIZE_OR_ZERO; 6269 } 6270 6271 static bool arg_type_is_release(enum bpf_arg_type type) 6272 { 6273 return type & OBJ_RELEASE; 6274 } 6275 6276 static bool arg_type_is_dynptr(enum bpf_arg_type type) 6277 { 6278 return base_type(type) == ARG_PTR_TO_DYNPTR; 6279 } 6280 6281 static int int_ptr_type_to_size(enum bpf_arg_type type) 6282 { 6283 if (type == ARG_PTR_TO_INT) 6284 return sizeof(u32); 6285 else if (type == ARG_PTR_TO_LONG) 6286 return sizeof(u64); 6287 6288 return -EINVAL; 6289 } 6290 6291 static int resolve_map_arg_type(struct bpf_verifier_env *env, 6292 const struct bpf_call_arg_meta *meta, 6293 enum bpf_arg_type *arg_type) 6294 { 6295 if (!meta->map_ptr) { 6296 /* kernel subsystem misconfigured verifier */ 6297 verbose(env, "invalid map_ptr to access map->type\n"); 6298 return -EACCES; 6299 } 6300 6301 switch (meta->map_ptr->map_type) { 6302 case BPF_MAP_TYPE_SOCKMAP: 6303 case BPF_MAP_TYPE_SOCKHASH: 6304 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 6305 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 6306 } else { 6307 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 6308 return -EINVAL; 6309 } 6310 break; 6311 case BPF_MAP_TYPE_BLOOM_FILTER: 6312 if (meta->func_id == BPF_FUNC_map_peek_elem) 6313 *arg_type = ARG_PTR_TO_MAP_VALUE; 6314 break; 6315 default: 6316 break; 6317 } 6318 return 0; 6319 } 6320 6321 struct bpf_reg_types { 6322 const enum bpf_reg_type types[10]; 6323 u32 *btf_id; 6324 }; 6325 6326 static const struct bpf_reg_types sock_types = { 6327 .types = { 6328 PTR_TO_SOCK_COMMON, 6329 PTR_TO_SOCKET, 6330 PTR_TO_TCP_SOCK, 6331 PTR_TO_XDP_SOCK, 6332 }, 6333 }; 6334 6335 #ifdef CONFIG_NET 6336 static const struct bpf_reg_types btf_id_sock_common_types = { 6337 .types = { 6338 PTR_TO_SOCK_COMMON, 6339 PTR_TO_SOCKET, 6340 PTR_TO_TCP_SOCK, 6341 PTR_TO_XDP_SOCK, 6342 PTR_TO_BTF_ID, 6343 PTR_TO_BTF_ID | PTR_TRUSTED, 6344 }, 6345 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 6346 }; 6347 #endif 6348 6349 static const struct bpf_reg_types mem_types = { 6350 .types = { 6351 PTR_TO_STACK, 6352 PTR_TO_PACKET, 6353 PTR_TO_PACKET_META, 6354 PTR_TO_MAP_KEY, 6355 PTR_TO_MAP_VALUE, 6356 PTR_TO_MEM, 6357 PTR_TO_MEM | MEM_RINGBUF, 6358 PTR_TO_BUF, 6359 }, 6360 }; 6361 6362 static const struct bpf_reg_types int_ptr_types = { 6363 .types = { 6364 PTR_TO_STACK, 6365 PTR_TO_PACKET, 6366 PTR_TO_PACKET_META, 6367 PTR_TO_MAP_KEY, 6368 PTR_TO_MAP_VALUE, 6369 }, 6370 }; 6371 6372 static const struct bpf_reg_types spin_lock_types = { 6373 .types = { 6374 PTR_TO_MAP_VALUE, 6375 PTR_TO_BTF_ID | MEM_ALLOC, 6376 } 6377 }; 6378 6379 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 6380 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 6381 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 6382 static const struct bpf_reg_types ringbuf_mem_types = { .types = { PTR_TO_MEM | MEM_RINGBUF } }; 6383 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 6384 static const struct bpf_reg_types btf_ptr_types = { 6385 .types = { 6386 PTR_TO_BTF_ID, 6387 PTR_TO_BTF_ID | PTR_TRUSTED, 6388 PTR_TO_BTF_ID | MEM_RCU, 6389 }, 6390 }; 6391 static const struct bpf_reg_types percpu_btf_ptr_types = { 6392 .types = { 6393 PTR_TO_BTF_ID | MEM_PERCPU, 6394 PTR_TO_BTF_ID | MEM_PERCPU | PTR_TRUSTED, 6395 } 6396 }; 6397 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 6398 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 6399 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 6400 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 6401 static const struct bpf_reg_types kptr_types = { .types = { PTR_TO_MAP_VALUE } }; 6402 static const struct bpf_reg_types dynptr_types = { 6403 .types = { 6404 PTR_TO_STACK, 6405 CONST_PTR_TO_DYNPTR, 6406 } 6407 }; 6408 6409 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 6410 [ARG_PTR_TO_MAP_KEY] = &mem_types, 6411 [ARG_PTR_TO_MAP_VALUE] = &mem_types, 6412 [ARG_CONST_SIZE] = &scalar_types, 6413 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 6414 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 6415 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 6416 [ARG_PTR_TO_CTX] = &context_types, 6417 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 6418 #ifdef CONFIG_NET 6419 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 6420 #endif 6421 [ARG_PTR_TO_SOCKET] = &fullsock_types, 6422 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 6423 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 6424 [ARG_PTR_TO_MEM] = &mem_types, 6425 [ARG_PTR_TO_RINGBUF_MEM] = &ringbuf_mem_types, 6426 [ARG_PTR_TO_INT] = &int_ptr_types, 6427 [ARG_PTR_TO_LONG] = &int_ptr_types, 6428 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 6429 [ARG_PTR_TO_FUNC] = &func_ptr_types, 6430 [ARG_PTR_TO_STACK] = &stack_ptr_types, 6431 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 6432 [ARG_PTR_TO_TIMER] = &timer_types, 6433 [ARG_PTR_TO_KPTR] = &kptr_types, 6434 [ARG_PTR_TO_DYNPTR] = &dynptr_types, 6435 }; 6436 6437 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 6438 enum bpf_arg_type arg_type, 6439 const u32 *arg_btf_id, 6440 struct bpf_call_arg_meta *meta) 6441 { 6442 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6443 enum bpf_reg_type expected, type = reg->type; 6444 const struct bpf_reg_types *compatible; 6445 int i, j; 6446 6447 compatible = compatible_reg_types[base_type(arg_type)]; 6448 if (!compatible) { 6449 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 6450 return -EFAULT; 6451 } 6452 6453 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 6454 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 6455 * 6456 * Same for MAYBE_NULL: 6457 * 6458 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 6459 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 6460 * 6461 * Therefore we fold these flags depending on the arg_type before comparison. 6462 */ 6463 if (arg_type & MEM_RDONLY) 6464 type &= ~MEM_RDONLY; 6465 if (arg_type & PTR_MAYBE_NULL) 6466 type &= ~PTR_MAYBE_NULL; 6467 6468 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 6469 expected = compatible->types[i]; 6470 if (expected == NOT_INIT) 6471 break; 6472 6473 if (type == expected) 6474 goto found; 6475 } 6476 6477 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 6478 for (j = 0; j + 1 < i; j++) 6479 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 6480 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 6481 return -EACCES; 6482 6483 found: 6484 if (reg->type == PTR_TO_BTF_ID || reg->type & PTR_TRUSTED) { 6485 /* For bpf_sk_release, it needs to match against first member 6486 * 'struct sock_common', hence make an exception for it. This 6487 * allows bpf_sk_release to work for multiple socket types. 6488 */ 6489 bool strict_type_match = arg_type_is_release(arg_type) && 6490 meta->func_id != BPF_FUNC_sk_release; 6491 6492 if (!arg_btf_id) { 6493 if (!compatible->btf_id) { 6494 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 6495 return -EFAULT; 6496 } 6497 arg_btf_id = compatible->btf_id; 6498 } 6499 6500 if (meta->func_id == BPF_FUNC_kptr_xchg) { 6501 if (map_kptr_match_type(env, meta->kptr_field, reg, regno)) 6502 return -EACCES; 6503 } else { 6504 if (arg_btf_id == BPF_PTR_POISON) { 6505 verbose(env, "verifier internal error:"); 6506 verbose(env, "R%d has non-overwritten BPF_PTR_POISON type\n", 6507 regno); 6508 return -EACCES; 6509 } 6510 6511 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 6512 btf_vmlinux, *arg_btf_id, 6513 strict_type_match)) { 6514 verbose(env, "R%d is of type %s but %s is expected\n", 6515 regno, kernel_type_name(reg->btf, reg->btf_id), 6516 kernel_type_name(btf_vmlinux, *arg_btf_id)); 6517 return -EACCES; 6518 } 6519 } 6520 } else if (type_is_alloc(reg->type)) { 6521 if (meta->func_id != BPF_FUNC_spin_lock && meta->func_id != BPF_FUNC_spin_unlock) { 6522 verbose(env, "verifier internal error: unimplemented handling of MEM_ALLOC\n"); 6523 return -EFAULT; 6524 } 6525 } 6526 6527 return 0; 6528 } 6529 6530 int check_func_arg_reg_off(struct bpf_verifier_env *env, 6531 const struct bpf_reg_state *reg, int regno, 6532 enum bpf_arg_type arg_type) 6533 { 6534 u32 type = reg->type; 6535 6536 /* When referenced register is passed to release function, its fixed 6537 * offset must be 0. 6538 * 6539 * We will check arg_type_is_release reg has ref_obj_id when storing 6540 * meta->release_regno. 6541 */ 6542 if (arg_type_is_release(arg_type)) { 6543 /* ARG_PTR_TO_DYNPTR with OBJ_RELEASE is a bit special, as it 6544 * may not directly point to the object being released, but to 6545 * dynptr pointing to such object, which might be at some offset 6546 * on the stack. In that case, we simply to fallback to the 6547 * default handling. 6548 */ 6549 if (arg_type_is_dynptr(arg_type) && type == PTR_TO_STACK) 6550 return 0; 6551 /* Doing check_ptr_off_reg check for the offset will catch this 6552 * because fixed_off_ok is false, but checking here allows us 6553 * to give the user a better error message. 6554 */ 6555 if (reg->off) { 6556 verbose(env, "R%d must have zero offset when passed to release func or trusted arg to kfunc\n", 6557 regno); 6558 return -EINVAL; 6559 } 6560 return __check_ptr_off_reg(env, reg, regno, false); 6561 } 6562 6563 switch (type) { 6564 /* Pointer types where both fixed and variable offset is explicitly allowed: */ 6565 case PTR_TO_STACK: 6566 case PTR_TO_PACKET: 6567 case PTR_TO_PACKET_META: 6568 case PTR_TO_MAP_KEY: 6569 case PTR_TO_MAP_VALUE: 6570 case PTR_TO_MEM: 6571 case PTR_TO_MEM | MEM_RDONLY: 6572 case PTR_TO_MEM | MEM_RINGBUF: 6573 case PTR_TO_BUF: 6574 case PTR_TO_BUF | MEM_RDONLY: 6575 case SCALAR_VALUE: 6576 return 0; 6577 /* All the rest must be rejected, except PTR_TO_BTF_ID which allows 6578 * fixed offset. 6579 */ 6580 case PTR_TO_BTF_ID: 6581 case PTR_TO_BTF_ID | MEM_ALLOC: 6582 case PTR_TO_BTF_ID | PTR_TRUSTED: 6583 case PTR_TO_BTF_ID | MEM_RCU: 6584 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED: 6585 /* When referenced PTR_TO_BTF_ID is passed to release function, 6586 * its fixed offset must be 0. In the other cases, fixed offset 6587 * can be non-zero. This was already checked above. So pass 6588 * fixed_off_ok as true to allow fixed offset for all other 6589 * cases. var_off always must be 0 for PTR_TO_BTF_ID, hence we 6590 * still need to do checks instead of returning. 6591 */ 6592 return __check_ptr_off_reg(env, reg, regno, true); 6593 default: 6594 return __check_ptr_off_reg(env, reg, regno, false); 6595 } 6596 } 6597 6598 static int dynptr_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 6599 { 6600 struct bpf_func_state *state = func(env, reg); 6601 int spi; 6602 6603 if (reg->type == CONST_PTR_TO_DYNPTR) 6604 return reg->id; 6605 spi = dynptr_get_spi(env, reg); 6606 if (spi < 0) 6607 return spi; 6608 return state->stack[spi].spilled_ptr.id; 6609 } 6610 6611 static int dynptr_ref_obj_id(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 6612 { 6613 struct bpf_func_state *state = func(env, reg); 6614 int spi; 6615 6616 if (reg->type == CONST_PTR_TO_DYNPTR) 6617 return reg->ref_obj_id; 6618 spi = dynptr_get_spi(env, reg); 6619 if (spi < 0) 6620 return spi; 6621 return state->stack[spi].spilled_ptr.ref_obj_id; 6622 } 6623 6624 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 6625 struct bpf_call_arg_meta *meta, 6626 const struct bpf_func_proto *fn) 6627 { 6628 u32 regno = BPF_REG_1 + arg; 6629 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 6630 enum bpf_arg_type arg_type = fn->arg_type[arg]; 6631 enum bpf_reg_type type = reg->type; 6632 u32 *arg_btf_id = NULL; 6633 int err = 0; 6634 6635 if (arg_type == ARG_DONTCARE) 6636 return 0; 6637 6638 err = check_reg_arg(env, regno, SRC_OP); 6639 if (err) 6640 return err; 6641 6642 if (arg_type == ARG_ANYTHING) { 6643 if (is_pointer_value(env, regno)) { 6644 verbose(env, "R%d leaks addr into helper function\n", 6645 regno); 6646 return -EACCES; 6647 } 6648 return 0; 6649 } 6650 6651 if (type_is_pkt_pointer(type) && 6652 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 6653 verbose(env, "helper access to the packet is not allowed\n"); 6654 return -EACCES; 6655 } 6656 6657 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE) { 6658 err = resolve_map_arg_type(env, meta, &arg_type); 6659 if (err) 6660 return err; 6661 } 6662 6663 if (register_is_null(reg) && type_may_be_null(arg_type)) 6664 /* A NULL register has a SCALAR_VALUE type, so skip 6665 * type checking. 6666 */ 6667 goto skip_type_check; 6668 6669 /* arg_btf_id and arg_size are in a union. */ 6670 if (base_type(arg_type) == ARG_PTR_TO_BTF_ID || 6671 base_type(arg_type) == ARG_PTR_TO_SPIN_LOCK) 6672 arg_btf_id = fn->arg_btf_id[arg]; 6673 6674 err = check_reg_type(env, regno, arg_type, arg_btf_id, meta); 6675 if (err) 6676 return err; 6677 6678 err = check_func_arg_reg_off(env, reg, regno, arg_type); 6679 if (err) 6680 return err; 6681 6682 skip_type_check: 6683 if (arg_type_is_release(arg_type)) { 6684 if (arg_type_is_dynptr(arg_type)) { 6685 struct bpf_func_state *state = func(env, reg); 6686 int spi; 6687 6688 /* Only dynptr created on stack can be released, thus 6689 * the get_spi and stack state checks for spilled_ptr 6690 * should only be done before process_dynptr_func for 6691 * PTR_TO_STACK. 6692 */ 6693 if (reg->type == PTR_TO_STACK) { 6694 spi = dynptr_get_spi(env, reg); 6695 if (spi < 0 || !state->stack[spi].spilled_ptr.ref_obj_id) { 6696 verbose(env, "arg %d is an unacquired reference\n", regno); 6697 return -EINVAL; 6698 } 6699 } else { 6700 verbose(env, "cannot release unowned const bpf_dynptr\n"); 6701 return -EINVAL; 6702 } 6703 } else if (!reg->ref_obj_id && !register_is_null(reg)) { 6704 verbose(env, "R%d must be referenced when passed to release function\n", 6705 regno); 6706 return -EINVAL; 6707 } 6708 if (meta->release_regno) { 6709 verbose(env, "verifier internal error: more than one release argument\n"); 6710 return -EFAULT; 6711 } 6712 meta->release_regno = regno; 6713 } 6714 6715 if (reg->ref_obj_id) { 6716 if (meta->ref_obj_id) { 6717 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 6718 regno, reg->ref_obj_id, 6719 meta->ref_obj_id); 6720 return -EFAULT; 6721 } 6722 meta->ref_obj_id = reg->ref_obj_id; 6723 } 6724 6725 switch (base_type(arg_type)) { 6726 case ARG_CONST_MAP_PTR: 6727 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 6728 if (meta->map_ptr) { 6729 /* Use map_uid (which is unique id of inner map) to reject: 6730 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 6731 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 6732 * if (inner_map1 && inner_map2) { 6733 * timer = bpf_map_lookup_elem(inner_map1); 6734 * if (timer) 6735 * // mismatch would have been allowed 6736 * bpf_timer_init(timer, inner_map2); 6737 * } 6738 * 6739 * Comparing map_ptr is enough to distinguish normal and outer maps. 6740 */ 6741 if (meta->map_ptr != reg->map_ptr || 6742 meta->map_uid != reg->map_uid) { 6743 verbose(env, 6744 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 6745 meta->map_uid, reg->map_uid); 6746 return -EINVAL; 6747 } 6748 } 6749 meta->map_ptr = reg->map_ptr; 6750 meta->map_uid = reg->map_uid; 6751 break; 6752 case ARG_PTR_TO_MAP_KEY: 6753 /* bpf_map_xxx(..., map_ptr, ..., key) call: 6754 * check that [key, key + map->key_size) are within 6755 * stack limits and initialized 6756 */ 6757 if (!meta->map_ptr) { 6758 /* in function declaration map_ptr must come before 6759 * map_key, so that it's verified and known before 6760 * we have to check map_key here. Otherwise it means 6761 * that kernel subsystem misconfigured verifier 6762 */ 6763 verbose(env, "invalid map_ptr to access map->key\n"); 6764 return -EACCES; 6765 } 6766 err = check_helper_mem_access(env, regno, 6767 meta->map_ptr->key_size, false, 6768 NULL); 6769 break; 6770 case ARG_PTR_TO_MAP_VALUE: 6771 if (type_may_be_null(arg_type) && register_is_null(reg)) 6772 return 0; 6773 6774 /* bpf_map_xxx(..., map_ptr, ..., value) call: 6775 * check [value, value + map->value_size) validity 6776 */ 6777 if (!meta->map_ptr) { 6778 /* kernel subsystem misconfigured verifier */ 6779 verbose(env, "invalid map_ptr to access map->value\n"); 6780 return -EACCES; 6781 } 6782 meta->raw_mode = arg_type & MEM_UNINIT; 6783 err = check_helper_mem_access(env, regno, 6784 meta->map_ptr->value_size, false, 6785 meta); 6786 break; 6787 case ARG_PTR_TO_PERCPU_BTF_ID: 6788 if (!reg->btf_id) { 6789 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 6790 return -EACCES; 6791 } 6792 meta->ret_btf = reg->btf; 6793 meta->ret_btf_id = reg->btf_id; 6794 break; 6795 case ARG_PTR_TO_SPIN_LOCK: 6796 if (meta->func_id == BPF_FUNC_spin_lock) { 6797 err = process_spin_lock(env, regno, true); 6798 if (err) 6799 return err; 6800 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 6801 err = process_spin_lock(env, regno, false); 6802 if (err) 6803 return err; 6804 } else { 6805 verbose(env, "verifier internal error\n"); 6806 return -EFAULT; 6807 } 6808 break; 6809 case ARG_PTR_TO_TIMER: 6810 err = process_timer_func(env, regno, meta); 6811 if (err) 6812 return err; 6813 break; 6814 case ARG_PTR_TO_FUNC: 6815 meta->subprogno = reg->subprogno; 6816 break; 6817 case ARG_PTR_TO_MEM: 6818 /* The access to this pointer is only checked when we hit the 6819 * next is_mem_size argument below. 6820 */ 6821 meta->raw_mode = arg_type & MEM_UNINIT; 6822 if (arg_type & MEM_FIXED_SIZE) { 6823 err = check_helper_mem_access(env, regno, 6824 fn->arg_size[arg], false, 6825 meta); 6826 } 6827 break; 6828 case ARG_CONST_SIZE: 6829 err = check_mem_size_reg(env, reg, regno, false, meta); 6830 break; 6831 case ARG_CONST_SIZE_OR_ZERO: 6832 err = check_mem_size_reg(env, reg, regno, true, meta); 6833 break; 6834 case ARG_PTR_TO_DYNPTR: 6835 err = process_dynptr_func(env, regno, arg_type, meta); 6836 if (err) 6837 return err; 6838 break; 6839 case ARG_CONST_ALLOC_SIZE_OR_ZERO: 6840 if (!tnum_is_const(reg->var_off)) { 6841 verbose(env, "R%d is not a known constant'\n", 6842 regno); 6843 return -EACCES; 6844 } 6845 meta->mem_size = reg->var_off.value; 6846 err = mark_chain_precision(env, regno); 6847 if (err) 6848 return err; 6849 break; 6850 case ARG_PTR_TO_INT: 6851 case ARG_PTR_TO_LONG: 6852 { 6853 int size = int_ptr_type_to_size(arg_type); 6854 6855 err = check_helper_mem_access(env, regno, size, false, meta); 6856 if (err) 6857 return err; 6858 err = check_ptr_alignment(env, reg, 0, size, true); 6859 break; 6860 } 6861 case ARG_PTR_TO_CONST_STR: 6862 { 6863 struct bpf_map *map = reg->map_ptr; 6864 int map_off; 6865 u64 map_addr; 6866 char *str_ptr; 6867 6868 if (!bpf_map_is_rdonly(map)) { 6869 verbose(env, "R%d does not point to a readonly map'\n", regno); 6870 return -EACCES; 6871 } 6872 6873 if (!tnum_is_const(reg->var_off)) { 6874 verbose(env, "R%d is not a constant address'\n", regno); 6875 return -EACCES; 6876 } 6877 6878 if (!map->ops->map_direct_value_addr) { 6879 verbose(env, "no direct value access support for this map type\n"); 6880 return -EACCES; 6881 } 6882 6883 err = check_map_access(env, regno, reg->off, 6884 map->value_size - reg->off, false, 6885 ACCESS_HELPER); 6886 if (err) 6887 return err; 6888 6889 map_off = reg->off + reg->var_off.value; 6890 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 6891 if (err) { 6892 verbose(env, "direct value access on string failed\n"); 6893 return err; 6894 } 6895 6896 str_ptr = (char *)(long)(map_addr); 6897 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 6898 verbose(env, "string is not zero-terminated\n"); 6899 return -EINVAL; 6900 } 6901 break; 6902 } 6903 case ARG_PTR_TO_KPTR: 6904 err = process_kptr_func(env, regno, meta); 6905 if (err) 6906 return err; 6907 break; 6908 } 6909 6910 return err; 6911 } 6912 6913 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 6914 { 6915 enum bpf_attach_type eatype = env->prog->expected_attach_type; 6916 enum bpf_prog_type type = resolve_prog_type(env->prog); 6917 6918 if (func_id != BPF_FUNC_map_update_elem) 6919 return false; 6920 6921 /* It's not possible to get access to a locked struct sock in these 6922 * contexts, so updating is safe. 6923 */ 6924 switch (type) { 6925 case BPF_PROG_TYPE_TRACING: 6926 if (eatype == BPF_TRACE_ITER) 6927 return true; 6928 break; 6929 case BPF_PROG_TYPE_SOCKET_FILTER: 6930 case BPF_PROG_TYPE_SCHED_CLS: 6931 case BPF_PROG_TYPE_SCHED_ACT: 6932 case BPF_PROG_TYPE_XDP: 6933 case BPF_PROG_TYPE_SK_REUSEPORT: 6934 case BPF_PROG_TYPE_FLOW_DISSECTOR: 6935 case BPF_PROG_TYPE_SK_LOOKUP: 6936 return true; 6937 default: 6938 break; 6939 } 6940 6941 verbose(env, "cannot update sockmap in this context\n"); 6942 return false; 6943 } 6944 6945 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 6946 { 6947 return env->prog->jit_requested && 6948 bpf_jit_supports_subprog_tailcalls(); 6949 } 6950 6951 static int check_map_func_compatibility(struct bpf_verifier_env *env, 6952 struct bpf_map *map, int func_id) 6953 { 6954 if (!map) 6955 return 0; 6956 6957 /* We need a two way check, first is from map perspective ... */ 6958 switch (map->map_type) { 6959 case BPF_MAP_TYPE_PROG_ARRAY: 6960 if (func_id != BPF_FUNC_tail_call) 6961 goto error; 6962 break; 6963 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 6964 if (func_id != BPF_FUNC_perf_event_read && 6965 func_id != BPF_FUNC_perf_event_output && 6966 func_id != BPF_FUNC_skb_output && 6967 func_id != BPF_FUNC_perf_event_read_value && 6968 func_id != BPF_FUNC_xdp_output) 6969 goto error; 6970 break; 6971 case BPF_MAP_TYPE_RINGBUF: 6972 if (func_id != BPF_FUNC_ringbuf_output && 6973 func_id != BPF_FUNC_ringbuf_reserve && 6974 func_id != BPF_FUNC_ringbuf_query && 6975 func_id != BPF_FUNC_ringbuf_reserve_dynptr && 6976 func_id != BPF_FUNC_ringbuf_submit_dynptr && 6977 func_id != BPF_FUNC_ringbuf_discard_dynptr) 6978 goto error; 6979 break; 6980 case BPF_MAP_TYPE_USER_RINGBUF: 6981 if (func_id != BPF_FUNC_user_ringbuf_drain) 6982 goto error; 6983 break; 6984 case BPF_MAP_TYPE_STACK_TRACE: 6985 if (func_id != BPF_FUNC_get_stackid) 6986 goto error; 6987 break; 6988 case BPF_MAP_TYPE_CGROUP_ARRAY: 6989 if (func_id != BPF_FUNC_skb_under_cgroup && 6990 func_id != BPF_FUNC_current_task_under_cgroup) 6991 goto error; 6992 break; 6993 case BPF_MAP_TYPE_CGROUP_STORAGE: 6994 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 6995 if (func_id != BPF_FUNC_get_local_storage) 6996 goto error; 6997 break; 6998 case BPF_MAP_TYPE_DEVMAP: 6999 case BPF_MAP_TYPE_DEVMAP_HASH: 7000 if (func_id != BPF_FUNC_redirect_map && 7001 func_id != BPF_FUNC_map_lookup_elem) 7002 goto error; 7003 break; 7004 /* Restrict bpf side of cpumap and xskmap, open when use-cases 7005 * appear. 7006 */ 7007 case BPF_MAP_TYPE_CPUMAP: 7008 if (func_id != BPF_FUNC_redirect_map) 7009 goto error; 7010 break; 7011 case BPF_MAP_TYPE_XSKMAP: 7012 if (func_id != BPF_FUNC_redirect_map && 7013 func_id != BPF_FUNC_map_lookup_elem) 7014 goto error; 7015 break; 7016 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 7017 case BPF_MAP_TYPE_HASH_OF_MAPS: 7018 if (func_id != BPF_FUNC_map_lookup_elem) 7019 goto error; 7020 break; 7021 case BPF_MAP_TYPE_SOCKMAP: 7022 if (func_id != BPF_FUNC_sk_redirect_map && 7023 func_id != BPF_FUNC_sock_map_update && 7024 func_id != BPF_FUNC_map_delete_elem && 7025 func_id != BPF_FUNC_msg_redirect_map && 7026 func_id != BPF_FUNC_sk_select_reuseport && 7027 func_id != BPF_FUNC_map_lookup_elem && 7028 !may_update_sockmap(env, func_id)) 7029 goto error; 7030 break; 7031 case BPF_MAP_TYPE_SOCKHASH: 7032 if (func_id != BPF_FUNC_sk_redirect_hash && 7033 func_id != BPF_FUNC_sock_hash_update && 7034 func_id != BPF_FUNC_map_delete_elem && 7035 func_id != BPF_FUNC_msg_redirect_hash && 7036 func_id != BPF_FUNC_sk_select_reuseport && 7037 func_id != BPF_FUNC_map_lookup_elem && 7038 !may_update_sockmap(env, func_id)) 7039 goto error; 7040 break; 7041 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 7042 if (func_id != BPF_FUNC_sk_select_reuseport) 7043 goto error; 7044 break; 7045 case BPF_MAP_TYPE_QUEUE: 7046 case BPF_MAP_TYPE_STACK: 7047 if (func_id != BPF_FUNC_map_peek_elem && 7048 func_id != BPF_FUNC_map_pop_elem && 7049 func_id != BPF_FUNC_map_push_elem) 7050 goto error; 7051 break; 7052 case BPF_MAP_TYPE_SK_STORAGE: 7053 if (func_id != BPF_FUNC_sk_storage_get && 7054 func_id != BPF_FUNC_sk_storage_delete) 7055 goto error; 7056 break; 7057 case BPF_MAP_TYPE_INODE_STORAGE: 7058 if (func_id != BPF_FUNC_inode_storage_get && 7059 func_id != BPF_FUNC_inode_storage_delete) 7060 goto error; 7061 break; 7062 case BPF_MAP_TYPE_TASK_STORAGE: 7063 if (func_id != BPF_FUNC_task_storage_get && 7064 func_id != BPF_FUNC_task_storage_delete) 7065 goto error; 7066 break; 7067 case BPF_MAP_TYPE_CGRP_STORAGE: 7068 if (func_id != BPF_FUNC_cgrp_storage_get && 7069 func_id != BPF_FUNC_cgrp_storage_delete) 7070 goto error; 7071 break; 7072 case BPF_MAP_TYPE_BLOOM_FILTER: 7073 if (func_id != BPF_FUNC_map_peek_elem && 7074 func_id != BPF_FUNC_map_push_elem) 7075 goto error; 7076 break; 7077 default: 7078 break; 7079 } 7080 7081 /* ... and second from the function itself. */ 7082 switch (func_id) { 7083 case BPF_FUNC_tail_call: 7084 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 7085 goto error; 7086 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 7087 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 7088 return -EINVAL; 7089 } 7090 break; 7091 case BPF_FUNC_perf_event_read: 7092 case BPF_FUNC_perf_event_output: 7093 case BPF_FUNC_perf_event_read_value: 7094 case BPF_FUNC_skb_output: 7095 case BPF_FUNC_xdp_output: 7096 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 7097 goto error; 7098 break; 7099 case BPF_FUNC_ringbuf_output: 7100 case BPF_FUNC_ringbuf_reserve: 7101 case BPF_FUNC_ringbuf_query: 7102 case BPF_FUNC_ringbuf_reserve_dynptr: 7103 case BPF_FUNC_ringbuf_submit_dynptr: 7104 case BPF_FUNC_ringbuf_discard_dynptr: 7105 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 7106 goto error; 7107 break; 7108 case BPF_FUNC_user_ringbuf_drain: 7109 if (map->map_type != BPF_MAP_TYPE_USER_RINGBUF) 7110 goto error; 7111 break; 7112 case BPF_FUNC_get_stackid: 7113 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 7114 goto error; 7115 break; 7116 case BPF_FUNC_current_task_under_cgroup: 7117 case BPF_FUNC_skb_under_cgroup: 7118 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 7119 goto error; 7120 break; 7121 case BPF_FUNC_redirect_map: 7122 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 7123 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 7124 map->map_type != BPF_MAP_TYPE_CPUMAP && 7125 map->map_type != BPF_MAP_TYPE_XSKMAP) 7126 goto error; 7127 break; 7128 case BPF_FUNC_sk_redirect_map: 7129 case BPF_FUNC_msg_redirect_map: 7130 case BPF_FUNC_sock_map_update: 7131 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 7132 goto error; 7133 break; 7134 case BPF_FUNC_sk_redirect_hash: 7135 case BPF_FUNC_msg_redirect_hash: 7136 case BPF_FUNC_sock_hash_update: 7137 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 7138 goto error; 7139 break; 7140 case BPF_FUNC_get_local_storage: 7141 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 7142 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 7143 goto error; 7144 break; 7145 case BPF_FUNC_sk_select_reuseport: 7146 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 7147 map->map_type != BPF_MAP_TYPE_SOCKMAP && 7148 map->map_type != BPF_MAP_TYPE_SOCKHASH) 7149 goto error; 7150 break; 7151 case BPF_FUNC_map_pop_elem: 7152 if (map->map_type != BPF_MAP_TYPE_QUEUE && 7153 map->map_type != BPF_MAP_TYPE_STACK) 7154 goto error; 7155 break; 7156 case BPF_FUNC_map_peek_elem: 7157 case BPF_FUNC_map_push_elem: 7158 if (map->map_type != BPF_MAP_TYPE_QUEUE && 7159 map->map_type != BPF_MAP_TYPE_STACK && 7160 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 7161 goto error; 7162 break; 7163 case BPF_FUNC_map_lookup_percpu_elem: 7164 if (map->map_type != BPF_MAP_TYPE_PERCPU_ARRAY && 7165 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 7166 map->map_type != BPF_MAP_TYPE_LRU_PERCPU_HASH) 7167 goto error; 7168 break; 7169 case BPF_FUNC_sk_storage_get: 7170 case BPF_FUNC_sk_storage_delete: 7171 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 7172 goto error; 7173 break; 7174 case BPF_FUNC_inode_storage_get: 7175 case BPF_FUNC_inode_storage_delete: 7176 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 7177 goto error; 7178 break; 7179 case BPF_FUNC_task_storage_get: 7180 case BPF_FUNC_task_storage_delete: 7181 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 7182 goto error; 7183 break; 7184 case BPF_FUNC_cgrp_storage_get: 7185 case BPF_FUNC_cgrp_storage_delete: 7186 if (map->map_type != BPF_MAP_TYPE_CGRP_STORAGE) 7187 goto error; 7188 break; 7189 default: 7190 break; 7191 } 7192 7193 return 0; 7194 error: 7195 verbose(env, "cannot pass map_type %d into func %s#%d\n", 7196 map->map_type, func_id_name(func_id), func_id); 7197 return -EINVAL; 7198 } 7199 7200 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 7201 { 7202 int count = 0; 7203 7204 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 7205 count++; 7206 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 7207 count++; 7208 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 7209 count++; 7210 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 7211 count++; 7212 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 7213 count++; 7214 7215 /* We only support one arg being in raw mode at the moment, 7216 * which is sufficient for the helper functions we have 7217 * right now. 7218 */ 7219 return count <= 1; 7220 } 7221 7222 static bool check_args_pair_invalid(const struct bpf_func_proto *fn, int arg) 7223 { 7224 bool is_fixed = fn->arg_type[arg] & MEM_FIXED_SIZE; 7225 bool has_size = fn->arg_size[arg] != 0; 7226 bool is_next_size = false; 7227 7228 if (arg + 1 < ARRAY_SIZE(fn->arg_type)) 7229 is_next_size = arg_type_is_mem_size(fn->arg_type[arg + 1]); 7230 7231 if (base_type(fn->arg_type[arg]) != ARG_PTR_TO_MEM) 7232 return is_next_size; 7233 7234 return has_size == is_next_size || is_next_size == is_fixed; 7235 } 7236 7237 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 7238 { 7239 /* bpf_xxx(..., buf, len) call will access 'len' 7240 * bytes from memory 'buf'. Both arg types need 7241 * to be paired, so make sure there's no buggy 7242 * helper function specification. 7243 */ 7244 if (arg_type_is_mem_size(fn->arg1_type) || 7245 check_args_pair_invalid(fn, 0) || 7246 check_args_pair_invalid(fn, 1) || 7247 check_args_pair_invalid(fn, 2) || 7248 check_args_pair_invalid(fn, 3) || 7249 check_args_pair_invalid(fn, 4)) 7250 return false; 7251 7252 return true; 7253 } 7254 7255 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 7256 { 7257 int i; 7258 7259 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 7260 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_BTF_ID) 7261 return !!fn->arg_btf_id[i]; 7262 if (base_type(fn->arg_type[i]) == ARG_PTR_TO_SPIN_LOCK) 7263 return fn->arg_btf_id[i] == BPF_PTR_POISON; 7264 if (base_type(fn->arg_type[i]) != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i] && 7265 /* arg_btf_id and arg_size are in a union. */ 7266 (base_type(fn->arg_type[i]) != ARG_PTR_TO_MEM || 7267 !(fn->arg_type[i] & MEM_FIXED_SIZE))) 7268 return false; 7269 } 7270 7271 return true; 7272 } 7273 7274 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 7275 { 7276 return check_raw_mode_ok(fn) && 7277 check_arg_pair_ok(fn) && 7278 check_btf_id_ok(fn) ? 0 : -EINVAL; 7279 } 7280 7281 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 7282 * are now invalid, so turn them into unknown SCALAR_VALUE. 7283 */ 7284 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 7285 { 7286 struct bpf_func_state *state; 7287 struct bpf_reg_state *reg; 7288 7289 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 7290 if (reg_is_pkt_pointer_any(reg)) 7291 __mark_reg_unknown(env, reg); 7292 })); 7293 } 7294 7295 enum { 7296 AT_PKT_END = -1, 7297 BEYOND_PKT_END = -2, 7298 }; 7299 7300 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 7301 { 7302 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7303 struct bpf_reg_state *reg = &state->regs[regn]; 7304 7305 if (reg->type != PTR_TO_PACKET) 7306 /* PTR_TO_PACKET_META is not supported yet */ 7307 return; 7308 7309 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 7310 * How far beyond pkt_end it goes is unknown. 7311 * if (!range_open) it's the case of pkt >= pkt_end 7312 * if (range_open) it's the case of pkt > pkt_end 7313 * hence this pointer is at least 1 byte bigger than pkt_end 7314 */ 7315 if (range_open) 7316 reg->range = BEYOND_PKT_END; 7317 else 7318 reg->range = AT_PKT_END; 7319 } 7320 7321 /* The pointer with the specified id has released its reference to kernel 7322 * resources. Identify all copies of the same pointer and clear the reference. 7323 */ 7324 static int release_reference(struct bpf_verifier_env *env, 7325 int ref_obj_id) 7326 { 7327 struct bpf_func_state *state; 7328 struct bpf_reg_state *reg; 7329 int err; 7330 7331 err = release_reference_state(cur_func(env), ref_obj_id); 7332 if (err) 7333 return err; 7334 7335 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 7336 if (reg->ref_obj_id == ref_obj_id) { 7337 if (!env->allow_ptr_leaks) 7338 __mark_reg_not_init(env, reg); 7339 else 7340 __mark_reg_unknown(env, reg); 7341 } 7342 })); 7343 7344 return 0; 7345 } 7346 7347 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 7348 struct bpf_reg_state *regs) 7349 { 7350 int i; 7351 7352 /* after the call registers r0 - r5 were scratched */ 7353 for (i = 0; i < CALLER_SAVED_REGS; i++) { 7354 mark_reg_not_init(env, regs, caller_saved[i]); 7355 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 7356 } 7357 } 7358 7359 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 7360 struct bpf_func_state *caller, 7361 struct bpf_func_state *callee, 7362 int insn_idx); 7363 7364 static int set_callee_state(struct bpf_verifier_env *env, 7365 struct bpf_func_state *caller, 7366 struct bpf_func_state *callee, int insn_idx); 7367 7368 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7369 int *insn_idx, int subprog, 7370 set_callee_state_fn set_callee_state_cb) 7371 { 7372 struct bpf_verifier_state *state = env->cur_state; 7373 struct bpf_func_info_aux *func_info_aux; 7374 struct bpf_func_state *caller, *callee; 7375 int err; 7376 bool is_global = false; 7377 7378 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 7379 verbose(env, "the call stack of %d frames is too deep\n", 7380 state->curframe + 2); 7381 return -E2BIG; 7382 } 7383 7384 caller = state->frame[state->curframe]; 7385 if (state->frame[state->curframe + 1]) { 7386 verbose(env, "verifier bug. Frame %d already allocated\n", 7387 state->curframe + 1); 7388 return -EFAULT; 7389 } 7390 7391 func_info_aux = env->prog->aux->func_info_aux; 7392 if (func_info_aux) 7393 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 7394 err = btf_check_subprog_call(env, subprog, caller->regs); 7395 if (err == -EFAULT) 7396 return err; 7397 if (is_global) { 7398 if (err) { 7399 verbose(env, "Caller passes invalid args into func#%d\n", 7400 subprog); 7401 return err; 7402 } else { 7403 if (env->log.level & BPF_LOG_LEVEL) 7404 verbose(env, 7405 "Func#%d is global and valid. Skipping.\n", 7406 subprog); 7407 clear_caller_saved_regs(env, caller->regs); 7408 7409 /* All global functions return a 64-bit SCALAR_VALUE */ 7410 mark_reg_unknown(env, caller->regs, BPF_REG_0); 7411 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 7412 7413 /* continue with next insn after call */ 7414 return 0; 7415 } 7416 } 7417 7418 /* set_callee_state is used for direct subprog calls, but we are 7419 * interested in validating only BPF helpers that can call subprogs as 7420 * callbacks 7421 */ 7422 if (set_callee_state_cb != set_callee_state && !is_callback_calling_function(insn->imm)) { 7423 verbose(env, "verifier bug: helper %s#%d is not marked as callback-calling\n", 7424 func_id_name(insn->imm), insn->imm); 7425 return -EFAULT; 7426 } 7427 7428 if (insn->code == (BPF_JMP | BPF_CALL) && 7429 insn->src_reg == 0 && 7430 insn->imm == BPF_FUNC_timer_set_callback) { 7431 struct bpf_verifier_state *async_cb; 7432 7433 /* there is no real recursion here. timer callbacks are async */ 7434 env->subprog_info[subprog].is_async_cb = true; 7435 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 7436 *insn_idx, subprog); 7437 if (!async_cb) 7438 return -EFAULT; 7439 callee = async_cb->frame[0]; 7440 callee->async_entry_cnt = caller->async_entry_cnt + 1; 7441 7442 /* Convert bpf_timer_set_callback() args into timer callback args */ 7443 err = set_callee_state_cb(env, caller, callee, *insn_idx); 7444 if (err) 7445 return err; 7446 7447 clear_caller_saved_regs(env, caller->regs); 7448 mark_reg_unknown(env, caller->regs, BPF_REG_0); 7449 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 7450 /* continue with next insn after call */ 7451 return 0; 7452 } 7453 7454 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 7455 if (!callee) 7456 return -ENOMEM; 7457 state->frame[state->curframe + 1] = callee; 7458 7459 /* callee cannot access r0, r6 - r9 for reading and has to write 7460 * into its own stack before reading from it. 7461 * callee can read/write into caller's stack 7462 */ 7463 init_func_state(env, callee, 7464 /* remember the callsite, it will be used by bpf_exit */ 7465 *insn_idx /* callsite */, 7466 state->curframe + 1 /* frameno within this callchain */, 7467 subprog /* subprog number within this prog */); 7468 7469 /* Transfer references to the callee */ 7470 err = copy_reference_state(callee, caller); 7471 if (err) 7472 goto err_out; 7473 7474 err = set_callee_state_cb(env, caller, callee, *insn_idx); 7475 if (err) 7476 goto err_out; 7477 7478 clear_caller_saved_regs(env, caller->regs); 7479 7480 /* only increment it after check_reg_arg() finished */ 7481 state->curframe++; 7482 7483 /* and go analyze first insn of the callee */ 7484 *insn_idx = env->subprog_info[subprog].start - 1; 7485 7486 if (env->log.level & BPF_LOG_LEVEL) { 7487 verbose(env, "caller:\n"); 7488 print_verifier_state(env, caller, true); 7489 verbose(env, "callee:\n"); 7490 print_verifier_state(env, callee, true); 7491 } 7492 return 0; 7493 7494 err_out: 7495 free_func_state(callee); 7496 state->frame[state->curframe + 1] = NULL; 7497 return err; 7498 } 7499 7500 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 7501 struct bpf_func_state *caller, 7502 struct bpf_func_state *callee) 7503 { 7504 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 7505 * void *callback_ctx, u64 flags); 7506 * callback_fn(struct bpf_map *map, void *key, void *value, 7507 * void *callback_ctx); 7508 */ 7509 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 7510 7511 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 7512 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7513 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 7514 7515 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 7516 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 7517 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 7518 7519 /* pointer to stack or null */ 7520 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 7521 7522 /* unused */ 7523 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7524 return 0; 7525 } 7526 7527 static int set_callee_state(struct bpf_verifier_env *env, 7528 struct bpf_func_state *caller, 7529 struct bpf_func_state *callee, int insn_idx) 7530 { 7531 int i; 7532 7533 /* copy r1 - r5 args that callee can access. The copy includes parent 7534 * pointers, which connects us up to the liveness chain 7535 */ 7536 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 7537 callee->regs[i] = caller->regs[i]; 7538 return 0; 7539 } 7540 7541 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7542 int *insn_idx) 7543 { 7544 int subprog, target_insn; 7545 7546 target_insn = *insn_idx + insn->imm + 1; 7547 subprog = find_subprog(env, target_insn); 7548 if (subprog < 0) { 7549 verbose(env, "verifier bug. No program starts at insn %d\n", 7550 target_insn); 7551 return -EFAULT; 7552 } 7553 7554 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 7555 } 7556 7557 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 7558 struct bpf_func_state *caller, 7559 struct bpf_func_state *callee, 7560 int insn_idx) 7561 { 7562 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 7563 struct bpf_map *map; 7564 int err; 7565 7566 if (bpf_map_ptr_poisoned(insn_aux)) { 7567 verbose(env, "tail_call abusing map_ptr\n"); 7568 return -EINVAL; 7569 } 7570 7571 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 7572 if (!map->ops->map_set_for_each_callback_args || 7573 !map->ops->map_for_each_callback) { 7574 verbose(env, "callback function not allowed for map\n"); 7575 return -ENOTSUPP; 7576 } 7577 7578 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 7579 if (err) 7580 return err; 7581 7582 callee->in_callback_fn = true; 7583 callee->callback_ret_range = tnum_range(0, 1); 7584 return 0; 7585 } 7586 7587 static int set_loop_callback_state(struct bpf_verifier_env *env, 7588 struct bpf_func_state *caller, 7589 struct bpf_func_state *callee, 7590 int insn_idx) 7591 { 7592 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 7593 * u64 flags); 7594 * callback_fn(u32 index, void *callback_ctx); 7595 */ 7596 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 7597 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 7598 7599 /* unused */ 7600 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 7601 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7602 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7603 7604 callee->in_callback_fn = true; 7605 callee->callback_ret_range = tnum_range(0, 1); 7606 return 0; 7607 } 7608 7609 static int set_timer_callback_state(struct bpf_verifier_env *env, 7610 struct bpf_func_state *caller, 7611 struct bpf_func_state *callee, 7612 int insn_idx) 7613 { 7614 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 7615 7616 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 7617 * callback_fn(struct bpf_map *map, void *key, void *value); 7618 */ 7619 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 7620 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 7621 callee->regs[BPF_REG_1].map_ptr = map_ptr; 7622 7623 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 7624 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7625 callee->regs[BPF_REG_2].map_ptr = map_ptr; 7626 7627 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 7628 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 7629 callee->regs[BPF_REG_3].map_ptr = map_ptr; 7630 7631 /* unused */ 7632 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7633 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7634 callee->in_async_callback_fn = true; 7635 callee->callback_ret_range = tnum_range(0, 1); 7636 return 0; 7637 } 7638 7639 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 7640 struct bpf_func_state *caller, 7641 struct bpf_func_state *callee, 7642 int insn_idx) 7643 { 7644 /* bpf_find_vma(struct task_struct *task, u64 addr, 7645 * void *callback_fn, void *callback_ctx, u64 flags) 7646 * (callback_fn)(struct task_struct *task, 7647 * struct vm_area_struct *vma, void *callback_ctx); 7648 */ 7649 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 7650 7651 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 7652 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 7653 callee->regs[BPF_REG_2].btf = btf_vmlinux; 7654 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 7655 7656 /* pointer to stack or null */ 7657 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 7658 7659 /* unused */ 7660 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7661 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7662 callee->in_callback_fn = true; 7663 callee->callback_ret_range = tnum_range(0, 1); 7664 return 0; 7665 } 7666 7667 static int set_user_ringbuf_callback_state(struct bpf_verifier_env *env, 7668 struct bpf_func_state *caller, 7669 struct bpf_func_state *callee, 7670 int insn_idx) 7671 { 7672 /* bpf_user_ringbuf_drain(struct bpf_map *map, void *callback_fn, void 7673 * callback_ctx, u64 flags); 7674 * callback_fn(const struct bpf_dynptr_t* dynptr, void *callback_ctx); 7675 */ 7676 __mark_reg_not_init(env, &callee->regs[BPF_REG_0]); 7677 mark_dynptr_cb_reg(env, &callee->regs[BPF_REG_1], BPF_DYNPTR_TYPE_LOCAL); 7678 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 7679 7680 /* unused */ 7681 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 7682 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 7683 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 7684 7685 callee->in_callback_fn = true; 7686 callee->callback_ret_range = tnum_range(0, 1); 7687 return 0; 7688 } 7689 7690 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 7691 { 7692 struct bpf_verifier_state *state = env->cur_state; 7693 struct bpf_func_state *caller, *callee; 7694 struct bpf_reg_state *r0; 7695 int err; 7696 7697 callee = state->frame[state->curframe]; 7698 r0 = &callee->regs[BPF_REG_0]; 7699 if (r0->type == PTR_TO_STACK) { 7700 /* technically it's ok to return caller's stack pointer 7701 * (or caller's caller's pointer) back to the caller, 7702 * since these pointers are valid. Only current stack 7703 * pointer will be invalid as soon as function exits, 7704 * but let's be conservative 7705 */ 7706 verbose(env, "cannot return stack pointer to the caller\n"); 7707 return -EINVAL; 7708 } 7709 7710 caller = state->frame[state->curframe - 1]; 7711 if (callee->in_callback_fn) { 7712 /* enforce R0 return value range [0, 1]. */ 7713 struct tnum range = callee->callback_ret_range; 7714 7715 if (r0->type != SCALAR_VALUE) { 7716 verbose(env, "R0 not a scalar value\n"); 7717 return -EACCES; 7718 } 7719 if (!tnum_in(range, r0->var_off)) { 7720 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 7721 return -EINVAL; 7722 } 7723 } else { 7724 /* return to the caller whatever r0 had in the callee */ 7725 caller->regs[BPF_REG_0] = *r0; 7726 } 7727 7728 /* callback_fn frame should have released its own additions to parent's 7729 * reference state at this point, or check_reference_leak would 7730 * complain, hence it must be the same as the caller. There is no need 7731 * to copy it back. 7732 */ 7733 if (!callee->in_callback_fn) { 7734 /* Transfer references to the caller */ 7735 err = copy_reference_state(caller, callee); 7736 if (err) 7737 return err; 7738 } 7739 7740 *insn_idx = callee->callsite + 1; 7741 if (env->log.level & BPF_LOG_LEVEL) { 7742 verbose(env, "returning from callee:\n"); 7743 print_verifier_state(env, callee, true); 7744 verbose(env, "to caller at %d:\n", *insn_idx); 7745 print_verifier_state(env, caller, true); 7746 } 7747 /* clear everything in the callee */ 7748 free_func_state(callee); 7749 state->frame[state->curframe--] = NULL; 7750 return 0; 7751 } 7752 7753 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 7754 int func_id, 7755 struct bpf_call_arg_meta *meta) 7756 { 7757 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 7758 7759 if (ret_type != RET_INTEGER || 7760 (func_id != BPF_FUNC_get_stack && 7761 func_id != BPF_FUNC_get_task_stack && 7762 func_id != BPF_FUNC_probe_read_str && 7763 func_id != BPF_FUNC_probe_read_kernel_str && 7764 func_id != BPF_FUNC_probe_read_user_str)) 7765 return; 7766 7767 ret_reg->smax_value = meta->msize_max_value; 7768 ret_reg->s32_max_value = meta->msize_max_value; 7769 ret_reg->smin_value = -MAX_ERRNO; 7770 ret_reg->s32_min_value = -MAX_ERRNO; 7771 reg_bounds_sync(ret_reg); 7772 } 7773 7774 static int 7775 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 7776 int func_id, int insn_idx) 7777 { 7778 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 7779 struct bpf_map *map = meta->map_ptr; 7780 7781 if (func_id != BPF_FUNC_tail_call && 7782 func_id != BPF_FUNC_map_lookup_elem && 7783 func_id != BPF_FUNC_map_update_elem && 7784 func_id != BPF_FUNC_map_delete_elem && 7785 func_id != BPF_FUNC_map_push_elem && 7786 func_id != BPF_FUNC_map_pop_elem && 7787 func_id != BPF_FUNC_map_peek_elem && 7788 func_id != BPF_FUNC_for_each_map_elem && 7789 func_id != BPF_FUNC_redirect_map && 7790 func_id != BPF_FUNC_map_lookup_percpu_elem) 7791 return 0; 7792 7793 if (map == NULL) { 7794 verbose(env, "kernel subsystem misconfigured verifier\n"); 7795 return -EINVAL; 7796 } 7797 7798 /* In case of read-only, some additional restrictions 7799 * need to be applied in order to prevent altering the 7800 * state of the map from program side. 7801 */ 7802 if ((map->map_flags & BPF_F_RDONLY_PROG) && 7803 (func_id == BPF_FUNC_map_delete_elem || 7804 func_id == BPF_FUNC_map_update_elem || 7805 func_id == BPF_FUNC_map_push_elem || 7806 func_id == BPF_FUNC_map_pop_elem)) { 7807 verbose(env, "write into map forbidden\n"); 7808 return -EACCES; 7809 } 7810 7811 if (!BPF_MAP_PTR(aux->map_ptr_state)) 7812 bpf_map_ptr_store(aux, meta->map_ptr, 7813 !meta->map_ptr->bypass_spec_v1); 7814 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 7815 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 7816 !meta->map_ptr->bypass_spec_v1); 7817 return 0; 7818 } 7819 7820 static int 7821 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 7822 int func_id, int insn_idx) 7823 { 7824 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 7825 struct bpf_reg_state *regs = cur_regs(env), *reg; 7826 struct bpf_map *map = meta->map_ptr; 7827 u64 val, max; 7828 int err; 7829 7830 if (func_id != BPF_FUNC_tail_call) 7831 return 0; 7832 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 7833 verbose(env, "kernel subsystem misconfigured verifier\n"); 7834 return -EINVAL; 7835 } 7836 7837 reg = ®s[BPF_REG_3]; 7838 val = reg->var_off.value; 7839 max = map->max_entries; 7840 7841 if (!(register_is_const(reg) && val < max)) { 7842 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 7843 return 0; 7844 } 7845 7846 err = mark_chain_precision(env, BPF_REG_3); 7847 if (err) 7848 return err; 7849 if (bpf_map_key_unseen(aux)) 7850 bpf_map_key_store(aux, val); 7851 else if (!bpf_map_key_poisoned(aux) && 7852 bpf_map_key_immediate(aux) != val) 7853 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 7854 return 0; 7855 } 7856 7857 static int check_reference_leak(struct bpf_verifier_env *env) 7858 { 7859 struct bpf_func_state *state = cur_func(env); 7860 bool refs_lingering = false; 7861 int i; 7862 7863 if (state->frameno && !state->in_callback_fn) 7864 return 0; 7865 7866 for (i = 0; i < state->acquired_refs; i++) { 7867 if (state->in_callback_fn && state->refs[i].callback_ref != state->frameno) 7868 continue; 7869 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 7870 state->refs[i].id, state->refs[i].insn_idx); 7871 refs_lingering = true; 7872 } 7873 return refs_lingering ? -EINVAL : 0; 7874 } 7875 7876 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 7877 struct bpf_reg_state *regs) 7878 { 7879 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 7880 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 7881 struct bpf_map *fmt_map = fmt_reg->map_ptr; 7882 struct bpf_bprintf_data data = {}; 7883 int err, fmt_map_off, num_args; 7884 u64 fmt_addr; 7885 char *fmt; 7886 7887 /* data must be an array of u64 */ 7888 if (data_len_reg->var_off.value % 8) 7889 return -EINVAL; 7890 num_args = data_len_reg->var_off.value / 8; 7891 7892 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 7893 * and map_direct_value_addr is set. 7894 */ 7895 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 7896 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 7897 fmt_map_off); 7898 if (err) { 7899 verbose(env, "verifier bug\n"); 7900 return -EFAULT; 7901 } 7902 fmt = (char *)(long)fmt_addr + fmt_map_off; 7903 7904 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 7905 * can focus on validating the format specifiers. 7906 */ 7907 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, num_args, &data); 7908 if (err < 0) 7909 verbose(env, "Invalid format string\n"); 7910 7911 return err; 7912 } 7913 7914 static int check_get_func_ip(struct bpf_verifier_env *env) 7915 { 7916 enum bpf_prog_type type = resolve_prog_type(env->prog); 7917 int func_id = BPF_FUNC_get_func_ip; 7918 7919 if (type == BPF_PROG_TYPE_TRACING) { 7920 if (!bpf_prog_has_trampoline(env->prog)) { 7921 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 7922 func_id_name(func_id), func_id); 7923 return -ENOTSUPP; 7924 } 7925 return 0; 7926 } else if (type == BPF_PROG_TYPE_KPROBE) { 7927 return 0; 7928 } 7929 7930 verbose(env, "func %s#%d not supported for program type %d\n", 7931 func_id_name(func_id), func_id, type); 7932 return -ENOTSUPP; 7933 } 7934 7935 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 7936 { 7937 return &env->insn_aux_data[env->insn_idx]; 7938 } 7939 7940 static bool loop_flag_is_zero(struct bpf_verifier_env *env) 7941 { 7942 struct bpf_reg_state *regs = cur_regs(env); 7943 struct bpf_reg_state *reg = ®s[BPF_REG_4]; 7944 bool reg_is_null = register_is_null(reg); 7945 7946 if (reg_is_null) 7947 mark_chain_precision(env, BPF_REG_4); 7948 7949 return reg_is_null; 7950 } 7951 7952 static void update_loop_inline_state(struct bpf_verifier_env *env, u32 subprogno) 7953 { 7954 struct bpf_loop_inline_state *state = &cur_aux(env)->loop_inline_state; 7955 7956 if (!state->initialized) { 7957 state->initialized = 1; 7958 state->fit_for_inline = loop_flag_is_zero(env); 7959 state->callback_subprogno = subprogno; 7960 return; 7961 } 7962 7963 if (!state->fit_for_inline) 7964 return; 7965 7966 state->fit_for_inline = (loop_flag_is_zero(env) && 7967 state->callback_subprogno == subprogno); 7968 } 7969 7970 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 7971 int *insn_idx_p) 7972 { 7973 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 7974 const struct bpf_func_proto *fn = NULL; 7975 enum bpf_return_type ret_type; 7976 enum bpf_type_flag ret_flag; 7977 struct bpf_reg_state *regs; 7978 struct bpf_call_arg_meta meta; 7979 int insn_idx = *insn_idx_p; 7980 bool changes_data; 7981 int i, err, func_id; 7982 7983 /* find function prototype */ 7984 func_id = insn->imm; 7985 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 7986 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 7987 func_id); 7988 return -EINVAL; 7989 } 7990 7991 if (env->ops->get_func_proto) 7992 fn = env->ops->get_func_proto(func_id, env->prog); 7993 if (!fn) { 7994 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 7995 func_id); 7996 return -EINVAL; 7997 } 7998 7999 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 8000 if (!env->prog->gpl_compatible && fn->gpl_only) { 8001 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 8002 return -EINVAL; 8003 } 8004 8005 if (fn->allowed && !fn->allowed(env->prog)) { 8006 verbose(env, "helper call is not allowed in probe\n"); 8007 return -EINVAL; 8008 } 8009 8010 if (!env->prog->aux->sleepable && fn->might_sleep) { 8011 verbose(env, "helper call might sleep in a non-sleepable prog\n"); 8012 return -EINVAL; 8013 } 8014 8015 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 8016 changes_data = bpf_helper_changes_pkt_data(fn->func); 8017 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 8018 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 8019 func_id_name(func_id), func_id); 8020 return -EINVAL; 8021 } 8022 8023 memset(&meta, 0, sizeof(meta)); 8024 meta.pkt_access = fn->pkt_access; 8025 8026 err = check_func_proto(fn, func_id); 8027 if (err) { 8028 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 8029 func_id_name(func_id), func_id); 8030 return err; 8031 } 8032 8033 if (env->cur_state->active_rcu_lock) { 8034 if (fn->might_sleep) { 8035 verbose(env, "sleepable helper %s#%d in rcu_read_lock region\n", 8036 func_id_name(func_id), func_id); 8037 return -EINVAL; 8038 } 8039 8040 if (env->prog->aux->sleepable && is_storage_get_function(func_id)) 8041 env->insn_aux_data[insn_idx].storage_get_func_atomic = true; 8042 } 8043 8044 meta.func_id = func_id; 8045 /* check args */ 8046 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 8047 err = check_func_arg(env, i, &meta, fn); 8048 if (err) 8049 return err; 8050 } 8051 8052 err = record_func_map(env, &meta, func_id, insn_idx); 8053 if (err) 8054 return err; 8055 8056 err = record_func_key(env, &meta, func_id, insn_idx); 8057 if (err) 8058 return err; 8059 8060 /* Mark slots with STACK_MISC in case of raw mode, stack offset 8061 * is inferred from register state. 8062 */ 8063 for (i = 0; i < meta.access_size; i++) { 8064 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 8065 BPF_WRITE, -1, false); 8066 if (err) 8067 return err; 8068 } 8069 8070 regs = cur_regs(env); 8071 8072 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 8073 * be reinitialized by any dynptr helper. Hence, mark_stack_slots_dynptr 8074 * is safe to do directly. 8075 */ 8076 if (meta.uninit_dynptr_regno) { 8077 if (regs[meta.uninit_dynptr_regno].type == CONST_PTR_TO_DYNPTR) { 8078 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be initialized\n"); 8079 return -EFAULT; 8080 } 8081 /* we write BPF_DW bits (8 bytes) at a time */ 8082 for (i = 0; i < BPF_DYNPTR_SIZE; i += 8) { 8083 err = check_mem_access(env, insn_idx, meta.uninit_dynptr_regno, 8084 i, BPF_DW, BPF_WRITE, -1, false); 8085 if (err) 8086 return err; 8087 } 8088 8089 err = mark_stack_slots_dynptr(env, ®s[meta.uninit_dynptr_regno], 8090 fn->arg_type[meta.uninit_dynptr_regno - BPF_REG_1], 8091 insn_idx); 8092 if (err) 8093 return err; 8094 } 8095 8096 if (meta.release_regno) { 8097 err = -EINVAL; 8098 /* This can only be set for PTR_TO_STACK, as CONST_PTR_TO_DYNPTR cannot 8099 * be released by any dynptr helper. Hence, unmark_stack_slots_dynptr 8100 * is safe to do directly. 8101 */ 8102 if (arg_type_is_dynptr(fn->arg_type[meta.release_regno - BPF_REG_1])) { 8103 if (regs[meta.release_regno].type == CONST_PTR_TO_DYNPTR) { 8104 verbose(env, "verifier internal error: CONST_PTR_TO_DYNPTR cannot be released\n"); 8105 return -EFAULT; 8106 } 8107 err = unmark_stack_slots_dynptr(env, ®s[meta.release_regno]); 8108 } else if (meta.ref_obj_id) { 8109 err = release_reference(env, meta.ref_obj_id); 8110 } else if (register_is_null(®s[meta.release_regno])) { 8111 /* meta.ref_obj_id can only be 0 if register that is meant to be 8112 * released is NULL, which must be > R0. 8113 */ 8114 err = 0; 8115 } 8116 if (err) { 8117 verbose(env, "func %s#%d reference has not been acquired before\n", 8118 func_id_name(func_id), func_id); 8119 return err; 8120 } 8121 } 8122 8123 switch (func_id) { 8124 case BPF_FUNC_tail_call: 8125 err = check_reference_leak(env); 8126 if (err) { 8127 verbose(env, "tail_call would lead to reference leak\n"); 8128 return err; 8129 } 8130 break; 8131 case BPF_FUNC_get_local_storage: 8132 /* check that flags argument in get_local_storage(map, flags) is 0, 8133 * this is required because get_local_storage() can't return an error. 8134 */ 8135 if (!register_is_null(®s[BPF_REG_2])) { 8136 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 8137 return -EINVAL; 8138 } 8139 break; 8140 case BPF_FUNC_for_each_map_elem: 8141 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8142 set_map_elem_callback_state); 8143 break; 8144 case BPF_FUNC_timer_set_callback: 8145 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8146 set_timer_callback_state); 8147 break; 8148 case BPF_FUNC_find_vma: 8149 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8150 set_find_vma_callback_state); 8151 break; 8152 case BPF_FUNC_snprintf: 8153 err = check_bpf_snprintf_call(env, regs); 8154 break; 8155 case BPF_FUNC_loop: 8156 update_loop_inline_state(env, meta.subprogno); 8157 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8158 set_loop_callback_state); 8159 break; 8160 case BPF_FUNC_dynptr_from_mem: 8161 if (regs[BPF_REG_1].type != PTR_TO_MAP_VALUE) { 8162 verbose(env, "Unsupported reg type %s for bpf_dynptr_from_mem data\n", 8163 reg_type_str(env, regs[BPF_REG_1].type)); 8164 return -EACCES; 8165 } 8166 break; 8167 case BPF_FUNC_set_retval: 8168 if (prog_type == BPF_PROG_TYPE_LSM && 8169 env->prog->expected_attach_type == BPF_LSM_CGROUP) { 8170 if (!env->prog->aux->attach_func_proto->type) { 8171 /* Make sure programs that attach to void 8172 * hooks don't try to modify return value. 8173 */ 8174 verbose(env, "BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 8175 return -EINVAL; 8176 } 8177 } 8178 break; 8179 case BPF_FUNC_dynptr_data: 8180 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 8181 if (arg_type_is_dynptr(fn->arg_type[i])) { 8182 struct bpf_reg_state *reg = ®s[BPF_REG_1 + i]; 8183 int id, ref_obj_id; 8184 8185 if (meta.dynptr_id) { 8186 verbose(env, "verifier internal error: meta.dynptr_id already set\n"); 8187 return -EFAULT; 8188 } 8189 8190 if (meta.ref_obj_id) { 8191 verbose(env, "verifier internal error: meta.ref_obj_id already set\n"); 8192 return -EFAULT; 8193 } 8194 8195 id = dynptr_id(env, reg); 8196 if (id < 0) { 8197 verbose(env, "verifier internal error: failed to obtain dynptr id\n"); 8198 return id; 8199 } 8200 8201 ref_obj_id = dynptr_ref_obj_id(env, reg); 8202 if (ref_obj_id < 0) { 8203 verbose(env, "verifier internal error: failed to obtain dynptr ref_obj_id\n"); 8204 return ref_obj_id; 8205 } 8206 8207 meta.dynptr_id = id; 8208 meta.ref_obj_id = ref_obj_id; 8209 break; 8210 } 8211 } 8212 if (i == MAX_BPF_FUNC_REG_ARGS) { 8213 verbose(env, "verifier internal error: no dynptr in bpf_dynptr_data()\n"); 8214 return -EFAULT; 8215 } 8216 break; 8217 case BPF_FUNC_user_ringbuf_drain: 8218 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 8219 set_user_ringbuf_callback_state); 8220 break; 8221 } 8222 8223 if (err) 8224 return err; 8225 8226 /* reset caller saved regs */ 8227 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8228 mark_reg_not_init(env, regs, caller_saved[i]); 8229 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8230 } 8231 8232 /* helper call returns 64-bit value. */ 8233 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 8234 8235 /* update return register (already marked as written above) */ 8236 ret_type = fn->ret_type; 8237 ret_flag = type_flag(ret_type); 8238 8239 switch (base_type(ret_type)) { 8240 case RET_INTEGER: 8241 /* sets type to SCALAR_VALUE */ 8242 mark_reg_unknown(env, regs, BPF_REG_0); 8243 break; 8244 case RET_VOID: 8245 regs[BPF_REG_0].type = NOT_INIT; 8246 break; 8247 case RET_PTR_TO_MAP_VALUE: 8248 /* There is no offset yet applied, variable or fixed */ 8249 mark_reg_known_zero(env, regs, BPF_REG_0); 8250 /* remember map_ptr, so that check_map_access() 8251 * can check 'value_size' boundary of memory access 8252 * to map element returned from bpf_map_lookup_elem() 8253 */ 8254 if (meta.map_ptr == NULL) { 8255 verbose(env, 8256 "kernel subsystem misconfigured verifier\n"); 8257 return -EINVAL; 8258 } 8259 regs[BPF_REG_0].map_ptr = meta.map_ptr; 8260 regs[BPF_REG_0].map_uid = meta.map_uid; 8261 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 8262 if (!type_may_be_null(ret_type) && 8263 btf_record_has_field(meta.map_ptr->record, BPF_SPIN_LOCK)) { 8264 regs[BPF_REG_0].id = ++env->id_gen; 8265 } 8266 break; 8267 case RET_PTR_TO_SOCKET: 8268 mark_reg_known_zero(env, regs, BPF_REG_0); 8269 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 8270 break; 8271 case RET_PTR_TO_SOCK_COMMON: 8272 mark_reg_known_zero(env, regs, BPF_REG_0); 8273 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 8274 break; 8275 case RET_PTR_TO_TCP_SOCK: 8276 mark_reg_known_zero(env, regs, BPF_REG_0); 8277 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 8278 break; 8279 case RET_PTR_TO_MEM: 8280 mark_reg_known_zero(env, regs, BPF_REG_0); 8281 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 8282 regs[BPF_REG_0].mem_size = meta.mem_size; 8283 break; 8284 case RET_PTR_TO_MEM_OR_BTF_ID: 8285 { 8286 const struct btf_type *t; 8287 8288 mark_reg_known_zero(env, regs, BPF_REG_0); 8289 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 8290 if (!btf_type_is_struct(t)) { 8291 u32 tsize; 8292 const struct btf_type *ret; 8293 const char *tname; 8294 8295 /* resolve the type size of ksym. */ 8296 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 8297 if (IS_ERR(ret)) { 8298 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 8299 verbose(env, "unable to resolve the size of type '%s': %ld\n", 8300 tname, PTR_ERR(ret)); 8301 return -EINVAL; 8302 } 8303 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 8304 regs[BPF_REG_0].mem_size = tsize; 8305 } else { 8306 /* MEM_RDONLY may be carried from ret_flag, but it 8307 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 8308 * it will confuse the check of PTR_TO_BTF_ID in 8309 * check_mem_access(). 8310 */ 8311 ret_flag &= ~MEM_RDONLY; 8312 8313 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 8314 regs[BPF_REG_0].btf = meta.ret_btf; 8315 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 8316 } 8317 break; 8318 } 8319 case RET_PTR_TO_BTF_ID: 8320 { 8321 struct btf *ret_btf; 8322 int ret_btf_id; 8323 8324 mark_reg_known_zero(env, regs, BPF_REG_0); 8325 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 8326 if (func_id == BPF_FUNC_kptr_xchg) { 8327 ret_btf = meta.kptr_field->kptr.btf; 8328 ret_btf_id = meta.kptr_field->kptr.btf_id; 8329 } else { 8330 if (fn->ret_btf_id == BPF_PTR_POISON) { 8331 verbose(env, "verifier internal error:"); 8332 verbose(env, "func %s has non-overwritten BPF_PTR_POISON return type\n", 8333 func_id_name(func_id)); 8334 return -EINVAL; 8335 } 8336 ret_btf = btf_vmlinux; 8337 ret_btf_id = *fn->ret_btf_id; 8338 } 8339 if (ret_btf_id == 0) { 8340 verbose(env, "invalid return type %u of func %s#%d\n", 8341 base_type(ret_type), func_id_name(func_id), 8342 func_id); 8343 return -EINVAL; 8344 } 8345 regs[BPF_REG_0].btf = ret_btf; 8346 regs[BPF_REG_0].btf_id = ret_btf_id; 8347 break; 8348 } 8349 default: 8350 verbose(env, "unknown return type %u of func %s#%d\n", 8351 base_type(ret_type), func_id_name(func_id), func_id); 8352 return -EINVAL; 8353 } 8354 8355 if (type_may_be_null(regs[BPF_REG_0].type)) 8356 regs[BPF_REG_0].id = ++env->id_gen; 8357 8358 if (helper_multiple_ref_obj_use(func_id, meta.map_ptr)) { 8359 verbose(env, "verifier internal error: func %s#%d sets ref_obj_id more than once\n", 8360 func_id_name(func_id), func_id); 8361 return -EFAULT; 8362 } 8363 8364 if (is_dynptr_ref_function(func_id)) 8365 regs[BPF_REG_0].dynptr_id = meta.dynptr_id; 8366 8367 if (is_ptr_cast_function(func_id) || is_dynptr_ref_function(func_id)) { 8368 /* For release_reference() */ 8369 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 8370 } else if (is_acquire_function(func_id, meta.map_ptr)) { 8371 int id = acquire_reference_state(env, insn_idx); 8372 8373 if (id < 0) 8374 return id; 8375 /* For mark_ptr_or_null_reg() */ 8376 regs[BPF_REG_0].id = id; 8377 /* For release_reference() */ 8378 regs[BPF_REG_0].ref_obj_id = id; 8379 } 8380 8381 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 8382 8383 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 8384 if (err) 8385 return err; 8386 8387 if ((func_id == BPF_FUNC_get_stack || 8388 func_id == BPF_FUNC_get_task_stack) && 8389 !env->prog->has_callchain_buf) { 8390 const char *err_str; 8391 8392 #ifdef CONFIG_PERF_EVENTS 8393 err = get_callchain_buffers(sysctl_perf_event_max_stack); 8394 err_str = "cannot get callchain buffer for func %s#%d\n"; 8395 #else 8396 err = -ENOTSUPP; 8397 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 8398 #endif 8399 if (err) { 8400 verbose(env, err_str, func_id_name(func_id), func_id); 8401 return err; 8402 } 8403 8404 env->prog->has_callchain_buf = true; 8405 } 8406 8407 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 8408 env->prog->call_get_stack = true; 8409 8410 if (func_id == BPF_FUNC_get_func_ip) { 8411 if (check_get_func_ip(env)) 8412 return -ENOTSUPP; 8413 env->prog->call_get_func_ip = true; 8414 } 8415 8416 if (changes_data) 8417 clear_all_pkt_pointers(env); 8418 return 0; 8419 } 8420 8421 /* mark_btf_func_reg_size() is used when the reg size is determined by 8422 * the BTF func_proto's return value size and argument. 8423 */ 8424 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 8425 size_t reg_size) 8426 { 8427 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 8428 8429 if (regno == BPF_REG_0) { 8430 /* Function return value */ 8431 reg->live |= REG_LIVE_WRITTEN; 8432 reg->subreg_def = reg_size == sizeof(u64) ? 8433 DEF_NOT_SUBREG : env->insn_idx + 1; 8434 } else { 8435 /* Function argument */ 8436 if (reg_size == sizeof(u64)) { 8437 mark_insn_zext(env, reg); 8438 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 8439 } else { 8440 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 8441 } 8442 } 8443 } 8444 8445 struct bpf_kfunc_call_arg_meta { 8446 /* In parameters */ 8447 struct btf *btf; 8448 u32 func_id; 8449 u32 kfunc_flags; 8450 const struct btf_type *func_proto; 8451 const char *func_name; 8452 /* Out parameters */ 8453 u32 ref_obj_id; 8454 u8 release_regno; 8455 bool r0_rdonly; 8456 u32 ret_btf_id; 8457 u64 r0_size; 8458 struct { 8459 u64 value; 8460 bool found; 8461 } arg_constant; 8462 struct { 8463 struct btf *btf; 8464 u32 btf_id; 8465 } arg_obj_drop; 8466 struct { 8467 struct btf_field *field; 8468 } arg_list_head; 8469 }; 8470 8471 static bool is_kfunc_acquire(struct bpf_kfunc_call_arg_meta *meta) 8472 { 8473 return meta->kfunc_flags & KF_ACQUIRE; 8474 } 8475 8476 static bool is_kfunc_ret_null(struct bpf_kfunc_call_arg_meta *meta) 8477 { 8478 return meta->kfunc_flags & KF_RET_NULL; 8479 } 8480 8481 static bool is_kfunc_release(struct bpf_kfunc_call_arg_meta *meta) 8482 { 8483 return meta->kfunc_flags & KF_RELEASE; 8484 } 8485 8486 static bool is_kfunc_trusted_args(struct bpf_kfunc_call_arg_meta *meta) 8487 { 8488 return meta->kfunc_flags & KF_TRUSTED_ARGS; 8489 } 8490 8491 static bool is_kfunc_sleepable(struct bpf_kfunc_call_arg_meta *meta) 8492 { 8493 return meta->kfunc_flags & KF_SLEEPABLE; 8494 } 8495 8496 static bool is_kfunc_destructive(struct bpf_kfunc_call_arg_meta *meta) 8497 { 8498 return meta->kfunc_flags & KF_DESTRUCTIVE; 8499 } 8500 8501 static bool is_kfunc_rcu(struct bpf_kfunc_call_arg_meta *meta) 8502 { 8503 return meta->kfunc_flags & KF_RCU; 8504 } 8505 8506 static bool is_kfunc_arg_kptr_get(struct bpf_kfunc_call_arg_meta *meta, int arg) 8507 { 8508 return arg == 0 && (meta->kfunc_flags & KF_KPTR_GET); 8509 } 8510 8511 static bool __kfunc_param_match_suffix(const struct btf *btf, 8512 const struct btf_param *arg, 8513 const char *suffix) 8514 { 8515 int suffix_len = strlen(suffix), len; 8516 const char *param_name; 8517 8518 /* In the future, this can be ported to use BTF tagging */ 8519 param_name = btf_name_by_offset(btf, arg->name_off); 8520 if (str_is_empty(param_name)) 8521 return false; 8522 len = strlen(param_name); 8523 if (len < suffix_len) 8524 return false; 8525 param_name += len - suffix_len; 8526 return !strncmp(param_name, suffix, suffix_len); 8527 } 8528 8529 static bool is_kfunc_arg_mem_size(const struct btf *btf, 8530 const struct btf_param *arg, 8531 const struct bpf_reg_state *reg) 8532 { 8533 const struct btf_type *t; 8534 8535 t = btf_type_skip_modifiers(btf, arg->type, NULL); 8536 if (!btf_type_is_scalar(t) || reg->type != SCALAR_VALUE) 8537 return false; 8538 8539 return __kfunc_param_match_suffix(btf, arg, "__sz"); 8540 } 8541 8542 static bool is_kfunc_arg_constant(const struct btf *btf, const struct btf_param *arg) 8543 { 8544 return __kfunc_param_match_suffix(btf, arg, "__k"); 8545 } 8546 8547 static bool is_kfunc_arg_ignore(const struct btf *btf, const struct btf_param *arg) 8548 { 8549 return __kfunc_param_match_suffix(btf, arg, "__ign"); 8550 } 8551 8552 static bool is_kfunc_arg_alloc_obj(const struct btf *btf, const struct btf_param *arg) 8553 { 8554 return __kfunc_param_match_suffix(btf, arg, "__alloc"); 8555 } 8556 8557 static bool is_kfunc_arg_scalar_with_name(const struct btf *btf, 8558 const struct btf_param *arg, 8559 const char *name) 8560 { 8561 int len, target_len = strlen(name); 8562 const char *param_name; 8563 8564 param_name = btf_name_by_offset(btf, arg->name_off); 8565 if (str_is_empty(param_name)) 8566 return false; 8567 len = strlen(param_name); 8568 if (len != target_len) 8569 return false; 8570 if (strcmp(param_name, name)) 8571 return false; 8572 8573 return true; 8574 } 8575 8576 enum { 8577 KF_ARG_DYNPTR_ID, 8578 KF_ARG_LIST_HEAD_ID, 8579 KF_ARG_LIST_NODE_ID, 8580 }; 8581 8582 BTF_ID_LIST(kf_arg_btf_ids) 8583 BTF_ID(struct, bpf_dynptr_kern) 8584 BTF_ID(struct, bpf_list_head) 8585 BTF_ID(struct, bpf_list_node) 8586 8587 static bool __is_kfunc_ptr_arg_type(const struct btf *btf, 8588 const struct btf_param *arg, int type) 8589 { 8590 const struct btf_type *t; 8591 u32 res_id; 8592 8593 t = btf_type_skip_modifiers(btf, arg->type, NULL); 8594 if (!t) 8595 return false; 8596 if (!btf_type_is_ptr(t)) 8597 return false; 8598 t = btf_type_skip_modifiers(btf, t->type, &res_id); 8599 if (!t) 8600 return false; 8601 return btf_types_are_same(btf, res_id, btf_vmlinux, kf_arg_btf_ids[type]); 8602 } 8603 8604 static bool is_kfunc_arg_dynptr(const struct btf *btf, const struct btf_param *arg) 8605 { 8606 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_DYNPTR_ID); 8607 } 8608 8609 static bool is_kfunc_arg_list_head(const struct btf *btf, const struct btf_param *arg) 8610 { 8611 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_HEAD_ID); 8612 } 8613 8614 static bool is_kfunc_arg_list_node(const struct btf *btf, const struct btf_param *arg) 8615 { 8616 return __is_kfunc_ptr_arg_type(btf, arg, KF_ARG_LIST_NODE_ID); 8617 } 8618 8619 /* Returns true if struct is composed of scalars, 4 levels of nesting allowed */ 8620 static bool __btf_type_is_scalar_struct(struct bpf_verifier_env *env, 8621 const struct btf *btf, 8622 const struct btf_type *t, int rec) 8623 { 8624 const struct btf_type *member_type; 8625 const struct btf_member *member; 8626 u32 i; 8627 8628 if (!btf_type_is_struct(t)) 8629 return false; 8630 8631 for_each_member(i, t, member) { 8632 const struct btf_array *array; 8633 8634 member_type = btf_type_skip_modifiers(btf, member->type, NULL); 8635 if (btf_type_is_struct(member_type)) { 8636 if (rec >= 3) { 8637 verbose(env, "max struct nesting depth exceeded\n"); 8638 return false; 8639 } 8640 if (!__btf_type_is_scalar_struct(env, btf, member_type, rec + 1)) 8641 return false; 8642 continue; 8643 } 8644 if (btf_type_is_array(member_type)) { 8645 array = btf_array(member_type); 8646 if (!array->nelems) 8647 return false; 8648 member_type = btf_type_skip_modifiers(btf, array->type, NULL); 8649 if (!btf_type_is_scalar(member_type)) 8650 return false; 8651 continue; 8652 } 8653 if (!btf_type_is_scalar(member_type)) 8654 return false; 8655 } 8656 return true; 8657 } 8658 8659 8660 static u32 *reg2btf_ids[__BPF_REG_TYPE_MAX] = { 8661 #ifdef CONFIG_NET 8662 [PTR_TO_SOCKET] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK], 8663 [PTR_TO_SOCK_COMMON] = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 8664 [PTR_TO_TCP_SOCK] = &btf_sock_ids[BTF_SOCK_TYPE_TCP], 8665 #endif 8666 }; 8667 8668 enum kfunc_ptr_arg_type { 8669 KF_ARG_PTR_TO_CTX, 8670 KF_ARG_PTR_TO_ALLOC_BTF_ID, /* Allocated object */ 8671 KF_ARG_PTR_TO_KPTR, /* PTR_TO_KPTR but type specific */ 8672 KF_ARG_PTR_TO_DYNPTR, 8673 KF_ARG_PTR_TO_LIST_HEAD, 8674 KF_ARG_PTR_TO_LIST_NODE, 8675 KF_ARG_PTR_TO_BTF_ID, /* Also covers reg2btf_ids conversions */ 8676 KF_ARG_PTR_TO_MEM, 8677 KF_ARG_PTR_TO_MEM_SIZE, /* Size derived from next argument, skip it */ 8678 }; 8679 8680 enum special_kfunc_type { 8681 KF_bpf_obj_new_impl, 8682 KF_bpf_obj_drop_impl, 8683 KF_bpf_list_push_front, 8684 KF_bpf_list_push_back, 8685 KF_bpf_list_pop_front, 8686 KF_bpf_list_pop_back, 8687 KF_bpf_cast_to_kern_ctx, 8688 KF_bpf_rdonly_cast, 8689 KF_bpf_rcu_read_lock, 8690 KF_bpf_rcu_read_unlock, 8691 }; 8692 8693 BTF_SET_START(special_kfunc_set) 8694 BTF_ID(func, bpf_obj_new_impl) 8695 BTF_ID(func, bpf_obj_drop_impl) 8696 BTF_ID(func, bpf_list_push_front) 8697 BTF_ID(func, bpf_list_push_back) 8698 BTF_ID(func, bpf_list_pop_front) 8699 BTF_ID(func, bpf_list_pop_back) 8700 BTF_ID(func, bpf_cast_to_kern_ctx) 8701 BTF_ID(func, bpf_rdonly_cast) 8702 BTF_SET_END(special_kfunc_set) 8703 8704 BTF_ID_LIST(special_kfunc_list) 8705 BTF_ID(func, bpf_obj_new_impl) 8706 BTF_ID(func, bpf_obj_drop_impl) 8707 BTF_ID(func, bpf_list_push_front) 8708 BTF_ID(func, bpf_list_push_back) 8709 BTF_ID(func, bpf_list_pop_front) 8710 BTF_ID(func, bpf_list_pop_back) 8711 BTF_ID(func, bpf_cast_to_kern_ctx) 8712 BTF_ID(func, bpf_rdonly_cast) 8713 BTF_ID(func, bpf_rcu_read_lock) 8714 BTF_ID(func, bpf_rcu_read_unlock) 8715 8716 static bool is_kfunc_bpf_rcu_read_lock(struct bpf_kfunc_call_arg_meta *meta) 8717 { 8718 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_lock]; 8719 } 8720 8721 static bool is_kfunc_bpf_rcu_read_unlock(struct bpf_kfunc_call_arg_meta *meta) 8722 { 8723 return meta->func_id == special_kfunc_list[KF_bpf_rcu_read_unlock]; 8724 } 8725 8726 static enum kfunc_ptr_arg_type 8727 get_kfunc_ptr_arg_type(struct bpf_verifier_env *env, 8728 struct bpf_kfunc_call_arg_meta *meta, 8729 const struct btf_type *t, const struct btf_type *ref_t, 8730 const char *ref_tname, const struct btf_param *args, 8731 int argno, int nargs) 8732 { 8733 u32 regno = argno + 1; 8734 struct bpf_reg_state *regs = cur_regs(env); 8735 struct bpf_reg_state *reg = ®s[regno]; 8736 bool arg_mem_size = false; 8737 8738 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) 8739 return KF_ARG_PTR_TO_CTX; 8740 8741 /* In this function, we verify the kfunc's BTF as per the argument type, 8742 * leaving the rest of the verification with respect to the register 8743 * type to our caller. When a set of conditions hold in the BTF type of 8744 * arguments, we resolve it to a known kfunc_ptr_arg_type. 8745 */ 8746 if (btf_get_prog_ctx_type(&env->log, meta->btf, t, resolve_prog_type(env->prog), argno)) 8747 return KF_ARG_PTR_TO_CTX; 8748 8749 if (is_kfunc_arg_alloc_obj(meta->btf, &args[argno])) 8750 return KF_ARG_PTR_TO_ALLOC_BTF_ID; 8751 8752 if (is_kfunc_arg_kptr_get(meta, argno)) { 8753 if (!btf_type_is_ptr(ref_t)) { 8754 verbose(env, "arg#0 BTF type must be a double pointer for kptr_get kfunc\n"); 8755 return -EINVAL; 8756 } 8757 ref_t = btf_type_by_id(meta->btf, ref_t->type); 8758 ref_tname = btf_name_by_offset(meta->btf, ref_t->name_off); 8759 if (!btf_type_is_struct(ref_t)) { 8760 verbose(env, "kernel function %s args#0 pointer type %s %s is not supported\n", 8761 meta->func_name, btf_type_str(ref_t), ref_tname); 8762 return -EINVAL; 8763 } 8764 return KF_ARG_PTR_TO_KPTR; 8765 } 8766 8767 if (is_kfunc_arg_dynptr(meta->btf, &args[argno])) 8768 return KF_ARG_PTR_TO_DYNPTR; 8769 8770 if (is_kfunc_arg_list_head(meta->btf, &args[argno])) 8771 return KF_ARG_PTR_TO_LIST_HEAD; 8772 8773 if (is_kfunc_arg_list_node(meta->btf, &args[argno])) 8774 return KF_ARG_PTR_TO_LIST_NODE; 8775 8776 if ((base_type(reg->type) == PTR_TO_BTF_ID || reg2btf_ids[base_type(reg->type)])) { 8777 if (!btf_type_is_struct(ref_t)) { 8778 verbose(env, "kernel function %s args#%d pointer type %s %s is not supported\n", 8779 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 8780 return -EINVAL; 8781 } 8782 return KF_ARG_PTR_TO_BTF_ID; 8783 } 8784 8785 if (argno + 1 < nargs && is_kfunc_arg_mem_size(meta->btf, &args[argno + 1], ®s[regno + 1])) 8786 arg_mem_size = true; 8787 8788 /* This is the catch all argument type of register types supported by 8789 * check_helper_mem_access. However, we only allow when argument type is 8790 * pointer to scalar, or struct composed (recursively) of scalars. When 8791 * arg_mem_size is true, the pointer can be void *. 8792 */ 8793 if (!btf_type_is_scalar(ref_t) && !__btf_type_is_scalar_struct(env, meta->btf, ref_t, 0) && 8794 (arg_mem_size ? !btf_type_is_void(ref_t) : 1)) { 8795 verbose(env, "arg#%d pointer type %s %s must point to %sscalar, or struct with scalar\n", 8796 argno, btf_type_str(ref_t), ref_tname, arg_mem_size ? "void, " : ""); 8797 return -EINVAL; 8798 } 8799 return arg_mem_size ? KF_ARG_PTR_TO_MEM_SIZE : KF_ARG_PTR_TO_MEM; 8800 } 8801 8802 static int process_kf_arg_ptr_to_btf_id(struct bpf_verifier_env *env, 8803 struct bpf_reg_state *reg, 8804 const struct btf_type *ref_t, 8805 const char *ref_tname, u32 ref_id, 8806 struct bpf_kfunc_call_arg_meta *meta, 8807 int argno) 8808 { 8809 const struct btf_type *reg_ref_t; 8810 bool strict_type_match = false; 8811 const struct btf *reg_btf; 8812 const char *reg_ref_tname; 8813 u32 reg_ref_id; 8814 8815 if (base_type(reg->type) == PTR_TO_BTF_ID) { 8816 reg_btf = reg->btf; 8817 reg_ref_id = reg->btf_id; 8818 } else { 8819 reg_btf = btf_vmlinux; 8820 reg_ref_id = *reg2btf_ids[base_type(reg->type)]; 8821 } 8822 8823 /* Enforce strict type matching for calls to kfuncs that are acquiring 8824 * or releasing a reference, or are no-cast aliases. We do _not_ 8825 * enforce strict matching for plain KF_TRUSTED_ARGS kfuncs by default, 8826 * as we want to enable BPF programs to pass types that are bitwise 8827 * equivalent without forcing them to explicitly cast with something 8828 * like bpf_cast_to_kern_ctx(). 8829 * 8830 * For example, say we had a type like the following: 8831 * 8832 * struct bpf_cpumask { 8833 * cpumask_t cpumask; 8834 * refcount_t usage; 8835 * }; 8836 * 8837 * Note that as specified in <linux/cpumask.h>, cpumask_t is typedef'ed 8838 * to a struct cpumask, so it would be safe to pass a struct 8839 * bpf_cpumask * to a kfunc expecting a struct cpumask *. 8840 * 8841 * The philosophy here is similar to how we allow scalars of different 8842 * types to be passed to kfuncs as long as the size is the same. The 8843 * only difference here is that we're simply allowing 8844 * btf_struct_ids_match() to walk the struct at the 0th offset, and 8845 * resolve types. 8846 */ 8847 if (is_kfunc_acquire(meta) || 8848 (is_kfunc_release(meta) && reg->ref_obj_id) || 8849 btf_type_ids_nocast_alias(&env->log, reg_btf, reg_ref_id, meta->btf, ref_id)) 8850 strict_type_match = true; 8851 8852 WARN_ON_ONCE(is_kfunc_trusted_args(meta) && reg->off); 8853 8854 reg_ref_t = btf_type_skip_modifiers(reg_btf, reg_ref_id, ®_ref_id); 8855 reg_ref_tname = btf_name_by_offset(reg_btf, reg_ref_t->name_off); 8856 if (!btf_struct_ids_match(&env->log, reg_btf, reg_ref_id, reg->off, meta->btf, ref_id, strict_type_match)) { 8857 verbose(env, "kernel function %s args#%d expected pointer to %s %s but R%d has a pointer to %s %s\n", 8858 meta->func_name, argno, btf_type_str(ref_t), ref_tname, argno + 1, 8859 btf_type_str(reg_ref_t), reg_ref_tname); 8860 return -EINVAL; 8861 } 8862 return 0; 8863 } 8864 8865 static int process_kf_arg_ptr_to_kptr(struct bpf_verifier_env *env, 8866 struct bpf_reg_state *reg, 8867 const struct btf_type *ref_t, 8868 const char *ref_tname, 8869 struct bpf_kfunc_call_arg_meta *meta, 8870 int argno) 8871 { 8872 struct btf_field *kptr_field; 8873 8874 /* check_func_arg_reg_off allows var_off for 8875 * PTR_TO_MAP_VALUE, but we need fixed offset to find 8876 * off_desc. 8877 */ 8878 if (!tnum_is_const(reg->var_off)) { 8879 verbose(env, "arg#0 must have constant offset\n"); 8880 return -EINVAL; 8881 } 8882 8883 kptr_field = btf_record_find(reg->map_ptr->record, reg->off + reg->var_off.value, BPF_KPTR); 8884 if (!kptr_field || kptr_field->type != BPF_KPTR_REF) { 8885 verbose(env, "arg#0 no referenced kptr at map value offset=%llu\n", 8886 reg->off + reg->var_off.value); 8887 return -EINVAL; 8888 } 8889 8890 if (!btf_struct_ids_match(&env->log, meta->btf, ref_t->type, 0, kptr_field->kptr.btf, 8891 kptr_field->kptr.btf_id, true)) { 8892 verbose(env, "kernel function %s args#%d expected pointer to %s %s\n", 8893 meta->func_name, argno, btf_type_str(ref_t), ref_tname); 8894 return -EINVAL; 8895 } 8896 return 0; 8897 } 8898 8899 static int ref_set_release_on_unlock(struct bpf_verifier_env *env, u32 ref_obj_id) 8900 { 8901 struct bpf_func_state *state = cur_func(env); 8902 struct bpf_reg_state *reg; 8903 int i; 8904 8905 /* bpf_spin_lock only allows calling list_push and list_pop, no BPF 8906 * subprogs, no global functions. This means that the references would 8907 * not be released inside the critical section but they may be added to 8908 * the reference state, and the acquired_refs are never copied out for a 8909 * different frame as BPF to BPF calls don't work in bpf_spin_lock 8910 * critical sections. 8911 */ 8912 if (!ref_obj_id) { 8913 verbose(env, "verifier internal error: ref_obj_id is zero for release_on_unlock\n"); 8914 return -EFAULT; 8915 } 8916 for (i = 0; i < state->acquired_refs; i++) { 8917 if (state->refs[i].id == ref_obj_id) { 8918 if (state->refs[i].release_on_unlock) { 8919 verbose(env, "verifier internal error: expected false release_on_unlock"); 8920 return -EFAULT; 8921 } 8922 state->refs[i].release_on_unlock = true; 8923 /* Now mark everyone sharing same ref_obj_id as untrusted */ 8924 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 8925 if (reg->ref_obj_id == ref_obj_id) 8926 reg->type |= PTR_UNTRUSTED; 8927 })); 8928 return 0; 8929 } 8930 } 8931 verbose(env, "verifier internal error: ref state missing for ref_obj_id\n"); 8932 return -EFAULT; 8933 } 8934 8935 /* Implementation details: 8936 * 8937 * Each register points to some region of memory, which we define as an 8938 * allocation. Each allocation may embed a bpf_spin_lock which protects any 8939 * special BPF objects (bpf_list_head, bpf_rb_root, etc.) part of the same 8940 * allocation. The lock and the data it protects are colocated in the same 8941 * memory region. 8942 * 8943 * Hence, everytime a register holds a pointer value pointing to such 8944 * allocation, the verifier preserves a unique reg->id for it. 8945 * 8946 * The verifier remembers the lock 'ptr' and the lock 'id' whenever 8947 * bpf_spin_lock is called. 8948 * 8949 * To enable this, lock state in the verifier captures two values: 8950 * active_lock.ptr = Register's type specific pointer 8951 * active_lock.id = A unique ID for each register pointer value 8952 * 8953 * Currently, PTR_TO_MAP_VALUE and PTR_TO_BTF_ID | MEM_ALLOC are the two 8954 * supported register types. 8955 * 8956 * The active_lock.ptr in case of map values is the reg->map_ptr, and in case of 8957 * allocated objects is the reg->btf pointer. 8958 * 8959 * The active_lock.id is non-unique for maps supporting direct_value_addr, as we 8960 * can establish the provenance of the map value statically for each distinct 8961 * lookup into such maps. They always contain a single map value hence unique 8962 * IDs for each pseudo load pessimizes the algorithm and rejects valid programs. 8963 * 8964 * So, in case of global variables, they use array maps with max_entries = 1, 8965 * hence their active_lock.ptr becomes map_ptr and id = 0 (since they all point 8966 * into the same map value as max_entries is 1, as described above). 8967 * 8968 * In case of inner map lookups, the inner map pointer has same map_ptr as the 8969 * outer map pointer (in verifier context), but each lookup into an inner map 8970 * assigns a fresh reg->id to the lookup, so while lookups into distinct inner 8971 * maps from the same outer map share the same map_ptr as active_lock.ptr, they 8972 * will get different reg->id assigned to each lookup, hence different 8973 * active_lock.id. 8974 * 8975 * In case of allocated objects, active_lock.ptr is the reg->btf, and the 8976 * reg->id is a unique ID preserved after the NULL pointer check on the pointer 8977 * returned from bpf_obj_new. Each allocation receives a new reg->id. 8978 */ 8979 static int check_reg_allocation_locked(struct bpf_verifier_env *env, struct bpf_reg_state *reg) 8980 { 8981 void *ptr; 8982 u32 id; 8983 8984 switch ((int)reg->type) { 8985 case PTR_TO_MAP_VALUE: 8986 ptr = reg->map_ptr; 8987 break; 8988 case PTR_TO_BTF_ID | MEM_ALLOC: 8989 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_TRUSTED: 8990 ptr = reg->btf; 8991 break; 8992 default: 8993 verbose(env, "verifier internal error: unknown reg type for lock check\n"); 8994 return -EFAULT; 8995 } 8996 id = reg->id; 8997 8998 if (!env->cur_state->active_lock.ptr) 8999 return -EINVAL; 9000 if (env->cur_state->active_lock.ptr != ptr || 9001 env->cur_state->active_lock.id != id) { 9002 verbose(env, "held lock and object are not in the same allocation\n"); 9003 return -EINVAL; 9004 } 9005 return 0; 9006 } 9007 9008 static bool is_bpf_list_api_kfunc(u32 btf_id) 9009 { 9010 return btf_id == special_kfunc_list[KF_bpf_list_push_front] || 9011 btf_id == special_kfunc_list[KF_bpf_list_push_back] || 9012 btf_id == special_kfunc_list[KF_bpf_list_pop_front] || 9013 btf_id == special_kfunc_list[KF_bpf_list_pop_back]; 9014 } 9015 9016 static int process_kf_arg_ptr_to_list_head(struct bpf_verifier_env *env, 9017 struct bpf_reg_state *reg, u32 regno, 9018 struct bpf_kfunc_call_arg_meta *meta) 9019 { 9020 struct btf_field *field; 9021 struct btf_record *rec; 9022 u32 list_head_off; 9023 9024 if (meta->btf != btf_vmlinux || !is_bpf_list_api_kfunc(meta->func_id)) { 9025 verbose(env, "verifier internal error: bpf_list_head argument for unknown kfunc\n"); 9026 return -EFAULT; 9027 } 9028 9029 if (!tnum_is_const(reg->var_off)) { 9030 verbose(env, 9031 "R%d doesn't have constant offset. bpf_list_head has to be at the constant offset\n", 9032 regno); 9033 return -EINVAL; 9034 } 9035 9036 rec = reg_btf_record(reg); 9037 list_head_off = reg->off + reg->var_off.value; 9038 field = btf_record_find(rec, list_head_off, BPF_LIST_HEAD); 9039 if (!field) { 9040 verbose(env, "bpf_list_head not found at offset=%u\n", list_head_off); 9041 return -EINVAL; 9042 } 9043 9044 /* All functions require bpf_list_head to be protected using a bpf_spin_lock */ 9045 if (check_reg_allocation_locked(env, reg)) { 9046 verbose(env, "bpf_spin_lock at off=%d must be held for bpf_list_head\n", 9047 rec->spin_lock_off); 9048 return -EINVAL; 9049 } 9050 9051 if (meta->arg_list_head.field) { 9052 verbose(env, "verifier internal error: repeating bpf_list_head arg\n"); 9053 return -EFAULT; 9054 } 9055 meta->arg_list_head.field = field; 9056 return 0; 9057 } 9058 9059 static int process_kf_arg_ptr_to_list_node(struct bpf_verifier_env *env, 9060 struct bpf_reg_state *reg, u32 regno, 9061 struct bpf_kfunc_call_arg_meta *meta) 9062 { 9063 const struct btf_type *et, *t; 9064 struct btf_field *field; 9065 struct btf_record *rec; 9066 u32 list_node_off; 9067 9068 if (meta->btf != btf_vmlinux || 9069 (meta->func_id != special_kfunc_list[KF_bpf_list_push_front] && 9070 meta->func_id != special_kfunc_list[KF_bpf_list_push_back])) { 9071 verbose(env, "verifier internal error: bpf_list_node argument for unknown kfunc\n"); 9072 return -EFAULT; 9073 } 9074 9075 if (!tnum_is_const(reg->var_off)) { 9076 verbose(env, 9077 "R%d doesn't have constant offset. bpf_list_node has to be at the constant offset\n", 9078 regno); 9079 return -EINVAL; 9080 } 9081 9082 rec = reg_btf_record(reg); 9083 list_node_off = reg->off + reg->var_off.value; 9084 field = btf_record_find(rec, list_node_off, BPF_LIST_NODE); 9085 if (!field || field->offset != list_node_off) { 9086 verbose(env, "bpf_list_node not found at offset=%u\n", list_node_off); 9087 return -EINVAL; 9088 } 9089 9090 field = meta->arg_list_head.field; 9091 9092 et = btf_type_by_id(field->graph_root.btf, field->graph_root.value_btf_id); 9093 t = btf_type_by_id(reg->btf, reg->btf_id); 9094 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, 0, field->graph_root.btf, 9095 field->graph_root.value_btf_id, true)) { 9096 verbose(env, "operation on bpf_list_head expects arg#1 bpf_list_node at offset=%d " 9097 "in struct %s, but arg is at offset=%d in struct %s\n", 9098 field->graph_root.node_offset, 9099 btf_name_by_offset(field->graph_root.btf, et->name_off), 9100 list_node_off, btf_name_by_offset(reg->btf, t->name_off)); 9101 return -EINVAL; 9102 } 9103 9104 if (list_node_off != field->graph_root.node_offset) { 9105 verbose(env, "arg#1 offset=%d, but expected bpf_list_node at offset=%d in struct %s\n", 9106 list_node_off, field->graph_root.node_offset, 9107 btf_name_by_offset(field->graph_root.btf, et->name_off)); 9108 return -EINVAL; 9109 } 9110 /* Set arg#1 for expiration after unlock */ 9111 return ref_set_release_on_unlock(env, reg->ref_obj_id); 9112 } 9113 9114 static int check_kfunc_args(struct bpf_verifier_env *env, struct bpf_kfunc_call_arg_meta *meta) 9115 { 9116 const char *func_name = meta->func_name, *ref_tname; 9117 const struct btf *btf = meta->btf; 9118 const struct btf_param *args; 9119 u32 i, nargs; 9120 int ret; 9121 9122 args = (const struct btf_param *)(meta->func_proto + 1); 9123 nargs = btf_type_vlen(meta->func_proto); 9124 if (nargs > MAX_BPF_FUNC_REG_ARGS) { 9125 verbose(env, "Function %s has %d > %d args\n", func_name, nargs, 9126 MAX_BPF_FUNC_REG_ARGS); 9127 return -EINVAL; 9128 } 9129 9130 /* Check that BTF function arguments match actual types that the 9131 * verifier sees. 9132 */ 9133 for (i = 0; i < nargs; i++) { 9134 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[i + 1]; 9135 const struct btf_type *t, *ref_t, *resolve_ret; 9136 enum bpf_arg_type arg_type = ARG_DONTCARE; 9137 u32 regno = i + 1, ref_id, type_size; 9138 bool is_ret_buf_sz = false; 9139 int kf_arg_type; 9140 9141 t = btf_type_skip_modifiers(btf, args[i].type, NULL); 9142 9143 if (is_kfunc_arg_ignore(btf, &args[i])) 9144 continue; 9145 9146 if (btf_type_is_scalar(t)) { 9147 if (reg->type != SCALAR_VALUE) { 9148 verbose(env, "R%d is not a scalar\n", regno); 9149 return -EINVAL; 9150 } 9151 9152 if (is_kfunc_arg_constant(meta->btf, &args[i])) { 9153 if (meta->arg_constant.found) { 9154 verbose(env, "verifier internal error: only one constant argument permitted\n"); 9155 return -EFAULT; 9156 } 9157 if (!tnum_is_const(reg->var_off)) { 9158 verbose(env, "R%d must be a known constant\n", regno); 9159 return -EINVAL; 9160 } 9161 ret = mark_chain_precision(env, regno); 9162 if (ret < 0) 9163 return ret; 9164 meta->arg_constant.found = true; 9165 meta->arg_constant.value = reg->var_off.value; 9166 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdonly_buf_size")) { 9167 meta->r0_rdonly = true; 9168 is_ret_buf_sz = true; 9169 } else if (is_kfunc_arg_scalar_with_name(btf, &args[i], "rdwr_buf_size")) { 9170 is_ret_buf_sz = true; 9171 } 9172 9173 if (is_ret_buf_sz) { 9174 if (meta->r0_size) { 9175 verbose(env, "2 or more rdonly/rdwr_buf_size parameters for kfunc"); 9176 return -EINVAL; 9177 } 9178 9179 if (!tnum_is_const(reg->var_off)) { 9180 verbose(env, "R%d is not a const\n", regno); 9181 return -EINVAL; 9182 } 9183 9184 meta->r0_size = reg->var_off.value; 9185 ret = mark_chain_precision(env, regno); 9186 if (ret) 9187 return ret; 9188 } 9189 continue; 9190 } 9191 9192 if (!btf_type_is_ptr(t)) { 9193 verbose(env, "Unrecognized arg#%d type %s\n", i, btf_type_str(t)); 9194 return -EINVAL; 9195 } 9196 9197 if (is_kfunc_trusted_args(meta) && 9198 (register_is_null(reg) || type_may_be_null(reg->type))) { 9199 verbose(env, "Possibly NULL pointer passed to trusted arg%d\n", i); 9200 return -EACCES; 9201 } 9202 9203 if (reg->ref_obj_id) { 9204 if (is_kfunc_release(meta) && meta->ref_obj_id) { 9205 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 9206 regno, reg->ref_obj_id, 9207 meta->ref_obj_id); 9208 return -EFAULT; 9209 } 9210 meta->ref_obj_id = reg->ref_obj_id; 9211 if (is_kfunc_release(meta)) 9212 meta->release_regno = regno; 9213 } 9214 9215 ref_t = btf_type_skip_modifiers(btf, t->type, &ref_id); 9216 ref_tname = btf_name_by_offset(btf, ref_t->name_off); 9217 9218 kf_arg_type = get_kfunc_ptr_arg_type(env, meta, t, ref_t, ref_tname, args, i, nargs); 9219 if (kf_arg_type < 0) 9220 return kf_arg_type; 9221 9222 switch (kf_arg_type) { 9223 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 9224 case KF_ARG_PTR_TO_BTF_ID: 9225 if (!is_kfunc_trusted_args(meta) && !is_kfunc_rcu(meta)) 9226 break; 9227 9228 if (!is_trusted_reg(reg)) { 9229 if (!is_kfunc_rcu(meta)) { 9230 verbose(env, "R%d must be referenced or trusted\n", regno); 9231 return -EINVAL; 9232 } 9233 if (!is_rcu_reg(reg)) { 9234 verbose(env, "R%d must be a rcu pointer\n", regno); 9235 return -EINVAL; 9236 } 9237 } 9238 9239 fallthrough; 9240 case KF_ARG_PTR_TO_CTX: 9241 /* Trusted arguments have the same offset checks as release arguments */ 9242 arg_type |= OBJ_RELEASE; 9243 break; 9244 case KF_ARG_PTR_TO_KPTR: 9245 case KF_ARG_PTR_TO_DYNPTR: 9246 case KF_ARG_PTR_TO_LIST_HEAD: 9247 case KF_ARG_PTR_TO_LIST_NODE: 9248 case KF_ARG_PTR_TO_MEM: 9249 case KF_ARG_PTR_TO_MEM_SIZE: 9250 /* Trusted by default */ 9251 break; 9252 default: 9253 WARN_ON_ONCE(1); 9254 return -EFAULT; 9255 } 9256 9257 if (is_kfunc_release(meta) && reg->ref_obj_id) 9258 arg_type |= OBJ_RELEASE; 9259 ret = check_func_arg_reg_off(env, reg, regno, arg_type); 9260 if (ret < 0) 9261 return ret; 9262 9263 switch (kf_arg_type) { 9264 case KF_ARG_PTR_TO_CTX: 9265 if (reg->type != PTR_TO_CTX) { 9266 verbose(env, "arg#%d expected pointer to ctx, but got %s\n", i, btf_type_str(t)); 9267 return -EINVAL; 9268 } 9269 9270 if (meta->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 9271 ret = get_kern_ctx_btf_id(&env->log, resolve_prog_type(env->prog)); 9272 if (ret < 0) 9273 return -EINVAL; 9274 meta->ret_btf_id = ret; 9275 } 9276 break; 9277 case KF_ARG_PTR_TO_ALLOC_BTF_ID: 9278 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9279 verbose(env, "arg#%d expected pointer to allocated object\n", i); 9280 return -EINVAL; 9281 } 9282 if (!reg->ref_obj_id) { 9283 verbose(env, "allocated object must be referenced\n"); 9284 return -EINVAL; 9285 } 9286 if (meta->btf == btf_vmlinux && 9287 meta->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 9288 meta->arg_obj_drop.btf = reg->btf; 9289 meta->arg_obj_drop.btf_id = reg->btf_id; 9290 } 9291 break; 9292 case KF_ARG_PTR_TO_KPTR: 9293 if (reg->type != PTR_TO_MAP_VALUE) { 9294 verbose(env, "arg#0 expected pointer to map value\n"); 9295 return -EINVAL; 9296 } 9297 ret = process_kf_arg_ptr_to_kptr(env, reg, ref_t, ref_tname, meta, i); 9298 if (ret < 0) 9299 return ret; 9300 break; 9301 case KF_ARG_PTR_TO_DYNPTR: 9302 if (reg->type != PTR_TO_STACK && 9303 reg->type != CONST_PTR_TO_DYNPTR) { 9304 verbose(env, "arg#%d expected pointer to stack or dynptr_ptr\n", i); 9305 return -EINVAL; 9306 } 9307 9308 ret = process_dynptr_func(env, regno, ARG_PTR_TO_DYNPTR | MEM_RDONLY, NULL); 9309 if (ret < 0) 9310 return ret; 9311 break; 9312 case KF_ARG_PTR_TO_LIST_HEAD: 9313 if (reg->type != PTR_TO_MAP_VALUE && 9314 reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9315 verbose(env, "arg#%d expected pointer to map value or allocated object\n", i); 9316 return -EINVAL; 9317 } 9318 if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && !reg->ref_obj_id) { 9319 verbose(env, "allocated object must be referenced\n"); 9320 return -EINVAL; 9321 } 9322 ret = process_kf_arg_ptr_to_list_head(env, reg, regno, meta); 9323 if (ret < 0) 9324 return ret; 9325 break; 9326 case KF_ARG_PTR_TO_LIST_NODE: 9327 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC)) { 9328 verbose(env, "arg#%d expected pointer to allocated object\n", i); 9329 return -EINVAL; 9330 } 9331 if (!reg->ref_obj_id) { 9332 verbose(env, "allocated object must be referenced\n"); 9333 return -EINVAL; 9334 } 9335 ret = process_kf_arg_ptr_to_list_node(env, reg, regno, meta); 9336 if (ret < 0) 9337 return ret; 9338 break; 9339 case KF_ARG_PTR_TO_BTF_ID: 9340 /* Only base_type is checked, further checks are done here */ 9341 if ((base_type(reg->type) != PTR_TO_BTF_ID || 9342 (bpf_type_has_unsafe_modifiers(reg->type) && !is_rcu_reg(reg))) && 9343 !reg2btf_ids[base_type(reg->type)]) { 9344 verbose(env, "arg#%d is %s ", i, reg_type_str(env, reg->type)); 9345 verbose(env, "expected %s or socket\n", 9346 reg_type_str(env, base_type(reg->type) | 9347 (type_flag(reg->type) & BPF_REG_TRUSTED_MODIFIERS))); 9348 return -EINVAL; 9349 } 9350 ret = process_kf_arg_ptr_to_btf_id(env, reg, ref_t, ref_tname, ref_id, meta, i); 9351 if (ret < 0) 9352 return ret; 9353 break; 9354 case KF_ARG_PTR_TO_MEM: 9355 resolve_ret = btf_resolve_size(btf, ref_t, &type_size); 9356 if (IS_ERR(resolve_ret)) { 9357 verbose(env, "arg#%d reference type('%s %s') size cannot be determined: %ld\n", 9358 i, btf_type_str(ref_t), ref_tname, PTR_ERR(resolve_ret)); 9359 return -EINVAL; 9360 } 9361 ret = check_mem_reg(env, reg, regno, type_size); 9362 if (ret < 0) 9363 return ret; 9364 break; 9365 case KF_ARG_PTR_TO_MEM_SIZE: 9366 ret = check_kfunc_mem_size_reg(env, ®s[regno + 1], regno + 1); 9367 if (ret < 0) { 9368 verbose(env, "arg#%d arg#%d memory, len pair leads to invalid memory access\n", i, i + 1); 9369 return ret; 9370 } 9371 /* Skip next '__sz' argument */ 9372 i++; 9373 break; 9374 } 9375 } 9376 9377 if (is_kfunc_release(meta) && !meta->release_regno) { 9378 verbose(env, "release kernel function %s expects refcounted PTR_TO_BTF_ID\n", 9379 func_name); 9380 return -EINVAL; 9381 } 9382 9383 return 0; 9384 } 9385 9386 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 9387 int *insn_idx_p) 9388 { 9389 const struct btf_type *t, *func, *func_proto, *ptr_type; 9390 struct bpf_reg_state *regs = cur_regs(env); 9391 const char *func_name, *ptr_type_name; 9392 bool sleepable, rcu_lock, rcu_unlock; 9393 struct bpf_kfunc_call_arg_meta meta; 9394 u32 i, nargs, func_id, ptr_type_id; 9395 int err, insn_idx = *insn_idx_p; 9396 const struct btf_param *args; 9397 const struct btf_type *ret_t; 9398 struct btf *desc_btf; 9399 u32 *kfunc_flags; 9400 9401 /* skip for now, but return error when we find this in fixup_kfunc_call */ 9402 if (!insn->imm) 9403 return 0; 9404 9405 desc_btf = find_kfunc_desc_btf(env, insn->off); 9406 if (IS_ERR(desc_btf)) 9407 return PTR_ERR(desc_btf); 9408 9409 func_id = insn->imm; 9410 func = btf_type_by_id(desc_btf, func_id); 9411 func_name = btf_name_by_offset(desc_btf, func->name_off); 9412 func_proto = btf_type_by_id(desc_btf, func->type); 9413 9414 kfunc_flags = btf_kfunc_id_set_contains(desc_btf, resolve_prog_type(env->prog), func_id); 9415 if (!kfunc_flags) { 9416 verbose(env, "calling kernel function %s is not allowed\n", 9417 func_name); 9418 return -EACCES; 9419 } 9420 9421 /* Prepare kfunc call metadata */ 9422 memset(&meta, 0, sizeof(meta)); 9423 meta.btf = desc_btf; 9424 meta.func_id = func_id; 9425 meta.kfunc_flags = *kfunc_flags; 9426 meta.func_proto = func_proto; 9427 meta.func_name = func_name; 9428 9429 if (is_kfunc_destructive(&meta) && !capable(CAP_SYS_BOOT)) { 9430 verbose(env, "destructive kfunc calls require CAP_SYS_BOOT capability\n"); 9431 return -EACCES; 9432 } 9433 9434 sleepable = is_kfunc_sleepable(&meta); 9435 if (sleepable && !env->prog->aux->sleepable) { 9436 verbose(env, "program must be sleepable to call sleepable kfunc %s\n", func_name); 9437 return -EACCES; 9438 } 9439 9440 rcu_lock = is_kfunc_bpf_rcu_read_lock(&meta); 9441 rcu_unlock = is_kfunc_bpf_rcu_read_unlock(&meta); 9442 if ((rcu_lock || rcu_unlock) && !env->rcu_tag_supported) { 9443 verbose(env, "no vmlinux btf rcu tag support for kfunc %s\n", func_name); 9444 return -EACCES; 9445 } 9446 9447 if (env->cur_state->active_rcu_lock) { 9448 struct bpf_func_state *state; 9449 struct bpf_reg_state *reg; 9450 9451 if (rcu_lock) { 9452 verbose(env, "nested rcu read lock (kernel function %s)\n", func_name); 9453 return -EINVAL; 9454 } else if (rcu_unlock) { 9455 bpf_for_each_reg_in_vstate(env->cur_state, state, reg, ({ 9456 if (reg->type & MEM_RCU) { 9457 reg->type &= ~(MEM_RCU | PTR_MAYBE_NULL); 9458 reg->type |= PTR_UNTRUSTED; 9459 } 9460 })); 9461 env->cur_state->active_rcu_lock = false; 9462 } else if (sleepable) { 9463 verbose(env, "kernel func %s is sleepable within rcu_read_lock region\n", func_name); 9464 return -EACCES; 9465 } 9466 } else if (rcu_lock) { 9467 env->cur_state->active_rcu_lock = true; 9468 } else if (rcu_unlock) { 9469 verbose(env, "unmatched rcu read unlock (kernel function %s)\n", func_name); 9470 return -EINVAL; 9471 } 9472 9473 /* Check the arguments */ 9474 err = check_kfunc_args(env, &meta); 9475 if (err < 0) 9476 return err; 9477 /* In case of release function, we get register number of refcounted 9478 * PTR_TO_BTF_ID in bpf_kfunc_arg_meta, do the release now. 9479 */ 9480 if (meta.release_regno) { 9481 err = release_reference(env, regs[meta.release_regno].ref_obj_id); 9482 if (err) { 9483 verbose(env, "kfunc %s#%d reference has not been acquired before\n", 9484 func_name, func_id); 9485 return err; 9486 } 9487 } 9488 9489 for (i = 0; i < CALLER_SAVED_REGS; i++) 9490 mark_reg_not_init(env, regs, caller_saved[i]); 9491 9492 /* Check return type */ 9493 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL); 9494 9495 if (is_kfunc_acquire(&meta) && !btf_type_is_struct_ptr(meta.btf, t)) { 9496 /* Only exception is bpf_obj_new_impl */ 9497 if (meta.btf != btf_vmlinux || meta.func_id != special_kfunc_list[KF_bpf_obj_new_impl]) { 9498 verbose(env, "acquire kernel function does not return PTR_TO_BTF_ID\n"); 9499 return -EINVAL; 9500 } 9501 } 9502 9503 if (btf_type_is_scalar(t)) { 9504 mark_reg_unknown(env, regs, BPF_REG_0); 9505 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 9506 } else if (btf_type_is_ptr(t)) { 9507 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, &ptr_type_id); 9508 9509 if (meta.btf == btf_vmlinux && btf_id_set_contains(&special_kfunc_set, meta.func_id)) { 9510 if (meta.func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 9511 struct btf *ret_btf; 9512 u32 ret_btf_id; 9513 9514 if (unlikely(!bpf_global_ma_set)) 9515 return -ENOMEM; 9516 9517 if (((u64)(u32)meta.arg_constant.value) != meta.arg_constant.value) { 9518 verbose(env, "local type ID argument must be in range [0, U32_MAX]\n"); 9519 return -EINVAL; 9520 } 9521 9522 ret_btf = env->prog->aux->btf; 9523 ret_btf_id = meta.arg_constant.value; 9524 9525 /* This may be NULL due to user not supplying a BTF */ 9526 if (!ret_btf) { 9527 verbose(env, "bpf_obj_new requires prog BTF\n"); 9528 return -EINVAL; 9529 } 9530 9531 ret_t = btf_type_by_id(ret_btf, ret_btf_id); 9532 if (!ret_t || !__btf_type_is_struct(ret_t)) { 9533 verbose(env, "bpf_obj_new type ID argument must be of a struct\n"); 9534 return -EINVAL; 9535 } 9536 9537 mark_reg_known_zero(env, regs, BPF_REG_0); 9538 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 9539 regs[BPF_REG_0].btf = ret_btf; 9540 regs[BPF_REG_0].btf_id = ret_btf_id; 9541 9542 env->insn_aux_data[insn_idx].obj_new_size = ret_t->size; 9543 env->insn_aux_data[insn_idx].kptr_struct_meta = 9544 btf_find_struct_meta(ret_btf, ret_btf_id); 9545 } else if (meta.func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 9546 env->insn_aux_data[insn_idx].kptr_struct_meta = 9547 btf_find_struct_meta(meta.arg_obj_drop.btf, 9548 meta.arg_obj_drop.btf_id); 9549 } else if (meta.func_id == special_kfunc_list[KF_bpf_list_pop_front] || 9550 meta.func_id == special_kfunc_list[KF_bpf_list_pop_back]) { 9551 struct btf_field *field = meta.arg_list_head.field; 9552 9553 mark_reg_known_zero(env, regs, BPF_REG_0); 9554 regs[BPF_REG_0].type = PTR_TO_BTF_ID | MEM_ALLOC; 9555 regs[BPF_REG_0].btf = field->graph_root.btf; 9556 regs[BPF_REG_0].btf_id = field->graph_root.value_btf_id; 9557 regs[BPF_REG_0].off = field->graph_root.node_offset; 9558 } else if (meta.func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx]) { 9559 mark_reg_known_zero(env, regs, BPF_REG_0); 9560 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_TRUSTED; 9561 regs[BPF_REG_0].btf = desc_btf; 9562 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 9563 } else if (meta.func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 9564 ret_t = btf_type_by_id(desc_btf, meta.arg_constant.value); 9565 if (!ret_t || !btf_type_is_struct(ret_t)) { 9566 verbose(env, 9567 "kfunc bpf_rdonly_cast type ID argument must be of a struct\n"); 9568 return -EINVAL; 9569 } 9570 9571 mark_reg_known_zero(env, regs, BPF_REG_0); 9572 regs[BPF_REG_0].type = PTR_TO_BTF_ID | PTR_UNTRUSTED; 9573 regs[BPF_REG_0].btf = desc_btf; 9574 regs[BPF_REG_0].btf_id = meta.arg_constant.value; 9575 } else { 9576 verbose(env, "kernel function %s unhandled dynamic return type\n", 9577 meta.func_name); 9578 return -EFAULT; 9579 } 9580 } else if (!__btf_type_is_struct(ptr_type)) { 9581 if (!meta.r0_size) { 9582 ptr_type_name = btf_name_by_offset(desc_btf, 9583 ptr_type->name_off); 9584 verbose(env, 9585 "kernel function %s returns pointer type %s %s is not supported\n", 9586 func_name, 9587 btf_type_str(ptr_type), 9588 ptr_type_name); 9589 return -EINVAL; 9590 } 9591 9592 mark_reg_known_zero(env, regs, BPF_REG_0); 9593 regs[BPF_REG_0].type = PTR_TO_MEM; 9594 regs[BPF_REG_0].mem_size = meta.r0_size; 9595 9596 if (meta.r0_rdonly) 9597 regs[BPF_REG_0].type |= MEM_RDONLY; 9598 9599 /* Ensures we don't access the memory after a release_reference() */ 9600 if (meta.ref_obj_id) 9601 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 9602 } else { 9603 mark_reg_known_zero(env, regs, BPF_REG_0); 9604 regs[BPF_REG_0].btf = desc_btf; 9605 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 9606 regs[BPF_REG_0].btf_id = ptr_type_id; 9607 } 9608 9609 if (is_kfunc_ret_null(&meta)) { 9610 regs[BPF_REG_0].type |= PTR_MAYBE_NULL; 9611 /* For mark_ptr_or_null_reg, see 93c230e3f5bd6 */ 9612 regs[BPF_REG_0].id = ++env->id_gen; 9613 } 9614 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 9615 if (is_kfunc_acquire(&meta)) { 9616 int id = acquire_reference_state(env, insn_idx); 9617 9618 if (id < 0) 9619 return id; 9620 if (is_kfunc_ret_null(&meta)) 9621 regs[BPF_REG_0].id = id; 9622 regs[BPF_REG_0].ref_obj_id = id; 9623 } 9624 if (reg_may_point_to_spin_lock(®s[BPF_REG_0]) && !regs[BPF_REG_0].id) 9625 regs[BPF_REG_0].id = ++env->id_gen; 9626 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */ 9627 9628 nargs = btf_type_vlen(func_proto); 9629 args = (const struct btf_param *)(func_proto + 1); 9630 for (i = 0; i < nargs; i++) { 9631 u32 regno = i + 1; 9632 9633 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 9634 if (btf_type_is_ptr(t)) 9635 mark_btf_func_reg_size(env, regno, sizeof(void *)); 9636 else 9637 /* scalar. ensured by btf_check_kfunc_arg_match() */ 9638 mark_btf_func_reg_size(env, regno, t->size); 9639 } 9640 9641 return 0; 9642 } 9643 9644 static bool signed_add_overflows(s64 a, s64 b) 9645 { 9646 /* Do the add in u64, where overflow is well-defined */ 9647 s64 res = (s64)((u64)a + (u64)b); 9648 9649 if (b < 0) 9650 return res > a; 9651 return res < a; 9652 } 9653 9654 static bool signed_add32_overflows(s32 a, s32 b) 9655 { 9656 /* Do the add in u32, where overflow is well-defined */ 9657 s32 res = (s32)((u32)a + (u32)b); 9658 9659 if (b < 0) 9660 return res > a; 9661 return res < a; 9662 } 9663 9664 static bool signed_sub_overflows(s64 a, s64 b) 9665 { 9666 /* Do the sub in u64, where overflow is well-defined */ 9667 s64 res = (s64)((u64)a - (u64)b); 9668 9669 if (b < 0) 9670 return res < a; 9671 return res > a; 9672 } 9673 9674 static bool signed_sub32_overflows(s32 a, s32 b) 9675 { 9676 /* Do the sub in u32, where overflow is well-defined */ 9677 s32 res = (s32)((u32)a - (u32)b); 9678 9679 if (b < 0) 9680 return res < a; 9681 return res > a; 9682 } 9683 9684 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 9685 const struct bpf_reg_state *reg, 9686 enum bpf_reg_type type) 9687 { 9688 bool known = tnum_is_const(reg->var_off); 9689 s64 val = reg->var_off.value; 9690 s64 smin = reg->smin_value; 9691 9692 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 9693 verbose(env, "math between %s pointer and %lld is not allowed\n", 9694 reg_type_str(env, type), val); 9695 return false; 9696 } 9697 9698 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 9699 verbose(env, "%s pointer offset %d is not allowed\n", 9700 reg_type_str(env, type), reg->off); 9701 return false; 9702 } 9703 9704 if (smin == S64_MIN) { 9705 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 9706 reg_type_str(env, type)); 9707 return false; 9708 } 9709 9710 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 9711 verbose(env, "value %lld makes %s pointer be out of bounds\n", 9712 smin, reg_type_str(env, type)); 9713 return false; 9714 } 9715 9716 return true; 9717 } 9718 9719 enum { 9720 REASON_BOUNDS = -1, 9721 REASON_TYPE = -2, 9722 REASON_PATHS = -3, 9723 REASON_LIMIT = -4, 9724 REASON_STACK = -5, 9725 }; 9726 9727 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 9728 u32 *alu_limit, bool mask_to_left) 9729 { 9730 u32 max = 0, ptr_limit = 0; 9731 9732 switch (ptr_reg->type) { 9733 case PTR_TO_STACK: 9734 /* Offset 0 is out-of-bounds, but acceptable start for the 9735 * left direction, see BPF_REG_FP. Also, unknown scalar 9736 * offset where we would need to deal with min/max bounds is 9737 * currently prohibited for unprivileged. 9738 */ 9739 max = MAX_BPF_STACK + mask_to_left; 9740 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 9741 break; 9742 case PTR_TO_MAP_VALUE: 9743 max = ptr_reg->map_ptr->value_size; 9744 ptr_limit = (mask_to_left ? 9745 ptr_reg->smin_value : 9746 ptr_reg->umax_value) + ptr_reg->off; 9747 break; 9748 default: 9749 return REASON_TYPE; 9750 } 9751 9752 if (ptr_limit >= max) 9753 return REASON_LIMIT; 9754 *alu_limit = ptr_limit; 9755 return 0; 9756 } 9757 9758 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 9759 const struct bpf_insn *insn) 9760 { 9761 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 9762 } 9763 9764 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 9765 u32 alu_state, u32 alu_limit) 9766 { 9767 /* If we arrived here from different branches with different 9768 * state or limits to sanitize, then this won't work. 9769 */ 9770 if (aux->alu_state && 9771 (aux->alu_state != alu_state || 9772 aux->alu_limit != alu_limit)) 9773 return REASON_PATHS; 9774 9775 /* Corresponding fixup done in do_misc_fixups(). */ 9776 aux->alu_state = alu_state; 9777 aux->alu_limit = alu_limit; 9778 return 0; 9779 } 9780 9781 static int sanitize_val_alu(struct bpf_verifier_env *env, 9782 struct bpf_insn *insn) 9783 { 9784 struct bpf_insn_aux_data *aux = cur_aux(env); 9785 9786 if (can_skip_alu_sanitation(env, insn)) 9787 return 0; 9788 9789 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 9790 } 9791 9792 static bool sanitize_needed(u8 opcode) 9793 { 9794 return opcode == BPF_ADD || opcode == BPF_SUB; 9795 } 9796 9797 struct bpf_sanitize_info { 9798 struct bpf_insn_aux_data aux; 9799 bool mask_to_left; 9800 }; 9801 9802 static struct bpf_verifier_state * 9803 sanitize_speculative_path(struct bpf_verifier_env *env, 9804 const struct bpf_insn *insn, 9805 u32 next_idx, u32 curr_idx) 9806 { 9807 struct bpf_verifier_state *branch; 9808 struct bpf_reg_state *regs; 9809 9810 branch = push_stack(env, next_idx, curr_idx, true); 9811 if (branch && insn) { 9812 regs = branch->frame[branch->curframe]->regs; 9813 if (BPF_SRC(insn->code) == BPF_K) { 9814 mark_reg_unknown(env, regs, insn->dst_reg); 9815 } else if (BPF_SRC(insn->code) == BPF_X) { 9816 mark_reg_unknown(env, regs, insn->dst_reg); 9817 mark_reg_unknown(env, regs, insn->src_reg); 9818 } 9819 } 9820 return branch; 9821 } 9822 9823 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 9824 struct bpf_insn *insn, 9825 const struct bpf_reg_state *ptr_reg, 9826 const struct bpf_reg_state *off_reg, 9827 struct bpf_reg_state *dst_reg, 9828 struct bpf_sanitize_info *info, 9829 const bool commit_window) 9830 { 9831 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 9832 struct bpf_verifier_state *vstate = env->cur_state; 9833 bool off_is_imm = tnum_is_const(off_reg->var_off); 9834 bool off_is_neg = off_reg->smin_value < 0; 9835 bool ptr_is_dst_reg = ptr_reg == dst_reg; 9836 u8 opcode = BPF_OP(insn->code); 9837 u32 alu_state, alu_limit; 9838 struct bpf_reg_state tmp; 9839 bool ret; 9840 int err; 9841 9842 if (can_skip_alu_sanitation(env, insn)) 9843 return 0; 9844 9845 /* We already marked aux for masking from non-speculative 9846 * paths, thus we got here in the first place. We only care 9847 * to explore bad access from here. 9848 */ 9849 if (vstate->speculative) 9850 goto do_sim; 9851 9852 if (!commit_window) { 9853 if (!tnum_is_const(off_reg->var_off) && 9854 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 9855 return REASON_BOUNDS; 9856 9857 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 9858 (opcode == BPF_SUB && !off_is_neg); 9859 } 9860 9861 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 9862 if (err < 0) 9863 return err; 9864 9865 if (commit_window) { 9866 /* In commit phase we narrow the masking window based on 9867 * the observed pointer move after the simulated operation. 9868 */ 9869 alu_state = info->aux.alu_state; 9870 alu_limit = abs(info->aux.alu_limit - alu_limit); 9871 } else { 9872 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 9873 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 9874 alu_state |= ptr_is_dst_reg ? 9875 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 9876 9877 /* Limit pruning on unknown scalars to enable deep search for 9878 * potential masking differences from other program paths. 9879 */ 9880 if (!off_is_imm) 9881 env->explore_alu_limits = true; 9882 } 9883 9884 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 9885 if (err < 0) 9886 return err; 9887 do_sim: 9888 /* If we're in commit phase, we're done here given we already 9889 * pushed the truncated dst_reg into the speculative verification 9890 * stack. 9891 * 9892 * Also, when register is a known constant, we rewrite register-based 9893 * operation to immediate-based, and thus do not need masking (and as 9894 * a consequence, do not need to simulate the zero-truncation either). 9895 */ 9896 if (commit_window || off_is_imm) 9897 return 0; 9898 9899 /* Simulate and find potential out-of-bounds access under 9900 * speculative execution from truncation as a result of 9901 * masking when off was not within expected range. If off 9902 * sits in dst, then we temporarily need to move ptr there 9903 * to simulate dst (== 0) +/-= ptr. Needed, for example, 9904 * for cases where we use K-based arithmetic in one direction 9905 * and truncated reg-based in the other in order to explore 9906 * bad access. 9907 */ 9908 if (!ptr_is_dst_reg) { 9909 tmp = *dst_reg; 9910 *dst_reg = *ptr_reg; 9911 } 9912 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 9913 env->insn_idx); 9914 if (!ptr_is_dst_reg && ret) 9915 *dst_reg = tmp; 9916 return !ret ? REASON_STACK : 0; 9917 } 9918 9919 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 9920 { 9921 struct bpf_verifier_state *vstate = env->cur_state; 9922 9923 /* If we simulate paths under speculation, we don't update the 9924 * insn as 'seen' such that when we verify unreachable paths in 9925 * the non-speculative domain, sanitize_dead_code() can still 9926 * rewrite/sanitize them. 9927 */ 9928 if (!vstate->speculative) 9929 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 9930 } 9931 9932 static int sanitize_err(struct bpf_verifier_env *env, 9933 const struct bpf_insn *insn, int reason, 9934 const struct bpf_reg_state *off_reg, 9935 const struct bpf_reg_state *dst_reg) 9936 { 9937 static const char *err = "pointer arithmetic with it prohibited for !root"; 9938 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 9939 u32 dst = insn->dst_reg, src = insn->src_reg; 9940 9941 switch (reason) { 9942 case REASON_BOUNDS: 9943 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 9944 off_reg == dst_reg ? dst : src, err); 9945 break; 9946 case REASON_TYPE: 9947 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 9948 off_reg == dst_reg ? src : dst, err); 9949 break; 9950 case REASON_PATHS: 9951 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 9952 dst, op, err); 9953 break; 9954 case REASON_LIMIT: 9955 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 9956 dst, op, err); 9957 break; 9958 case REASON_STACK: 9959 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 9960 dst, err); 9961 break; 9962 default: 9963 verbose(env, "verifier internal error: unknown reason (%d)\n", 9964 reason); 9965 break; 9966 } 9967 9968 return -EACCES; 9969 } 9970 9971 /* check that stack access falls within stack limits and that 'reg' doesn't 9972 * have a variable offset. 9973 * 9974 * Variable offset is prohibited for unprivileged mode for simplicity since it 9975 * requires corresponding support in Spectre masking for stack ALU. See also 9976 * retrieve_ptr_limit(). 9977 * 9978 * 9979 * 'off' includes 'reg->off'. 9980 */ 9981 static int check_stack_access_for_ptr_arithmetic( 9982 struct bpf_verifier_env *env, 9983 int regno, 9984 const struct bpf_reg_state *reg, 9985 int off) 9986 { 9987 if (!tnum_is_const(reg->var_off)) { 9988 char tn_buf[48]; 9989 9990 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 9991 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 9992 regno, tn_buf, off); 9993 return -EACCES; 9994 } 9995 9996 if (off >= 0 || off < -MAX_BPF_STACK) { 9997 verbose(env, "R%d stack pointer arithmetic goes out of range, " 9998 "prohibited for !root; off=%d\n", regno, off); 9999 return -EACCES; 10000 } 10001 10002 return 0; 10003 } 10004 10005 static int sanitize_check_bounds(struct bpf_verifier_env *env, 10006 const struct bpf_insn *insn, 10007 const struct bpf_reg_state *dst_reg) 10008 { 10009 u32 dst = insn->dst_reg; 10010 10011 /* For unprivileged we require that resulting offset must be in bounds 10012 * in order to be able to sanitize access later on. 10013 */ 10014 if (env->bypass_spec_v1) 10015 return 0; 10016 10017 switch (dst_reg->type) { 10018 case PTR_TO_STACK: 10019 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 10020 dst_reg->off + dst_reg->var_off.value)) 10021 return -EACCES; 10022 break; 10023 case PTR_TO_MAP_VALUE: 10024 if (check_map_access(env, dst, dst_reg->off, 1, false, ACCESS_HELPER)) { 10025 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 10026 "prohibited for !root\n", dst); 10027 return -EACCES; 10028 } 10029 break; 10030 default: 10031 break; 10032 } 10033 10034 return 0; 10035 } 10036 10037 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 10038 * Caller should also handle BPF_MOV case separately. 10039 * If we return -EACCES, caller may want to try again treating pointer as a 10040 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 10041 */ 10042 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 10043 struct bpf_insn *insn, 10044 const struct bpf_reg_state *ptr_reg, 10045 const struct bpf_reg_state *off_reg) 10046 { 10047 struct bpf_verifier_state *vstate = env->cur_state; 10048 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 10049 struct bpf_reg_state *regs = state->regs, *dst_reg; 10050 bool known = tnum_is_const(off_reg->var_off); 10051 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 10052 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 10053 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 10054 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 10055 struct bpf_sanitize_info info = {}; 10056 u8 opcode = BPF_OP(insn->code); 10057 u32 dst = insn->dst_reg; 10058 int ret; 10059 10060 dst_reg = ®s[dst]; 10061 10062 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 10063 smin_val > smax_val || umin_val > umax_val) { 10064 /* Taint dst register if offset had invalid bounds derived from 10065 * e.g. dead branches. 10066 */ 10067 __mark_reg_unknown(env, dst_reg); 10068 return 0; 10069 } 10070 10071 if (BPF_CLASS(insn->code) != BPF_ALU64) { 10072 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 10073 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 10074 __mark_reg_unknown(env, dst_reg); 10075 return 0; 10076 } 10077 10078 verbose(env, 10079 "R%d 32-bit pointer arithmetic prohibited\n", 10080 dst); 10081 return -EACCES; 10082 } 10083 10084 if (ptr_reg->type & PTR_MAYBE_NULL) { 10085 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 10086 dst, reg_type_str(env, ptr_reg->type)); 10087 return -EACCES; 10088 } 10089 10090 switch (base_type(ptr_reg->type)) { 10091 case CONST_PTR_TO_MAP: 10092 /* smin_val represents the known value */ 10093 if (known && smin_val == 0 && opcode == BPF_ADD) 10094 break; 10095 fallthrough; 10096 case PTR_TO_PACKET_END: 10097 case PTR_TO_SOCKET: 10098 case PTR_TO_SOCK_COMMON: 10099 case PTR_TO_TCP_SOCK: 10100 case PTR_TO_XDP_SOCK: 10101 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 10102 dst, reg_type_str(env, ptr_reg->type)); 10103 return -EACCES; 10104 default: 10105 break; 10106 } 10107 10108 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 10109 * The id may be overwritten later if we create a new variable offset. 10110 */ 10111 dst_reg->type = ptr_reg->type; 10112 dst_reg->id = ptr_reg->id; 10113 10114 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 10115 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 10116 return -EINVAL; 10117 10118 /* pointer types do not carry 32-bit bounds at the moment. */ 10119 __mark_reg32_unbounded(dst_reg); 10120 10121 if (sanitize_needed(opcode)) { 10122 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 10123 &info, false); 10124 if (ret < 0) 10125 return sanitize_err(env, insn, ret, off_reg, dst_reg); 10126 } 10127 10128 switch (opcode) { 10129 case BPF_ADD: 10130 /* We can take a fixed offset as long as it doesn't overflow 10131 * the s32 'off' field 10132 */ 10133 if (known && (ptr_reg->off + smin_val == 10134 (s64)(s32)(ptr_reg->off + smin_val))) { 10135 /* pointer += K. Accumulate it into fixed offset */ 10136 dst_reg->smin_value = smin_ptr; 10137 dst_reg->smax_value = smax_ptr; 10138 dst_reg->umin_value = umin_ptr; 10139 dst_reg->umax_value = umax_ptr; 10140 dst_reg->var_off = ptr_reg->var_off; 10141 dst_reg->off = ptr_reg->off + smin_val; 10142 dst_reg->raw = ptr_reg->raw; 10143 break; 10144 } 10145 /* A new variable offset is created. Note that off_reg->off 10146 * == 0, since it's a scalar. 10147 * dst_reg gets the pointer type and since some positive 10148 * integer value was added to the pointer, give it a new 'id' 10149 * if it's a PTR_TO_PACKET. 10150 * this creates a new 'base' pointer, off_reg (variable) gets 10151 * added into the variable offset, and we copy the fixed offset 10152 * from ptr_reg. 10153 */ 10154 if (signed_add_overflows(smin_ptr, smin_val) || 10155 signed_add_overflows(smax_ptr, smax_val)) { 10156 dst_reg->smin_value = S64_MIN; 10157 dst_reg->smax_value = S64_MAX; 10158 } else { 10159 dst_reg->smin_value = smin_ptr + smin_val; 10160 dst_reg->smax_value = smax_ptr + smax_val; 10161 } 10162 if (umin_ptr + umin_val < umin_ptr || 10163 umax_ptr + umax_val < umax_ptr) { 10164 dst_reg->umin_value = 0; 10165 dst_reg->umax_value = U64_MAX; 10166 } else { 10167 dst_reg->umin_value = umin_ptr + umin_val; 10168 dst_reg->umax_value = umax_ptr + umax_val; 10169 } 10170 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 10171 dst_reg->off = ptr_reg->off; 10172 dst_reg->raw = ptr_reg->raw; 10173 if (reg_is_pkt_pointer(ptr_reg)) { 10174 dst_reg->id = ++env->id_gen; 10175 /* something was added to pkt_ptr, set range to zero */ 10176 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 10177 } 10178 break; 10179 case BPF_SUB: 10180 if (dst_reg == off_reg) { 10181 /* scalar -= pointer. Creates an unknown scalar */ 10182 verbose(env, "R%d tried to subtract pointer from scalar\n", 10183 dst); 10184 return -EACCES; 10185 } 10186 /* We don't allow subtraction from FP, because (according to 10187 * test_verifier.c test "invalid fp arithmetic", JITs might not 10188 * be able to deal with it. 10189 */ 10190 if (ptr_reg->type == PTR_TO_STACK) { 10191 verbose(env, "R%d subtraction from stack pointer prohibited\n", 10192 dst); 10193 return -EACCES; 10194 } 10195 if (known && (ptr_reg->off - smin_val == 10196 (s64)(s32)(ptr_reg->off - smin_val))) { 10197 /* pointer -= K. Subtract it from fixed offset */ 10198 dst_reg->smin_value = smin_ptr; 10199 dst_reg->smax_value = smax_ptr; 10200 dst_reg->umin_value = umin_ptr; 10201 dst_reg->umax_value = umax_ptr; 10202 dst_reg->var_off = ptr_reg->var_off; 10203 dst_reg->id = ptr_reg->id; 10204 dst_reg->off = ptr_reg->off - smin_val; 10205 dst_reg->raw = ptr_reg->raw; 10206 break; 10207 } 10208 /* A new variable offset is created. If the subtrahend is known 10209 * nonnegative, then any reg->range we had before is still good. 10210 */ 10211 if (signed_sub_overflows(smin_ptr, smax_val) || 10212 signed_sub_overflows(smax_ptr, smin_val)) { 10213 /* Overflow possible, we know nothing */ 10214 dst_reg->smin_value = S64_MIN; 10215 dst_reg->smax_value = S64_MAX; 10216 } else { 10217 dst_reg->smin_value = smin_ptr - smax_val; 10218 dst_reg->smax_value = smax_ptr - smin_val; 10219 } 10220 if (umin_ptr < umax_val) { 10221 /* Overflow possible, we know nothing */ 10222 dst_reg->umin_value = 0; 10223 dst_reg->umax_value = U64_MAX; 10224 } else { 10225 /* Cannot overflow (as long as bounds are consistent) */ 10226 dst_reg->umin_value = umin_ptr - umax_val; 10227 dst_reg->umax_value = umax_ptr - umin_val; 10228 } 10229 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 10230 dst_reg->off = ptr_reg->off; 10231 dst_reg->raw = ptr_reg->raw; 10232 if (reg_is_pkt_pointer(ptr_reg)) { 10233 dst_reg->id = ++env->id_gen; 10234 /* something was added to pkt_ptr, set range to zero */ 10235 if (smin_val < 0) 10236 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 10237 } 10238 break; 10239 case BPF_AND: 10240 case BPF_OR: 10241 case BPF_XOR: 10242 /* bitwise ops on pointers are troublesome, prohibit. */ 10243 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 10244 dst, bpf_alu_string[opcode >> 4]); 10245 return -EACCES; 10246 default: 10247 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 10248 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 10249 dst, bpf_alu_string[opcode >> 4]); 10250 return -EACCES; 10251 } 10252 10253 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 10254 return -EINVAL; 10255 reg_bounds_sync(dst_reg); 10256 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 10257 return -EACCES; 10258 if (sanitize_needed(opcode)) { 10259 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 10260 &info, true); 10261 if (ret < 0) 10262 return sanitize_err(env, insn, ret, off_reg, dst_reg); 10263 } 10264 10265 return 0; 10266 } 10267 10268 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 10269 struct bpf_reg_state *src_reg) 10270 { 10271 s32 smin_val = src_reg->s32_min_value; 10272 s32 smax_val = src_reg->s32_max_value; 10273 u32 umin_val = src_reg->u32_min_value; 10274 u32 umax_val = src_reg->u32_max_value; 10275 10276 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 10277 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 10278 dst_reg->s32_min_value = S32_MIN; 10279 dst_reg->s32_max_value = S32_MAX; 10280 } else { 10281 dst_reg->s32_min_value += smin_val; 10282 dst_reg->s32_max_value += smax_val; 10283 } 10284 if (dst_reg->u32_min_value + umin_val < umin_val || 10285 dst_reg->u32_max_value + umax_val < umax_val) { 10286 dst_reg->u32_min_value = 0; 10287 dst_reg->u32_max_value = U32_MAX; 10288 } else { 10289 dst_reg->u32_min_value += umin_val; 10290 dst_reg->u32_max_value += umax_val; 10291 } 10292 } 10293 10294 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 10295 struct bpf_reg_state *src_reg) 10296 { 10297 s64 smin_val = src_reg->smin_value; 10298 s64 smax_val = src_reg->smax_value; 10299 u64 umin_val = src_reg->umin_value; 10300 u64 umax_val = src_reg->umax_value; 10301 10302 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 10303 signed_add_overflows(dst_reg->smax_value, smax_val)) { 10304 dst_reg->smin_value = S64_MIN; 10305 dst_reg->smax_value = S64_MAX; 10306 } else { 10307 dst_reg->smin_value += smin_val; 10308 dst_reg->smax_value += smax_val; 10309 } 10310 if (dst_reg->umin_value + umin_val < umin_val || 10311 dst_reg->umax_value + umax_val < umax_val) { 10312 dst_reg->umin_value = 0; 10313 dst_reg->umax_value = U64_MAX; 10314 } else { 10315 dst_reg->umin_value += umin_val; 10316 dst_reg->umax_value += umax_val; 10317 } 10318 } 10319 10320 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 10321 struct bpf_reg_state *src_reg) 10322 { 10323 s32 smin_val = src_reg->s32_min_value; 10324 s32 smax_val = src_reg->s32_max_value; 10325 u32 umin_val = src_reg->u32_min_value; 10326 u32 umax_val = src_reg->u32_max_value; 10327 10328 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 10329 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 10330 /* Overflow possible, we know nothing */ 10331 dst_reg->s32_min_value = S32_MIN; 10332 dst_reg->s32_max_value = S32_MAX; 10333 } else { 10334 dst_reg->s32_min_value -= smax_val; 10335 dst_reg->s32_max_value -= smin_val; 10336 } 10337 if (dst_reg->u32_min_value < umax_val) { 10338 /* Overflow possible, we know nothing */ 10339 dst_reg->u32_min_value = 0; 10340 dst_reg->u32_max_value = U32_MAX; 10341 } else { 10342 /* Cannot overflow (as long as bounds are consistent) */ 10343 dst_reg->u32_min_value -= umax_val; 10344 dst_reg->u32_max_value -= umin_val; 10345 } 10346 } 10347 10348 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 10349 struct bpf_reg_state *src_reg) 10350 { 10351 s64 smin_val = src_reg->smin_value; 10352 s64 smax_val = src_reg->smax_value; 10353 u64 umin_val = src_reg->umin_value; 10354 u64 umax_val = src_reg->umax_value; 10355 10356 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 10357 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 10358 /* Overflow possible, we know nothing */ 10359 dst_reg->smin_value = S64_MIN; 10360 dst_reg->smax_value = S64_MAX; 10361 } else { 10362 dst_reg->smin_value -= smax_val; 10363 dst_reg->smax_value -= smin_val; 10364 } 10365 if (dst_reg->umin_value < umax_val) { 10366 /* Overflow possible, we know nothing */ 10367 dst_reg->umin_value = 0; 10368 dst_reg->umax_value = U64_MAX; 10369 } else { 10370 /* Cannot overflow (as long as bounds are consistent) */ 10371 dst_reg->umin_value -= umax_val; 10372 dst_reg->umax_value -= umin_val; 10373 } 10374 } 10375 10376 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 10377 struct bpf_reg_state *src_reg) 10378 { 10379 s32 smin_val = src_reg->s32_min_value; 10380 u32 umin_val = src_reg->u32_min_value; 10381 u32 umax_val = src_reg->u32_max_value; 10382 10383 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 10384 /* Ain't nobody got time to multiply that sign */ 10385 __mark_reg32_unbounded(dst_reg); 10386 return; 10387 } 10388 /* Both values are positive, so we can work with unsigned and 10389 * copy the result to signed (unless it exceeds S32_MAX). 10390 */ 10391 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 10392 /* Potential overflow, we know nothing */ 10393 __mark_reg32_unbounded(dst_reg); 10394 return; 10395 } 10396 dst_reg->u32_min_value *= umin_val; 10397 dst_reg->u32_max_value *= umax_val; 10398 if (dst_reg->u32_max_value > S32_MAX) { 10399 /* Overflow possible, we know nothing */ 10400 dst_reg->s32_min_value = S32_MIN; 10401 dst_reg->s32_max_value = S32_MAX; 10402 } else { 10403 dst_reg->s32_min_value = dst_reg->u32_min_value; 10404 dst_reg->s32_max_value = dst_reg->u32_max_value; 10405 } 10406 } 10407 10408 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 10409 struct bpf_reg_state *src_reg) 10410 { 10411 s64 smin_val = src_reg->smin_value; 10412 u64 umin_val = src_reg->umin_value; 10413 u64 umax_val = src_reg->umax_value; 10414 10415 if (smin_val < 0 || dst_reg->smin_value < 0) { 10416 /* Ain't nobody got time to multiply that sign */ 10417 __mark_reg64_unbounded(dst_reg); 10418 return; 10419 } 10420 /* Both values are positive, so we can work with unsigned and 10421 * copy the result to signed (unless it exceeds S64_MAX). 10422 */ 10423 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 10424 /* Potential overflow, we know nothing */ 10425 __mark_reg64_unbounded(dst_reg); 10426 return; 10427 } 10428 dst_reg->umin_value *= umin_val; 10429 dst_reg->umax_value *= umax_val; 10430 if (dst_reg->umax_value > S64_MAX) { 10431 /* Overflow possible, we know nothing */ 10432 dst_reg->smin_value = S64_MIN; 10433 dst_reg->smax_value = S64_MAX; 10434 } else { 10435 dst_reg->smin_value = dst_reg->umin_value; 10436 dst_reg->smax_value = dst_reg->umax_value; 10437 } 10438 } 10439 10440 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 10441 struct bpf_reg_state *src_reg) 10442 { 10443 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10444 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10445 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10446 s32 smin_val = src_reg->s32_min_value; 10447 u32 umax_val = src_reg->u32_max_value; 10448 10449 if (src_known && dst_known) { 10450 __mark_reg32_known(dst_reg, var32_off.value); 10451 return; 10452 } 10453 10454 /* We get our minimum from the var_off, since that's inherently 10455 * bitwise. Our maximum is the minimum of the operands' maxima. 10456 */ 10457 dst_reg->u32_min_value = var32_off.value; 10458 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 10459 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 10460 /* Lose signed bounds when ANDing negative numbers, 10461 * ain't nobody got time for that. 10462 */ 10463 dst_reg->s32_min_value = S32_MIN; 10464 dst_reg->s32_max_value = S32_MAX; 10465 } else { 10466 /* ANDing two positives gives a positive, so safe to 10467 * cast result into s64. 10468 */ 10469 dst_reg->s32_min_value = dst_reg->u32_min_value; 10470 dst_reg->s32_max_value = dst_reg->u32_max_value; 10471 } 10472 } 10473 10474 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 10475 struct bpf_reg_state *src_reg) 10476 { 10477 bool src_known = tnum_is_const(src_reg->var_off); 10478 bool dst_known = tnum_is_const(dst_reg->var_off); 10479 s64 smin_val = src_reg->smin_value; 10480 u64 umax_val = src_reg->umax_value; 10481 10482 if (src_known && dst_known) { 10483 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10484 return; 10485 } 10486 10487 /* We get our minimum from the var_off, since that's inherently 10488 * bitwise. Our maximum is the minimum of the operands' maxima. 10489 */ 10490 dst_reg->umin_value = dst_reg->var_off.value; 10491 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 10492 if (dst_reg->smin_value < 0 || smin_val < 0) { 10493 /* Lose signed bounds when ANDing negative numbers, 10494 * ain't nobody got time for that. 10495 */ 10496 dst_reg->smin_value = S64_MIN; 10497 dst_reg->smax_value = S64_MAX; 10498 } else { 10499 /* ANDing two positives gives a positive, so safe to 10500 * cast result into s64. 10501 */ 10502 dst_reg->smin_value = dst_reg->umin_value; 10503 dst_reg->smax_value = dst_reg->umax_value; 10504 } 10505 /* We may learn something more from the var_off */ 10506 __update_reg_bounds(dst_reg); 10507 } 10508 10509 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 10510 struct bpf_reg_state *src_reg) 10511 { 10512 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10513 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10514 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10515 s32 smin_val = src_reg->s32_min_value; 10516 u32 umin_val = src_reg->u32_min_value; 10517 10518 if (src_known && dst_known) { 10519 __mark_reg32_known(dst_reg, var32_off.value); 10520 return; 10521 } 10522 10523 /* We get our maximum from the var_off, and our minimum is the 10524 * maximum of the operands' minima 10525 */ 10526 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 10527 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 10528 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 10529 /* Lose signed bounds when ORing negative numbers, 10530 * ain't nobody got time for that. 10531 */ 10532 dst_reg->s32_min_value = S32_MIN; 10533 dst_reg->s32_max_value = S32_MAX; 10534 } else { 10535 /* ORing two positives gives a positive, so safe to 10536 * cast result into s64. 10537 */ 10538 dst_reg->s32_min_value = dst_reg->u32_min_value; 10539 dst_reg->s32_max_value = dst_reg->u32_max_value; 10540 } 10541 } 10542 10543 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 10544 struct bpf_reg_state *src_reg) 10545 { 10546 bool src_known = tnum_is_const(src_reg->var_off); 10547 bool dst_known = tnum_is_const(dst_reg->var_off); 10548 s64 smin_val = src_reg->smin_value; 10549 u64 umin_val = src_reg->umin_value; 10550 10551 if (src_known && dst_known) { 10552 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10553 return; 10554 } 10555 10556 /* We get our maximum from the var_off, and our minimum is the 10557 * maximum of the operands' minima 10558 */ 10559 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 10560 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 10561 if (dst_reg->smin_value < 0 || smin_val < 0) { 10562 /* Lose signed bounds when ORing negative numbers, 10563 * ain't nobody got time for that. 10564 */ 10565 dst_reg->smin_value = S64_MIN; 10566 dst_reg->smax_value = S64_MAX; 10567 } else { 10568 /* ORing two positives gives a positive, so safe to 10569 * cast result into s64. 10570 */ 10571 dst_reg->smin_value = dst_reg->umin_value; 10572 dst_reg->smax_value = dst_reg->umax_value; 10573 } 10574 /* We may learn something more from the var_off */ 10575 __update_reg_bounds(dst_reg); 10576 } 10577 10578 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 10579 struct bpf_reg_state *src_reg) 10580 { 10581 bool src_known = tnum_subreg_is_const(src_reg->var_off); 10582 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 10583 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 10584 s32 smin_val = src_reg->s32_min_value; 10585 10586 if (src_known && dst_known) { 10587 __mark_reg32_known(dst_reg, var32_off.value); 10588 return; 10589 } 10590 10591 /* We get both minimum and maximum from the var32_off. */ 10592 dst_reg->u32_min_value = var32_off.value; 10593 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 10594 10595 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 10596 /* XORing two positive sign numbers gives a positive, 10597 * so safe to cast u32 result into s32. 10598 */ 10599 dst_reg->s32_min_value = dst_reg->u32_min_value; 10600 dst_reg->s32_max_value = dst_reg->u32_max_value; 10601 } else { 10602 dst_reg->s32_min_value = S32_MIN; 10603 dst_reg->s32_max_value = S32_MAX; 10604 } 10605 } 10606 10607 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 10608 struct bpf_reg_state *src_reg) 10609 { 10610 bool src_known = tnum_is_const(src_reg->var_off); 10611 bool dst_known = tnum_is_const(dst_reg->var_off); 10612 s64 smin_val = src_reg->smin_value; 10613 10614 if (src_known && dst_known) { 10615 /* dst_reg->var_off.value has been updated earlier */ 10616 __mark_reg_known(dst_reg, dst_reg->var_off.value); 10617 return; 10618 } 10619 10620 /* We get both minimum and maximum from the var_off. */ 10621 dst_reg->umin_value = dst_reg->var_off.value; 10622 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 10623 10624 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 10625 /* XORing two positive sign numbers gives a positive, 10626 * so safe to cast u64 result into s64. 10627 */ 10628 dst_reg->smin_value = dst_reg->umin_value; 10629 dst_reg->smax_value = dst_reg->umax_value; 10630 } else { 10631 dst_reg->smin_value = S64_MIN; 10632 dst_reg->smax_value = S64_MAX; 10633 } 10634 10635 __update_reg_bounds(dst_reg); 10636 } 10637 10638 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 10639 u64 umin_val, u64 umax_val) 10640 { 10641 /* We lose all sign bit information (except what we can pick 10642 * up from var_off) 10643 */ 10644 dst_reg->s32_min_value = S32_MIN; 10645 dst_reg->s32_max_value = S32_MAX; 10646 /* If we might shift our top bit out, then we know nothing */ 10647 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 10648 dst_reg->u32_min_value = 0; 10649 dst_reg->u32_max_value = U32_MAX; 10650 } else { 10651 dst_reg->u32_min_value <<= umin_val; 10652 dst_reg->u32_max_value <<= umax_val; 10653 } 10654 } 10655 10656 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 10657 struct bpf_reg_state *src_reg) 10658 { 10659 u32 umax_val = src_reg->u32_max_value; 10660 u32 umin_val = src_reg->u32_min_value; 10661 /* u32 alu operation will zext upper bits */ 10662 struct tnum subreg = tnum_subreg(dst_reg->var_off); 10663 10664 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 10665 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 10666 /* Not required but being careful mark reg64 bounds as unknown so 10667 * that we are forced to pick them up from tnum and zext later and 10668 * if some path skips this step we are still safe. 10669 */ 10670 __mark_reg64_unbounded(dst_reg); 10671 __update_reg32_bounds(dst_reg); 10672 } 10673 10674 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 10675 u64 umin_val, u64 umax_val) 10676 { 10677 /* Special case <<32 because it is a common compiler pattern to sign 10678 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 10679 * positive we know this shift will also be positive so we can track 10680 * bounds correctly. Otherwise we lose all sign bit information except 10681 * what we can pick up from var_off. Perhaps we can generalize this 10682 * later to shifts of any length. 10683 */ 10684 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 10685 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 10686 else 10687 dst_reg->smax_value = S64_MAX; 10688 10689 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 10690 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 10691 else 10692 dst_reg->smin_value = S64_MIN; 10693 10694 /* If we might shift our top bit out, then we know nothing */ 10695 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 10696 dst_reg->umin_value = 0; 10697 dst_reg->umax_value = U64_MAX; 10698 } else { 10699 dst_reg->umin_value <<= umin_val; 10700 dst_reg->umax_value <<= umax_val; 10701 } 10702 } 10703 10704 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 10705 struct bpf_reg_state *src_reg) 10706 { 10707 u64 umax_val = src_reg->umax_value; 10708 u64 umin_val = src_reg->umin_value; 10709 10710 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 10711 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 10712 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 10713 10714 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 10715 /* We may learn something more from the var_off */ 10716 __update_reg_bounds(dst_reg); 10717 } 10718 10719 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 10720 struct bpf_reg_state *src_reg) 10721 { 10722 struct tnum subreg = tnum_subreg(dst_reg->var_off); 10723 u32 umax_val = src_reg->u32_max_value; 10724 u32 umin_val = src_reg->u32_min_value; 10725 10726 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 10727 * be negative, then either: 10728 * 1) src_reg might be zero, so the sign bit of the result is 10729 * unknown, so we lose our signed bounds 10730 * 2) it's known negative, thus the unsigned bounds capture the 10731 * signed bounds 10732 * 3) the signed bounds cross zero, so they tell us nothing 10733 * about the result 10734 * If the value in dst_reg is known nonnegative, then again the 10735 * unsigned bounds capture the signed bounds. 10736 * Thus, in all cases it suffices to blow away our signed bounds 10737 * and rely on inferring new ones from the unsigned bounds and 10738 * var_off of the result. 10739 */ 10740 dst_reg->s32_min_value = S32_MIN; 10741 dst_reg->s32_max_value = S32_MAX; 10742 10743 dst_reg->var_off = tnum_rshift(subreg, umin_val); 10744 dst_reg->u32_min_value >>= umax_val; 10745 dst_reg->u32_max_value >>= umin_val; 10746 10747 __mark_reg64_unbounded(dst_reg); 10748 __update_reg32_bounds(dst_reg); 10749 } 10750 10751 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 10752 struct bpf_reg_state *src_reg) 10753 { 10754 u64 umax_val = src_reg->umax_value; 10755 u64 umin_val = src_reg->umin_value; 10756 10757 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 10758 * be negative, then either: 10759 * 1) src_reg might be zero, so the sign bit of the result is 10760 * unknown, so we lose our signed bounds 10761 * 2) it's known negative, thus the unsigned bounds capture the 10762 * signed bounds 10763 * 3) the signed bounds cross zero, so they tell us nothing 10764 * about the result 10765 * If the value in dst_reg is known nonnegative, then again the 10766 * unsigned bounds capture the signed bounds. 10767 * Thus, in all cases it suffices to blow away our signed bounds 10768 * and rely on inferring new ones from the unsigned bounds and 10769 * var_off of the result. 10770 */ 10771 dst_reg->smin_value = S64_MIN; 10772 dst_reg->smax_value = S64_MAX; 10773 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 10774 dst_reg->umin_value >>= umax_val; 10775 dst_reg->umax_value >>= umin_val; 10776 10777 /* Its not easy to operate on alu32 bounds here because it depends 10778 * on bits being shifted in. Take easy way out and mark unbounded 10779 * so we can recalculate later from tnum. 10780 */ 10781 __mark_reg32_unbounded(dst_reg); 10782 __update_reg_bounds(dst_reg); 10783 } 10784 10785 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 10786 struct bpf_reg_state *src_reg) 10787 { 10788 u64 umin_val = src_reg->u32_min_value; 10789 10790 /* Upon reaching here, src_known is true and 10791 * umax_val is equal to umin_val. 10792 */ 10793 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 10794 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 10795 10796 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 10797 10798 /* blow away the dst_reg umin_value/umax_value and rely on 10799 * dst_reg var_off to refine the result. 10800 */ 10801 dst_reg->u32_min_value = 0; 10802 dst_reg->u32_max_value = U32_MAX; 10803 10804 __mark_reg64_unbounded(dst_reg); 10805 __update_reg32_bounds(dst_reg); 10806 } 10807 10808 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 10809 struct bpf_reg_state *src_reg) 10810 { 10811 u64 umin_val = src_reg->umin_value; 10812 10813 /* Upon reaching here, src_known is true and umax_val is equal 10814 * to umin_val. 10815 */ 10816 dst_reg->smin_value >>= umin_val; 10817 dst_reg->smax_value >>= umin_val; 10818 10819 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 10820 10821 /* blow away the dst_reg umin_value/umax_value and rely on 10822 * dst_reg var_off to refine the result. 10823 */ 10824 dst_reg->umin_value = 0; 10825 dst_reg->umax_value = U64_MAX; 10826 10827 /* Its not easy to operate on alu32 bounds here because it depends 10828 * on bits being shifted in from upper 32-bits. Take easy way out 10829 * and mark unbounded so we can recalculate later from tnum. 10830 */ 10831 __mark_reg32_unbounded(dst_reg); 10832 __update_reg_bounds(dst_reg); 10833 } 10834 10835 /* WARNING: This function does calculations on 64-bit values, but the actual 10836 * execution may occur on 32-bit values. Therefore, things like bitshifts 10837 * need extra checks in the 32-bit case. 10838 */ 10839 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 10840 struct bpf_insn *insn, 10841 struct bpf_reg_state *dst_reg, 10842 struct bpf_reg_state src_reg) 10843 { 10844 struct bpf_reg_state *regs = cur_regs(env); 10845 u8 opcode = BPF_OP(insn->code); 10846 bool src_known; 10847 s64 smin_val, smax_val; 10848 u64 umin_val, umax_val; 10849 s32 s32_min_val, s32_max_val; 10850 u32 u32_min_val, u32_max_val; 10851 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 10852 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 10853 int ret; 10854 10855 smin_val = src_reg.smin_value; 10856 smax_val = src_reg.smax_value; 10857 umin_val = src_reg.umin_value; 10858 umax_val = src_reg.umax_value; 10859 10860 s32_min_val = src_reg.s32_min_value; 10861 s32_max_val = src_reg.s32_max_value; 10862 u32_min_val = src_reg.u32_min_value; 10863 u32_max_val = src_reg.u32_max_value; 10864 10865 if (alu32) { 10866 src_known = tnum_subreg_is_const(src_reg.var_off); 10867 if ((src_known && 10868 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 10869 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 10870 /* Taint dst register if offset had invalid bounds 10871 * derived from e.g. dead branches. 10872 */ 10873 __mark_reg_unknown(env, dst_reg); 10874 return 0; 10875 } 10876 } else { 10877 src_known = tnum_is_const(src_reg.var_off); 10878 if ((src_known && 10879 (smin_val != smax_val || umin_val != umax_val)) || 10880 smin_val > smax_val || umin_val > umax_val) { 10881 /* Taint dst register if offset had invalid bounds 10882 * derived from e.g. dead branches. 10883 */ 10884 __mark_reg_unknown(env, dst_reg); 10885 return 0; 10886 } 10887 } 10888 10889 if (!src_known && 10890 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 10891 __mark_reg_unknown(env, dst_reg); 10892 return 0; 10893 } 10894 10895 if (sanitize_needed(opcode)) { 10896 ret = sanitize_val_alu(env, insn); 10897 if (ret < 0) 10898 return sanitize_err(env, insn, ret, NULL, NULL); 10899 } 10900 10901 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 10902 * There are two classes of instructions: The first class we track both 10903 * alu32 and alu64 sign/unsigned bounds independently this provides the 10904 * greatest amount of precision when alu operations are mixed with jmp32 10905 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 10906 * and BPF_OR. This is possible because these ops have fairly easy to 10907 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 10908 * See alu32 verifier tests for examples. The second class of 10909 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 10910 * with regards to tracking sign/unsigned bounds because the bits may 10911 * cross subreg boundaries in the alu64 case. When this happens we mark 10912 * the reg unbounded in the subreg bound space and use the resulting 10913 * tnum to calculate an approximation of the sign/unsigned bounds. 10914 */ 10915 switch (opcode) { 10916 case BPF_ADD: 10917 scalar32_min_max_add(dst_reg, &src_reg); 10918 scalar_min_max_add(dst_reg, &src_reg); 10919 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 10920 break; 10921 case BPF_SUB: 10922 scalar32_min_max_sub(dst_reg, &src_reg); 10923 scalar_min_max_sub(dst_reg, &src_reg); 10924 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 10925 break; 10926 case BPF_MUL: 10927 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 10928 scalar32_min_max_mul(dst_reg, &src_reg); 10929 scalar_min_max_mul(dst_reg, &src_reg); 10930 break; 10931 case BPF_AND: 10932 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 10933 scalar32_min_max_and(dst_reg, &src_reg); 10934 scalar_min_max_and(dst_reg, &src_reg); 10935 break; 10936 case BPF_OR: 10937 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 10938 scalar32_min_max_or(dst_reg, &src_reg); 10939 scalar_min_max_or(dst_reg, &src_reg); 10940 break; 10941 case BPF_XOR: 10942 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 10943 scalar32_min_max_xor(dst_reg, &src_reg); 10944 scalar_min_max_xor(dst_reg, &src_reg); 10945 break; 10946 case BPF_LSH: 10947 if (umax_val >= insn_bitness) { 10948 /* Shifts greater than 31 or 63 are undefined. 10949 * This includes shifts by a negative number. 10950 */ 10951 mark_reg_unknown(env, regs, insn->dst_reg); 10952 break; 10953 } 10954 if (alu32) 10955 scalar32_min_max_lsh(dst_reg, &src_reg); 10956 else 10957 scalar_min_max_lsh(dst_reg, &src_reg); 10958 break; 10959 case BPF_RSH: 10960 if (umax_val >= insn_bitness) { 10961 /* Shifts greater than 31 or 63 are undefined. 10962 * This includes shifts by a negative number. 10963 */ 10964 mark_reg_unknown(env, regs, insn->dst_reg); 10965 break; 10966 } 10967 if (alu32) 10968 scalar32_min_max_rsh(dst_reg, &src_reg); 10969 else 10970 scalar_min_max_rsh(dst_reg, &src_reg); 10971 break; 10972 case BPF_ARSH: 10973 if (umax_val >= insn_bitness) { 10974 /* Shifts greater than 31 or 63 are undefined. 10975 * This includes shifts by a negative number. 10976 */ 10977 mark_reg_unknown(env, regs, insn->dst_reg); 10978 break; 10979 } 10980 if (alu32) 10981 scalar32_min_max_arsh(dst_reg, &src_reg); 10982 else 10983 scalar_min_max_arsh(dst_reg, &src_reg); 10984 break; 10985 default: 10986 mark_reg_unknown(env, regs, insn->dst_reg); 10987 break; 10988 } 10989 10990 /* ALU32 ops are zero extended into 64bit register */ 10991 if (alu32) 10992 zext_32_to_64(dst_reg); 10993 reg_bounds_sync(dst_reg); 10994 return 0; 10995 } 10996 10997 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 10998 * and var_off. 10999 */ 11000 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 11001 struct bpf_insn *insn) 11002 { 11003 struct bpf_verifier_state *vstate = env->cur_state; 11004 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 11005 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 11006 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 11007 u8 opcode = BPF_OP(insn->code); 11008 int err; 11009 11010 dst_reg = ®s[insn->dst_reg]; 11011 src_reg = NULL; 11012 if (dst_reg->type != SCALAR_VALUE) 11013 ptr_reg = dst_reg; 11014 else 11015 /* Make sure ID is cleared otherwise dst_reg min/max could be 11016 * incorrectly propagated into other registers by find_equal_scalars() 11017 */ 11018 dst_reg->id = 0; 11019 if (BPF_SRC(insn->code) == BPF_X) { 11020 src_reg = ®s[insn->src_reg]; 11021 if (src_reg->type != SCALAR_VALUE) { 11022 if (dst_reg->type != SCALAR_VALUE) { 11023 /* Combining two pointers by any ALU op yields 11024 * an arbitrary scalar. Disallow all math except 11025 * pointer subtraction 11026 */ 11027 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 11028 mark_reg_unknown(env, regs, insn->dst_reg); 11029 return 0; 11030 } 11031 verbose(env, "R%d pointer %s pointer prohibited\n", 11032 insn->dst_reg, 11033 bpf_alu_string[opcode >> 4]); 11034 return -EACCES; 11035 } else { 11036 /* scalar += pointer 11037 * This is legal, but we have to reverse our 11038 * src/dest handling in computing the range 11039 */ 11040 err = mark_chain_precision(env, insn->dst_reg); 11041 if (err) 11042 return err; 11043 return adjust_ptr_min_max_vals(env, insn, 11044 src_reg, dst_reg); 11045 } 11046 } else if (ptr_reg) { 11047 /* pointer += scalar */ 11048 err = mark_chain_precision(env, insn->src_reg); 11049 if (err) 11050 return err; 11051 return adjust_ptr_min_max_vals(env, insn, 11052 dst_reg, src_reg); 11053 } else if (dst_reg->precise) { 11054 /* if dst_reg is precise, src_reg should be precise as well */ 11055 err = mark_chain_precision(env, insn->src_reg); 11056 if (err) 11057 return err; 11058 } 11059 } else { 11060 /* Pretend the src is a reg with a known value, since we only 11061 * need to be able to read from this state. 11062 */ 11063 off_reg.type = SCALAR_VALUE; 11064 __mark_reg_known(&off_reg, insn->imm); 11065 src_reg = &off_reg; 11066 if (ptr_reg) /* pointer += K */ 11067 return adjust_ptr_min_max_vals(env, insn, 11068 ptr_reg, src_reg); 11069 } 11070 11071 /* Got here implies adding two SCALAR_VALUEs */ 11072 if (WARN_ON_ONCE(ptr_reg)) { 11073 print_verifier_state(env, state, true); 11074 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 11075 return -EINVAL; 11076 } 11077 if (WARN_ON(!src_reg)) { 11078 print_verifier_state(env, state, true); 11079 verbose(env, "verifier internal error: no src_reg\n"); 11080 return -EINVAL; 11081 } 11082 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 11083 } 11084 11085 /* check validity of 32-bit and 64-bit arithmetic operations */ 11086 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 11087 { 11088 struct bpf_reg_state *regs = cur_regs(env); 11089 u8 opcode = BPF_OP(insn->code); 11090 int err; 11091 11092 if (opcode == BPF_END || opcode == BPF_NEG) { 11093 if (opcode == BPF_NEG) { 11094 if (BPF_SRC(insn->code) != BPF_K || 11095 insn->src_reg != BPF_REG_0 || 11096 insn->off != 0 || insn->imm != 0) { 11097 verbose(env, "BPF_NEG uses reserved fields\n"); 11098 return -EINVAL; 11099 } 11100 } else { 11101 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 11102 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 11103 BPF_CLASS(insn->code) == BPF_ALU64) { 11104 verbose(env, "BPF_END uses reserved fields\n"); 11105 return -EINVAL; 11106 } 11107 } 11108 11109 /* check src operand */ 11110 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11111 if (err) 11112 return err; 11113 11114 if (is_pointer_value(env, insn->dst_reg)) { 11115 verbose(env, "R%d pointer arithmetic prohibited\n", 11116 insn->dst_reg); 11117 return -EACCES; 11118 } 11119 11120 /* check dest operand */ 11121 err = check_reg_arg(env, insn->dst_reg, DST_OP); 11122 if (err) 11123 return err; 11124 11125 } else if (opcode == BPF_MOV) { 11126 11127 if (BPF_SRC(insn->code) == BPF_X) { 11128 if (insn->imm != 0 || insn->off != 0) { 11129 verbose(env, "BPF_MOV uses reserved fields\n"); 11130 return -EINVAL; 11131 } 11132 11133 /* check src operand */ 11134 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11135 if (err) 11136 return err; 11137 } else { 11138 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 11139 verbose(env, "BPF_MOV uses reserved fields\n"); 11140 return -EINVAL; 11141 } 11142 } 11143 11144 /* check dest operand, mark as required later */ 11145 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 11146 if (err) 11147 return err; 11148 11149 if (BPF_SRC(insn->code) == BPF_X) { 11150 struct bpf_reg_state *src_reg = regs + insn->src_reg; 11151 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 11152 11153 if (BPF_CLASS(insn->code) == BPF_ALU64) { 11154 /* case: R1 = R2 11155 * copy register state to dest reg 11156 */ 11157 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 11158 /* Assign src and dst registers the same ID 11159 * that will be used by find_equal_scalars() 11160 * to propagate min/max range. 11161 */ 11162 src_reg->id = ++env->id_gen; 11163 *dst_reg = *src_reg; 11164 dst_reg->live |= REG_LIVE_WRITTEN; 11165 dst_reg->subreg_def = DEF_NOT_SUBREG; 11166 } else { 11167 /* R1 = (u32) R2 */ 11168 if (is_pointer_value(env, insn->src_reg)) { 11169 verbose(env, 11170 "R%d partial copy of pointer\n", 11171 insn->src_reg); 11172 return -EACCES; 11173 } else if (src_reg->type == SCALAR_VALUE) { 11174 *dst_reg = *src_reg; 11175 /* Make sure ID is cleared otherwise 11176 * dst_reg min/max could be incorrectly 11177 * propagated into src_reg by find_equal_scalars() 11178 */ 11179 dst_reg->id = 0; 11180 dst_reg->live |= REG_LIVE_WRITTEN; 11181 dst_reg->subreg_def = env->insn_idx + 1; 11182 } else { 11183 mark_reg_unknown(env, regs, 11184 insn->dst_reg); 11185 } 11186 zext_32_to_64(dst_reg); 11187 reg_bounds_sync(dst_reg); 11188 } 11189 } else { 11190 /* case: R = imm 11191 * remember the value we stored into this reg 11192 */ 11193 /* clear any state __mark_reg_known doesn't set */ 11194 mark_reg_unknown(env, regs, insn->dst_reg); 11195 regs[insn->dst_reg].type = SCALAR_VALUE; 11196 if (BPF_CLASS(insn->code) == BPF_ALU64) { 11197 __mark_reg_known(regs + insn->dst_reg, 11198 insn->imm); 11199 } else { 11200 __mark_reg_known(regs + insn->dst_reg, 11201 (u32)insn->imm); 11202 } 11203 } 11204 11205 } else if (opcode > BPF_END) { 11206 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 11207 return -EINVAL; 11208 11209 } else { /* all other ALU ops: and, sub, xor, add, ... */ 11210 11211 if (BPF_SRC(insn->code) == BPF_X) { 11212 if (insn->imm != 0 || insn->off != 0) { 11213 verbose(env, "BPF_ALU uses reserved fields\n"); 11214 return -EINVAL; 11215 } 11216 /* check src1 operand */ 11217 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11218 if (err) 11219 return err; 11220 } else { 11221 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 11222 verbose(env, "BPF_ALU uses reserved fields\n"); 11223 return -EINVAL; 11224 } 11225 } 11226 11227 /* check src2 operand */ 11228 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11229 if (err) 11230 return err; 11231 11232 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 11233 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 11234 verbose(env, "div by zero\n"); 11235 return -EINVAL; 11236 } 11237 11238 if ((opcode == BPF_LSH || opcode == BPF_RSH || 11239 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 11240 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 11241 11242 if (insn->imm < 0 || insn->imm >= size) { 11243 verbose(env, "invalid shift %d\n", insn->imm); 11244 return -EINVAL; 11245 } 11246 } 11247 11248 /* check dest operand */ 11249 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 11250 if (err) 11251 return err; 11252 11253 return adjust_reg_min_max_vals(env, insn); 11254 } 11255 11256 return 0; 11257 } 11258 11259 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 11260 struct bpf_reg_state *dst_reg, 11261 enum bpf_reg_type type, 11262 bool range_right_open) 11263 { 11264 struct bpf_func_state *state; 11265 struct bpf_reg_state *reg; 11266 int new_range; 11267 11268 if (dst_reg->off < 0 || 11269 (dst_reg->off == 0 && range_right_open)) 11270 /* This doesn't give us any range */ 11271 return; 11272 11273 if (dst_reg->umax_value > MAX_PACKET_OFF || 11274 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 11275 /* Risk of overflow. For instance, ptr + (1<<63) may be less 11276 * than pkt_end, but that's because it's also less than pkt. 11277 */ 11278 return; 11279 11280 new_range = dst_reg->off; 11281 if (range_right_open) 11282 new_range++; 11283 11284 /* Examples for register markings: 11285 * 11286 * pkt_data in dst register: 11287 * 11288 * r2 = r3; 11289 * r2 += 8; 11290 * if (r2 > pkt_end) goto <handle exception> 11291 * <access okay> 11292 * 11293 * r2 = r3; 11294 * r2 += 8; 11295 * if (r2 < pkt_end) goto <access okay> 11296 * <handle exception> 11297 * 11298 * Where: 11299 * r2 == dst_reg, pkt_end == src_reg 11300 * r2=pkt(id=n,off=8,r=0) 11301 * r3=pkt(id=n,off=0,r=0) 11302 * 11303 * pkt_data in src register: 11304 * 11305 * r2 = r3; 11306 * r2 += 8; 11307 * if (pkt_end >= r2) goto <access okay> 11308 * <handle exception> 11309 * 11310 * r2 = r3; 11311 * r2 += 8; 11312 * if (pkt_end <= r2) goto <handle exception> 11313 * <access okay> 11314 * 11315 * Where: 11316 * pkt_end == dst_reg, r2 == src_reg 11317 * r2=pkt(id=n,off=8,r=0) 11318 * r3=pkt(id=n,off=0,r=0) 11319 * 11320 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 11321 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 11322 * and [r3, r3 + 8-1) respectively is safe to access depending on 11323 * the check. 11324 */ 11325 11326 /* If our ids match, then we must have the same max_value. And we 11327 * don't care about the other reg's fixed offset, since if it's too big 11328 * the range won't allow anything. 11329 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 11330 */ 11331 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 11332 if (reg->type == type && reg->id == dst_reg->id) 11333 /* keep the maximum range already checked */ 11334 reg->range = max(reg->range, new_range); 11335 })); 11336 } 11337 11338 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 11339 { 11340 struct tnum subreg = tnum_subreg(reg->var_off); 11341 s32 sval = (s32)val; 11342 11343 switch (opcode) { 11344 case BPF_JEQ: 11345 if (tnum_is_const(subreg)) 11346 return !!tnum_equals_const(subreg, val); 11347 break; 11348 case BPF_JNE: 11349 if (tnum_is_const(subreg)) 11350 return !tnum_equals_const(subreg, val); 11351 break; 11352 case BPF_JSET: 11353 if ((~subreg.mask & subreg.value) & val) 11354 return 1; 11355 if (!((subreg.mask | subreg.value) & val)) 11356 return 0; 11357 break; 11358 case BPF_JGT: 11359 if (reg->u32_min_value > val) 11360 return 1; 11361 else if (reg->u32_max_value <= val) 11362 return 0; 11363 break; 11364 case BPF_JSGT: 11365 if (reg->s32_min_value > sval) 11366 return 1; 11367 else if (reg->s32_max_value <= sval) 11368 return 0; 11369 break; 11370 case BPF_JLT: 11371 if (reg->u32_max_value < val) 11372 return 1; 11373 else if (reg->u32_min_value >= val) 11374 return 0; 11375 break; 11376 case BPF_JSLT: 11377 if (reg->s32_max_value < sval) 11378 return 1; 11379 else if (reg->s32_min_value >= sval) 11380 return 0; 11381 break; 11382 case BPF_JGE: 11383 if (reg->u32_min_value >= val) 11384 return 1; 11385 else if (reg->u32_max_value < val) 11386 return 0; 11387 break; 11388 case BPF_JSGE: 11389 if (reg->s32_min_value >= sval) 11390 return 1; 11391 else if (reg->s32_max_value < sval) 11392 return 0; 11393 break; 11394 case BPF_JLE: 11395 if (reg->u32_max_value <= val) 11396 return 1; 11397 else if (reg->u32_min_value > val) 11398 return 0; 11399 break; 11400 case BPF_JSLE: 11401 if (reg->s32_max_value <= sval) 11402 return 1; 11403 else if (reg->s32_min_value > sval) 11404 return 0; 11405 break; 11406 } 11407 11408 return -1; 11409 } 11410 11411 11412 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 11413 { 11414 s64 sval = (s64)val; 11415 11416 switch (opcode) { 11417 case BPF_JEQ: 11418 if (tnum_is_const(reg->var_off)) 11419 return !!tnum_equals_const(reg->var_off, val); 11420 break; 11421 case BPF_JNE: 11422 if (tnum_is_const(reg->var_off)) 11423 return !tnum_equals_const(reg->var_off, val); 11424 break; 11425 case BPF_JSET: 11426 if ((~reg->var_off.mask & reg->var_off.value) & val) 11427 return 1; 11428 if (!((reg->var_off.mask | reg->var_off.value) & val)) 11429 return 0; 11430 break; 11431 case BPF_JGT: 11432 if (reg->umin_value > val) 11433 return 1; 11434 else if (reg->umax_value <= val) 11435 return 0; 11436 break; 11437 case BPF_JSGT: 11438 if (reg->smin_value > sval) 11439 return 1; 11440 else if (reg->smax_value <= sval) 11441 return 0; 11442 break; 11443 case BPF_JLT: 11444 if (reg->umax_value < val) 11445 return 1; 11446 else if (reg->umin_value >= val) 11447 return 0; 11448 break; 11449 case BPF_JSLT: 11450 if (reg->smax_value < sval) 11451 return 1; 11452 else if (reg->smin_value >= sval) 11453 return 0; 11454 break; 11455 case BPF_JGE: 11456 if (reg->umin_value >= val) 11457 return 1; 11458 else if (reg->umax_value < val) 11459 return 0; 11460 break; 11461 case BPF_JSGE: 11462 if (reg->smin_value >= sval) 11463 return 1; 11464 else if (reg->smax_value < sval) 11465 return 0; 11466 break; 11467 case BPF_JLE: 11468 if (reg->umax_value <= val) 11469 return 1; 11470 else if (reg->umin_value > val) 11471 return 0; 11472 break; 11473 case BPF_JSLE: 11474 if (reg->smax_value <= sval) 11475 return 1; 11476 else if (reg->smin_value > sval) 11477 return 0; 11478 break; 11479 } 11480 11481 return -1; 11482 } 11483 11484 /* compute branch direction of the expression "if (reg opcode val) goto target;" 11485 * and return: 11486 * 1 - branch will be taken and "goto target" will be executed 11487 * 0 - branch will not be taken and fall-through to next insn 11488 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 11489 * range [0,10] 11490 */ 11491 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 11492 bool is_jmp32) 11493 { 11494 if (__is_pointer_value(false, reg)) { 11495 if (!reg_type_not_null(reg->type)) 11496 return -1; 11497 11498 /* If pointer is valid tests against zero will fail so we can 11499 * use this to direct branch taken. 11500 */ 11501 if (val != 0) 11502 return -1; 11503 11504 switch (opcode) { 11505 case BPF_JEQ: 11506 return 0; 11507 case BPF_JNE: 11508 return 1; 11509 default: 11510 return -1; 11511 } 11512 } 11513 11514 if (is_jmp32) 11515 return is_branch32_taken(reg, val, opcode); 11516 return is_branch64_taken(reg, val, opcode); 11517 } 11518 11519 static int flip_opcode(u32 opcode) 11520 { 11521 /* How can we transform "a <op> b" into "b <op> a"? */ 11522 static const u8 opcode_flip[16] = { 11523 /* these stay the same */ 11524 [BPF_JEQ >> 4] = BPF_JEQ, 11525 [BPF_JNE >> 4] = BPF_JNE, 11526 [BPF_JSET >> 4] = BPF_JSET, 11527 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 11528 [BPF_JGE >> 4] = BPF_JLE, 11529 [BPF_JGT >> 4] = BPF_JLT, 11530 [BPF_JLE >> 4] = BPF_JGE, 11531 [BPF_JLT >> 4] = BPF_JGT, 11532 [BPF_JSGE >> 4] = BPF_JSLE, 11533 [BPF_JSGT >> 4] = BPF_JSLT, 11534 [BPF_JSLE >> 4] = BPF_JSGE, 11535 [BPF_JSLT >> 4] = BPF_JSGT 11536 }; 11537 return opcode_flip[opcode >> 4]; 11538 } 11539 11540 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 11541 struct bpf_reg_state *src_reg, 11542 u8 opcode) 11543 { 11544 struct bpf_reg_state *pkt; 11545 11546 if (src_reg->type == PTR_TO_PACKET_END) { 11547 pkt = dst_reg; 11548 } else if (dst_reg->type == PTR_TO_PACKET_END) { 11549 pkt = src_reg; 11550 opcode = flip_opcode(opcode); 11551 } else { 11552 return -1; 11553 } 11554 11555 if (pkt->range >= 0) 11556 return -1; 11557 11558 switch (opcode) { 11559 case BPF_JLE: 11560 /* pkt <= pkt_end */ 11561 fallthrough; 11562 case BPF_JGT: 11563 /* pkt > pkt_end */ 11564 if (pkt->range == BEYOND_PKT_END) 11565 /* pkt has at last one extra byte beyond pkt_end */ 11566 return opcode == BPF_JGT; 11567 break; 11568 case BPF_JLT: 11569 /* pkt < pkt_end */ 11570 fallthrough; 11571 case BPF_JGE: 11572 /* pkt >= pkt_end */ 11573 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 11574 return opcode == BPF_JGE; 11575 break; 11576 } 11577 return -1; 11578 } 11579 11580 /* Adjusts the register min/max values in the case that the dst_reg is the 11581 * variable register that we are working on, and src_reg is a constant or we're 11582 * simply doing a BPF_K check. 11583 * In JEQ/JNE cases we also adjust the var_off values. 11584 */ 11585 static void reg_set_min_max(struct bpf_reg_state *true_reg, 11586 struct bpf_reg_state *false_reg, 11587 u64 val, u32 val32, 11588 u8 opcode, bool is_jmp32) 11589 { 11590 struct tnum false_32off = tnum_subreg(false_reg->var_off); 11591 struct tnum false_64off = false_reg->var_off; 11592 struct tnum true_32off = tnum_subreg(true_reg->var_off); 11593 struct tnum true_64off = true_reg->var_off; 11594 s64 sval = (s64)val; 11595 s32 sval32 = (s32)val32; 11596 11597 /* If the dst_reg is a pointer, we can't learn anything about its 11598 * variable offset from the compare (unless src_reg were a pointer into 11599 * the same object, but we don't bother with that. 11600 * Since false_reg and true_reg have the same type by construction, we 11601 * only need to check one of them for pointerness. 11602 */ 11603 if (__is_pointer_value(false, false_reg)) 11604 return; 11605 11606 switch (opcode) { 11607 /* JEQ/JNE comparison doesn't change the register equivalence. 11608 * 11609 * r1 = r2; 11610 * if (r1 == 42) goto label; 11611 * ... 11612 * label: // here both r1 and r2 are known to be 42. 11613 * 11614 * Hence when marking register as known preserve it's ID. 11615 */ 11616 case BPF_JEQ: 11617 if (is_jmp32) { 11618 __mark_reg32_known(true_reg, val32); 11619 true_32off = tnum_subreg(true_reg->var_off); 11620 } else { 11621 ___mark_reg_known(true_reg, val); 11622 true_64off = true_reg->var_off; 11623 } 11624 break; 11625 case BPF_JNE: 11626 if (is_jmp32) { 11627 __mark_reg32_known(false_reg, val32); 11628 false_32off = tnum_subreg(false_reg->var_off); 11629 } else { 11630 ___mark_reg_known(false_reg, val); 11631 false_64off = false_reg->var_off; 11632 } 11633 break; 11634 case BPF_JSET: 11635 if (is_jmp32) { 11636 false_32off = tnum_and(false_32off, tnum_const(~val32)); 11637 if (is_power_of_2(val32)) 11638 true_32off = tnum_or(true_32off, 11639 tnum_const(val32)); 11640 } else { 11641 false_64off = tnum_and(false_64off, tnum_const(~val)); 11642 if (is_power_of_2(val)) 11643 true_64off = tnum_or(true_64off, 11644 tnum_const(val)); 11645 } 11646 break; 11647 case BPF_JGE: 11648 case BPF_JGT: 11649 { 11650 if (is_jmp32) { 11651 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 11652 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 11653 11654 false_reg->u32_max_value = min(false_reg->u32_max_value, 11655 false_umax); 11656 true_reg->u32_min_value = max(true_reg->u32_min_value, 11657 true_umin); 11658 } else { 11659 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 11660 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 11661 11662 false_reg->umax_value = min(false_reg->umax_value, false_umax); 11663 true_reg->umin_value = max(true_reg->umin_value, true_umin); 11664 } 11665 break; 11666 } 11667 case BPF_JSGE: 11668 case BPF_JSGT: 11669 { 11670 if (is_jmp32) { 11671 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 11672 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 11673 11674 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 11675 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 11676 } else { 11677 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 11678 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 11679 11680 false_reg->smax_value = min(false_reg->smax_value, false_smax); 11681 true_reg->smin_value = max(true_reg->smin_value, true_smin); 11682 } 11683 break; 11684 } 11685 case BPF_JLE: 11686 case BPF_JLT: 11687 { 11688 if (is_jmp32) { 11689 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 11690 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 11691 11692 false_reg->u32_min_value = max(false_reg->u32_min_value, 11693 false_umin); 11694 true_reg->u32_max_value = min(true_reg->u32_max_value, 11695 true_umax); 11696 } else { 11697 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 11698 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 11699 11700 false_reg->umin_value = max(false_reg->umin_value, false_umin); 11701 true_reg->umax_value = min(true_reg->umax_value, true_umax); 11702 } 11703 break; 11704 } 11705 case BPF_JSLE: 11706 case BPF_JSLT: 11707 { 11708 if (is_jmp32) { 11709 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 11710 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 11711 11712 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 11713 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 11714 } else { 11715 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 11716 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 11717 11718 false_reg->smin_value = max(false_reg->smin_value, false_smin); 11719 true_reg->smax_value = min(true_reg->smax_value, true_smax); 11720 } 11721 break; 11722 } 11723 default: 11724 return; 11725 } 11726 11727 if (is_jmp32) { 11728 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 11729 tnum_subreg(false_32off)); 11730 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 11731 tnum_subreg(true_32off)); 11732 __reg_combine_32_into_64(false_reg); 11733 __reg_combine_32_into_64(true_reg); 11734 } else { 11735 false_reg->var_off = false_64off; 11736 true_reg->var_off = true_64off; 11737 __reg_combine_64_into_32(false_reg); 11738 __reg_combine_64_into_32(true_reg); 11739 } 11740 } 11741 11742 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 11743 * the variable reg. 11744 */ 11745 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 11746 struct bpf_reg_state *false_reg, 11747 u64 val, u32 val32, 11748 u8 opcode, bool is_jmp32) 11749 { 11750 opcode = flip_opcode(opcode); 11751 /* This uses zero as "not present in table"; luckily the zero opcode, 11752 * BPF_JA, can't get here. 11753 */ 11754 if (opcode) 11755 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 11756 } 11757 11758 /* Regs are known to be equal, so intersect their min/max/var_off */ 11759 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 11760 struct bpf_reg_state *dst_reg) 11761 { 11762 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 11763 dst_reg->umin_value); 11764 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 11765 dst_reg->umax_value); 11766 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 11767 dst_reg->smin_value); 11768 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 11769 dst_reg->smax_value); 11770 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 11771 dst_reg->var_off); 11772 reg_bounds_sync(src_reg); 11773 reg_bounds_sync(dst_reg); 11774 } 11775 11776 static void reg_combine_min_max(struct bpf_reg_state *true_src, 11777 struct bpf_reg_state *true_dst, 11778 struct bpf_reg_state *false_src, 11779 struct bpf_reg_state *false_dst, 11780 u8 opcode) 11781 { 11782 switch (opcode) { 11783 case BPF_JEQ: 11784 __reg_combine_min_max(true_src, true_dst); 11785 break; 11786 case BPF_JNE: 11787 __reg_combine_min_max(false_src, false_dst); 11788 break; 11789 } 11790 } 11791 11792 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 11793 struct bpf_reg_state *reg, u32 id, 11794 bool is_null) 11795 { 11796 if (type_may_be_null(reg->type) && reg->id == id && 11797 (is_rcu_reg(reg) || !WARN_ON_ONCE(!reg->id))) { 11798 /* Old offset (both fixed and variable parts) should have been 11799 * known-zero, because we don't allow pointer arithmetic on 11800 * pointers that might be NULL. If we see this happening, don't 11801 * convert the register. 11802 * 11803 * But in some cases, some helpers that return local kptrs 11804 * advance offset for the returned pointer. In those cases, it 11805 * is fine to expect to see reg->off. 11806 */ 11807 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || !tnum_equals_const(reg->var_off, 0))) 11808 return; 11809 if (reg->type != (PTR_TO_BTF_ID | MEM_ALLOC | PTR_MAYBE_NULL) && WARN_ON_ONCE(reg->off)) 11810 return; 11811 if (is_null) { 11812 reg->type = SCALAR_VALUE; 11813 /* We don't need id and ref_obj_id from this point 11814 * onwards anymore, thus we should better reset it, 11815 * so that state pruning has chances to take effect. 11816 */ 11817 reg->id = 0; 11818 reg->ref_obj_id = 0; 11819 11820 return; 11821 } 11822 11823 mark_ptr_not_null_reg(reg); 11824 11825 if (!reg_may_point_to_spin_lock(reg)) { 11826 /* For not-NULL ptr, reg->ref_obj_id will be reset 11827 * in release_reference(). 11828 * 11829 * reg->id is still used by spin_lock ptr. Other 11830 * than spin_lock ptr type, reg->id can be reset. 11831 */ 11832 reg->id = 0; 11833 } 11834 } 11835 } 11836 11837 /* The logic is similar to find_good_pkt_pointers(), both could eventually 11838 * be folded together at some point. 11839 */ 11840 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 11841 bool is_null) 11842 { 11843 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 11844 struct bpf_reg_state *regs = state->regs, *reg; 11845 u32 ref_obj_id = regs[regno].ref_obj_id; 11846 u32 id = regs[regno].id; 11847 11848 if (ref_obj_id && ref_obj_id == id && is_null) 11849 /* regs[regno] is in the " == NULL" branch. 11850 * No one could have freed the reference state before 11851 * doing the NULL check. 11852 */ 11853 WARN_ON_ONCE(release_reference_state(state, id)); 11854 11855 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 11856 mark_ptr_or_null_reg(state, reg, id, is_null); 11857 })); 11858 } 11859 11860 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 11861 struct bpf_reg_state *dst_reg, 11862 struct bpf_reg_state *src_reg, 11863 struct bpf_verifier_state *this_branch, 11864 struct bpf_verifier_state *other_branch) 11865 { 11866 if (BPF_SRC(insn->code) != BPF_X) 11867 return false; 11868 11869 /* Pointers are always 64-bit. */ 11870 if (BPF_CLASS(insn->code) == BPF_JMP32) 11871 return false; 11872 11873 switch (BPF_OP(insn->code)) { 11874 case BPF_JGT: 11875 if ((dst_reg->type == PTR_TO_PACKET && 11876 src_reg->type == PTR_TO_PACKET_END) || 11877 (dst_reg->type == PTR_TO_PACKET_META && 11878 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11879 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 11880 find_good_pkt_pointers(this_branch, dst_reg, 11881 dst_reg->type, false); 11882 mark_pkt_end(other_branch, insn->dst_reg, true); 11883 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11884 src_reg->type == PTR_TO_PACKET) || 11885 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11886 src_reg->type == PTR_TO_PACKET_META)) { 11887 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 11888 find_good_pkt_pointers(other_branch, src_reg, 11889 src_reg->type, true); 11890 mark_pkt_end(this_branch, insn->src_reg, false); 11891 } else { 11892 return false; 11893 } 11894 break; 11895 case BPF_JLT: 11896 if ((dst_reg->type == PTR_TO_PACKET && 11897 src_reg->type == PTR_TO_PACKET_END) || 11898 (dst_reg->type == PTR_TO_PACKET_META && 11899 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11900 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 11901 find_good_pkt_pointers(other_branch, dst_reg, 11902 dst_reg->type, true); 11903 mark_pkt_end(this_branch, insn->dst_reg, false); 11904 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11905 src_reg->type == PTR_TO_PACKET) || 11906 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11907 src_reg->type == PTR_TO_PACKET_META)) { 11908 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 11909 find_good_pkt_pointers(this_branch, src_reg, 11910 src_reg->type, false); 11911 mark_pkt_end(other_branch, insn->src_reg, true); 11912 } else { 11913 return false; 11914 } 11915 break; 11916 case BPF_JGE: 11917 if ((dst_reg->type == PTR_TO_PACKET && 11918 src_reg->type == PTR_TO_PACKET_END) || 11919 (dst_reg->type == PTR_TO_PACKET_META && 11920 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11921 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 11922 find_good_pkt_pointers(this_branch, dst_reg, 11923 dst_reg->type, true); 11924 mark_pkt_end(other_branch, insn->dst_reg, false); 11925 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11926 src_reg->type == PTR_TO_PACKET) || 11927 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11928 src_reg->type == PTR_TO_PACKET_META)) { 11929 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 11930 find_good_pkt_pointers(other_branch, src_reg, 11931 src_reg->type, false); 11932 mark_pkt_end(this_branch, insn->src_reg, true); 11933 } else { 11934 return false; 11935 } 11936 break; 11937 case BPF_JLE: 11938 if ((dst_reg->type == PTR_TO_PACKET && 11939 src_reg->type == PTR_TO_PACKET_END) || 11940 (dst_reg->type == PTR_TO_PACKET_META && 11941 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 11942 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 11943 find_good_pkt_pointers(other_branch, dst_reg, 11944 dst_reg->type, false); 11945 mark_pkt_end(this_branch, insn->dst_reg, true); 11946 } else if ((dst_reg->type == PTR_TO_PACKET_END && 11947 src_reg->type == PTR_TO_PACKET) || 11948 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 11949 src_reg->type == PTR_TO_PACKET_META)) { 11950 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 11951 find_good_pkt_pointers(this_branch, src_reg, 11952 src_reg->type, true); 11953 mark_pkt_end(other_branch, insn->src_reg, false); 11954 } else { 11955 return false; 11956 } 11957 break; 11958 default: 11959 return false; 11960 } 11961 11962 return true; 11963 } 11964 11965 static void find_equal_scalars(struct bpf_verifier_state *vstate, 11966 struct bpf_reg_state *known_reg) 11967 { 11968 struct bpf_func_state *state; 11969 struct bpf_reg_state *reg; 11970 11971 bpf_for_each_reg_in_vstate(vstate, state, reg, ({ 11972 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 11973 *reg = *known_reg; 11974 })); 11975 } 11976 11977 static int check_cond_jmp_op(struct bpf_verifier_env *env, 11978 struct bpf_insn *insn, int *insn_idx) 11979 { 11980 struct bpf_verifier_state *this_branch = env->cur_state; 11981 struct bpf_verifier_state *other_branch; 11982 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 11983 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 11984 struct bpf_reg_state *eq_branch_regs; 11985 u8 opcode = BPF_OP(insn->code); 11986 bool is_jmp32; 11987 int pred = -1; 11988 int err; 11989 11990 /* Only conditional jumps are expected to reach here. */ 11991 if (opcode == BPF_JA || opcode > BPF_JSLE) { 11992 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 11993 return -EINVAL; 11994 } 11995 11996 if (BPF_SRC(insn->code) == BPF_X) { 11997 if (insn->imm != 0) { 11998 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 11999 return -EINVAL; 12000 } 12001 12002 /* check src1 operand */ 12003 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12004 if (err) 12005 return err; 12006 12007 if (is_pointer_value(env, insn->src_reg)) { 12008 verbose(env, "R%d pointer comparison prohibited\n", 12009 insn->src_reg); 12010 return -EACCES; 12011 } 12012 src_reg = ®s[insn->src_reg]; 12013 } else { 12014 if (insn->src_reg != BPF_REG_0) { 12015 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 12016 return -EINVAL; 12017 } 12018 } 12019 12020 /* check src2 operand */ 12021 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 12022 if (err) 12023 return err; 12024 12025 dst_reg = ®s[insn->dst_reg]; 12026 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 12027 12028 if (BPF_SRC(insn->code) == BPF_K) { 12029 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 12030 } else if (src_reg->type == SCALAR_VALUE && 12031 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 12032 pred = is_branch_taken(dst_reg, 12033 tnum_subreg(src_reg->var_off).value, 12034 opcode, 12035 is_jmp32); 12036 } else if (src_reg->type == SCALAR_VALUE && 12037 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 12038 pred = is_branch_taken(dst_reg, 12039 src_reg->var_off.value, 12040 opcode, 12041 is_jmp32); 12042 } else if (reg_is_pkt_pointer_any(dst_reg) && 12043 reg_is_pkt_pointer_any(src_reg) && 12044 !is_jmp32) { 12045 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 12046 } 12047 12048 if (pred >= 0) { 12049 /* If we get here with a dst_reg pointer type it is because 12050 * above is_branch_taken() special cased the 0 comparison. 12051 */ 12052 if (!__is_pointer_value(false, dst_reg)) 12053 err = mark_chain_precision(env, insn->dst_reg); 12054 if (BPF_SRC(insn->code) == BPF_X && !err && 12055 !__is_pointer_value(false, src_reg)) 12056 err = mark_chain_precision(env, insn->src_reg); 12057 if (err) 12058 return err; 12059 } 12060 12061 if (pred == 1) { 12062 /* Only follow the goto, ignore fall-through. If needed, push 12063 * the fall-through branch for simulation under speculative 12064 * execution. 12065 */ 12066 if (!env->bypass_spec_v1 && 12067 !sanitize_speculative_path(env, insn, *insn_idx + 1, 12068 *insn_idx)) 12069 return -EFAULT; 12070 *insn_idx += insn->off; 12071 return 0; 12072 } else if (pred == 0) { 12073 /* Only follow the fall-through branch, since that's where the 12074 * program will go. If needed, push the goto branch for 12075 * simulation under speculative execution. 12076 */ 12077 if (!env->bypass_spec_v1 && 12078 !sanitize_speculative_path(env, insn, 12079 *insn_idx + insn->off + 1, 12080 *insn_idx)) 12081 return -EFAULT; 12082 return 0; 12083 } 12084 12085 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 12086 false); 12087 if (!other_branch) 12088 return -EFAULT; 12089 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 12090 12091 /* detect if we are comparing against a constant value so we can adjust 12092 * our min/max values for our dst register. 12093 * this is only legit if both are scalars (or pointers to the same 12094 * object, I suppose, see the PTR_MAYBE_NULL related if block below), 12095 * because otherwise the different base pointers mean the offsets aren't 12096 * comparable. 12097 */ 12098 if (BPF_SRC(insn->code) == BPF_X) { 12099 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 12100 12101 if (dst_reg->type == SCALAR_VALUE && 12102 src_reg->type == SCALAR_VALUE) { 12103 if (tnum_is_const(src_reg->var_off) || 12104 (is_jmp32 && 12105 tnum_is_const(tnum_subreg(src_reg->var_off)))) 12106 reg_set_min_max(&other_branch_regs[insn->dst_reg], 12107 dst_reg, 12108 src_reg->var_off.value, 12109 tnum_subreg(src_reg->var_off).value, 12110 opcode, is_jmp32); 12111 else if (tnum_is_const(dst_reg->var_off) || 12112 (is_jmp32 && 12113 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 12114 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 12115 src_reg, 12116 dst_reg->var_off.value, 12117 tnum_subreg(dst_reg->var_off).value, 12118 opcode, is_jmp32); 12119 else if (!is_jmp32 && 12120 (opcode == BPF_JEQ || opcode == BPF_JNE)) 12121 /* Comparing for equality, we can combine knowledge */ 12122 reg_combine_min_max(&other_branch_regs[insn->src_reg], 12123 &other_branch_regs[insn->dst_reg], 12124 src_reg, dst_reg, opcode); 12125 if (src_reg->id && 12126 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 12127 find_equal_scalars(this_branch, src_reg); 12128 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 12129 } 12130 12131 } 12132 } else if (dst_reg->type == SCALAR_VALUE) { 12133 reg_set_min_max(&other_branch_regs[insn->dst_reg], 12134 dst_reg, insn->imm, (u32)insn->imm, 12135 opcode, is_jmp32); 12136 } 12137 12138 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 12139 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 12140 find_equal_scalars(this_branch, dst_reg); 12141 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 12142 } 12143 12144 /* if one pointer register is compared to another pointer 12145 * register check if PTR_MAYBE_NULL could be lifted. 12146 * E.g. register A - maybe null 12147 * register B - not null 12148 * for JNE A, B, ... - A is not null in the false branch; 12149 * for JEQ A, B, ... - A is not null in the true branch. 12150 * 12151 * Since PTR_TO_BTF_ID points to a kernel struct that does 12152 * not need to be null checked by the BPF program, i.e., 12153 * could be null even without PTR_MAYBE_NULL marking, so 12154 * only propagate nullness when neither reg is that type. 12155 */ 12156 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_X && 12157 __is_pointer_value(false, src_reg) && __is_pointer_value(false, dst_reg) && 12158 type_may_be_null(src_reg->type) != type_may_be_null(dst_reg->type) && 12159 base_type(src_reg->type) != PTR_TO_BTF_ID && 12160 base_type(dst_reg->type) != PTR_TO_BTF_ID) { 12161 eq_branch_regs = NULL; 12162 switch (opcode) { 12163 case BPF_JEQ: 12164 eq_branch_regs = other_branch_regs; 12165 break; 12166 case BPF_JNE: 12167 eq_branch_regs = regs; 12168 break; 12169 default: 12170 /* do nothing */ 12171 break; 12172 } 12173 if (eq_branch_regs) { 12174 if (type_may_be_null(src_reg->type)) 12175 mark_ptr_not_null_reg(&eq_branch_regs[insn->src_reg]); 12176 else 12177 mark_ptr_not_null_reg(&eq_branch_regs[insn->dst_reg]); 12178 } 12179 } 12180 12181 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 12182 * NOTE: these optimizations below are related with pointer comparison 12183 * which will never be JMP32. 12184 */ 12185 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 12186 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 12187 type_may_be_null(dst_reg->type)) { 12188 /* Mark all identical registers in each branch as either 12189 * safe or unknown depending R == 0 or R != 0 conditional. 12190 */ 12191 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 12192 opcode == BPF_JNE); 12193 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 12194 opcode == BPF_JEQ); 12195 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 12196 this_branch, other_branch) && 12197 is_pointer_value(env, insn->dst_reg)) { 12198 verbose(env, "R%d pointer comparison prohibited\n", 12199 insn->dst_reg); 12200 return -EACCES; 12201 } 12202 if (env->log.level & BPF_LOG_LEVEL) 12203 print_insn_state(env, this_branch->frame[this_branch->curframe]); 12204 return 0; 12205 } 12206 12207 /* verify BPF_LD_IMM64 instruction */ 12208 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 12209 { 12210 struct bpf_insn_aux_data *aux = cur_aux(env); 12211 struct bpf_reg_state *regs = cur_regs(env); 12212 struct bpf_reg_state *dst_reg; 12213 struct bpf_map *map; 12214 int err; 12215 12216 if (BPF_SIZE(insn->code) != BPF_DW) { 12217 verbose(env, "invalid BPF_LD_IMM insn\n"); 12218 return -EINVAL; 12219 } 12220 if (insn->off != 0) { 12221 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 12222 return -EINVAL; 12223 } 12224 12225 err = check_reg_arg(env, insn->dst_reg, DST_OP); 12226 if (err) 12227 return err; 12228 12229 dst_reg = ®s[insn->dst_reg]; 12230 if (insn->src_reg == 0) { 12231 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 12232 12233 dst_reg->type = SCALAR_VALUE; 12234 __mark_reg_known(®s[insn->dst_reg], imm); 12235 return 0; 12236 } 12237 12238 /* All special src_reg cases are listed below. From this point onwards 12239 * we either succeed and assign a corresponding dst_reg->type after 12240 * zeroing the offset, or fail and reject the program. 12241 */ 12242 mark_reg_known_zero(env, regs, insn->dst_reg); 12243 12244 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 12245 dst_reg->type = aux->btf_var.reg_type; 12246 switch (base_type(dst_reg->type)) { 12247 case PTR_TO_MEM: 12248 dst_reg->mem_size = aux->btf_var.mem_size; 12249 break; 12250 case PTR_TO_BTF_ID: 12251 dst_reg->btf = aux->btf_var.btf; 12252 dst_reg->btf_id = aux->btf_var.btf_id; 12253 break; 12254 default: 12255 verbose(env, "bpf verifier is misconfigured\n"); 12256 return -EFAULT; 12257 } 12258 return 0; 12259 } 12260 12261 if (insn->src_reg == BPF_PSEUDO_FUNC) { 12262 struct bpf_prog_aux *aux = env->prog->aux; 12263 u32 subprogno = find_subprog(env, 12264 env->insn_idx + insn->imm + 1); 12265 12266 if (!aux->func_info) { 12267 verbose(env, "missing btf func_info\n"); 12268 return -EINVAL; 12269 } 12270 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 12271 verbose(env, "callback function not static\n"); 12272 return -EINVAL; 12273 } 12274 12275 dst_reg->type = PTR_TO_FUNC; 12276 dst_reg->subprogno = subprogno; 12277 return 0; 12278 } 12279 12280 map = env->used_maps[aux->map_index]; 12281 dst_reg->map_ptr = map; 12282 12283 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 12284 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 12285 dst_reg->type = PTR_TO_MAP_VALUE; 12286 dst_reg->off = aux->map_off; 12287 WARN_ON_ONCE(map->max_entries != 1); 12288 /* We want reg->id to be same (0) as map_value is not distinct */ 12289 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 12290 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 12291 dst_reg->type = CONST_PTR_TO_MAP; 12292 } else { 12293 verbose(env, "bpf verifier is misconfigured\n"); 12294 return -EINVAL; 12295 } 12296 12297 return 0; 12298 } 12299 12300 static bool may_access_skb(enum bpf_prog_type type) 12301 { 12302 switch (type) { 12303 case BPF_PROG_TYPE_SOCKET_FILTER: 12304 case BPF_PROG_TYPE_SCHED_CLS: 12305 case BPF_PROG_TYPE_SCHED_ACT: 12306 return true; 12307 default: 12308 return false; 12309 } 12310 } 12311 12312 /* verify safety of LD_ABS|LD_IND instructions: 12313 * - they can only appear in the programs where ctx == skb 12314 * - since they are wrappers of function calls, they scratch R1-R5 registers, 12315 * preserve R6-R9, and store return value into R0 12316 * 12317 * Implicit input: 12318 * ctx == skb == R6 == CTX 12319 * 12320 * Explicit input: 12321 * SRC == any register 12322 * IMM == 32-bit immediate 12323 * 12324 * Output: 12325 * R0 - 8/16/32-bit skb data converted to cpu endianness 12326 */ 12327 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 12328 { 12329 struct bpf_reg_state *regs = cur_regs(env); 12330 static const int ctx_reg = BPF_REG_6; 12331 u8 mode = BPF_MODE(insn->code); 12332 int i, err; 12333 12334 if (!may_access_skb(resolve_prog_type(env->prog))) { 12335 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 12336 return -EINVAL; 12337 } 12338 12339 if (!env->ops->gen_ld_abs) { 12340 verbose(env, "bpf verifier is misconfigured\n"); 12341 return -EINVAL; 12342 } 12343 12344 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 12345 BPF_SIZE(insn->code) == BPF_DW || 12346 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 12347 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 12348 return -EINVAL; 12349 } 12350 12351 /* check whether implicit source operand (register R6) is readable */ 12352 err = check_reg_arg(env, ctx_reg, SRC_OP); 12353 if (err) 12354 return err; 12355 12356 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 12357 * gen_ld_abs() may terminate the program at runtime, leading to 12358 * reference leak. 12359 */ 12360 err = check_reference_leak(env); 12361 if (err) { 12362 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 12363 return err; 12364 } 12365 12366 if (env->cur_state->active_lock.ptr) { 12367 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 12368 return -EINVAL; 12369 } 12370 12371 if (env->cur_state->active_rcu_lock) { 12372 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_rcu_read_lock-ed region\n"); 12373 return -EINVAL; 12374 } 12375 12376 if (regs[ctx_reg].type != PTR_TO_CTX) { 12377 verbose(env, 12378 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 12379 return -EINVAL; 12380 } 12381 12382 if (mode == BPF_IND) { 12383 /* check explicit source operand */ 12384 err = check_reg_arg(env, insn->src_reg, SRC_OP); 12385 if (err) 12386 return err; 12387 } 12388 12389 err = check_ptr_off_reg(env, ®s[ctx_reg], ctx_reg); 12390 if (err < 0) 12391 return err; 12392 12393 /* reset caller saved regs to unreadable */ 12394 for (i = 0; i < CALLER_SAVED_REGS; i++) { 12395 mark_reg_not_init(env, regs, caller_saved[i]); 12396 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 12397 } 12398 12399 /* mark destination R0 register as readable, since it contains 12400 * the value fetched from the packet. 12401 * Already marked as written above. 12402 */ 12403 mark_reg_unknown(env, regs, BPF_REG_0); 12404 /* ld_abs load up to 32-bit skb data. */ 12405 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 12406 return 0; 12407 } 12408 12409 static int check_return_code(struct bpf_verifier_env *env) 12410 { 12411 struct tnum enforce_attach_type_range = tnum_unknown; 12412 const struct bpf_prog *prog = env->prog; 12413 struct bpf_reg_state *reg; 12414 struct tnum range = tnum_range(0, 1); 12415 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 12416 int err; 12417 struct bpf_func_state *frame = env->cur_state->frame[0]; 12418 const bool is_subprog = frame->subprogno; 12419 12420 /* LSM and struct_ops func-ptr's return type could be "void" */ 12421 if (!is_subprog) { 12422 switch (prog_type) { 12423 case BPF_PROG_TYPE_LSM: 12424 if (prog->expected_attach_type == BPF_LSM_CGROUP) 12425 /* See below, can be 0 or 0-1 depending on hook. */ 12426 break; 12427 fallthrough; 12428 case BPF_PROG_TYPE_STRUCT_OPS: 12429 if (!prog->aux->attach_func_proto->type) 12430 return 0; 12431 break; 12432 default: 12433 break; 12434 } 12435 } 12436 12437 /* eBPF calling convention is such that R0 is used 12438 * to return the value from eBPF program. 12439 * Make sure that it's readable at this time 12440 * of bpf_exit, which means that program wrote 12441 * something into it earlier 12442 */ 12443 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 12444 if (err) 12445 return err; 12446 12447 if (is_pointer_value(env, BPF_REG_0)) { 12448 verbose(env, "R0 leaks addr as return value\n"); 12449 return -EACCES; 12450 } 12451 12452 reg = cur_regs(env) + BPF_REG_0; 12453 12454 if (frame->in_async_callback_fn) { 12455 /* enforce return zero from async callbacks like timer */ 12456 if (reg->type != SCALAR_VALUE) { 12457 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 12458 reg_type_str(env, reg->type)); 12459 return -EINVAL; 12460 } 12461 12462 if (!tnum_in(tnum_const(0), reg->var_off)) { 12463 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 12464 return -EINVAL; 12465 } 12466 return 0; 12467 } 12468 12469 if (is_subprog) { 12470 if (reg->type != SCALAR_VALUE) { 12471 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 12472 reg_type_str(env, reg->type)); 12473 return -EINVAL; 12474 } 12475 return 0; 12476 } 12477 12478 switch (prog_type) { 12479 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 12480 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 12481 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 12482 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 12483 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 12484 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 12485 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 12486 range = tnum_range(1, 1); 12487 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 12488 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 12489 range = tnum_range(0, 3); 12490 break; 12491 case BPF_PROG_TYPE_CGROUP_SKB: 12492 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 12493 range = tnum_range(0, 3); 12494 enforce_attach_type_range = tnum_range(2, 3); 12495 } 12496 break; 12497 case BPF_PROG_TYPE_CGROUP_SOCK: 12498 case BPF_PROG_TYPE_SOCK_OPS: 12499 case BPF_PROG_TYPE_CGROUP_DEVICE: 12500 case BPF_PROG_TYPE_CGROUP_SYSCTL: 12501 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 12502 break; 12503 case BPF_PROG_TYPE_RAW_TRACEPOINT: 12504 if (!env->prog->aux->attach_btf_id) 12505 return 0; 12506 range = tnum_const(0); 12507 break; 12508 case BPF_PROG_TYPE_TRACING: 12509 switch (env->prog->expected_attach_type) { 12510 case BPF_TRACE_FENTRY: 12511 case BPF_TRACE_FEXIT: 12512 range = tnum_const(0); 12513 break; 12514 case BPF_TRACE_RAW_TP: 12515 case BPF_MODIFY_RETURN: 12516 return 0; 12517 case BPF_TRACE_ITER: 12518 break; 12519 default: 12520 return -ENOTSUPP; 12521 } 12522 break; 12523 case BPF_PROG_TYPE_SK_LOOKUP: 12524 range = tnum_range(SK_DROP, SK_PASS); 12525 break; 12526 12527 case BPF_PROG_TYPE_LSM: 12528 if (env->prog->expected_attach_type != BPF_LSM_CGROUP) { 12529 /* Regular BPF_PROG_TYPE_LSM programs can return 12530 * any value. 12531 */ 12532 return 0; 12533 } 12534 if (!env->prog->aux->attach_func_proto->type) { 12535 /* Make sure programs that attach to void 12536 * hooks don't try to modify return value. 12537 */ 12538 range = tnum_range(1, 1); 12539 } 12540 break; 12541 12542 case BPF_PROG_TYPE_EXT: 12543 /* freplace program can return anything as its return value 12544 * depends on the to-be-replaced kernel func or bpf program. 12545 */ 12546 default: 12547 return 0; 12548 } 12549 12550 if (reg->type != SCALAR_VALUE) { 12551 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 12552 reg_type_str(env, reg->type)); 12553 return -EINVAL; 12554 } 12555 12556 if (!tnum_in(range, reg->var_off)) { 12557 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 12558 if (prog->expected_attach_type == BPF_LSM_CGROUP && 12559 prog_type == BPF_PROG_TYPE_LSM && 12560 !prog->aux->attach_func_proto->type) 12561 verbose(env, "Note, BPF_LSM_CGROUP that attach to void LSM hooks can't modify return value!\n"); 12562 return -EINVAL; 12563 } 12564 12565 if (!tnum_is_unknown(enforce_attach_type_range) && 12566 tnum_in(enforce_attach_type_range, reg->var_off)) 12567 env->prog->enforce_expected_attach_type = 1; 12568 return 0; 12569 } 12570 12571 /* non-recursive DFS pseudo code 12572 * 1 procedure DFS-iterative(G,v): 12573 * 2 label v as discovered 12574 * 3 let S be a stack 12575 * 4 S.push(v) 12576 * 5 while S is not empty 12577 * 6 t <- S.peek() 12578 * 7 if t is what we're looking for: 12579 * 8 return t 12580 * 9 for all edges e in G.adjacentEdges(t) do 12581 * 10 if edge e is already labelled 12582 * 11 continue with the next edge 12583 * 12 w <- G.adjacentVertex(t,e) 12584 * 13 if vertex w is not discovered and not explored 12585 * 14 label e as tree-edge 12586 * 15 label w as discovered 12587 * 16 S.push(w) 12588 * 17 continue at 5 12589 * 18 else if vertex w is discovered 12590 * 19 label e as back-edge 12591 * 20 else 12592 * 21 // vertex w is explored 12593 * 22 label e as forward- or cross-edge 12594 * 23 label t as explored 12595 * 24 S.pop() 12596 * 12597 * convention: 12598 * 0x10 - discovered 12599 * 0x11 - discovered and fall-through edge labelled 12600 * 0x12 - discovered and fall-through and branch edges labelled 12601 * 0x20 - explored 12602 */ 12603 12604 enum { 12605 DISCOVERED = 0x10, 12606 EXPLORED = 0x20, 12607 FALLTHROUGH = 1, 12608 BRANCH = 2, 12609 }; 12610 12611 static u32 state_htab_size(struct bpf_verifier_env *env) 12612 { 12613 return env->prog->len; 12614 } 12615 12616 static struct bpf_verifier_state_list **explored_state( 12617 struct bpf_verifier_env *env, 12618 int idx) 12619 { 12620 struct bpf_verifier_state *cur = env->cur_state; 12621 struct bpf_func_state *state = cur->frame[cur->curframe]; 12622 12623 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 12624 } 12625 12626 static void mark_prune_point(struct bpf_verifier_env *env, int idx) 12627 { 12628 env->insn_aux_data[idx].prune_point = true; 12629 } 12630 12631 static bool is_prune_point(struct bpf_verifier_env *env, int insn_idx) 12632 { 12633 return env->insn_aux_data[insn_idx].prune_point; 12634 } 12635 12636 enum { 12637 DONE_EXPLORING = 0, 12638 KEEP_EXPLORING = 1, 12639 }; 12640 12641 /* t, w, e - match pseudo-code above: 12642 * t - index of current instruction 12643 * w - next instruction 12644 * e - edge 12645 */ 12646 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 12647 bool loop_ok) 12648 { 12649 int *insn_stack = env->cfg.insn_stack; 12650 int *insn_state = env->cfg.insn_state; 12651 12652 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 12653 return DONE_EXPLORING; 12654 12655 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 12656 return DONE_EXPLORING; 12657 12658 if (w < 0 || w >= env->prog->len) { 12659 verbose_linfo(env, t, "%d: ", t); 12660 verbose(env, "jump out of range from insn %d to %d\n", t, w); 12661 return -EINVAL; 12662 } 12663 12664 if (e == BRANCH) { 12665 /* mark branch target for state pruning */ 12666 mark_prune_point(env, w); 12667 mark_jmp_point(env, w); 12668 } 12669 12670 if (insn_state[w] == 0) { 12671 /* tree-edge */ 12672 insn_state[t] = DISCOVERED | e; 12673 insn_state[w] = DISCOVERED; 12674 if (env->cfg.cur_stack >= env->prog->len) 12675 return -E2BIG; 12676 insn_stack[env->cfg.cur_stack++] = w; 12677 return KEEP_EXPLORING; 12678 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 12679 if (loop_ok && env->bpf_capable) 12680 return DONE_EXPLORING; 12681 verbose_linfo(env, t, "%d: ", t); 12682 verbose_linfo(env, w, "%d: ", w); 12683 verbose(env, "back-edge from insn %d to %d\n", t, w); 12684 return -EINVAL; 12685 } else if (insn_state[w] == EXPLORED) { 12686 /* forward- or cross-edge */ 12687 insn_state[t] = DISCOVERED | e; 12688 } else { 12689 verbose(env, "insn state internal bug\n"); 12690 return -EFAULT; 12691 } 12692 return DONE_EXPLORING; 12693 } 12694 12695 static int visit_func_call_insn(int t, struct bpf_insn *insns, 12696 struct bpf_verifier_env *env, 12697 bool visit_callee) 12698 { 12699 int ret; 12700 12701 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 12702 if (ret) 12703 return ret; 12704 12705 mark_prune_point(env, t + 1); 12706 /* when we exit from subprog, we need to record non-linear history */ 12707 mark_jmp_point(env, t + 1); 12708 12709 if (visit_callee) { 12710 mark_prune_point(env, t); 12711 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 12712 /* It's ok to allow recursion from CFG point of 12713 * view. __check_func_call() will do the actual 12714 * check. 12715 */ 12716 bpf_pseudo_func(insns + t)); 12717 } 12718 return ret; 12719 } 12720 12721 /* Visits the instruction at index t and returns one of the following: 12722 * < 0 - an error occurred 12723 * DONE_EXPLORING - the instruction was fully explored 12724 * KEEP_EXPLORING - there is still work to be done before it is fully explored 12725 */ 12726 static int visit_insn(int t, struct bpf_verifier_env *env) 12727 { 12728 struct bpf_insn *insns = env->prog->insnsi; 12729 int ret; 12730 12731 if (bpf_pseudo_func(insns + t)) 12732 return visit_func_call_insn(t, insns, env, true); 12733 12734 /* All non-branch instructions have a single fall-through edge. */ 12735 if (BPF_CLASS(insns[t].code) != BPF_JMP && 12736 BPF_CLASS(insns[t].code) != BPF_JMP32) 12737 return push_insn(t, t + 1, FALLTHROUGH, env, false); 12738 12739 switch (BPF_OP(insns[t].code)) { 12740 case BPF_EXIT: 12741 return DONE_EXPLORING; 12742 12743 case BPF_CALL: 12744 if (insns[t].imm == BPF_FUNC_timer_set_callback) 12745 /* Mark this call insn as a prune point to trigger 12746 * is_state_visited() check before call itself is 12747 * processed by __check_func_call(). Otherwise new 12748 * async state will be pushed for further exploration. 12749 */ 12750 mark_prune_point(env, t); 12751 return visit_func_call_insn(t, insns, env, 12752 insns[t].src_reg == BPF_PSEUDO_CALL); 12753 12754 case BPF_JA: 12755 if (BPF_SRC(insns[t].code) != BPF_K) 12756 return -EINVAL; 12757 12758 /* unconditional jump with single edge */ 12759 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env, 12760 true); 12761 if (ret) 12762 return ret; 12763 12764 mark_prune_point(env, t + insns[t].off + 1); 12765 mark_jmp_point(env, t + insns[t].off + 1); 12766 12767 return ret; 12768 12769 default: 12770 /* conditional jump with two edges */ 12771 mark_prune_point(env, t); 12772 12773 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 12774 if (ret) 12775 return ret; 12776 12777 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true); 12778 } 12779 } 12780 12781 /* non-recursive depth-first-search to detect loops in BPF program 12782 * loop == back-edge in directed graph 12783 */ 12784 static int check_cfg(struct bpf_verifier_env *env) 12785 { 12786 int insn_cnt = env->prog->len; 12787 int *insn_stack, *insn_state; 12788 int ret = 0; 12789 int i; 12790 12791 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 12792 if (!insn_state) 12793 return -ENOMEM; 12794 12795 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 12796 if (!insn_stack) { 12797 kvfree(insn_state); 12798 return -ENOMEM; 12799 } 12800 12801 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 12802 insn_stack[0] = 0; /* 0 is the first instruction */ 12803 env->cfg.cur_stack = 1; 12804 12805 while (env->cfg.cur_stack > 0) { 12806 int t = insn_stack[env->cfg.cur_stack - 1]; 12807 12808 ret = visit_insn(t, env); 12809 switch (ret) { 12810 case DONE_EXPLORING: 12811 insn_state[t] = EXPLORED; 12812 env->cfg.cur_stack--; 12813 break; 12814 case KEEP_EXPLORING: 12815 break; 12816 default: 12817 if (ret > 0) { 12818 verbose(env, "visit_insn internal bug\n"); 12819 ret = -EFAULT; 12820 } 12821 goto err_free; 12822 } 12823 } 12824 12825 if (env->cfg.cur_stack < 0) { 12826 verbose(env, "pop stack internal bug\n"); 12827 ret = -EFAULT; 12828 goto err_free; 12829 } 12830 12831 for (i = 0; i < insn_cnt; i++) { 12832 if (insn_state[i] != EXPLORED) { 12833 verbose(env, "unreachable insn %d\n", i); 12834 ret = -EINVAL; 12835 goto err_free; 12836 } 12837 } 12838 ret = 0; /* cfg looks good */ 12839 12840 err_free: 12841 kvfree(insn_state); 12842 kvfree(insn_stack); 12843 env->cfg.insn_state = env->cfg.insn_stack = NULL; 12844 return ret; 12845 } 12846 12847 static int check_abnormal_return(struct bpf_verifier_env *env) 12848 { 12849 int i; 12850 12851 for (i = 1; i < env->subprog_cnt; i++) { 12852 if (env->subprog_info[i].has_ld_abs) { 12853 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 12854 return -EINVAL; 12855 } 12856 if (env->subprog_info[i].has_tail_call) { 12857 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 12858 return -EINVAL; 12859 } 12860 } 12861 return 0; 12862 } 12863 12864 /* The minimum supported BTF func info size */ 12865 #define MIN_BPF_FUNCINFO_SIZE 8 12866 #define MAX_FUNCINFO_REC_SIZE 252 12867 12868 static int check_btf_func(struct bpf_verifier_env *env, 12869 const union bpf_attr *attr, 12870 bpfptr_t uattr) 12871 { 12872 const struct btf_type *type, *func_proto, *ret_type; 12873 u32 i, nfuncs, urec_size, min_size; 12874 u32 krec_size = sizeof(struct bpf_func_info); 12875 struct bpf_func_info *krecord; 12876 struct bpf_func_info_aux *info_aux = NULL; 12877 struct bpf_prog *prog; 12878 const struct btf *btf; 12879 bpfptr_t urecord; 12880 u32 prev_offset = 0; 12881 bool scalar_return; 12882 int ret = -ENOMEM; 12883 12884 nfuncs = attr->func_info_cnt; 12885 if (!nfuncs) { 12886 if (check_abnormal_return(env)) 12887 return -EINVAL; 12888 return 0; 12889 } 12890 12891 if (nfuncs != env->subprog_cnt) { 12892 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 12893 return -EINVAL; 12894 } 12895 12896 urec_size = attr->func_info_rec_size; 12897 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 12898 urec_size > MAX_FUNCINFO_REC_SIZE || 12899 urec_size % sizeof(u32)) { 12900 verbose(env, "invalid func info rec size %u\n", urec_size); 12901 return -EINVAL; 12902 } 12903 12904 prog = env->prog; 12905 btf = prog->aux->btf; 12906 12907 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 12908 min_size = min_t(u32, krec_size, urec_size); 12909 12910 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 12911 if (!krecord) 12912 return -ENOMEM; 12913 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 12914 if (!info_aux) 12915 goto err_free; 12916 12917 for (i = 0; i < nfuncs; i++) { 12918 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 12919 if (ret) { 12920 if (ret == -E2BIG) { 12921 verbose(env, "nonzero tailing record in func info"); 12922 /* set the size kernel expects so loader can zero 12923 * out the rest of the record. 12924 */ 12925 if (copy_to_bpfptr_offset(uattr, 12926 offsetof(union bpf_attr, func_info_rec_size), 12927 &min_size, sizeof(min_size))) 12928 ret = -EFAULT; 12929 } 12930 goto err_free; 12931 } 12932 12933 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 12934 ret = -EFAULT; 12935 goto err_free; 12936 } 12937 12938 /* check insn_off */ 12939 ret = -EINVAL; 12940 if (i == 0) { 12941 if (krecord[i].insn_off) { 12942 verbose(env, 12943 "nonzero insn_off %u for the first func info record", 12944 krecord[i].insn_off); 12945 goto err_free; 12946 } 12947 } else if (krecord[i].insn_off <= prev_offset) { 12948 verbose(env, 12949 "same or smaller insn offset (%u) than previous func info record (%u)", 12950 krecord[i].insn_off, prev_offset); 12951 goto err_free; 12952 } 12953 12954 if (env->subprog_info[i].start != krecord[i].insn_off) { 12955 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 12956 goto err_free; 12957 } 12958 12959 /* check type_id */ 12960 type = btf_type_by_id(btf, krecord[i].type_id); 12961 if (!type || !btf_type_is_func(type)) { 12962 verbose(env, "invalid type id %d in func info", 12963 krecord[i].type_id); 12964 goto err_free; 12965 } 12966 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 12967 12968 func_proto = btf_type_by_id(btf, type->type); 12969 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 12970 /* btf_func_check() already verified it during BTF load */ 12971 goto err_free; 12972 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 12973 scalar_return = 12974 btf_type_is_small_int(ret_type) || btf_is_any_enum(ret_type); 12975 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 12976 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 12977 goto err_free; 12978 } 12979 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 12980 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 12981 goto err_free; 12982 } 12983 12984 prev_offset = krecord[i].insn_off; 12985 bpfptr_add(&urecord, urec_size); 12986 } 12987 12988 prog->aux->func_info = krecord; 12989 prog->aux->func_info_cnt = nfuncs; 12990 prog->aux->func_info_aux = info_aux; 12991 return 0; 12992 12993 err_free: 12994 kvfree(krecord); 12995 kfree(info_aux); 12996 return ret; 12997 } 12998 12999 static void adjust_btf_func(struct bpf_verifier_env *env) 13000 { 13001 struct bpf_prog_aux *aux = env->prog->aux; 13002 int i; 13003 13004 if (!aux->func_info) 13005 return; 13006 13007 for (i = 0; i < env->subprog_cnt; i++) 13008 aux->func_info[i].insn_off = env->subprog_info[i].start; 13009 } 13010 13011 #define MIN_BPF_LINEINFO_SIZE offsetofend(struct bpf_line_info, line_col) 13012 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 13013 13014 static int check_btf_line(struct bpf_verifier_env *env, 13015 const union bpf_attr *attr, 13016 bpfptr_t uattr) 13017 { 13018 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 13019 struct bpf_subprog_info *sub; 13020 struct bpf_line_info *linfo; 13021 struct bpf_prog *prog; 13022 const struct btf *btf; 13023 bpfptr_t ulinfo; 13024 int err; 13025 13026 nr_linfo = attr->line_info_cnt; 13027 if (!nr_linfo) 13028 return 0; 13029 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 13030 return -EINVAL; 13031 13032 rec_size = attr->line_info_rec_size; 13033 if (rec_size < MIN_BPF_LINEINFO_SIZE || 13034 rec_size > MAX_LINEINFO_REC_SIZE || 13035 rec_size & (sizeof(u32) - 1)) 13036 return -EINVAL; 13037 13038 /* Need to zero it in case the userspace may 13039 * pass in a smaller bpf_line_info object. 13040 */ 13041 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 13042 GFP_KERNEL | __GFP_NOWARN); 13043 if (!linfo) 13044 return -ENOMEM; 13045 13046 prog = env->prog; 13047 btf = prog->aux->btf; 13048 13049 s = 0; 13050 sub = env->subprog_info; 13051 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 13052 expected_size = sizeof(struct bpf_line_info); 13053 ncopy = min_t(u32, expected_size, rec_size); 13054 for (i = 0; i < nr_linfo; i++) { 13055 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 13056 if (err) { 13057 if (err == -E2BIG) { 13058 verbose(env, "nonzero tailing record in line_info"); 13059 if (copy_to_bpfptr_offset(uattr, 13060 offsetof(union bpf_attr, line_info_rec_size), 13061 &expected_size, sizeof(expected_size))) 13062 err = -EFAULT; 13063 } 13064 goto err_free; 13065 } 13066 13067 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 13068 err = -EFAULT; 13069 goto err_free; 13070 } 13071 13072 /* 13073 * Check insn_off to ensure 13074 * 1) strictly increasing AND 13075 * 2) bounded by prog->len 13076 * 13077 * The linfo[0].insn_off == 0 check logically falls into 13078 * the later "missing bpf_line_info for func..." case 13079 * because the first linfo[0].insn_off must be the 13080 * first sub also and the first sub must have 13081 * subprog_info[0].start == 0. 13082 */ 13083 if ((i && linfo[i].insn_off <= prev_offset) || 13084 linfo[i].insn_off >= prog->len) { 13085 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 13086 i, linfo[i].insn_off, prev_offset, 13087 prog->len); 13088 err = -EINVAL; 13089 goto err_free; 13090 } 13091 13092 if (!prog->insnsi[linfo[i].insn_off].code) { 13093 verbose(env, 13094 "Invalid insn code at line_info[%u].insn_off\n", 13095 i); 13096 err = -EINVAL; 13097 goto err_free; 13098 } 13099 13100 if (!btf_name_by_offset(btf, linfo[i].line_off) || 13101 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 13102 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 13103 err = -EINVAL; 13104 goto err_free; 13105 } 13106 13107 if (s != env->subprog_cnt) { 13108 if (linfo[i].insn_off == sub[s].start) { 13109 sub[s].linfo_idx = i; 13110 s++; 13111 } else if (sub[s].start < linfo[i].insn_off) { 13112 verbose(env, "missing bpf_line_info for func#%u\n", s); 13113 err = -EINVAL; 13114 goto err_free; 13115 } 13116 } 13117 13118 prev_offset = linfo[i].insn_off; 13119 bpfptr_add(&ulinfo, rec_size); 13120 } 13121 13122 if (s != env->subprog_cnt) { 13123 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 13124 env->subprog_cnt - s, s); 13125 err = -EINVAL; 13126 goto err_free; 13127 } 13128 13129 prog->aux->linfo = linfo; 13130 prog->aux->nr_linfo = nr_linfo; 13131 13132 return 0; 13133 13134 err_free: 13135 kvfree(linfo); 13136 return err; 13137 } 13138 13139 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 13140 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 13141 13142 static int check_core_relo(struct bpf_verifier_env *env, 13143 const union bpf_attr *attr, 13144 bpfptr_t uattr) 13145 { 13146 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 13147 struct bpf_core_relo core_relo = {}; 13148 struct bpf_prog *prog = env->prog; 13149 const struct btf *btf = prog->aux->btf; 13150 struct bpf_core_ctx ctx = { 13151 .log = &env->log, 13152 .btf = btf, 13153 }; 13154 bpfptr_t u_core_relo; 13155 int err; 13156 13157 nr_core_relo = attr->core_relo_cnt; 13158 if (!nr_core_relo) 13159 return 0; 13160 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 13161 return -EINVAL; 13162 13163 rec_size = attr->core_relo_rec_size; 13164 if (rec_size < MIN_CORE_RELO_SIZE || 13165 rec_size > MAX_CORE_RELO_SIZE || 13166 rec_size % sizeof(u32)) 13167 return -EINVAL; 13168 13169 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 13170 expected_size = sizeof(struct bpf_core_relo); 13171 ncopy = min_t(u32, expected_size, rec_size); 13172 13173 /* Unlike func_info and line_info, copy and apply each CO-RE 13174 * relocation record one at a time. 13175 */ 13176 for (i = 0; i < nr_core_relo; i++) { 13177 /* future proofing when sizeof(bpf_core_relo) changes */ 13178 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 13179 if (err) { 13180 if (err == -E2BIG) { 13181 verbose(env, "nonzero tailing record in core_relo"); 13182 if (copy_to_bpfptr_offset(uattr, 13183 offsetof(union bpf_attr, core_relo_rec_size), 13184 &expected_size, sizeof(expected_size))) 13185 err = -EFAULT; 13186 } 13187 break; 13188 } 13189 13190 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 13191 err = -EFAULT; 13192 break; 13193 } 13194 13195 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 13196 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 13197 i, core_relo.insn_off, prog->len); 13198 err = -EINVAL; 13199 break; 13200 } 13201 13202 err = bpf_core_apply(&ctx, &core_relo, i, 13203 &prog->insnsi[core_relo.insn_off / 8]); 13204 if (err) 13205 break; 13206 bpfptr_add(&u_core_relo, rec_size); 13207 } 13208 return err; 13209 } 13210 13211 static int check_btf_info(struct bpf_verifier_env *env, 13212 const union bpf_attr *attr, 13213 bpfptr_t uattr) 13214 { 13215 struct btf *btf; 13216 int err; 13217 13218 if (!attr->func_info_cnt && !attr->line_info_cnt) { 13219 if (check_abnormal_return(env)) 13220 return -EINVAL; 13221 return 0; 13222 } 13223 13224 btf = btf_get_by_fd(attr->prog_btf_fd); 13225 if (IS_ERR(btf)) 13226 return PTR_ERR(btf); 13227 if (btf_is_kernel(btf)) { 13228 btf_put(btf); 13229 return -EACCES; 13230 } 13231 env->prog->aux->btf = btf; 13232 13233 err = check_btf_func(env, attr, uattr); 13234 if (err) 13235 return err; 13236 13237 err = check_btf_line(env, attr, uattr); 13238 if (err) 13239 return err; 13240 13241 err = check_core_relo(env, attr, uattr); 13242 if (err) 13243 return err; 13244 13245 return 0; 13246 } 13247 13248 /* check %cur's range satisfies %old's */ 13249 static bool range_within(struct bpf_reg_state *old, 13250 struct bpf_reg_state *cur) 13251 { 13252 return old->umin_value <= cur->umin_value && 13253 old->umax_value >= cur->umax_value && 13254 old->smin_value <= cur->smin_value && 13255 old->smax_value >= cur->smax_value && 13256 old->u32_min_value <= cur->u32_min_value && 13257 old->u32_max_value >= cur->u32_max_value && 13258 old->s32_min_value <= cur->s32_min_value && 13259 old->s32_max_value >= cur->s32_max_value; 13260 } 13261 13262 /* If in the old state two registers had the same id, then they need to have 13263 * the same id in the new state as well. But that id could be different from 13264 * the old state, so we need to track the mapping from old to new ids. 13265 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 13266 * regs with old id 5 must also have new id 9 for the new state to be safe. But 13267 * regs with a different old id could still have new id 9, we don't care about 13268 * that. 13269 * So we look through our idmap to see if this old id has been seen before. If 13270 * so, we require the new id to match; otherwise, we add the id pair to the map. 13271 */ 13272 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap) 13273 { 13274 unsigned int i; 13275 13276 /* either both IDs should be set or both should be zero */ 13277 if (!!old_id != !!cur_id) 13278 return false; 13279 13280 if (old_id == 0) /* cur_id == 0 as well */ 13281 return true; 13282 13283 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 13284 if (!idmap[i].old) { 13285 /* Reached an empty slot; haven't seen this id before */ 13286 idmap[i].old = old_id; 13287 idmap[i].cur = cur_id; 13288 return true; 13289 } 13290 if (idmap[i].old == old_id) 13291 return idmap[i].cur == cur_id; 13292 } 13293 /* We ran out of idmap slots, which should be impossible */ 13294 WARN_ON_ONCE(1); 13295 return false; 13296 } 13297 13298 static void clean_func_state(struct bpf_verifier_env *env, 13299 struct bpf_func_state *st) 13300 { 13301 enum bpf_reg_liveness live; 13302 int i, j; 13303 13304 for (i = 0; i < BPF_REG_FP; i++) { 13305 live = st->regs[i].live; 13306 /* liveness must not touch this register anymore */ 13307 st->regs[i].live |= REG_LIVE_DONE; 13308 if (!(live & REG_LIVE_READ)) 13309 /* since the register is unused, clear its state 13310 * to make further comparison simpler 13311 */ 13312 __mark_reg_not_init(env, &st->regs[i]); 13313 } 13314 13315 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 13316 live = st->stack[i].spilled_ptr.live; 13317 /* liveness must not touch this stack slot anymore */ 13318 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 13319 if (!(live & REG_LIVE_READ)) { 13320 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 13321 for (j = 0; j < BPF_REG_SIZE; j++) 13322 st->stack[i].slot_type[j] = STACK_INVALID; 13323 } 13324 } 13325 } 13326 13327 static void clean_verifier_state(struct bpf_verifier_env *env, 13328 struct bpf_verifier_state *st) 13329 { 13330 int i; 13331 13332 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 13333 /* all regs in this state in all frames were already marked */ 13334 return; 13335 13336 for (i = 0; i <= st->curframe; i++) 13337 clean_func_state(env, st->frame[i]); 13338 } 13339 13340 /* the parentage chains form a tree. 13341 * the verifier states are added to state lists at given insn and 13342 * pushed into state stack for future exploration. 13343 * when the verifier reaches bpf_exit insn some of the verifer states 13344 * stored in the state lists have their final liveness state already, 13345 * but a lot of states will get revised from liveness point of view when 13346 * the verifier explores other branches. 13347 * Example: 13348 * 1: r0 = 1 13349 * 2: if r1 == 100 goto pc+1 13350 * 3: r0 = 2 13351 * 4: exit 13352 * when the verifier reaches exit insn the register r0 in the state list of 13353 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 13354 * of insn 2 and goes exploring further. At the insn 4 it will walk the 13355 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 13356 * 13357 * Since the verifier pushes the branch states as it sees them while exploring 13358 * the program the condition of walking the branch instruction for the second 13359 * time means that all states below this branch were already explored and 13360 * their final liveness marks are already propagated. 13361 * Hence when the verifier completes the search of state list in is_state_visited() 13362 * we can call this clean_live_states() function to mark all liveness states 13363 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 13364 * will not be used. 13365 * This function also clears the registers and stack for states that !READ 13366 * to simplify state merging. 13367 * 13368 * Important note here that walking the same branch instruction in the callee 13369 * doesn't meant that the states are DONE. The verifier has to compare 13370 * the callsites 13371 */ 13372 static void clean_live_states(struct bpf_verifier_env *env, int insn, 13373 struct bpf_verifier_state *cur) 13374 { 13375 struct bpf_verifier_state_list *sl; 13376 int i; 13377 13378 sl = *explored_state(env, insn); 13379 while (sl) { 13380 if (sl->state.branches) 13381 goto next; 13382 if (sl->state.insn_idx != insn || 13383 sl->state.curframe != cur->curframe) 13384 goto next; 13385 for (i = 0; i <= cur->curframe; i++) 13386 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 13387 goto next; 13388 clean_verifier_state(env, &sl->state); 13389 next: 13390 sl = sl->next; 13391 } 13392 } 13393 13394 static bool regs_exact(const struct bpf_reg_state *rold, 13395 const struct bpf_reg_state *rcur, 13396 struct bpf_id_pair *idmap) 13397 { 13398 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 13399 check_ids(rold->id, rcur->id, idmap) && 13400 check_ids(rold->ref_obj_id, rcur->ref_obj_id, idmap); 13401 } 13402 13403 /* Returns true if (rold safe implies rcur safe) */ 13404 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 13405 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap) 13406 { 13407 if (!(rold->live & REG_LIVE_READ)) 13408 /* explored state didn't use this */ 13409 return true; 13410 if (rold->type == NOT_INIT) 13411 /* explored state can't have used this */ 13412 return true; 13413 if (rcur->type == NOT_INIT) 13414 return false; 13415 13416 /* Enforce that register types have to match exactly, including their 13417 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 13418 * rule. 13419 * 13420 * One can make a point that using a pointer register as unbounded 13421 * SCALAR would be technically acceptable, but this could lead to 13422 * pointer leaks because scalars are allowed to leak while pointers 13423 * are not. We could make this safe in special cases if root is 13424 * calling us, but it's probably not worth the hassle. 13425 * 13426 * Also, register types that are *not* MAYBE_NULL could technically be 13427 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 13428 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 13429 * to the same map). 13430 * However, if the old MAYBE_NULL register then got NULL checked, 13431 * doing so could have affected others with the same id, and we can't 13432 * check for that because we lost the id when we converted to 13433 * a non-MAYBE_NULL variant. 13434 * So, as a general rule we don't allow mixing MAYBE_NULL and 13435 * non-MAYBE_NULL registers as well. 13436 */ 13437 if (rold->type != rcur->type) 13438 return false; 13439 13440 switch (base_type(rold->type)) { 13441 case SCALAR_VALUE: 13442 if (regs_exact(rold, rcur, idmap)) 13443 return true; 13444 if (env->explore_alu_limits) 13445 return false; 13446 if (!rold->precise) 13447 return true; 13448 /* new val must satisfy old val knowledge */ 13449 return range_within(rold, rcur) && 13450 tnum_in(rold->var_off, rcur->var_off); 13451 case PTR_TO_MAP_KEY: 13452 case PTR_TO_MAP_VALUE: 13453 /* If the new min/max/var_off satisfy the old ones and 13454 * everything else matches, we are OK. 13455 */ 13456 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 13457 range_within(rold, rcur) && 13458 tnum_in(rold->var_off, rcur->var_off) && 13459 check_ids(rold->id, rcur->id, idmap); 13460 case PTR_TO_PACKET_META: 13461 case PTR_TO_PACKET: 13462 /* We must have at least as much range as the old ptr 13463 * did, so that any accesses which were safe before are 13464 * still safe. This is true even if old range < old off, 13465 * since someone could have accessed through (ptr - k), or 13466 * even done ptr -= k in a register, to get a safe access. 13467 */ 13468 if (rold->range > rcur->range) 13469 return false; 13470 /* If the offsets don't match, we can't trust our alignment; 13471 * nor can we be sure that we won't fall out of range. 13472 */ 13473 if (rold->off != rcur->off) 13474 return false; 13475 /* id relations must be preserved */ 13476 if (!check_ids(rold->id, rcur->id, idmap)) 13477 return false; 13478 /* new val must satisfy old val knowledge */ 13479 return range_within(rold, rcur) && 13480 tnum_in(rold->var_off, rcur->var_off); 13481 case PTR_TO_STACK: 13482 /* two stack pointers are equal only if they're pointing to 13483 * the same stack frame, since fp-8 in foo != fp-8 in bar 13484 */ 13485 return regs_exact(rold, rcur, idmap) && rold->frameno == rcur->frameno; 13486 default: 13487 return regs_exact(rold, rcur, idmap); 13488 } 13489 } 13490 13491 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 13492 struct bpf_func_state *cur, struct bpf_id_pair *idmap) 13493 { 13494 int i, spi; 13495 13496 /* walk slots of the explored stack and ignore any additional 13497 * slots in the current stack, since explored(safe) state 13498 * didn't use them 13499 */ 13500 for (i = 0; i < old->allocated_stack; i++) { 13501 spi = i / BPF_REG_SIZE; 13502 13503 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 13504 i += BPF_REG_SIZE - 1; 13505 /* explored state didn't use this */ 13506 continue; 13507 } 13508 13509 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 13510 continue; 13511 13512 /* explored stack has more populated slots than current stack 13513 * and these slots were used 13514 */ 13515 if (i >= cur->allocated_stack) 13516 return false; 13517 13518 /* if old state was safe with misc data in the stack 13519 * it will be safe with zero-initialized stack. 13520 * The opposite is not true 13521 */ 13522 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 13523 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 13524 continue; 13525 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 13526 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 13527 /* Ex: old explored (safe) state has STACK_SPILL in 13528 * this stack slot, but current has STACK_MISC -> 13529 * this verifier states are not equivalent, 13530 * return false to continue verification of this path 13531 */ 13532 return false; 13533 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 13534 continue; 13535 /* Both old and cur are having same slot_type */ 13536 switch (old->stack[spi].slot_type[BPF_REG_SIZE - 1]) { 13537 case STACK_SPILL: 13538 /* when explored and current stack slot are both storing 13539 * spilled registers, check that stored pointers types 13540 * are the same as well. 13541 * Ex: explored safe path could have stored 13542 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 13543 * but current path has stored: 13544 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 13545 * such verifier states are not equivalent. 13546 * return false to continue verification of this path 13547 */ 13548 if (!regsafe(env, &old->stack[spi].spilled_ptr, 13549 &cur->stack[spi].spilled_ptr, idmap)) 13550 return false; 13551 break; 13552 case STACK_DYNPTR: 13553 { 13554 const struct bpf_reg_state *old_reg, *cur_reg; 13555 13556 old_reg = &old->stack[spi].spilled_ptr; 13557 cur_reg = &cur->stack[spi].spilled_ptr; 13558 if (old_reg->dynptr.type != cur_reg->dynptr.type || 13559 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 13560 !check_ids(old_reg->ref_obj_id, cur_reg->ref_obj_id, idmap)) 13561 return false; 13562 break; 13563 } 13564 case STACK_MISC: 13565 case STACK_ZERO: 13566 case STACK_INVALID: 13567 continue; 13568 /* Ensure that new unhandled slot types return false by default */ 13569 default: 13570 return false; 13571 } 13572 } 13573 return true; 13574 } 13575 13576 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur, 13577 struct bpf_id_pair *idmap) 13578 { 13579 int i; 13580 13581 if (old->acquired_refs != cur->acquired_refs) 13582 return false; 13583 13584 for (i = 0; i < old->acquired_refs; i++) { 13585 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap)) 13586 return false; 13587 } 13588 13589 return true; 13590 } 13591 13592 /* compare two verifier states 13593 * 13594 * all states stored in state_list are known to be valid, since 13595 * verifier reached 'bpf_exit' instruction through them 13596 * 13597 * this function is called when verifier exploring different branches of 13598 * execution popped from the state stack. If it sees an old state that has 13599 * more strict register state and more strict stack state then this execution 13600 * branch doesn't need to be explored further, since verifier already 13601 * concluded that more strict state leads to valid finish. 13602 * 13603 * Therefore two states are equivalent if register state is more conservative 13604 * and explored stack state is more conservative than the current one. 13605 * Example: 13606 * explored current 13607 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 13608 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 13609 * 13610 * In other words if current stack state (one being explored) has more 13611 * valid slots than old one that already passed validation, it means 13612 * the verifier can stop exploring and conclude that current state is valid too 13613 * 13614 * Similarly with registers. If explored state has register type as invalid 13615 * whereas register type in current state is meaningful, it means that 13616 * the current state will reach 'bpf_exit' instruction safely 13617 */ 13618 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 13619 struct bpf_func_state *cur) 13620 { 13621 int i; 13622 13623 for (i = 0; i < MAX_BPF_REG; i++) 13624 if (!regsafe(env, &old->regs[i], &cur->regs[i], 13625 env->idmap_scratch)) 13626 return false; 13627 13628 if (!stacksafe(env, old, cur, env->idmap_scratch)) 13629 return false; 13630 13631 if (!refsafe(old, cur, env->idmap_scratch)) 13632 return false; 13633 13634 return true; 13635 } 13636 13637 static bool states_equal(struct bpf_verifier_env *env, 13638 struct bpf_verifier_state *old, 13639 struct bpf_verifier_state *cur) 13640 { 13641 int i; 13642 13643 if (old->curframe != cur->curframe) 13644 return false; 13645 13646 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch)); 13647 13648 /* Verification state from speculative execution simulation 13649 * must never prune a non-speculative execution one. 13650 */ 13651 if (old->speculative && !cur->speculative) 13652 return false; 13653 13654 if (old->active_lock.ptr != cur->active_lock.ptr) 13655 return false; 13656 13657 /* Old and cur active_lock's have to be either both present 13658 * or both absent. 13659 */ 13660 if (!!old->active_lock.id != !!cur->active_lock.id) 13661 return false; 13662 13663 if (old->active_lock.id && 13664 !check_ids(old->active_lock.id, cur->active_lock.id, env->idmap_scratch)) 13665 return false; 13666 13667 if (old->active_rcu_lock != cur->active_rcu_lock) 13668 return false; 13669 13670 /* for states to be equal callsites have to be the same 13671 * and all frame states need to be equivalent 13672 */ 13673 for (i = 0; i <= old->curframe; i++) { 13674 if (old->frame[i]->callsite != cur->frame[i]->callsite) 13675 return false; 13676 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 13677 return false; 13678 } 13679 return true; 13680 } 13681 13682 /* Return 0 if no propagation happened. Return negative error code if error 13683 * happened. Otherwise, return the propagated bit. 13684 */ 13685 static int propagate_liveness_reg(struct bpf_verifier_env *env, 13686 struct bpf_reg_state *reg, 13687 struct bpf_reg_state *parent_reg) 13688 { 13689 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 13690 u8 flag = reg->live & REG_LIVE_READ; 13691 int err; 13692 13693 /* When comes here, read flags of PARENT_REG or REG could be any of 13694 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 13695 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 13696 */ 13697 if (parent_flag == REG_LIVE_READ64 || 13698 /* Or if there is no read flag from REG. */ 13699 !flag || 13700 /* Or if the read flag from REG is the same as PARENT_REG. */ 13701 parent_flag == flag) 13702 return 0; 13703 13704 err = mark_reg_read(env, reg, parent_reg, flag); 13705 if (err) 13706 return err; 13707 13708 return flag; 13709 } 13710 13711 /* A write screens off any subsequent reads; but write marks come from the 13712 * straight-line code between a state and its parent. When we arrive at an 13713 * equivalent state (jump target or such) we didn't arrive by the straight-line 13714 * code, so read marks in the state must propagate to the parent regardless 13715 * of the state's write marks. That's what 'parent == state->parent' comparison 13716 * in mark_reg_read() is for. 13717 */ 13718 static int propagate_liveness(struct bpf_verifier_env *env, 13719 const struct bpf_verifier_state *vstate, 13720 struct bpf_verifier_state *vparent) 13721 { 13722 struct bpf_reg_state *state_reg, *parent_reg; 13723 struct bpf_func_state *state, *parent; 13724 int i, frame, err = 0; 13725 13726 if (vparent->curframe != vstate->curframe) { 13727 WARN(1, "propagate_live: parent frame %d current frame %d\n", 13728 vparent->curframe, vstate->curframe); 13729 return -EFAULT; 13730 } 13731 /* Propagate read liveness of registers... */ 13732 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 13733 for (frame = 0; frame <= vstate->curframe; frame++) { 13734 parent = vparent->frame[frame]; 13735 state = vstate->frame[frame]; 13736 parent_reg = parent->regs; 13737 state_reg = state->regs; 13738 /* We don't need to worry about FP liveness, it's read-only */ 13739 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 13740 err = propagate_liveness_reg(env, &state_reg[i], 13741 &parent_reg[i]); 13742 if (err < 0) 13743 return err; 13744 if (err == REG_LIVE_READ64) 13745 mark_insn_zext(env, &parent_reg[i]); 13746 } 13747 13748 /* Propagate stack slots. */ 13749 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 13750 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 13751 parent_reg = &parent->stack[i].spilled_ptr; 13752 state_reg = &state->stack[i].spilled_ptr; 13753 err = propagate_liveness_reg(env, state_reg, 13754 parent_reg); 13755 if (err < 0) 13756 return err; 13757 } 13758 } 13759 return 0; 13760 } 13761 13762 /* find precise scalars in the previous equivalent state and 13763 * propagate them into the current state 13764 */ 13765 static int propagate_precision(struct bpf_verifier_env *env, 13766 const struct bpf_verifier_state *old) 13767 { 13768 struct bpf_reg_state *state_reg; 13769 struct bpf_func_state *state; 13770 int i, err = 0, fr; 13771 13772 for (fr = old->curframe; fr >= 0; fr--) { 13773 state = old->frame[fr]; 13774 state_reg = state->regs; 13775 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 13776 if (state_reg->type != SCALAR_VALUE || 13777 !state_reg->precise) 13778 continue; 13779 if (env->log.level & BPF_LOG_LEVEL2) 13780 verbose(env, "frame %d: propagating r%d\n", i, fr); 13781 err = mark_chain_precision_frame(env, fr, i); 13782 if (err < 0) 13783 return err; 13784 } 13785 13786 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 13787 if (!is_spilled_reg(&state->stack[i])) 13788 continue; 13789 state_reg = &state->stack[i].spilled_ptr; 13790 if (state_reg->type != SCALAR_VALUE || 13791 !state_reg->precise) 13792 continue; 13793 if (env->log.level & BPF_LOG_LEVEL2) 13794 verbose(env, "frame %d: propagating fp%d\n", 13795 (-i - 1) * BPF_REG_SIZE, fr); 13796 err = mark_chain_precision_stack_frame(env, fr, i); 13797 if (err < 0) 13798 return err; 13799 } 13800 } 13801 return 0; 13802 } 13803 13804 static bool states_maybe_looping(struct bpf_verifier_state *old, 13805 struct bpf_verifier_state *cur) 13806 { 13807 struct bpf_func_state *fold, *fcur; 13808 int i, fr = cur->curframe; 13809 13810 if (old->curframe != fr) 13811 return false; 13812 13813 fold = old->frame[fr]; 13814 fcur = cur->frame[fr]; 13815 for (i = 0; i < MAX_BPF_REG; i++) 13816 if (memcmp(&fold->regs[i], &fcur->regs[i], 13817 offsetof(struct bpf_reg_state, parent))) 13818 return false; 13819 return true; 13820 } 13821 13822 13823 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 13824 { 13825 struct bpf_verifier_state_list *new_sl; 13826 struct bpf_verifier_state_list *sl, **pprev; 13827 struct bpf_verifier_state *cur = env->cur_state, *new; 13828 int i, j, err, states_cnt = 0; 13829 bool add_new_state = env->test_state_freq ? true : false; 13830 13831 /* bpf progs typically have pruning point every 4 instructions 13832 * http://vger.kernel.org/bpfconf2019.html#session-1 13833 * Do not add new state for future pruning if the verifier hasn't seen 13834 * at least 2 jumps and at least 8 instructions. 13835 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 13836 * In tests that amounts to up to 50% reduction into total verifier 13837 * memory consumption and 20% verifier time speedup. 13838 */ 13839 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 13840 env->insn_processed - env->prev_insn_processed >= 8) 13841 add_new_state = true; 13842 13843 pprev = explored_state(env, insn_idx); 13844 sl = *pprev; 13845 13846 clean_live_states(env, insn_idx, cur); 13847 13848 while (sl) { 13849 states_cnt++; 13850 if (sl->state.insn_idx != insn_idx) 13851 goto next; 13852 13853 if (sl->state.branches) { 13854 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 13855 13856 if (frame->in_async_callback_fn && 13857 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 13858 /* Different async_entry_cnt means that the verifier is 13859 * processing another entry into async callback. 13860 * Seeing the same state is not an indication of infinite 13861 * loop or infinite recursion. 13862 * But finding the same state doesn't mean that it's safe 13863 * to stop processing the current state. The previous state 13864 * hasn't yet reached bpf_exit, since state.branches > 0. 13865 * Checking in_async_callback_fn alone is not enough either. 13866 * Since the verifier still needs to catch infinite loops 13867 * inside async callbacks. 13868 */ 13869 } else if (states_maybe_looping(&sl->state, cur) && 13870 states_equal(env, &sl->state, cur)) { 13871 verbose_linfo(env, insn_idx, "; "); 13872 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 13873 return -EINVAL; 13874 } 13875 /* if the verifier is processing a loop, avoid adding new state 13876 * too often, since different loop iterations have distinct 13877 * states and may not help future pruning. 13878 * This threshold shouldn't be too low to make sure that 13879 * a loop with large bound will be rejected quickly. 13880 * The most abusive loop will be: 13881 * r1 += 1 13882 * if r1 < 1000000 goto pc-2 13883 * 1M insn_procssed limit / 100 == 10k peak states. 13884 * This threshold shouldn't be too high either, since states 13885 * at the end of the loop are likely to be useful in pruning. 13886 */ 13887 if (env->jmps_processed - env->prev_jmps_processed < 20 && 13888 env->insn_processed - env->prev_insn_processed < 100) 13889 add_new_state = false; 13890 goto miss; 13891 } 13892 if (states_equal(env, &sl->state, cur)) { 13893 sl->hit_cnt++; 13894 /* reached equivalent register/stack state, 13895 * prune the search. 13896 * Registers read by the continuation are read by us. 13897 * If we have any write marks in env->cur_state, they 13898 * will prevent corresponding reads in the continuation 13899 * from reaching our parent (an explored_state). Our 13900 * own state will get the read marks recorded, but 13901 * they'll be immediately forgotten as we're pruning 13902 * this state and will pop a new one. 13903 */ 13904 err = propagate_liveness(env, &sl->state, cur); 13905 13906 /* if previous state reached the exit with precision and 13907 * current state is equivalent to it (except precsion marks) 13908 * the precision needs to be propagated back in 13909 * the current state. 13910 */ 13911 err = err ? : push_jmp_history(env, cur); 13912 err = err ? : propagate_precision(env, &sl->state); 13913 if (err) 13914 return err; 13915 return 1; 13916 } 13917 miss: 13918 /* when new state is not going to be added do not increase miss count. 13919 * Otherwise several loop iterations will remove the state 13920 * recorded earlier. The goal of these heuristics is to have 13921 * states from some iterations of the loop (some in the beginning 13922 * and some at the end) to help pruning. 13923 */ 13924 if (add_new_state) 13925 sl->miss_cnt++; 13926 /* heuristic to determine whether this state is beneficial 13927 * to keep checking from state equivalence point of view. 13928 * Higher numbers increase max_states_per_insn and verification time, 13929 * but do not meaningfully decrease insn_processed. 13930 */ 13931 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 13932 /* the state is unlikely to be useful. Remove it to 13933 * speed up verification 13934 */ 13935 *pprev = sl->next; 13936 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 13937 u32 br = sl->state.branches; 13938 13939 WARN_ONCE(br, 13940 "BUG live_done but branches_to_explore %d\n", 13941 br); 13942 free_verifier_state(&sl->state, false); 13943 kfree(sl); 13944 env->peak_states--; 13945 } else { 13946 /* cannot free this state, since parentage chain may 13947 * walk it later. Add it for free_list instead to 13948 * be freed at the end of verification 13949 */ 13950 sl->next = env->free_list; 13951 env->free_list = sl; 13952 } 13953 sl = *pprev; 13954 continue; 13955 } 13956 next: 13957 pprev = &sl->next; 13958 sl = *pprev; 13959 } 13960 13961 if (env->max_states_per_insn < states_cnt) 13962 env->max_states_per_insn = states_cnt; 13963 13964 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 13965 return 0; 13966 13967 if (!add_new_state) 13968 return 0; 13969 13970 /* There were no equivalent states, remember the current one. 13971 * Technically the current state is not proven to be safe yet, 13972 * but it will either reach outer most bpf_exit (which means it's safe) 13973 * or it will be rejected. When there are no loops the verifier won't be 13974 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 13975 * again on the way to bpf_exit. 13976 * When looping the sl->state.branches will be > 0 and this state 13977 * will not be considered for equivalence until branches == 0. 13978 */ 13979 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 13980 if (!new_sl) 13981 return -ENOMEM; 13982 env->total_states++; 13983 env->peak_states++; 13984 env->prev_jmps_processed = env->jmps_processed; 13985 env->prev_insn_processed = env->insn_processed; 13986 13987 /* forget precise markings we inherited, see __mark_chain_precision */ 13988 if (env->bpf_capable) 13989 mark_all_scalars_imprecise(env, cur); 13990 13991 /* add new state to the head of linked list */ 13992 new = &new_sl->state; 13993 err = copy_verifier_state(new, cur); 13994 if (err) { 13995 free_verifier_state(new, false); 13996 kfree(new_sl); 13997 return err; 13998 } 13999 new->insn_idx = insn_idx; 14000 WARN_ONCE(new->branches != 1, 14001 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 14002 14003 cur->parent = new; 14004 cur->first_insn_idx = insn_idx; 14005 clear_jmp_history(cur); 14006 new_sl->next = *explored_state(env, insn_idx); 14007 *explored_state(env, insn_idx) = new_sl; 14008 /* connect new state to parentage chain. Current frame needs all 14009 * registers connected. Only r6 - r9 of the callers are alive (pushed 14010 * to the stack implicitly by JITs) so in callers' frames connect just 14011 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 14012 * the state of the call instruction (with WRITTEN set), and r0 comes 14013 * from callee with its full parentage chain, anyway. 14014 */ 14015 /* clear write marks in current state: the writes we did are not writes 14016 * our child did, so they don't screen off its reads from us. 14017 * (There are no read marks in current state, because reads always mark 14018 * their parent and current state never has children yet. Only 14019 * explored_states can get read marks.) 14020 */ 14021 for (j = 0; j <= cur->curframe; j++) { 14022 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 14023 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 14024 for (i = 0; i < BPF_REG_FP; i++) 14025 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 14026 } 14027 14028 /* all stack frames are accessible from callee, clear them all */ 14029 for (j = 0; j <= cur->curframe; j++) { 14030 struct bpf_func_state *frame = cur->frame[j]; 14031 struct bpf_func_state *newframe = new->frame[j]; 14032 14033 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 14034 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 14035 frame->stack[i].spilled_ptr.parent = 14036 &newframe->stack[i].spilled_ptr; 14037 } 14038 } 14039 return 0; 14040 } 14041 14042 /* Return true if it's OK to have the same insn return a different type. */ 14043 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 14044 { 14045 switch (base_type(type)) { 14046 case PTR_TO_CTX: 14047 case PTR_TO_SOCKET: 14048 case PTR_TO_SOCK_COMMON: 14049 case PTR_TO_TCP_SOCK: 14050 case PTR_TO_XDP_SOCK: 14051 case PTR_TO_BTF_ID: 14052 return false; 14053 default: 14054 return true; 14055 } 14056 } 14057 14058 /* If an instruction was previously used with particular pointer types, then we 14059 * need to be careful to avoid cases such as the below, where it may be ok 14060 * for one branch accessing the pointer, but not ok for the other branch: 14061 * 14062 * R1 = sock_ptr 14063 * goto X; 14064 * ... 14065 * R1 = some_other_valid_ptr; 14066 * goto X; 14067 * ... 14068 * R2 = *(u32 *)(R1 + 0); 14069 */ 14070 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 14071 { 14072 return src != prev && (!reg_type_mismatch_ok(src) || 14073 !reg_type_mismatch_ok(prev)); 14074 } 14075 14076 static int do_check(struct bpf_verifier_env *env) 14077 { 14078 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 14079 struct bpf_verifier_state *state = env->cur_state; 14080 struct bpf_insn *insns = env->prog->insnsi; 14081 struct bpf_reg_state *regs; 14082 int insn_cnt = env->prog->len; 14083 bool do_print_state = false; 14084 int prev_insn_idx = -1; 14085 14086 for (;;) { 14087 struct bpf_insn *insn; 14088 u8 class; 14089 int err; 14090 14091 env->prev_insn_idx = prev_insn_idx; 14092 if (env->insn_idx >= insn_cnt) { 14093 verbose(env, "invalid insn idx %d insn_cnt %d\n", 14094 env->insn_idx, insn_cnt); 14095 return -EFAULT; 14096 } 14097 14098 insn = &insns[env->insn_idx]; 14099 class = BPF_CLASS(insn->code); 14100 14101 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 14102 verbose(env, 14103 "BPF program is too large. Processed %d insn\n", 14104 env->insn_processed); 14105 return -E2BIG; 14106 } 14107 14108 state->last_insn_idx = env->prev_insn_idx; 14109 14110 if (is_prune_point(env, env->insn_idx)) { 14111 err = is_state_visited(env, env->insn_idx); 14112 if (err < 0) 14113 return err; 14114 if (err == 1) { 14115 /* found equivalent state, can prune the search */ 14116 if (env->log.level & BPF_LOG_LEVEL) { 14117 if (do_print_state) 14118 verbose(env, "\nfrom %d to %d%s: safe\n", 14119 env->prev_insn_idx, env->insn_idx, 14120 env->cur_state->speculative ? 14121 " (speculative execution)" : ""); 14122 else 14123 verbose(env, "%d: safe\n", env->insn_idx); 14124 } 14125 goto process_bpf_exit; 14126 } 14127 } 14128 14129 if (is_jmp_point(env, env->insn_idx)) { 14130 err = push_jmp_history(env, state); 14131 if (err) 14132 return err; 14133 } 14134 14135 if (signal_pending(current)) 14136 return -EAGAIN; 14137 14138 if (need_resched()) 14139 cond_resched(); 14140 14141 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 14142 verbose(env, "\nfrom %d to %d%s:", 14143 env->prev_insn_idx, env->insn_idx, 14144 env->cur_state->speculative ? 14145 " (speculative execution)" : ""); 14146 print_verifier_state(env, state->frame[state->curframe], true); 14147 do_print_state = false; 14148 } 14149 14150 if (env->log.level & BPF_LOG_LEVEL) { 14151 const struct bpf_insn_cbs cbs = { 14152 .cb_call = disasm_kfunc_name, 14153 .cb_print = verbose, 14154 .private_data = env, 14155 }; 14156 14157 if (verifier_state_scratched(env)) 14158 print_insn_state(env, state->frame[state->curframe]); 14159 14160 verbose_linfo(env, env->insn_idx, "; "); 14161 env->prev_log_len = env->log.len_used; 14162 verbose(env, "%d: ", env->insn_idx); 14163 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 14164 env->prev_insn_print_len = env->log.len_used - env->prev_log_len; 14165 env->prev_log_len = env->log.len_used; 14166 } 14167 14168 if (bpf_prog_is_offloaded(env->prog->aux)) { 14169 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 14170 env->prev_insn_idx); 14171 if (err) 14172 return err; 14173 } 14174 14175 regs = cur_regs(env); 14176 sanitize_mark_insn_seen(env); 14177 prev_insn_idx = env->insn_idx; 14178 14179 if (class == BPF_ALU || class == BPF_ALU64) { 14180 err = check_alu_op(env, insn); 14181 if (err) 14182 return err; 14183 14184 } else if (class == BPF_LDX) { 14185 enum bpf_reg_type *prev_src_type, src_reg_type; 14186 14187 /* check for reserved fields is already done */ 14188 14189 /* check src operand */ 14190 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14191 if (err) 14192 return err; 14193 14194 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 14195 if (err) 14196 return err; 14197 14198 src_reg_type = regs[insn->src_reg].type; 14199 14200 /* check that memory (src_reg + off) is readable, 14201 * the state of dst_reg will be updated by this func 14202 */ 14203 err = check_mem_access(env, env->insn_idx, insn->src_reg, 14204 insn->off, BPF_SIZE(insn->code), 14205 BPF_READ, insn->dst_reg, false); 14206 if (err) 14207 return err; 14208 14209 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 14210 14211 if (*prev_src_type == NOT_INIT) { 14212 /* saw a valid insn 14213 * dst_reg = *(u32 *)(src_reg + off) 14214 * save type to validate intersecting paths 14215 */ 14216 *prev_src_type = src_reg_type; 14217 14218 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 14219 /* ABuser program is trying to use the same insn 14220 * dst_reg = *(u32*) (src_reg + off) 14221 * with different pointer types: 14222 * src_reg == ctx in one branch and 14223 * src_reg == stack|map in some other branch. 14224 * Reject it. 14225 */ 14226 verbose(env, "same insn cannot be used with different pointers\n"); 14227 return -EINVAL; 14228 } 14229 14230 } else if (class == BPF_STX) { 14231 enum bpf_reg_type *prev_dst_type, dst_reg_type; 14232 14233 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 14234 err = check_atomic(env, env->insn_idx, insn); 14235 if (err) 14236 return err; 14237 env->insn_idx++; 14238 continue; 14239 } 14240 14241 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 14242 verbose(env, "BPF_STX uses reserved fields\n"); 14243 return -EINVAL; 14244 } 14245 14246 /* check src1 operand */ 14247 err = check_reg_arg(env, insn->src_reg, SRC_OP); 14248 if (err) 14249 return err; 14250 /* check src2 operand */ 14251 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14252 if (err) 14253 return err; 14254 14255 dst_reg_type = regs[insn->dst_reg].type; 14256 14257 /* check that memory (dst_reg + off) is writeable */ 14258 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 14259 insn->off, BPF_SIZE(insn->code), 14260 BPF_WRITE, insn->src_reg, false); 14261 if (err) 14262 return err; 14263 14264 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 14265 14266 if (*prev_dst_type == NOT_INIT) { 14267 *prev_dst_type = dst_reg_type; 14268 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 14269 verbose(env, "same insn cannot be used with different pointers\n"); 14270 return -EINVAL; 14271 } 14272 14273 } else if (class == BPF_ST) { 14274 if (BPF_MODE(insn->code) != BPF_MEM || 14275 insn->src_reg != BPF_REG_0) { 14276 verbose(env, "BPF_ST uses reserved fields\n"); 14277 return -EINVAL; 14278 } 14279 /* check src operand */ 14280 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 14281 if (err) 14282 return err; 14283 14284 if (is_ctx_reg(env, insn->dst_reg)) { 14285 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 14286 insn->dst_reg, 14287 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 14288 return -EACCES; 14289 } 14290 14291 /* check that memory (dst_reg + off) is writeable */ 14292 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 14293 insn->off, BPF_SIZE(insn->code), 14294 BPF_WRITE, -1, false); 14295 if (err) 14296 return err; 14297 14298 } else if (class == BPF_JMP || class == BPF_JMP32) { 14299 u8 opcode = BPF_OP(insn->code); 14300 14301 env->jmps_processed++; 14302 if (opcode == BPF_CALL) { 14303 if (BPF_SRC(insn->code) != BPF_K || 14304 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 14305 && insn->off != 0) || 14306 (insn->src_reg != BPF_REG_0 && 14307 insn->src_reg != BPF_PSEUDO_CALL && 14308 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 14309 insn->dst_reg != BPF_REG_0 || 14310 class == BPF_JMP32) { 14311 verbose(env, "BPF_CALL uses reserved fields\n"); 14312 return -EINVAL; 14313 } 14314 14315 if (env->cur_state->active_lock.ptr) { 14316 if ((insn->src_reg == BPF_REG_0 && insn->imm != BPF_FUNC_spin_unlock) || 14317 (insn->src_reg == BPF_PSEUDO_CALL) || 14318 (insn->src_reg == BPF_PSEUDO_KFUNC_CALL && 14319 (insn->off != 0 || !is_bpf_list_api_kfunc(insn->imm)))) { 14320 verbose(env, "function calls are not allowed while holding a lock\n"); 14321 return -EINVAL; 14322 } 14323 } 14324 if (insn->src_reg == BPF_PSEUDO_CALL) 14325 err = check_func_call(env, insn, &env->insn_idx); 14326 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 14327 err = check_kfunc_call(env, insn, &env->insn_idx); 14328 else 14329 err = check_helper_call(env, insn, &env->insn_idx); 14330 if (err) 14331 return err; 14332 } else if (opcode == BPF_JA) { 14333 if (BPF_SRC(insn->code) != BPF_K || 14334 insn->imm != 0 || 14335 insn->src_reg != BPF_REG_0 || 14336 insn->dst_reg != BPF_REG_0 || 14337 class == BPF_JMP32) { 14338 verbose(env, "BPF_JA uses reserved fields\n"); 14339 return -EINVAL; 14340 } 14341 14342 env->insn_idx += insn->off + 1; 14343 continue; 14344 14345 } else if (opcode == BPF_EXIT) { 14346 if (BPF_SRC(insn->code) != BPF_K || 14347 insn->imm != 0 || 14348 insn->src_reg != BPF_REG_0 || 14349 insn->dst_reg != BPF_REG_0 || 14350 class == BPF_JMP32) { 14351 verbose(env, "BPF_EXIT uses reserved fields\n"); 14352 return -EINVAL; 14353 } 14354 14355 if (env->cur_state->active_lock.ptr) { 14356 verbose(env, "bpf_spin_unlock is missing\n"); 14357 return -EINVAL; 14358 } 14359 14360 if (env->cur_state->active_rcu_lock) { 14361 verbose(env, "bpf_rcu_read_unlock is missing\n"); 14362 return -EINVAL; 14363 } 14364 14365 /* We must do check_reference_leak here before 14366 * prepare_func_exit to handle the case when 14367 * state->curframe > 0, it may be a callback 14368 * function, for which reference_state must 14369 * match caller reference state when it exits. 14370 */ 14371 err = check_reference_leak(env); 14372 if (err) 14373 return err; 14374 14375 if (state->curframe) { 14376 /* exit from nested function */ 14377 err = prepare_func_exit(env, &env->insn_idx); 14378 if (err) 14379 return err; 14380 do_print_state = true; 14381 continue; 14382 } 14383 14384 err = check_return_code(env); 14385 if (err) 14386 return err; 14387 process_bpf_exit: 14388 mark_verifier_state_scratched(env); 14389 update_branch_counts(env, env->cur_state); 14390 err = pop_stack(env, &prev_insn_idx, 14391 &env->insn_idx, pop_log); 14392 if (err < 0) { 14393 if (err != -ENOENT) 14394 return err; 14395 break; 14396 } else { 14397 do_print_state = true; 14398 continue; 14399 } 14400 } else { 14401 err = check_cond_jmp_op(env, insn, &env->insn_idx); 14402 if (err) 14403 return err; 14404 } 14405 } else if (class == BPF_LD) { 14406 u8 mode = BPF_MODE(insn->code); 14407 14408 if (mode == BPF_ABS || mode == BPF_IND) { 14409 err = check_ld_abs(env, insn); 14410 if (err) 14411 return err; 14412 14413 } else if (mode == BPF_IMM) { 14414 err = check_ld_imm(env, insn); 14415 if (err) 14416 return err; 14417 14418 env->insn_idx++; 14419 sanitize_mark_insn_seen(env); 14420 } else { 14421 verbose(env, "invalid BPF_LD mode\n"); 14422 return -EINVAL; 14423 } 14424 } else { 14425 verbose(env, "unknown insn class %d\n", class); 14426 return -EINVAL; 14427 } 14428 14429 env->insn_idx++; 14430 } 14431 14432 return 0; 14433 } 14434 14435 static int find_btf_percpu_datasec(struct btf *btf) 14436 { 14437 const struct btf_type *t; 14438 const char *tname; 14439 int i, n; 14440 14441 /* 14442 * Both vmlinux and module each have their own ".data..percpu" 14443 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 14444 * types to look at only module's own BTF types. 14445 */ 14446 n = btf_nr_types(btf); 14447 if (btf_is_module(btf)) 14448 i = btf_nr_types(btf_vmlinux); 14449 else 14450 i = 1; 14451 14452 for(; i < n; i++) { 14453 t = btf_type_by_id(btf, i); 14454 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 14455 continue; 14456 14457 tname = btf_name_by_offset(btf, t->name_off); 14458 if (!strcmp(tname, ".data..percpu")) 14459 return i; 14460 } 14461 14462 return -ENOENT; 14463 } 14464 14465 /* replace pseudo btf_id with kernel symbol address */ 14466 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 14467 struct bpf_insn *insn, 14468 struct bpf_insn_aux_data *aux) 14469 { 14470 const struct btf_var_secinfo *vsi; 14471 const struct btf_type *datasec; 14472 struct btf_mod_pair *btf_mod; 14473 const struct btf_type *t; 14474 const char *sym_name; 14475 bool percpu = false; 14476 u32 type, id = insn->imm; 14477 struct btf *btf; 14478 s32 datasec_id; 14479 u64 addr; 14480 int i, btf_fd, err; 14481 14482 btf_fd = insn[1].imm; 14483 if (btf_fd) { 14484 btf = btf_get_by_fd(btf_fd); 14485 if (IS_ERR(btf)) { 14486 verbose(env, "invalid module BTF object FD specified.\n"); 14487 return -EINVAL; 14488 } 14489 } else { 14490 if (!btf_vmlinux) { 14491 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 14492 return -EINVAL; 14493 } 14494 btf = btf_vmlinux; 14495 btf_get(btf); 14496 } 14497 14498 t = btf_type_by_id(btf, id); 14499 if (!t) { 14500 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 14501 err = -ENOENT; 14502 goto err_put; 14503 } 14504 14505 if (!btf_type_is_var(t)) { 14506 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id); 14507 err = -EINVAL; 14508 goto err_put; 14509 } 14510 14511 sym_name = btf_name_by_offset(btf, t->name_off); 14512 addr = kallsyms_lookup_name(sym_name); 14513 if (!addr) { 14514 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 14515 sym_name); 14516 err = -ENOENT; 14517 goto err_put; 14518 } 14519 14520 datasec_id = find_btf_percpu_datasec(btf); 14521 if (datasec_id > 0) { 14522 datasec = btf_type_by_id(btf, datasec_id); 14523 for_each_vsi(i, datasec, vsi) { 14524 if (vsi->type == id) { 14525 percpu = true; 14526 break; 14527 } 14528 } 14529 } 14530 14531 insn[0].imm = (u32)addr; 14532 insn[1].imm = addr >> 32; 14533 14534 type = t->type; 14535 t = btf_type_skip_modifiers(btf, type, NULL); 14536 if (percpu) { 14537 aux->btf_var.reg_type = PTR_TO_BTF_ID | MEM_PERCPU; 14538 aux->btf_var.btf = btf; 14539 aux->btf_var.btf_id = type; 14540 } else if (!btf_type_is_struct(t)) { 14541 const struct btf_type *ret; 14542 const char *tname; 14543 u32 tsize; 14544 14545 /* resolve the type size of ksym. */ 14546 ret = btf_resolve_size(btf, t, &tsize); 14547 if (IS_ERR(ret)) { 14548 tname = btf_name_by_offset(btf, t->name_off); 14549 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 14550 tname, PTR_ERR(ret)); 14551 err = -EINVAL; 14552 goto err_put; 14553 } 14554 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 14555 aux->btf_var.mem_size = tsize; 14556 } else { 14557 aux->btf_var.reg_type = PTR_TO_BTF_ID; 14558 aux->btf_var.btf = btf; 14559 aux->btf_var.btf_id = type; 14560 } 14561 14562 /* check whether we recorded this BTF (and maybe module) already */ 14563 for (i = 0; i < env->used_btf_cnt; i++) { 14564 if (env->used_btfs[i].btf == btf) { 14565 btf_put(btf); 14566 return 0; 14567 } 14568 } 14569 14570 if (env->used_btf_cnt >= MAX_USED_BTFS) { 14571 err = -E2BIG; 14572 goto err_put; 14573 } 14574 14575 btf_mod = &env->used_btfs[env->used_btf_cnt]; 14576 btf_mod->btf = btf; 14577 btf_mod->module = NULL; 14578 14579 /* if we reference variables from kernel module, bump its refcount */ 14580 if (btf_is_module(btf)) { 14581 btf_mod->module = btf_try_get_module(btf); 14582 if (!btf_mod->module) { 14583 err = -ENXIO; 14584 goto err_put; 14585 } 14586 } 14587 14588 env->used_btf_cnt++; 14589 14590 return 0; 14591 err_put: 14592 btf_put(btf); 14593 return err; 14594 } 14595 14596 static bool is_tracing_prog_type(enum bpf_prog_type type) 14597 { 14598 switch (type) { 14599 case BPF_PROG_TYPE_KPROBE: 14600 case BPF_PROG_TYPE_TRACEPOINT: 14601 case BPF_PROG_TYPE_PERF_EVENT: 14602 case BPF_PROG_TYPE_RAW_TRACEPOINT: 14603 case BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE: 14604 return true; 14605 default: 14606 return false; 14607 } 14608 } 14609 14610 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 14611 struct bpf_map *map, 14612 struct bpf_prog *prog) 14613 14614 { 14615 enum bpf_prog_type prog_type = resolve_prog_type(prog); 14616 14617 if (btf_record_has_field(map->record, BPF_LIST_HEAD)) { 14618 if (is_tracing_prog_type(prog_type)) { 14619 verbose(env, "tracing progs cannot use bpf_list_head yet\n"); 14620 return -EINVAL; 14621 } 14622 } 14623 14624 if (btf_record_has_field(map->record, BPF_SPIN_LOCK)) { 14625 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 14626 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 14627 return -EINVAL; 14628 } 14629 14630 if (is_tracing_prog_type(prog_type)) { 14631 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 14632 return -EINVAL; 14633 } 14634 14635 if (prog->aux->sleepable) { 14636 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 14637 return -EINVAL; 14638 } 14639 } 14640 14641 if (btf_record_has_field(map->record, BPF_TIMER)) { 14642 if (is_tracing_prog_type(prog_type)) { 14643 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 14644 return -EINVAL; 14645 } 14646 } 14647 14648 if ((bpf_prog_is_offloaded(prog->aux) || bpf_map_is_offloaded(map)) && 14649 !bpf_offload_prog_map_match(prog, map)) { 14650 verbose(env, "offload device mismatch between prog and map\n"); 14651 return -EINVAL; 14652 } 14653 14654 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 14655 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 14656 return -EINVAL; 14657 } 14658 14659 if (prog->aux->sleepable) 14660 switch (map->map_type) { 14661 case BPF_MAP_TYPE_HASH: 14662 case BPF_MAP_TYPE_LRU_HASH: 14663 case BPF_MAP_TYPE_ARRAY: 14664 case BPF_MAP_TYPE_PERCPU_HASH: 14665 case BPF_MAP_TYPE_PERCPU_ARRAY: 14666 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 14667 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 14668 case BPF_MAP_TYPE_HASH_OF_MAPS: 14669 case BPF_MAP_TYPE_RINGBUF: 14670 case BPF_MAP_TYPE_USER_RINGBUF: 14671 case BPF_MAP_TYPE_INODE_STORAGE: 14672 case BPF_MAP_TYPE_SK_STORAGE: 14673 case BPF_MAP_TYPE_TASK_STORAGE: 14674 case BPF_MAP_TYPE_CGRP_STORAGE: 14675 break; 14676 default: 14677 verbose(env, 14678 "Sleepable programs can only use array, hash, ringbuf and local storage maps\n"); 14679 return -EINVAL; 14680 } 14681 14682 return 0; 14683 } 14684 14685 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 14686 { 14687 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 14688 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 14689 } 14690 14691 /* find and rewrite pseudo imm in ld_imm64 instructions: 14692 * 14693 * 1. if it accesses map FD, replace it with actual map pointer. 14694 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 14695 * 14696 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 14697 */ 14698 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 14699 { 14700 struct bpf_insn *insn = env->prog->insnsi; 14701 int insn_cnt = env->prog->len; 14702 int i, j, err; 14703 14704 err = bpf_prog_calc_tag(env->prog); 14705 if (err) 14706 return err; 14707 14708 for (i = 0; i < insn_cnt; i++, insn++) { 14709 if (BPF_CLASS(insn->code) == BPF_LDX && 14710 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 14711 verbose(env, "BPF_LDX uses reserved fields\n"); 14712 return -EINVAL; 14713 } 14714 14715 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 14716 struct bpf_insn_aux_data *aux; 14717 struct bpf_map *map; 14718 struct fd f; 14719 u64 addr; 14720 u32 fd; 14721 14722 if (i == insn_cnt - 1 || insn[1].code != 0 || 14723 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 14724 insn[1].off != 0) { 14725 verbose(env, "invalid bpf_ld_imm64 insn\n"); 14726 return -EINVAL; 14727 } 14728 14729 if (insn[0].src_reg == 0) 14730 /* valid generic load 64-bit imm */ 14731 goto next_insn; 14732 14733 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 14734 aux = &env->insn_aux_data[i]; 14735 err = check_pseudo_btf_id(env, insn, aux); 14736 if (err) 14737 return err; 14738 goto next_insn; 14739 } 14740 14741 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 14742 aux = &env->insn_aux_data[i]; 14743 aux->ptr_type = PTR_TO_FUNC; 14744 goto next_insn; 14745 } 14746 14747 /* In final convert_pseudo_ld_imm64() step, this is 14748 * converted into regular 64-bit imm load insn. 14749 */ 14750 switch (insn[0].src_reg) { 14751 case BPF_PSEUDO_MAP_VALUE: 14752 case BPF_PSEUDO_MAP_IDX_VALUE: 14753 break; 14754 case BPF_PSEUDO_MAP_FD: 14755 case BPF_PSEUDO_MAP_IDX: 14756 if (insn[1].imm == 0) 14757 break; 14758 fallthrough; 14759 default: 14760 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 14761 return -EINVAL; 14762 } 14763 14764 switch (insn[0].src_reg) { 14765 case BPF_PSEUDO_MAP_IDX_VALUE: 14766 case BPF_PSEUDO_MAP_IDX: 14767 if (bpfptr_is_null(env->fd_array)) { 14768 verbose(env, "fd_idx without fd_array is invalid\n"); 14769 return -EPROTO; 14770 } 14771 if (copy_from_bpfptr_offset(&fd, env->fd_array, 14772 insn[0].imm * sizeof(fd), 14773 sizeof(fd))) 14774 return -EFAULT; 14775 break; 14776 default: 14777 fd = insn[0].imm; 14778 break; 14779 } 14780 14781 f = fdget(fd); 14782 map = __bpf_map_get(f); 14783 if (IS_ERR(map)) { 14784 verbose(env, "fd %d is not pointing to valid bpf_map\n", 14785 insn[0].imm); 14786 return PTR_ERR(map); 14787 } 14788 14789 err = check_map_prog_compatibility(env, map, env->prog); 14790 if (err) { 14791 fdput(f); 14792 return err; 14793 } 14794 14795 aux = &env->insn_aux_data[i]; 14796 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 14797 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 14798 addr = (unsigned long)map; 14799 } else { 14800 u32 off = insn[1].imm; 14801 14802 if (off >= BPF_MAX_VAR_OFF) { 14803 verbose(env, "direct value offset of %u is not allowed\n", off); 14804 fdput(f); 14805 return -EINVAL; 14806 } 14807 14808 if (!map->ops->map_direct_value_addr) { 14809 verbose(env, "no direct value access support for this map type\n"); 14810 fdput(f); 14811 return -EINVAL; 14812 } 14813 14814 err = map->ops->map_direct_value_addr(map, &addr, off); 14815 if (err) { 14816 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 14817 map->value_size, off); 14818 fdput(f); 14819 return err; 14820 } 14821 14822 aux->map_off = off; 14823 addr += off; 14824 } 14825 14826 insn[0].imm = (u32)addr; 14827 insn[1].imm = addr >> 32; 14828 14829 /* check whether we recorded this map already */ 14830 for (j = 0; j < env->used_map_cnt; j++) { 14831 if (env->used_maps[j] == map) { 14832 aux->map_index = j; 14833 fdput(f); 14834 goto next_insn; 14835 } 14836 } 14837 14838 if (env->used_map_cnt >= MAX_USED_MAPS) { 14839 fdput(f); 14840 return -E2BIG; 14841 } 14842 14843 /* hold the map. If the program is rejected by verifier, 14844 * the map will be released by release_maps() or it 14845 * will be used by the valid program until it's unloaded 14846 * and all maps are released in free_used_maps() 14847 */ 14848 bpf_map_inc(map); 14849 14850 aux->map_index = env->used_map_cnt; 14851 env->used_maps[env->used_map_cnt++] = map; 14852 14853 if (bpf_map_is_cgroup_storage(map) && 14854 bpf_cgroup_storage_assign(env->prog->aux, map)) { 14855 verbose(env, "only one cgroup storage of each type is allowed\n"); 14856 fdput(f); 14857 return -EBUSY; 14858 } 14859 14860 fdput(f); 14861 next_insn: 14862 insn++; 14863 i++; 14864 continue; 14865 } 14866 14867 /* Basic sanity check before we invest more work here. */ 14868 if (!bpf_opcode_in_insntable(insn->code)) { 14869 verbose(env, "unknown opcode %02x\n", insn->code); 14870 return -EINVAL; 14871 } 14872 } 14873 14874 /* now all pseudo BPF_LD_IMM64 instructions load valid 14875 * 'struct bpf_map *' into a register instead of user map_fd. 14876 * These pointers will be used later by verifier to validate map access. 14877 */ 14878 return 0; 14879 } 14880 14881 /* drop refcnt of maps used by the rejected program */ 14882 static void release_maps(struct bpf_verifier_env *env) 14883 { 14884 __bpf_free_used_maps(env->prog->aux, env->used_maps, 14885 env->used_map_cnt); 14886 } 14887 14888 /* drop refcnt of maps used by the rejected program */ 14889 static void release_btfs(struct bpf_verifier_env *env) 14890 { 14891 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 14892 env->used_btf_cnt); 14893 } 14894 14895 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 14896 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 14897 { 14898 struct bpf_insn *insn = env->prog->insnsi; 14899 int insn_cnt = env->prog->len; 14900 int i; 14901 14902 for (i = 0; i < insn_cnt; i++, insn++) { 14903 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 14904 continue; 14905 if (insn->src_reg == BPF_PSEUDO_FUNC) 14906 continue; 14907 insn->src_reg = 0; 14908 } 14909 } 14910 14911 /* single env->prog->insni[off] instruction was replaced with the range 14912 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 14913 * [0, off) and [off, end) to new locations, so the patched range stays zero 14914 */ 14915 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 14916 struct bpf_insn_aux_data *new_data, 14917 struct bpf_prog *new_prog, u32 off, u32 cnt) 14918 { 14919 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 14920 struct bpf_insn *insn = new_prog->insnsi; 14921 u32 old_seen = old_data[off].seen; 14922 u32 prog_len; 14923 int i; 14924 14925 /* aux info at OFF always needs adjustment, no matter fast path 14926 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 14927 * original insn at old prog. 14928 */ 14929 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 14930 14931 if (cnt == 1) 14932 return; 14933 prog_len = new_prog->len; 14934 14935 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 14936 memcpy(new_data + off + cnt - 1, old_data + off, 14937 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 14938 for (i = off; i < off + cnt - 1; i++) { 14939 /* Expand insni[off]'s seen count to the patched range. */ 14940 new_data[i].seen = old_seen; 14941 new_data[i].zext_dst = insn_has_def32(env, insn + i); 14942 } 14943 env->insn_aux_data = new_data; 14944 vfree(old_data); 14945 } 14946 14947 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 14948 { 14949 int i; 14950 14951 if (len == 1) 14952 return; 14953 /* NOTE: fake 'exit' subprog should be updated as well. */ 14954 for (i = 0; i <= env->subprog_cnt; i++) { 14955 if (env->subprog_info[i].start <= off) 14956 continue; 14957 env->subprog_info[i].start += len - 1; 14958 } 14959 } 14960 14961 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 14962 { 14963 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 14964 int i, sz = prog->aux->size_poke_tab; 14965 struct bpf_jit_poke_descriptor *desc; 14966 14967 for (i = 0; i < sz; i++) { 14968 desc = &tab[i]; 14969 if (desc->insn_idx <= off) 14970 continue; 14971 desc->insn_idx += len - 1; 14972 } 14973 } 14974 14975 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 14976 const struct bpf_insn *patch, u32 len) 14977 { 14978 struct bpf_prog *new_prog; 14979 struct bpf_insn_aux_data *new_data = NULL; 14980 14981 if (len > 1) { 14982 new_data = vzalloc(array_size(env->prog->len + len - 1, 14983 sizeof(struct bpf_insn_aux_data))); 14984 if (!new_data) 14985 return NULL; 14986 } 14987 14988 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 14989 if (IS_ERR(new_prog)) { 14990 if (PTR_ERR(new_prog) == -ERANGE) 14991 verbose(env, 14992 "insn %d cannot be patched due to 16-bit range\n", 14993 env->insn_aux_data[off].orig_idx); 14994 vfree(new_data); 14995 return NULL; 14996 } 14997 adjust_insn_aux_data(env, new_data, new_prog, off, len); 14998 adjust_subprog_starts(env, off, len); 14999 adjust_poke_descs(new_prog, off, len); 15000 return new_prog; 15001 } 15002 15003 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 15004 u32 off, u32 cnt) 15005 { 15006 int i, j; 15007 15008 /* find first prog starting at or after off (first to remove) */ 15009 for (i = 0; i < env->subprog_cnt; i++) 15010 if (env->subprog_info[i].start >= off) 15011 break; 15012 /* find first prog starting at or after off + cnt (first to stay) */ 15013 for (j = i; j < env->subprog_cnt; j++) 15014 if (env->subprog_info[j].start >= off + cnt) 15015 break; 15016 /* if j doesn't start exactly at off + cnt, we are just removing 15017 * the front of previous prog 15018 */ 15019 if (env->subprog_info[j].start != off + cnt) 15020 j--; 15021 15022 if (j > i) { 15023 struct bpf_prog_aux *aux = env->prog->aux; 15024 int move; 15025 15026 /* move fake 'exit' subprog as well */ 15027 move = env->subprog_cnt + 1 - j; 15028 15029 memmove(env->subprog_info + i, 15030 env->subprog_info + j, 15031 sizeof(*env->subprog_info) * move); 15032 env->subprog_cnt -= j - i; 15033 15034 /* remove func_info */ 15035 if (aux->func_info) { 15036 move = aux->func_info_cnt - j; 15037 15038 memmove(aux->func_info + i, 15039 aux->func_info + j, 15040 sizeof(*aux->func_info) * move); 15041 aux->func_info_cnt -= j - i; 15042 /* func_info->insn_off is set after all code rewrites, 15043 * in adjust_btf_func() - no need to adjust 15044 */ 15045 } 15046 } else { 15047 /* convert i from "first prog to remove" to "first to adjust" */ 15048 if (env->subprog_info[i].start == off) 15049 i++; 15050 } 15051 15052 /* update fake 'exit' subprog as well */ 15053 for (; i <= env->subprog_cnt; i++) 15054 env->subprog_info[i].start -= cnt; 15055 15056 return 0; 15057 } 15058 15059 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 15060 u32 cnt) 15061 { 15062 struct bpf_prog *prog = env->prog; 15063 u32 i, l_off, l_cnt, nr_linfo; 15064 struct bpf_line_info *linfo; 15065 15066 nr_linfo = prog->aux->nr_linfo; 15067 if (!nr_linfo) 15068 return 0; 15069 15070 linfo = prog->aux->linfo; 15071 15072 /* find first line info to remove, count lines to be removed */ 15073 for (i = 0; i < nr_linfo; i++) 15074 if (linfo[i].insn_off >= off) 15075 break; 15076 15077 l_off = i; 15078 l_cnt = 0; 15079 for (; i < nr_linfo; i++) 15080 if (linfo[i].insn_off < off + cnt) 15081 l_cnt++; 15082 else 15083 break; 15084 15085 /* First live insn doesn't match first live linfo, it needs to "inherit" 15086 * last removed linfo. prog is already modified, so prog->len == off 15087 * means no live instructions after (tail of the program was removed). 15088 */ 15089 if (prog->len != off && l_cnt && 15090 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 15091 l_cnt--; 15092 linfo[--i].insn_off = off + cnt; 15093 } 15094 15095 /* remove the line info which refer to the removed instructions */ 15096 if (l_cnt) { 15097 memmove(linfo + l_off, linfo + i, 15098 sizeof(*linfo) * (nr_linfo - i)); 15099 15100 prog->aux->nr_linfo -= l_cnt; 15101 nr_linfo = prog->aux->nr_linfo; 15102 } 15103 15104 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 15105 for (i = l_off; i < nr_linfo; i++) 15106 linfo[i].insn_off -= cnt; 15107 15108 /* fix up all subprogs (incl. 'exit') which start >= off */ 15109 for (i = 0; i <= env->subprog_cnt; i++) 15110 if (env->subprog_info[i].linfo_idx > l_off) { 15111 /* program may have started in the removed region but 15112 * may not be fully removed 15113 */ 15114 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 15115 env->subprog_info[i].linfo_idx -= l_cnt; 15116 else 15117 env->subprog_info[i].linfo_idx = l_off; 15118 } 15119 15120 return 0; 15121 } 15122 15123 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 15124 { 15125 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15126 unsigned int orig_prog_len = env->prog->len; 15127 int err; 15128 15129 if (bpf_prog_is_offloaded(env->prog->aux)) 15130 bpf_prog_offload_remove_insns(env, off, cnt); 15131 15132 err = bpf_remove_insns(env->prog, off, cnt); 15133 if (err) 15134 return err; 15135 15136 err = adjust_subprog_starts_after_remove(env, off, cnt); 15137 if (err) 15138 return err; 15139 15140 err = bpf_adj_linfo_after_remove(env, off, cnt); 15141 if (err) 15142 return err; 15143 15144 memmove(aux_data + off, aux_data + off + cnt, 15145 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 15146 15147 return 0; 15148 } 15149 15150 /* The verifier does more data flow analysis than llvm and will not 15151 * explore branches that are dead at run time. Malicious programs can 15152 * have dead code too. Therefore replace all dead at-run-time code 15153 * with 'ja -1'. 15154 * 15155 * Just nops are not optimal, e.g. if they would sit at the end of the 15156 * program and through another bug we would manage to jump there, then 15157 * we'd execute beyond program memory otherwise. Returning exception 15158 * code also wouldn't work since we can have subprogs where the dead 15159 * code could be located. 15160 */ 15161 static void sanitize_dead_code(struct bpf_verifier_env *env) 15162 { 15163 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15164 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 15165 struct bpf_insn *insn = env->prog->insnsi; 15166 const int insn_cnt = env->prog->len; 15167 int i; 15168 15169 for (i = 0; i < insn_cnt; i++) { 15170 if (aux_data[i].seen) 15171 continue; 15172 memcpy(insn + i, &trap, sizeof(trap)); 15173 aux_data[i].zext_dst = false; 15174 } 15175 } 15176 15177 static bool insn_is_cond_jump(u8 code) 15178 { 15179 u8 op; 15180 15181 if (BPF_CLASS(code) == BPF_JMP32) 15182 return true; 15183 15184 if (BPF_CLASS(code) != BPF_JMP) 15185 return false; 15186 15187 op = BPF_OP(code); 15188 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 15189 } 15190 15191 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 15192 { 15193 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15194 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 15195 struct bpf_insn *insn = env->prog->insnsi; 15196 const int insn_cnt = env->prog->len; 15197 int i; 15198 15199 for (i = 0; i < insn_cnt; i++, insn++) { 15200 if (!insn_is_cond_jump(insn->code)) 15201 continue; 15202 15203 if (!aux_data[i + 1].seen) 15204 ja.off = insn->off; 15205 else if (!aux_data[i + 1 + insn->off].seen) 15206 ja.off = 0; 15207 else 15208 continue; 15209 15210 if (bpf_prog_is_offloaded(env->prog->aux)) 15211 bpf_prog_offload_replace_insn(env, i, &ja); 15212 15213 memcpy(insn, &ja, sizeof(ja)); 15214 } 15215 } 15216 15217 static int opt_remove_dead_code(struct bpf_verifier_env *env) 15218 { 15219 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 15220 int insn_cnt = env->prog->len; 15221 int i, err; 15222 15223 for (i = 0; i < insn_cnt; i++) { 15224 int j; 15225 15226 j = 0; 15227 while (i + j < insn_cnt && !aux_data[i + j].seen) 15228 j++; 15229 if (!j) 15230 continue; 15231 15232 err = verifier_remove_insns(env, i, j); 15233 if (err) 15234 return err; 15235 insn_cnt = env->prog->len; 15236 } 15237 15238 return 0; 15239 } 15240 15241 static int opt_remove_nops(struct bpf_verifier_env *env) 15242 { 15243 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 15244 struct bpf_insn *insn = env->prog->insnsi; 15245 int insn_cnt = env->prog->len; 15246 int i, err; 15247 15248 for (i = 0; i < insn_cnt; i++) { 15249 if (memcmp(&insn[i], &ja, sizeof(ja))) 15250 continue; 15251 15252 err = verifier_remove_insns(env, i, 1); 15253 if (err) 15254 return err; 15255 insn_cnt--; 15256 i--; 15257 } 15258 15259 return 0; 15260 } 15261 15262 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 15263 const union bpf_attr *attr) 15264 { 15265 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 15266 struct bpf_insn_aux_data *aux = env->insn_aux_data; 15267 int i, patch_len, delta = 0, len = env->prog->len; 15268 struct bpf_insn *insns = env->prog->insnsi; 15269 struct bpf_prog *new_prog; 15270 bool rnd_hi32; 15271 15272 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 15273 zext_patch[1] = BPF_ZEXT_REG(0); 15274 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 15275 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 15276 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 15277 for (i = 0; i < len; i++) { 15278 int adj_idx = i + delta; 15279 struct bpf_insn insn; 15280 int load_reg; 15281 15282 insn = insns[adj_idx]; 15283 load_reg = insn_def_regno(&insn); 15284 if (!aux[adj_idx].zext_dst) { 15285 u8 code, class; 15286 u32 imm_rnd; 15287 15288 if (!rnd_hi32) 15289 continue; 15290 15291 code = insn.code; 15292 class = BPF_CLASS(code); 15293 if (load_reg == -1) 15294 continue; 15295 15296 /* NOTE: arg "reg" (the fourth one) is only used for 15297 * BPF_STX + SRC_OP, so it is safe to pass NULL 15298 * here. 15299 */ 15300 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 15301 if (class == BPF_LD && 15302 BPF_MODE(code) == BPF_IMM) 15303 i++; 15304 continue; 15305 } 15306 15307 /* ctx load could be transformed into wider load. */ 15308 if (class == BPF_LDX && 15309 aux[adj_idx].ptr_type == PTR_TO_CTX) 15310 continue; 15311 15312 imm_rnd = get_random_u32(); 15313 rnd_hi32_patch[0] = insn; 15314 rnd_hi32_patch[1].imm = imm_rnd; 15315 rnd_hi32_patch[3].dst_reg = load_reg; 15316 patch = rnd_hi32_patch; 15317 patch_len = 4; 15318 goto apply_patch_buffer; 15319 } 15320 15321 /* Add in an zero-extend instruction if a) the JIT has requested 15322 * it or b) it's a CMPXCHG. 15323 * 15324 * The latter is because: BPF_CMPXCHG always loads a value into 15325 * R0, therefore always zero-extends. However some archs' 15326 * equivalent instruction only does this load when the 15327 * comparison is successful. This detail of CMPXCHG is 15328 * orthogonal to the general zero-extension behaviour of the 15329 * CPU, so it's treated independently of bpf_jit_needs_zext. 15330 */ 15331 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 15332 continue; 15333 15334 /* Zero-extension is done by the caller. */ 15335 if (bpf_pseudo_kfunc_call(&insn)) 15336 continue; 15337 15338 if (WARN_ON(load_reg == -1)) { 15339 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 15340 return -EFAULT; 15341 } 15342 15343 zext_patch[0] = insn; 15344 zext_patch[1].dst_reg = load_reg; 15345 zext_patch[1].src_reg = load_reg; 15346 patch = zext_patch; 15347 patch_len = 2; 15348 apply_patch_buffer: 15349 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 15350 if (!new_prog) 15351 return -ENOMEM; 15352 env->prog = new_prog; 15353 insns = new_prog->insnsi; 15354 aux = env->insn_aux_data; 15355 delta += patch_len - 1; 15356 } 15357 15358 return 0; 15359 } 15360 15361 /* convert load instructions that access fields of a context type into a 15362 * sequence of instructions that access fields of the underlying structure: 15363 * struct __sk_buff -> struct sk_buff 15364 * struct bpf_sock_ops -> struct sock 15365 */ 15366 static int convert_ctx_accesses(struct bpf_verifier_env *env) 15367 { 15368 const struct bpf_verifier_ops *ops = env->ops; 15369 int i, cnt, size, ctx_field_size, delta = 0; 15370 const int insn_cnt = env->prog->len; 15371 struct bpf_insn insn_buf[16], *insn; 15372 u32 target_size, size_default, off; 15373 struct bpf_prog *new_prog; 15374 enum bpf_access_type type; 15375 bool is_narrower_load; 15376 15377 if (ops->gen_prologue || env->seen_direct_write) { 15378 if (!ops->gen_prologue) { 15379 verbose(env, "bpf verifier is misconfigured\n"); 15380 return -EINVAL; 15381 } 15382 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 15383 env->prog); 15384 if (cnt >= ARRAY_SIZE(insn_buf)) { 15385 verbose(env, "bpf verifier is misconfigured\n"); 15386 return -EINVAL; 15387 } else if (cnt) { 15388 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 15389 if (!new_prog) 15390 return -ENOMEM; 15391 15392 env->prog = new_prog; 15393 delta += cnt - 1; 15394 } 15395 } 15396 15397 if (bpf_prog_is_offloaded(env->prog->aux)) 15398 return 0; 15399 15400 insn = env->prog->insnsi + delta; 15401 15402 for (i = 0; i < insn_cnt; i++, insn++) { 15403 bpf_convert_ctx_access_t convert_ctx_access; 15404 bool ctx_access; 15405 15406 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 15407 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 15408 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 15409 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) { 15410 type = BPF_READ; 15411 ctx_access = true; 15412 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 15413 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 15414 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 15415 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 15416 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 15417 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 15418 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 15419 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 15420 type = BPF_WRITE; 15421 ctx_access = BPF_CLASS(insn->code) == BPF_STX; 15422 } else { 15423 continue; 15424 } 15425 15426 if (type == BPF_WRITE && 15427 env->insn_aux_data[i + delta].sanitize_stack_spill) { 15428 struct bpf_insn patch[] = { 15429 *insn, 15430 BPF_ST_NOSPEC(), 15431 }; 15432 15433 cnt = ARRAY_SIZE(patch); 15434 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 15435 if (!new_prog) 15436 return -ENOMEM; 15437 15438 delta += cnt - 1; 15439 env->prog = new_prog; 15440 insn = new_prog->insnsi + i + delta; 15441 continue; 15442 } 15443 15444 if (!ctx_access) 15445 continue; 15446 15447 switch ((int)env->insn_aux_data[i + delta].ptr_type) { 15448 case PTR_TO_CTX: 15449 if (!ops->convert_ctx_access) 15450 continue; 15451 convert_ctx_access = ops->convert_ctx_access; 15452 break; 15453 case PTR_TO_SOCKET: 15454 case PTR_TO_SOCK_COMMON: 15455 convert_ctx_access = bpf_sock_convert_ctx_access; 15456 break; 15457 case PTR_TO_TCP_SOCK: 15458 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 15459 break; 15460 case PTR_TO_XDP_SOCK: 15461 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 15462 break; 15463 case PTR_TO_BTF_ID: 15464 case PTR_TO_BTF_ID | PTR_UNTRUSTED: 15465 /* PTR_TO_BTF_ID | MEM_ALLOC always has a valid lifetime, unlike 15466 * PTR_TO_BTF_ID, and an active ref_obj_id, but the same cannot 15467 * be said once it is marked PTR_UNTRUSTED, hence we must handle 15468 * any faults for loads into such types. BPF_WRITE is disallowed 15469 * for this case. 15470 */ 15471 case PTR_TO_BTF_ID | MEM_ALLOC | PTR_UNTRUSTED: 15472 if (type == BPF_READ) { 15473 insn->code = BPF_LDX | BPF_PROBE_MEM | 15474 BPF_SIZE((insn)->code); 15475 env->prog->aux->num_exentries++; 15476 } 15477 continue; 15478 default: 15479 continue; 15480 } 15481 15482 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 15483 size = BPF_LDST_BYTES(insn); 15484 15485 /* If the read access is a narrower load of the field, 15486 * convert to a 4/8-byte load, to minimum program type specific 15487 * convert_ctx_access changes. If conversion is successful, 15488 * we will apply proper mask to the result. 15489 */ 15490 is_narrower_load = size < ctx_field_size; 15491 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 15492 off = insn->off; 15493 if (is_narrower_load) { 15494 u8 size_code; 15495 15496 if (type == BPF_WRITE) { 15497 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 15498 return -EINVAL; 15499 } 15500 15501 size_code = BPF_H; 15502 if (ctx_field_size == 4) 15503 size_code = BPF_W; 15504 else if (ctx_field_size == 8) 15505 size_code = BPF_DW; 15506 15507 insn->off = off & ~(size_default - 1); 15508 insn->code = BPF_LDX | BPF_MEM | size_code; 15509 } 15510 15511 target_size = 0; 15512 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 15513 &target_size); 15514 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 15515 (ctx_field_size && !target_size)) { 15516 verbose(env, "bpf verifier is misconfigured\n"); 15517 return -EINVAL; 15518 } 15519 15520 if (is_narrower_load && size < target_size) { 15521 u8 shift = bpf_ctx_narrow_access_offset( 15522 off, size, size_default) * 8; 15523 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 15524 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 15525 return -EINVAL; 15526 } 15527 if (ctx_field_size <= 4) { 15528 if (shift) 15529 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 15530 insn->dst_reg, 15531 shift); 15532 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 15533 (1 << size * 8) - 1); 15534 } else { 15535 if (shift) 15536 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 15537 insn->dst_reg, 15538 shift); 15539 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 15540 (1ULL << size * 8) - 1); 15541 } 15542 } 15543 15544 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15545 if (!new_prog) 15546 return -ENOMEM; 15547 15548 delta += cnt - 1; 15549 15550 /* keep walking new program and skip insns we just inserted */ 15551 env->prog = new_prog; 15552 insn = new_prog->insnsi + i + delta; 15553 } 15554 15555 return 0; 15556 } 15557 15558 static int jit_subprogs(struct bpf_verifier_env *env) 15559 { 15560 struct bpf_prog *prog = env->prog, **func, *tmp; 15561 int i, j, subprog_start, subprog_end = 0, len, subprog; 15562 struct bpf_map *map_ptr; 15563 struct bpf_insn *insn; 15564 void *old_bpf_func; 15565 int err, num_exentries; 15566 15567 if (env->subprog_cnt <= 1) 15568 return 0; 15569 15570 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 15571 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 15572 continue; 15573 15574 /* Upon error here we cannot fall back to interpreter but 15575 * need a hard reject of the program. Thus -EFAULT is 15576 * propagated in any case. 15577 */ 15578 subprog = find_subprog(env, i + insn->imm + 1); 15579 if (subprog < 0) { 15580 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 15581 i + insn->imm + 1); 15582 return -EFAULT; 15583 } 15584 /* temporarily remember subprog id inside insn instead of 15585 * aux_data, since next loop will split up all insns into funcs 15586 */ 15587 insn->off = subprog; 15588 /* remember original imm in case JIT fails and fallback 15589 * to interpreter will be needed 15590 */ 15591 env->insn_aux_data[i].call_imm = insn->imm; 15592 /* point imm to __bpf_call_base+1 from JITs point of view */ 15593 insn->imm = 1; 15594 if (bpf_pseudo_func(insn)) 15595 /* jit (e.g. x86_64) may emit fewer instructions 15596 * if it learns a u32 imm is the same as a u64 imm. 15597 * Force a non zero here. 15598 */ 15599 insn[1].imm = 1; 15600 } 15601 15602 err = bpf_prog_alloc_jited_linfo(prog); 15603 if (err) 15604 goto out_undo_insn; 15605 15606 err = -ENOMEM; 15607 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 15608 if (!func) 15609 goto out_undo_insn; 15610 15611 for (i = 0; i < env->subprog_cnt; i++) { 15612 subprog_start = subprog_end; 15613 subprog_end = env->subprog_info[i + 1].start; 15614 15615 len = subprog_end - subprog_start; 15616 /* bpf_prog_run() doesn't call subprogs directly, 15617 * hence main prog stats include the runtime of subprogs. 15618 * subprogs don't have IDs and not reachable via prog_get_next_id 15619 * func[i]->stats will never be accessed and stays NULL 15620 */ 15621 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 15622 if (!func[i]) 15623 goto out_free; 15624 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 15625 len * sizeof(struct bpf_insn)); 15626 func[i]->type = prog->type; 15627 func[i]->len = len; 15628 if (bpf_prog_calc_tag(func[i])) 15629 goto out_free; 15630 func[i]->is_func = 1; 15631 func[i]->aux->func_idx = i; 15632 /* Below members will be freed only at prog->aux */ 15633 func[i]->aux->btf = prog->aux->btf; 15634 func[i]->aux->func_info = prog->aux->func_info; 15635 func[i]->aux->func_info_cnt = prog->aux->func_info_cnt; 15636 func[i]->aux->poke_tab = prog->aux->poke_tab; 15637 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 15638 15639 for (j = 0; j < prog->aux->size_poke_tab; j++) { 15640 struct bpf_jit_poke_descriptor *poke; 15641 15642 poke = &prog->aux->poke_tab[j]; 15643 if (poke->insn_idx < subprog_end && 15644 poke->insn_idx >= subprog_start) 15645 poke->aux = func[i]->aux; 15646 } 15647 15648 func[i]->aux->name[0] = 'F'; 15649 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 15650 func[i]->jit_requested = 1; 15651 func[i]->blinding_requested = prog->blinding_requested; 15652 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 15653 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 15654 func[i]->aux->linfo = prog->aux->linfo; 15655 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 15656 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 15657 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 15658 num_exentries = 0; 15659 insn = func[i]->insnsi; 15660 for (j = 0; j < func[i]->len; j++, insn++) { 15661 if (BPF_CLASS(insn->code) == BPF_LDX && 15662 BPF_MODE(insn->code) == BPF_PROBE_MEM) 15663 num_exentries++; 15664 } 15665 func[i]->aux->num_exentries = num_exentries; 15666 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 15667 func[i] = bpf_int_jit_compile(func[i]); 15668 if (!func[i]->jited) { 15669 err = -ENOTSUPP; 15670 goto out_free; 15671 } 15672 cond_resched(); 15673 } 15674 15675 /* at this point all bpf functions were successfully JITed 15676 * now populate all bpf_calls with correct addresses and 15677 * run last pass of JIT 15678 */ 15679 for (i = 0; i < env->subprog_cnt; i++) { 15680 insn = func[i]->insnsi; 15681 for (j = 0; j < func[i]->len; j++, insn++) { 15682 if (bpf_pseudo_func(insn)) { 15683 subprog = insn->off; 15684 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 15685 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 15686 continue; 15687 } 15688 if (!bpf_pseudo_call(insn)) 15689 continue; 15690 subprog = insn->off; 15691 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 15692 } 15693 15694 /* we use the aux data to keep a list of the start addresses 15695 * of the JITed images for each function in the program 15696 * 15697 * for some architectures, such as powerpc64, the imm field 15698 * might not be large enough to hold the offset of the start 15699 * address of the callee's JITed image from __bpf_call_base 15700 * 15701 * in such cases, we can lookup the start address of a callee 15702 * by using its subprog id, available from the off field of 15703 * the call instruction, as an index for this list 15704 */ 15705 func[i]->aux->func = func; 15706 func[i]->aux->func_cnt = env->subprog_cnt; 15707 } 15708 for (i = 0; i < env->subprog_cnt; i++) { 15709 old_bpf_func = func[i]->bpf_func; 15710 tmp = bpf_int_jit_compile(func[i]); 15711 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 15712 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 15713 err = -ENOTSUPP; 15714 goto out_free; 15715 } 15716 cond_resched(); 15717 } 15718 15719 /* finally lock prog and jit images for all functions and 15720 * populate kallsysm 15721 */ 15722 for (i = 0; i < env->subprog_cnt; i++) { 15723 bpf_prog_lock_ro(func[i]); 15724 bpf_prog_kallsyms_add(func[i]); 15725 } 15726 15727 /* Last step: make now unused interpreter insns from main 15728 * prog consistent for later dump requests, so they can 15729 * later look the same as if they were interpreted only. 15730 */ 15731 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 15732 if (bpf_pseudo_func(insn)) { 15733 insn[0].imm = env->insn_aux_data[i].call_imm; 15734 insn[1].imm = insn->off; 15735 insn->off = 0; 15736 continue; 15737 } 15738 if (!bpf_pseudo_call(insn)) 15739 continue; 15740 insn->off = env->insn_aux_data[i].call_imm; 15741 subprog = find_subprog(env, i + insn->off + 1); 15742 insn->imm = subprog; 15743 } 15744 15745 prog->jited = 1; 15746 prog->bpf_func = func[0]->bpf_func; 15747 prog->jited_len = func[0]->jited_len; 15748 prog->aux->func = func; 15749 prog->aux->func_cnt = env->subprog_cnt; 15750 bpf_prog_jit_attempt_done(prog); 15751 return 0; 15752 out_free: 15753 /* We failed JIT'ing, so at this point we need to unregister poke 15754 * descriptors from subprogs, so that kernel is not attempting to 15755 * patch it anymore as we're freeing the subprog JIT memory. 15756 */ 15757 for (i = 0; i < prog->aux->size_poke_tab; i++) { 15758 map_ptr = prog->aux->poke_tab[i].tail_call.map; 15759 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 15760 } 15761 /* At this point we're guaranteed that poke descriptors are not 15762 * live anymore. We can just unlink its descriptor table as it's 15763 * released with the main prog. 15764 */ 15765 for (i = 0; i < env->subprog_cnt; i++) { 15766 if (!func[i]) 15767 continue; 15768 func[i]->aux->poke_tab = NULL; 15769 bpf_jit_free(func[i]); 15770 } 15771 kfree(func); 15772 out_undo_insn: 15773 /* cleanup main prog to be interpreted */ 15774 prog->jit_requested = 0; 15775 prog->blinding_requested = 0; 15776 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 15777 if (!bpf_pseudo_call(insn)) 15778 continue; 15779 insn->off = 0; 15780 insn->imm = env->insn_aux_data[i].call_imm; 15781 } 15782 bpf_prog_jit_attempt_done(prog); 15783 return err; 15784 } 15785 15786 static int fixup_call_args(struct bpf_verifier_env *env) 15787 { 15788 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 15789 struct bpf_prog *prog = env->prog; 15790 struct bpf_insn *insn = prog->insnsi; 15791 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 15792 int i, depth; 15793 #endif 15794 int err = 0; 15795 15796 if (env->prog->jit_requested && 15797 !bpf_prog_is_offloaded(env->prog->aux)) { 15798 err = jit_subprogs(env); 15799 if (err == 0) 15800 return 0; 15801 if (err == -EFAULT) 15802 return err; 15803 } 15804 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 15805 if (has_kfunc_call) { 15806 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 15807 return -EINVAL; 15808 } 15809 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 15810 /* When JIT fails the progs with bpf2bpf calls and tail_calls 15811 * have to be rejected, since interpreter doesn't support them yet. 15812 */ 15813 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 15814 return -EINVAL; 15815 } 15816 for (i = 0; i < prog->len; i++, insn++) { 15817 if (bpf_pseudo_func(insn)) { 15818 /* When JIT fails the progs with callback calls 15819 * have to be rejected, since interpreter doesn't support them yet. 15820 */ 15821 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 15822 return -EINVAL; 15823 } 15824 15825 if (!bpf_pseudo_call(insn)) 15826 continue; 15827 depth = get_callee_stack_depth(env, insn, i); 15828 if (depth < 0) 15829 return depth; 15830 bpf_patch_call_args(insn, depth); 15831 } 15832 err = 0; 15833 #endif 15834 return err; 15835 } 15836 15837 static int fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 15838 struct bpf_insn *insn_buf, int insn_idx, int *cnt) 15839 { 15840 const struct bpf_kfunc_desc *desc; 15841 void *xdp_kfunc; 15842 15843 if (!insn->imm) { 15844 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 15845 return -EINVAL; 15846 } 15847 15848 *cnt = 0; 15849 15850 if (bpf_dev_bound_kfunc_id(insn->imm)) { 15851 xdp_kfunc = bpf_dev_bound_resolve_kfunc(env->prog, insn->imm); 15852 if (xdp_kfunc) { 15853 insn->imm = BPF_CALL_IMM(xdp_kfunc); 15854 return 0; 15855 } 15856 15857 /* fallback to default kfunc when not supported by netdev */ 15858 } 15859 15860 /* insn->imm has the btf func_id. Replace it with 15861 * an address (relative to __bpf_call_base). 15862 */ 15863 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 15864 if (!desc) { 15865 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 15866 insn->imm); 15867 return -EFAULT; 15868 } 15869 15870 insn->imm = desc->imm; 15871 if (insn->off) 15872 return 0; 15873 if (desc->func_id == special_kfunc_list[KF_bpf_obj_new_impl]) { 15874 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 15875 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 15876 u64 obj_new_size = env->insn_aux_data[insn_idx].obj_new_size; 15877 15878 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_1, obj_new_size); 15879 insn_buf[1] = addr[0]; 15880 insn_buf[2] = addr[1]; 15881 insn_buf[3] = *insn; 15882 *cnt = 4; 15883 } else if (desc->func_id == special_kfunc_list[KF_bpf_obj_drop_impl]) { 15884 struct btf_struct_meta *kptr_struct_meta = env->insn_aux_data[insn_idx].kptr_struct_meta; 15885 struct bpf_insn addr[2] = { BPF_LD_IMM64(BPF_REG_2, (long)kptr_struct_meta) }; 15886 15887 insn_buf[0] = addr[0]; 15888 insn_buf[1] = addr[1]; 15889 insn_buf[2] = *insn; 15890 *cnt = 3; 15891 } else if (desc->func_id == special_kfunc_list[KF_bpf_cast_to_kern_ctx] || 15892 desc->func_id == special_kfunc_list[KF_bpf_rdonly_cast]) { 15893 insn_buf[0] = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1); 15894 *cnt = 1; 15895 } 15896 return 0; 15897 } 15898 15899 /* Do various post-verification rewrites in a single program pass. 15900 * These rewrites simplify JIT and interpreter implementations. 15901 */ 15902 static int do_misc_fixups(struct bpf_verifier_env *env) 15903 { 15904 struct bpf_prog *prog = env->prog; 15905 enum bpf_attach_type eatype = prog->expected_attach_type; 15906 enum bpf_prog_type prog_type = resolve_prog_type(prog); 15907 struct bpf_insn *insn = prog->insnsi; 15908 const struct bpf_func_proto *fn; 15909 const int insn_cnt = prog->len; 15910 const struct bpf_map_ops *ops; 15911 struct bpf_insn_aux_data *aux; 15912 struct bpf_insn insn_buf[16]; 15913 struct bpf_prog *new_prog; 15914 struct bpf_map *map_ptr; 15915 int i, ret, cnt, delta = 0; 15916 15917 for (i = 0; i < insn_cnt; i++, insn++) { 15918 /* Make divide-by-zero exceptions impossible. */ 15919 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 15920 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 15921 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 15922 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 15923 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 15924 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 15925 struct bpf_insn *patchlet; 15926 struct bpf_insn chk_and_div[] = { 15927 /* [R,W]x div 0 -> 0 */ 15928 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 15929 BPF_JNE | BPF_K, insn->src_reg, 15930 0, 2, 0), 15931 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 15932 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 15933 *insn, 15934 }; 15935 struct bpf_insn chk_and_mod[] = { 15936 /* [R,W]x mod 0 -> [R,W]x */ 15937 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 15938 BPF_JEQ | BPF_K, insn->src_reg, 15939 0, 1 + (is64 ? 0 : 1), 0), 15940 *insn, 15941 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 15942 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 15943 }; 15944 15945 patchlet = isdiv ? chk_and_div : chk_and_mod; 15946 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 15947 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 15948 15949 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 15950 if (!new_prog) 15951 return -ENOMEM; 15952 15953 delta += cnt - 1; 15954 env->prog = prog = new_prog; 15955 insn = new_prog->insnsi + i + delta; 15956 continue; 15957 } 15958 15959 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 15960 if (BPF_CLASS(insn->code) == BPF_LD && 15961 (BPF_MODE(insn->code) == BPF_ABS || 15962 BPF_MODE(insn->code) == BPF_IND)) { 15963 cnt = env->ops->gen_ld_abs(insn, insn_buf); 15964 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 15965 verbose(env, "bpf verifier is misconfigured\n"); 15966 return -EINVAL; 15967 } 15968 15969 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 15970 if (!new_prog) 15971 return -ENOMEM; 15972 15973 delta += cnt - 1; 15974 env->prog = prog = new_prog; 15975 insn = new_prog->insnsi + i + delta; 15976 continue; 15977 } 15978 15979 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 15980 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 15981 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 15982 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 15983 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 15984 struct bpf_insn *patch = &insn_buf[0]; 15985 bool issrc, isneg, isimm; 15986 u32 off_reg; 15987 15988 aux = &env->insn_aux_data[i + delta]; 15989 if (!aux->alu_state || 15990 aux->alu_state == BPF_ALU_NON_POINTER) 15991 continue; 15992 15993 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 15994 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 15995 BPF_ALU_SANITIZE_SRC; 15996 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 15997 15998 off_reg = issrc ? insn->src_reg : insn->dst_reg; 15999 if (isimm) { 16000 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 16001 } else { 16002 if (isneg) 16003 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 16004 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 16005 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 16006 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 16007 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 16008 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 16009 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 16010 } 16011 if (!issrc) 16012 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 16013 insn->src_reg = BPF_REG_AX; 16014 if (isneg) 16015 insn->code = insn->code == code_add ? 16016 code_sub : code_add; 16017 *patch++ = *insn; 16018 if (issrc && isneg && !isimm) 16019 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 16020 cnt = patch - insn_buf; 16021 16022 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16023 if (!new_prog) 16024 return -ENOMEM; 16025 16026 delta += cnt - 1; 16027 env->prog = prog = new_prog; 16028 insn = new_prog->insnsi + i + delta; 16029 continue; 16030 } 16031 16032 if (insn->code != (BPF_JMP | BPF_CALL)) 16033 continue; 16034 if (insn->src_reg == BPF_PSEUDO_CALL) 16035 continue; 16036 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 16037 ret = fixup_kfunc_call(env, insn, insn_buf, i + delta, &cnt); 16038 if (ret) 16039 return ret; 16040 if (cnt == 0) 16041 continue; 16042 16043 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16044 if (!new_prog) 16045 return -ENOMEM; 16046 16047 delta += cnt - 1; 16048 env->prog = prog = new_prog; 16049 insn = new_prog->insnsi + i + delta; 16050 continue; 16051 } 16052 16053 if (insn->imm == BPF_FUNC_get_route_realm) 16054 prog->dst_needed = 1; 16055 if (insn->imm == BPF_FUNC_get_prandom_u32) 16056 bpf_user_rnd_init_once(); 16057 if (insn->imm == BPF_FUNC_override_return) 16058 prog->kprobe_override = 1; 16059 if (insn->imm == BPF_FUNC_tail_call) { 16060 /* If we tail call into other programs, we 16061 * cannot make any assumptions since they can 16062 * be replaced dynamically during runtime in 16063 * the program array. 16064 */ 16065 prog->cb_access = 1; 16066 if (!allow_tail_call_in_subprogs(env)) 16067 prog->aux->stack_depth = MAX_BPF_STACK; 16068 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 16069 16070 /* mark bpf_tail_call as different opcode to avoid 16071 * conditional branch in the interpreter for every normal 16072 * call and to prevent accidental JITing by JIT compiler 16073 * that doesn't support bpf_tail_call yet 16074 */ 16075 insn->imm = 0; 16076 insn->code = BPF_JMP | BPF_TAIL_CALL; 16077 16078 aux = &env->insn_aux_data[i + delta]; 16079 if (env->bpf_capable && !prog->blinding_requested && 16080 prog->jit_requested && 16081 !bpf_map_key_poisoned(aux) && 16082 !bpf_map_ptr_poisoned(aux) && 16083 !bpf_map_ptr_unpriv(aux)) { 16084 struct bpf_jit_poke_descriptor desc = { 16085 .reason = BPF_POKE_REASON_TAIL_CALL, 16086 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 16087 .tail_call.key = bpf_map_key_immediate(aux), 16088 .insn_idx = i + delta, 16089 }; 16090 16091 ret = bpf_jit_add_poke_descriptor(prog, &desc); 16092 if (ret < 0) { 16093 verbose(env, "adding tail call poke descriptor failed\n"); 16094 return ret; 16095 } 16096 16097 insn->imm = ret + 1; 16098 continue; 16099 } 16100 16101 if (!bpf_map_ptr_unpriv(aux)) 16102 continue; 16103 16104 /* instead of changing every JIT dealing with tail_call 16105 * emit two extra insns: 16106 * if (index >= max_entries) goto out; 16107 * index &= array->index_mask; 16108 * to avoid out-of-bounds cpu speculation 16109 */ 16110 if (bpf_map_ptr_poisoned(aux)) { 16111 verbose(env, "tail_call abusing map_ptr\n"); 16112 return -EINVAL; 16113 } 16114 16115 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 16116 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 16117 map_ptr->max_entries, 2); 16118 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 16119 container_of(map_ptr, 16120 struct bpf_array, 16121 map)->index_mask); 16122 insn_buf[2] = *insn; 16123 cnt = 3; 16124 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16125 if (!new_prog) 16126 return -ENOMEM; 16127 16128 delta += cnt - 1; 16129 env->prog = prog = new_prog; 16130 insn = new_prog->insnsi + i + delta; 16131 continue; 16132 } 16133 16134 if (insn->imm == BPF_FUNC_timer_set_callback) { 16135 /* The verifier will process callback_fn as many times as necessary 16136 * with different maps and the register states prepared by 16137 * set_timer_callback_state will be accurate. 16138 * 16139 * The following use case is valid: 16140 * map1 is shared by prog1, prog2, prog3. 16141 * prog1 calls bpf_timer_init for some map1 elements 16142 * prog2 calls bpf_timer_set_callback for some map1 elements. 16143 * Those that were not bpf_timer_init-ed will return -EINVAL. 16144 * prog3 calls bpf_timer_start for some map1 elements. 16145 * Those that were not both bpf_timer_init-ed and 16146 * bpf_timer_set_callback-ed will return -EINVAL. 16147 */ 16148 struct bpf_insn ld_addrs[2] = { 16149 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 16150 }; 16151 16152 insn_buf[0] = ld_addrs[0]; 16153 insn_buf[1] = ld_addrs[1]; 16154 insn_buf[2] = *insn; 16155 cnt = 3; 16156 16157 new_prog = bpf_patch_insn_data(env, i + delta, 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 goto patch_call_imm; 16165 } 16166 16167 if (is_storage_get_function(insn->imm)) { 16168 if (!env->prog->aux->sleepable || 16169 env->insn_aux_data[i + delta].storage_get_func_atomic) 16170 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_ATOMIC); 16171 else 16172 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_5, (__force __s32)GFP_KERNEL); 16173 insn_buf[1] = *insn; 16174 cnt = 2; 16175 16176 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16177 if (!new_prog) 16178 return -ENOMEM; 16179 16180 delta += cnt - 1; 16181 env->prog = prog = new_prog; 16182 insn = new_prog->insnsi + i + delta; 16183 goto patch_call_imm; 16184 } 16185 16186 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 16187 * and other inlining handlers are currently limited to 64 bit 16188 * only. 16189 */ 16190 if (prog->jit_requested && BITS_PER_LONG == 64 && 16191 (insn->imm == BPF_FUNC_map_lookup_elem || 16192 insn->imm == BPF_FUNC_map_update_elem || 16193 insn->imm == BPF_FUNC_map_delete_elem || 16194 insn->imm == BPF_FUNC_map_push_elem || 16195 insn->imm == BPF_FUNC_map_pop_elem || 16196 insn->imm == BPF_FUNC_map_peek_elem || 16197 insn->imm == BPF_FUNC_redirect_map || 16198 insn->imm == BPF_FUNC_for_each_map_elem || 16199 insn->imm == BPF_FUNC_map_lookup_percpu_elem)) { 16200 aux = &env->insn_aux_data[i + delta]; 16201 if (bpf_map_ptr_poisoned(aux)) 16202 goto patch_call_imm; 16203 16204 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 16205 ops = map_ptr->ops; 16206 if (insn->imm == BPF_FUNC_map_lookup_elem && 16207 ops->map_gen_lookup) { 16208 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 16209 if (cnt == -EOPNOTSUPP) 16210 goto patch_map_ops_generic; 16211 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 16212 verbose(env, "bpf verifier is misconfigured\n"); 16213 return -EINVAL; 16214 } 16215 16216 new_prog = bpf_patch_insn_data(env, i + delta, 16217 insn_buf, cnt); 16218 if (!new_prog) 16219 return -ENOMEM; 16220 16221 delta += cnt - 1; 16222 env->prog = prog = new_prog; 16223 insn = new_prog->insnsi + i + delta; 16224 continue; 16225 } 16226 16227 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 16228 (void *(*)(struct bpf_map *map, void *key))NULL)); 16229 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 16230 (int (*)(struct bpf_map *map, void *key))NULL)); 16231 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 16232 (int (*)(struct bpf_map *map, void *key, void *value, 16233 u64 flags))NULL)); 16234 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 16235 (int (*)(struct bpf_map *map, void *value, 16236 u64 flags))NULL)); 16237 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 16238 (int (*)(struct bpf_map *map, void *value))NULL)); 16239 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 16240 (int (*)(struct bpf_map *map, void *value))NULL)); 16241 BUILD_BUG_ON(!__same_type(ops->map_redirect, 16242 (int (*)(struct bpf_map *map, u64 index, u64 flags))NULL)); 16243 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 16244 (int (*)(struct bpf_map *map, 16245 bpf_callback_t callback_fn, 16246 void *callback_ctx, 16247 u64 flags))NULL)); 16248 BUILD_BUG_ON(!__same_type(ops->map_lookup_percpu_elem, 16249 (void *(*)(struct bpf_map *map, void *key, u32 cpu))NULL)); 16250 16251 patch_map_ops_generic: 16252 switch (insn->imm) { 16253 case BPF_FUNC_map_lookup_elem: 16254 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 16255 continue; 16256 case BPF_FUNC_map_update_elem: 16257 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 16258 continue; 16259 case BPF_FUNC_map_delete_elem: 16260 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 16261 continue; 16262 case BPF_FUNC_map_push_elem: 16263 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 16264 continue; 16265 case BPF_FUNC_map_pop_elem: 16266 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 16267 continue; 16268 case BPF_FUNC_map_peek_elem: 16269 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 16270 continue; 16271 case BPF_FUNC_redirect_map: 16272 insn->imm = BPF_CALL_IMM(ops->map_redirect); 16273 continue; 16274 case BPF_FUNC_for_each_map_elem: 16275 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 16276 continue; 16277 case BPF_FUNC_map_lookup_percpu_elem: 16278 insn->imm = BPF_CALL_IMM(ops->map_lookup_percpu_elem); 16279 continue; 16280 } 16281 16282 goto patch_call_imm; 16283 } 16284 16285 /* Implement bpf_jiffies64 inline. */ 16286 if (prog->jit_requested && BITS_PER_LONG == 64 && 16287 insn->imm == BPF_FUNC_jiffies64) { 16288 struct bpf_insn ld_jiffies_addr[2] = { 16289 BPF_LD_IMM64(BPF_REG_0, 16290 (unsigned long)&jiffies), 16291 }; 16292 16293 insn_buf[0] = ld_jiffies_addr[0]; 16294 insn_buf[1] = ld_jiffies_addr[1]; 16295 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 16296 BPF_REG_0, 0); 16297 cnt = 3; 16298 16299 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 16300 cnt); 16301 if (!new_prog) 16302 return -ENOMEM; 16303 16304 delta += cnt - 1; 16305 env->prog = prog = new_prog; 16306 insn = new_prog->insnsi + i + delta; 16307 continue; 16308 } 16309 16310 /* Implement bpf_get_func_arg inline. */ 16311 if (prog_type == BPF_PROG_TYPE_TRACING && 16312 insn->imm == BPF_FUNC_get_func_arg) { 16313 /* Load nr_args from ctx - 8 */ 16314 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 16315 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 16316 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 16317 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 16318 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 16319 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 16320 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 16321 insn_buf[7] = BPF_JMP_A(1); 16322 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 16323 cnt = 9; 16324 16325 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16326 if (!new_prog) 16327 return -ENOMEM; 16328 16329 delta += cnt - 1; 16330 env->prog = prog = new_prog; 16331 insn = new_prog->insnsi + i + delta; 16332 continue; 16333 } 16334 16335 /* Implement bpf_get_func_ret inline. */ 16336 if (prog_type == BPF_PROG_TYPE_TRACING && 16337 insn->imm == BPF_FUNC_get_func_ret) { 16338 if (eatype == BPF_TRACE_FEXIT || 16339 eatype == BPF_MODIFY_RETURN) { 16340 /* Load nr_args from ctx - 8 */ 16341 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 16342 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 16343 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 16344 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 16345 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 16346 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 16347 cnt = 6; 16348 } else { 16349 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 16350 cnt = 1; 16351 } 16352 16353 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 16354 if (!new_prog) 16355 return -ENOMEM; 16356 16357 delta += cnt - 1; 16358 env->prog = prog = new_prog; 16359 insn = new_prog->insnsi + i + delta; 16360 continue; 16361 } 16362 16363 /* Implement get_func_arg_cnt inline. */ 16364 if (prog_type == BPF_PROG_TYPE_TRACING && 16365 insn->imm == BPF_FUNC_get_func_arg_cnt) { 16366 /* Load nr_args from ctx - 8 */ 16367 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 16368 16369 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 16370 if (!new_prog) 16371 return -ENOMEM; 16372 16373 env->prog = prog = new_prog; 16374 insn = new_prog->insnsi + i + delta; 16375 continue; 16376 } 16377 16378 /* Implement bpf_get_func_ip inline. */ 16379 if (prog_type == BPF_PROG_TYPE_TRACING && 16380 insn->imm == BPF_FUNC_get_func_ip) { 16381 /* Load IP address from ctx - 16 */ 16382 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 16383 16384 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 16385 if (!new_prog) 16386 return -ENOMEM; 16387 16388 env->prog = prog = new_prog; 16389 insn = new_prog->insnsi + i + delta; 16390 continue; 16391 } 16392 16393 patch_call_imm: 16394 fn = env->ops->get_func_proto(insn->imm, env->prog); 16395 /* all functions that have prototype and verifier allowed 16396 * programs to call them, must be real in-kernel functions 16397 */ 16398 if (!fn->func) { 16399 verbose(env, 16400 "kernel subsystem misconfigured func %s#%d\n", 16401 func_id_name(insn->imm), insn->imm); 16402 return -EFAULT; 16403 } 16404 insn->imm = fn->func - __bpf_call_base; 16405 } 16406 16407 /* Since poke tab is now finalized, publish aux to tracker. */ 16408 for (i = 0; i < prog->aux->size_poke_tab; i++) { 16409 map_ptr = prog->aux->poke_tab[i].tail_call.map; 16410 if (!map_ptr->ops->map_poke_track || 16411 !map_ptr->ops->map_poke_untrack || 16412 !map_ptr->ops->map_poke_run) { 16413 verbose(env, "bpf verifier is misconfigured\n"); 16414 return -EINVAL; 16415 } 16416 16417 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 16418 if (ret < 0) { 16419 verbose(env, "tracking tail call prog failed\n"); 16420 return ret; 16421 } 16422 } 16423 16424 sort_kfunc_descs_by_imm(env->prog); 16425 16426 return 0; 16427 } 16428 16429 static struct bpf_prog *inline_bpf_loop(struct bpf_verifier_env *env, 16430 int position, 16431 s32 stack_base, 16432 u32 callback_subprogno, 16433 u32 *cnt) 16434 { 16435 s32 r6_offset = stack_base + 0 * BPF_REG_SIZE; 16436 s32 r7_offset = stack_base + 1 * BPF_REG_SIZE; 16437 s32 r8_offset = stack_base + 2 * BPF_REG_SIZE; 16438 int reg_loop_max = BPF_REG_6; 16439 int reg_loop_cnt = BPF_REG_7; 16440 int reg_loop_ctx = BPF_REG_8; 16441 16442 struct bpf_prog *new_prog; 16443 u32 callback_start; 16444 u32 call_insn_offset; 16445 s32 callback_offset; 16446 16447 /* This represents an inlined version of bpf_iter.c:bpf_loop, 16448 * be careful to modify this code in sync. 16449 */ 16450 struct bpf_insn insn_buf[] = { 16451 /* Return error and jump to the end of the patch if 16452 * expected number of iterations is too big. 16453 */ 16454 BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2), 16455 BPF_MOV32_IMM(BPF_REG_0, -E2BIG), 16456 BPF_JMP_IMM(BPF_JA, 0, 0, 16), 16457 /* spill R6, R7, R8 to use these as loop vars */ 16458 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset), 16459 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset), 16460 BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_8, r8_offset), 16461 /* initialize loop vars */ 16462 BPF_MOV64_REG(reg_loop_max, BPF_REG_1), 16463 BPF_MOV32_IMM(reg_loop_cnt, 0), 16464 BPF_MOV64_REG(reg_loop_ctx, BPF_REG_3), 16465 /* loop header, 16466 * if reg_loop_cnt >= reg_loop_max skip the loop body 16467 */ 16468 BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5), 16469 /* callback call, 16470 * correct callback offset would be set after patching 16471 */ 16472 BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt), 16473 BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx), 16474 BPF_CALL_REL(0), 16475 /* increment loop counter */ 16476 BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1), 16477 /* jump to loop header if callback returned 0 */ 16478 BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6), 16479 /* return value of bpf_loop, 16480 * set R0 to the number of iterations 16481 */ 16482 BPF_MOV64_REG(BPF_REG_0, reg_loop_cnt), 16483 /* restore original values of R6, R7, R8 */ 16484 BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset), 16485 BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset), 16486 BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset), 16487 }; 16488 16489 *cnt = ARRAY_SIZE(insn_buf); 16490 new_prog = bpf_patch_insn_data(env, position, insn_buf, *cnt); 16491 if (!new_prog) 16492 return new_prog; 16493 16494 /* callback start is known only after patching */ 16495 callback_start = env->subprog_info[callback_subprogno].start; 16496 /* Note: insn_buf[12] is an offset of BPF_CALL_REL instruction */ 16497 call_insn_offset = position + 12; 16498 callback_offset = callback_start - call_insn_offset - 1; 16499 new_prog->insnsi[call_insn_offset].imm = callback_offset; 16500 16501 return new_prog; 16502 } 16503 16504 static bool is_bpf_loop_call(struct bpf_insn *insn) 16505 { 16506 return insn->code == (BPF_JMP | BPF_CALL) && 16507 insn->src_reg == 0 && 16508 insn->imm == BPF_FUNC_loop; 16509 } 16510 16511 /* For all sub-programs in the program (including main) check 16512 * insn_aux_data to see if there are bpf_loop calls that require 16513 * inlining. If such calls are found the calls are replaced with a 16514 * sequence of instructions produced by `inline_bpf_loop` function and 16515 * subprog stack_depth is increased by the size of 3 registers. 16516 * This stack space is used to spill values of the R6, R7, R8. These 16517 * registers are used to store the loop bound, counter and context 16518 * variables. 16519 */ 16520 static int optimize_bpf_loop(struct bpf_verifier_env *env) 16521 { 16522 struct bpf_subprog_info *subprogs = env->subprog_info; 16523 int i, cur_subprog = 0, cnt, delta = 0; 16524 struct bpf_insn *insn = env->prog->insnsi; 16525 int insn_cnt = env->prog->len; 16526 u16 stack_depth = subprogs[cur_subprog].stack_depth; 16527 u16 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 16528 u16 stack_depth_extra = 0; 16529 16530 for (i = 0; i < insn_cnt; i++, insn++) { 16531 struct bpf_loop_inline_state *inline_state = 16532 &env->insn_aux_data[i + delta].loop_inline_state; 16533 16534 if (is_bpf_loop_call(insn) && inline_state->fit_for_inline) { 16535 struct bpf_prog *new_prog; 16536 16537 stack_depth_extra = BPF_REG_SIZE * 3 + stack_depth_roundup; 16538 new_prog = inline_bpf_loop(env, 16539 i + delta, 16540 -(stack_depth + stack_depth_extra), 16541 inline_state->callback_subprogno, 16542 &cnt); 16543 if (!new_prog) 16544 return -ENOMEM; 16545 16546 delta += cnt - 1; 16547 env->prog = new_prog; 16548 insn = new_prog->insnsi + i + delta; 16549 } 16550 16551 if (subprogs[cur_subprog + 1].start == i + delta + 1) { 16552 subprogs[cur_subprog].stack_depth += stack_depth_extra; 16553 cur_subprog++; 16554 stack_depth = subprogs[cur_subprog].stack_depth; 16555 stack_depth_roundup = round_up(stack_depth, 8) - stack_depth; 16556 stack_depth_extra = 0; 16557 } 16558 } 16559 16560 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 16561 16562 return 0; 16563 } 16564 16565 static void free_states(struct bpf_verifier_env *env) 16566 { 16567 struct bpf_verifier_state_list *sl, *sln; 16568 int i; 16569 16570 sl = env->free_list; 16571 while (sl) { 16572 sln = sl->next; 16573 free_verifier_state(&sl->state, false); 16574 kfree(sl); 16575 sl = sln; 16576 } 16577 env->free_list = NULL; 16578 16579 if (!env->explored_states) 16580 return; 16581 16582 for (i = 0; i < state_htab_size(env); i++) { 16583 sl = env->explored_states[i]; 16584 16585 while (sl) { 16586 sln = sl->next; 16587 free_verifier_state(&sl->state, false); 16588 kfree(sl); 16589 sl = sln; 16590 } 16591 env->explored_states[i] = NULL; 16592 } 16593 } 16594 16595 static int do_check_common(struct bpf_verifier_env *env, int subprog) 16596 { 16597 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 16598 struct bpf_verifier_state *state; 16599 struct bpf_reg_state *regs; 16600 int ret, i; 16601 16602 env->prev_linfo = NULL; 16603 env->pass_cnt++; 16604 16605 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 16606 if (!state) 16607 return -ENOMEM; 16608 state->curframe = 0; 16609 state->speculative = false; 16610 state->branches = 1; 16611 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 16612 if (!state->frame[0]) { 16613 kfree(state); 16614 return -ENOMEM; 16615 } 16616 env->cur_state = state; 16617 init_func_state(env, state->frame[0], 16618 BPF_MAIN_FUNC /* callsite */, 16619 0 /* frameno */, 16620 subprog); 16621 state->first_insn_idx = env->subprog_info[subprog].start; 16622 state->last_insn_idx = -1; 16623 16624 regs = state->frame[state->curframe]->regs; 16625 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 16626 ret = btf_prepare_func_args(env, subprog, regs); 16627 if (ret) 16628 goto out; 16629 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 16630 if (regs[i].type == PTR_TO_CTX) 16631 mark_reg_known_zero(env, regs, i); 16632 else if (regs[i].type == SCALAR_VALUE) 16633 mark_reg_unknown(env, regs, i); 16634 else if (base_type(regs[i].type) == PTR_TO_MEM) { 16635 const u32 mem_size = regs[i].mem_size; 16636 16637 mark_reg_known_zero(env, regs, i); 16638 regs[i].mem_size = mem_size; 16639 regs[i].id = ++env->id_gen; 16640 } 16641 } 16642 } else { 16643 /* 1st arg to a function */ 16644 regs[BPF_REG_1].type = PTR_TO_CTX; 16645 mark_reg_known_zero(env, regs, BPF_REG_1); 16646 ret = btf_check_subprog_arg_match(env, subprog, regs); 16647 if (ret == -EFAULT) 16648 /* unlikely verifier bug. abort. 16649 * ret == 0 and ret < 0 are sadly acceptable for 16650 * main() function due to backward compatibility. 16651 * Like socket filter program may be written as: 16652 * int bpf_prog(struct pt_regs *ctx) 16653 * and never dereference that ctx in the program. 16654 * 'struct pt_regs' is a type mismatch for socket 16655 * filter that should be using 'struct __sk_buff'. 16656 */ 16657 goto out; 16658 } 16659 16660 ret = do_check(env); 16661 out: 16662 /* check for NULL is necessary, since cur_state can be freed inside 16663 * do_check() under memory pressure. 16664 */ 16665 if (env->cur_state) { 16666 free_verifier_state(env->cur_state, true); 16667 env->cur_state = NULL; 16668 } 16669 while (!pop_stack(env, NULL, NULL, false)); 16670 if (!ret && pop_log) 16671 bpf_vlog_reset(&env->log, 0); 16672 free_states(env); 16673 return ret; 16674 } 16675 16676 /* Verify all global functions in a BPF program one by one based on their BTF. 16677 * All global functions must pass verification. Otherwise the whole program is rejected. 16678 * Consider: 16679 * int bar(int); 16680 * int foo(int f) 16681 * { 16682 * return bar(f); 16683 * } 16684 * int bar(int b) 16685 * { 16686 * ... 16687 * } 16688 * foo() will be verified first for R1=any_scalar_value. During verification it 16689 * will be assumed that bar() already verified successfully and call to bar() 16690 * from foo() will be checked for type match only. Later bar() will be verified 16691 * independently to check that it's safe for R1=any_scalar_value. 16692 */ 16693 static int do_check_subprogs(struct bpf_verifier_env *env) 16694 { 16695 struct bpf_prog_aux *aux = env->prog->aux; 16696 int i, ret; 16697 16698 if (!aux->func_info) 16699 return 0; 16700 16701 for (i = 1; i < env->subprog_cnt; i++) { 16702 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 16703 continue; 16704 env->insn_idx = env->subprog_info[i].start; 16705 WARN_ON_ONCE(env->insn_idx == 0); 16706 ret = do_check_common(env, i); 16707 if (ret) { 16708 return ret; 16709 } else if (env->log.level & BPF_LOG_LEVEL) { 16710 verbose(env, 16711 "Func#%d is safe for any args that match its prototype\n", 16712 i); 16713 } 16714 } 16715 return 0; 16716 } 16717 16718 static int do_check_main(struct bpf_verifier_env *env) 16719 { 16720 int ret; 16721 16722 env->insn_idx = 0; 16723 ret = do_check_common(env, 0); 16724 if (!ret) 16725 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 16726 return ret; 16727 } 16728 16729 16730 static void print_verification_stats(struct bpf_verifier_env *env) 16731 { 16732 int i; 16733 16734 if (env->log.level & BPF_LOG_STATS) { 16735 verbose(env, "verification time %lld usec\n", 16736 div_u64(env->verification_time, 1000)); 16737 verbose(env, "stack depth "); 16738 for (i = 0; i < env->subprog_cnt; i++) { 16739 u32 depth = env->subprog_info[i].stack_depth; 16740 16741 verbose(env, "%d", depth); 16742 if (i + 1 < env->subprog_cnt) 16743 verbose(env, "+"); 16744 } 16745 verbose(env, "\n"); 16746 } 16747 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 16748 "total_states %d peak_states %d mark_read %d\n", 16749 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 16750 env->max_states_per_insn, env->total_states, 16751 env->peak_states, env->longest_mark_read_walk); 16752 } 16753 16754 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 16755 { 16756 const struct btf_type *t, *func_proto; 16757 const struct bpf_struct_ops *st_ops; 16758 const struct btf_member *member; 16759 struct bpf_prog *prog = env->prog; 16760 u32 btf_id, member_idx; 16761 const char *mname; 16762 16763 if (!prog->gpl_compatible) { 16764 verbose(env, "struct ops programs must have a GPL compatible license\n"); 16765 return -EINVAL; 16766 } 16767 16768 btf_id = prog->aux->attach_btf_id; 16769 st_ops = bpf_struct_ops_find(btf_id); 16770 if (!st_ops) { 16771 verbose(env, "attach_btf_id %u is not a supported struct\n", 16772 btf_id); 16773 return -ENOTSUPP; 16774 } 16775 16776 t = st_ops->type; 16777 member_idx = prog->expected_attach_type; 16778 if (member_idx >= btf_type_vlen(t)) { 16779 verbose(env, "attach to invalid member idx %u of struct %s\n", 16780 member_idx, st_ops->name); 16781 return -EINVAL; 16782 } 16783 16784 member = &btf_type_member(t)[member_idx]; 16785 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 16786 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 16787 NULL); 16788 if (!func_proto) { 16789 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 16790 mname, member_idx, st_ops->name); 16791 return -EINVAL; 16792 } 16793 16794 if (st_ops->check_member) { 16795 int err = st_ops->check_member(t, member); 16796 16797 if (err) { 16798 verbose(env, "attach to unsupported member %s of struct %s\n", 16799 mname, st_ops->name); 16800 return err; 16801 } 16802 } 16803 16804 prog->aux->attach_func_proto = func_proto; 16805 prog->aux->attach_func_name = mname; 16806 env->ops = st_ops->verifier_ops; 16807 16808 return 0; 16809 } 16810 #define SECURITY_PREFIX "security_" 16811 16812 static int check_attach_modify_return(unsigned long addr, const char *func_name) 16813 { 16814 if (within_error_injection_list(addr) || 16815 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 16816 return 0; 16817 16818 return -EINVAL; 16819 } 16820 16821 /* list of non-sleepable functions that are otherwise on 16822 * ALLOW_ERROR_INJECTION list 16823 */ 16824 BTF_SET_START(btf_non_sleepable_error_inject) 16825 /* Three functions below can be called from sleepable and non-sleepable context. 16826 * Assume non-sleepable from bpf safety point of view. 16827 */ 16828 BTF_ID(func, __filemap_add_folio) 16829 BTF_ID(func, should_fail_alloc_page) 16830 BTF_ID(func, should_failslab) 16831 BTF_SET_END(btf_non_sleepable_error_inject) 16832 16833 static int check_non_sleepable_error_inject(u32 btf_id) 16834 { 16835 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 16836 } 16837 16838 int bpf_check_attach_target(struct bpf_verifier_log *log, 16839 const struct bpf_prog *prog, 16840 const struct bpf_prog *tgt_prog, 16841 u32 btf_id, 16842 struct bpf_attach_target_info *tgt_info) 16843 { 16844 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 16845 const char prefix[] = "btf_trace_"; 16846 int ret = 0, subprog = -1, i; 16847 const struct btf_type *t; 16848 bool conservative = true; 16849 const char *tname; 16850 struct btf *btf; 16851 long addr = 0; 16852 16853 if (!btf_id) { 16854 bpf_log(log, "Tracing programs must provide btf_id\n"); 16855 return -EINVAL; 16856 } 16857 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 16858 if (!btf) { 16859 bpf_log(log, 16860 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 16861 return -EINVAL; 16862 } 16863 t = btf_type_by_id(btf, btf_id); 16864 if (!t) { 16865 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 16866 return -EINVAL; 16867 } 16868 tname = btf_name_by_offset(btf, t->name_off); 16869 if (!tname) { 16870 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 16871 return -EINVAL; 16872 } 16873 if (tgt_prog) { 16874 struct bpf_prog_aux *aux = tgt_prog->aux; 16875 16876 if (bpf_prog_is_dev_bound(prog->aux) && 16877 !bpf_prog_dev_bound_match(prog, tgt_prog)) { 16878 bpf_log(log, "Target program bound device mismatch"); 16879 return -EINVAL; 16880 } 16881 16882 for (i = 0; i < aux->func_info_cnt; i++) 16883 if (aux->func_info[i].type_id == btf_id) { 16884 subprog = i; 16885 break; 16886 } 16887 if (subprog == -1) { 16888 bpf_log(log, "Subprog %s doesn't exist\n", tname); 16889 return -EINVAL; 16890 } 16891 conservative = aux->func_info_aux[subprog].unreliable; 16892 if (prog_extension) { 16893 if (conservative) { 16894 bpf_log(log, 16895 "Cannot replace static functions\n"); 16896 return -EINVAL; 16897 } 16898 if (!prog->jit_requested) { 16899 bpf_log(log, 16900 "Extension programs should be JITed\n"); 16901 return -EINVAL; 16902 } 16903 } 16904 if (!tgt_prog->jited) { 16905 bpf_log(log, "Can attach to only JITed progs\n"); 16906 return -EINVAL; 16907 } 16908 if (tgt_prog->type == prog->type) { 16909 /* Cannot fentry/fexit another fentry/fexit program. 16910 * Cannot attach program extension to another extension. 16911 * It's ok to attach fentry/fexit to extension program. 16912 */ 16913 bpf_log(log, "Cannot recursively attach\n"); 16914 return -EINVAL; 16915 } 16916 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 16917 prog_extension && 16918 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 16919 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 16920 /* Program extensions can extend all program types 16921 * except fentry/fexit. The reason is the following. 16922 * The fentry/fexit programs are used for performance 16923 * analysis, stats and can be attached to any program 16924 * type except themselves. When extension program is 16925 * replacing XDP function it is necessary to allow 16926 * performance analysis of all functions. Both original 16927 * XDP program and its program extension. Hence 16928 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 16929 * allowed. If extending of fentry/fexit was allowed it 16930 * would be possible to create long call chain 16931 * fentry->extension->fentry->extension beyond 16932 * reasonable stack size. Hence extending fentry is not 16933 * allowed. 16934 */ 16935 bpf_log(log, "Cannot extend fentry/fexit\n"); 16936 return -EINVAL; 16937 } 16938 } else { 16939 if (prog_extension) { 16940 bpf_log(log, "Cannot replace kernel functions\n"); 16941 return -EINVAL; 16942 } 16943 } 16944 16945 switch (prog->expected_attach_type) { 16946 case BPF_TRACE_RAW_TP: 16947 if (tgt_prog) { 16948 bpf_log(log, 16949 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 16950 return -EINVAL; 16951 } 16952 if (!btf_type_is_typedef(t)) { 16953 bpf_log(log, "attach_btf_id %u is not a typedef\n", 16954 btf_id); 16955 return -EINVAL; 16956 } 16957 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 16958 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 16959 btf_id, tname); 16960 return -EINVAL; 16961 } 16962 tname += sizeof(prefix) - 1; 16963 t = btf_type_by_id(btf, t->type); 16964 if (!btf_type_is_ptr(t)) 16965 /* should never happen in valid vmlinux build */ 16966 return -EINVAL; 16967 t = btf_type_by_id(btf, t->type); 16968 if (!btf_type_is_func_proto(t)) 16969 /* should never happen in valid vmlinux build */ 16970 return -EINVAL; 16971 16972 break; 16973 case BPF_TRACE_ITER: 16974 if (!btf_type_is_func(t)) { 16975 bpf_log(log, "attach_btf_id %u is not a function\n", 16976 btf_id); 16977 return -EINVAL; 16978 } 16979 t = btf_type_by_id(btf, t->type); 16980 if (!btf_type_is_func_proto(t)) 16981 return -EINVAL; 16982 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 16983 if (ret) 16984 return ret; 16985 break; 16986 default: 16987 if (!prog_extension) 16988 return -EINVAL; 16989 fallthrough; 16990 case BPF_MODIFY_RETURN: 16991 case BPF_LSM_MAC: 16992 case BPF_LSM_CGROUP: 16993 case BPF_TRACE_FENTRY: 16994 case BPF_TRACE_FEXIT: 16995 if (!btf_type_is_func(t)) { 16996 bpf_log(log, "attach_btf_id %u is not a function\n", 16997 btf_id); 16998 return -EINVAL; 16999 } 17000 if (prog_extension && 17001 btf_check_type_match(log, prog, btf, t)) 17002 return -EINVAL; 17003 t = btf_type_by_id(btf, t->type); 17004 if (!btf_type_is_func_proto(t)) 17005 return -EINVAL; 17006 17007 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 17008 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 17009 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 17010 return -EINVAL; 17011 17012 if (tgt_prog && conservative) 17013 t = NULL; 17014 17015 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 17016 if (ret < 0) 17017 return ret; 17018 17019 if (tgt_prog) { 17020 if (subprog == 0) 17021 addr = (long) tgt_prog->bpf_func; 17022 else 17023 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 17024 } else { 17025 addr = kallsyms_lookup_name(tname); 17026 if (!addr) { 17027 bpf_log(log, 17028 "The address of function %s cannot be found\n", 17029 tname); 17030 return -ENOENT; 17031 } 17032 } 17033 17034 if (prog->aux->sleepable) { 17035 ret = -EINVAL; 17036 switch (prog->type) { 17037 case BPF_PROG_TYPE_TRACING: 17038 17039 /* fentry/fexit/fmod_ret progs can be sleepable if they are 17040 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 17041 */ 17042 if (!check_non_sleepable_error_inject(btf_id) && 17043 within_error_injection_list(addr)) 17044 ret = 0; 17045 /* fentry/fexit/fmod_ret progs can also be sleepable if they are 17046 * in the fmodret id set with the KF_SLEEPABLE flag. 17047 */ 17048 else { 17049 u32 *flags = btf_kfunc_is_modify_return(btf, btf_id); 17050 17051 if (flags && (*flags & KF_SLEEPABLE)) 17052 ret = 0; 17053 } 17054 break; 17055 case BPF_PROG_TYPE_LSM: 17056 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 17057 * Only some of them are sleepable. 17058 */ 17059 if (bpf_lsm_is_sleepable_hook(btf_id)) 17060 ret = 0; 17061 break; 17062 default: 17063 break; 17064 } 17065 if (ret) { 17066 bpf_log(log, "%s is not sleepable\n", tname); 17067 return ret; 17068 } 17069 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 17070 if (tgt_prog) { 17071 bpf_log(log, "can't modify return codes of BPF programs\n"); 17072 return -EINVAL; 17073 } 17074 ret = -EINVAL; 17075 if (btf_kfunc_is_modify_return(btf, btf_id) || 17076 !check_attach_modify_return(addr, tname)) 17077 ret = 0; 17078 if (ret) { 17079 bpf_log(log, "%s() is not modifiable\n", tname); 17080 return ret; 17081 } 17082 } 17083 17084 break; 17085 } 17086 tgt_info->tgt_addr = addr; 17087 tgt_info->tgt_name = tname; 17088 tgt_info->tgt_type = t; 17089 return 0; 17090 } 17091 17092 BTF_SET_START(btf_id_deny) 17093 BTF_ID_UNUSED 17094 #ifdef CONFIG_SMP 17095 BTF_ID(func, migrate_disable) 17096 BTF_ID(func, migrate_enable) 17097 #endif 17098 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 17099 BTF_ID(func, rcu_read_unlock_strict) 17100 #endif 17101 BTF_SET_END(btf_id_deny) 17102 17103 static bool can_be_sleepable(struct bpf_prog *prog) 17104 { 17105 if (prog->type == BPF_PROG_TYPE_TRACING) { 17106 switch (prog->expected_attach_type) { 17107 case BPF_TRACE_FENTRY: 17108 case BPF_TRACE_FEXIT: 17109 case BPF_MODIFY_RETURN: 17110 case BPF_TRACE_ITER: 17111 return true; 17112 default: 17113 return false; 17114 } 17115 } 17116 return prog->type == BPF_PROG_TYPE_LSM || 17117 prog->type == BPF_PROG_TYPE_KPROBE /* only for uprobes */ || 17118 prog->type == BPF_PROG_TYPE_STRUCT_OPS; 17119 } 17120 17121 static int check_attach_btf_id(struct bpf_verifier_env *env) 17122 { 17123 struct bpf_prog *prog = env->prog; 17124 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 17125 struct bpf_attach_target_info tgt_info = {}; 17126 u32 btf_id = prog->aux->attach_btf_id; 17127 struct bpf_trampoline *tr; 17128 int ret; 17129 u64 key; 17130 17131 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 17132 if (prog->aux->sleepable) 17133 /* attach_btf_id checked to be zero already */ 17134 return 0; 17135 verbose(env, "Syscall programs can only be sleepable\n"); 17136 return -EINVAL; 17137 } 17138 17139 if (prog->aux->sleepable && !can_be_sleepable(prog)) { 17140 verbose(env, "Only fentry/fexit/fmod_ret, lsm, iter, uprobe, and struct_ops programs can be sleepable\n"); 17141 return -EINVAL; 17142 } 17143 17144 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 17145 return check_struct_ops_btf_id(env); 17146 17147 if (prog->type != BPF_PROG_TYPE_TRACING && 17148 prog->type != BPF_PROG_TYPE_LSM && 17149 prog->type != BPF_PROG_TYPE_EXT) 17150 return 0; 17151 17152 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 17153 if (ret) 17154 return ret; 17155 17156 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 17157 /* to make freplace equivalent to their targets, they need to 17158 * inherit env->ops and expected_attach_type for the rest of the 17159 * verification 17160 */ 17161 env->ops = bpf_verifier_ops[tgt_prog->type]; 17162 prog->expected_attach_type = tgt_prog->expected_attach_type; 17163 } 17164 17165 /* store info about the attachment target that will be used later */ 17166 prog->aux->attach_func_proto = tgt_info.tgt_type; 17167 prog->aux->attach_func_name = tgt_info.tgt_name; 17168 17169 if (tgt_prog) { 17170 prog->aux->saved_dst_prog_type = tgt_prog->type; 17171 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 17172 } 17173 17174 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 17175 prog->aux->attach_btf_trace = true; 17176 return 0; 17177 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 17178 if (!bpf_iter_prog_supported(prog)) 17179 return -EINVAL; 17180 return 0; 17181 } 17182 17183 if (prog->type == BPF_PROG_TYPE_LSM) { 17184 ret = bpf_lsm_verify_prog(&env->log, prog); 17185 if (ret < 0) 17186 return ret; 17187 } else if (prog->type == BPF_PROG_TYPE_TRACING && 17188 btf_id_set_contains(&btf_id_deny, btf_id)) { 17189 return -EINVAL; 17190 } 17191 17192 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 17193 tr = bpf_trampoline_get(key, &tgt_info); 17194 if (!tr) 17195 return -ENOMEM; 17196 17197 prog->aux->dst_trampoline = tr; 17198 return 0; 17199 } 17200 17201 struct btf *bpf_get_btf_vmlinux(void) 17202 { 17203 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 17204 mutex_lock(&bpf_verifier_lock); 17205 if (!btf_vmlinux) 17206 btf_vmlinux = btf_parse_vmlinux(); 17207 mutex_unlock(&bpf_verifier_lock); 17208 } 17209 return btf_vmlinux; 17210 } 17211 17212 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr) 17213 { 17214 u64 start_time = ktime_get_ns(); 17215 struct bpf_verifier_env *env; 17216 struct bpf_verifier_log *log; 17217 int i, len, ret = -EINVAL; 17218 bool is_priv; 17219 17220 /* no program is valid */ 17221 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 17222 return -EINVAL; 17223 17224 /* 'struct bpf_verifier_env' can be global, but since it's not small, 17225 * allocate/free it every time bpf_check() is called 17226 */ 17227 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 17228 if (!env) 17229 return -ENOMEM; 17230 log = &env->log; 17231 17232 len = (*prog)->len; 17233 env->insn_aux_data = 17234 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 17235 ret = -ENOMEM; 17236 if (!env->insn_aux_data) 17237 goto err_free_env; 17238 for (i = 0; i < len; i++) 17239 env->insn_aux_data[i].orig_idx = i; 17240 env->prog = *prog; 17241 env->ops = bpf_verifier_ops[env->prog->type]; 17242 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 17243 is_priv = bpf_capable(); 17244 17245 bpf_get_btf_vmlinux(); 17246 17247 /* grab the mutex to protect few globals used by verifier */ 17248 if (!is_priv) 17249 mutex_lock(&bpf_verifier_lock); 17250 17251 if (attr->log_level || attr->log_buf || attr->log_size) { 17252 /* user requested verbose verifier output 17253 * and supplied buffer to store the verification trace 17254 */ 17255 log->level = attr->log_level; 17256 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 17257 log->len_total = attr->log_size; 17258 17259 /* log attributes have to be sane */ 17260 if (!bpf_verifier_log_attr_valid(log)) { 17261 ret = -EINVAL; 17262 goto err_unlock; 17263 } 17264 } 17265 17266 mark_verifier_state_clean(env); 17267 17268 if (IS_ERR(btf_vmlinux)) { 17269 /* Either gcc or pahole or kernel are broken. */ 17270 verbose(env, "in-kernel BTF is malformed\n"); 17271 ret = PTR_ERR(btf_vmlinux); 17272 goto skip_full_check; 17273 } 17274 17275 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 17276 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 17277 env->strict_alignment = true; 17278 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 17279 env->strict_alignment = false; 17280 17281 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 17282 env->allow_uninit_stack = bpf_allow_uninit_stack(); 17283 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 17284 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 17285 env->bpf_capable = bpf_capable(); 17286 env->rcu_tag_supported = btf_vmlinux && 17287 btf_find_by_name_kind(btf_vmlinux, "rcu", BTF_KIND_TYPE_TAG) > 0; 17288 17289 if (is_priv) 17290 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 17291 17292 env->explored_states = kvcalloc(state_htab_size(env), 17293 sizeof(struct bpf_verifier_state_list *), 17294 GFP_USER); 17295 ret = -ENOMEM; 17296 if (!env->explored_states) 17297 goto skip_full_check; 17298 17299 ret = add_subprog_and_kfunc(env); 17300 if (ret < 0) 17301 goto skip_full_check; 17302 17303 ret = check_subprogs(env); 17304 if (ret < 0) 17305 goto skip_full_check; 17306 17307 ret = check_btf_info(env, attr, uattr); 17308 if (ret < 0) 17309 goto skip_full_check; 17310 17311 ret = check_attach_btf_id(env); 17312 if (ret) 17313 goto skip_full_check; 17314 17315 ret = resolve_pseudo_ldimm64(env); 17316 if (ret < 0) 17317 goto skip_full_check; 17318 17319 if (bpf_prog_is_offloaded(env->prog->aux)) { 17320 ret = bpf_prog_offload_verifier_prep(env->prog); 17321 if (ret) 17322 goto skip_full_check; 17323 } 17324 17325 ret = check_cfg(env); 17326 if (ret < 0) 17327 goto skip_full_check; 17328 17329 ret = do_check_subprogs(env); 17330 ret = ret ?: do_check_main(env); 17331 17332 if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux)) 17333 ret = bpf_prog_offload_finalize(env); 17334 17335 skip_full_check: 17336 kvfree(env->explored_states); 17337 17338 if (ret == 0) 17339 ret = check_max_stack_depth(env); 17340 17341 /* instruction rewrites happen after this point */ 17342 if (ret == 0) 17343 ret = optimize_bpf_loop(env); 17344 17345 if (is_priv) { 17346 if (ret == 0) 17347 opt_hard_wire_dead_code_branches(env); 17348 if (ret == 0) 17349 ret = opt_remove_dead_code(env); 17350 if (ret == 0) 17351 ret = opt_remove_nops(env); 17352 } else { 17353 if (ret == 0) 17354 sanitize_dead_code(env); 17355 } 17356 17357 if (ret == 0) 17358 /* program is valid, convert *(u32*)(ctx + off) accesses */ 17359 ret = convert_ctx_accesses(env); 17360 17361 if (ret == 0) 17362 ret = do_misc_fixups(env); 17363 17364 /* do 32-bit optimization after insn patching has done so those patched 17365 * insns could be handled correctly. 17366 */ 17367 if (ret == 0 && !bpf_prog_is_offloaded(env->prog->aux)) { 17368 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 17369 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 17370 : false; 17371 } 17372 17373 if (ret == 0) 17374 ret = fixup_call_args(env); 17375 17376 env->verification_time = ktime_get_ns() - start_time; 17377 print_verification_stats(env); 17378 env->prog->aux->verified_insns = env->insn_processed; 17379 17380 if (log->level && bpf_verifier_log_full(log)) 17381 ret = -ENOSPC; 17382 if (log->level && !log->ubuf) { 17383 ret = -EFAULT; 17384 goto err_release_maps; 17385 } 17386 17387 if (ret) 17388 goto err_release_maps; 17389 17390 if (env->used_map_cnt) { 17391 /* if program passed verifier, update used_maps in bpf_prog_info */ 17392 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 17393 sizeof(env->used_maps[0]), 17394 GFP_KERNEL); 17395 17396 if (!env->prog->aux->used_maps) { 17397 ret = -ENOMEM; 17398 goto err_release_maps; 17399 } 17400 17401 memcpy(env->prog->aux->used_maps, env->used_maps, 17402 sizeof(env->used_maps[0]) * env->used_map_cnt); 17403 env->prog->aux->used_map_cnt = env->used_map_cnt; 17404 } 17405 if (env->used_btf_cnt) { 17406 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 17407 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 17408 sizeof(env->used_btfs[0]), 17409 GFP_KERNEL); 17410 if (!env->prog->aux->used_btfs) { 17411 ret = -ENOMEM; 17412 goto err_release_maps; 17413 } 17414 17415 memcpy(env->prog->aux->used_btfs, env->used_btfs, 17416 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 17417 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 17418 } 17419 if (env->used_map_cnt || env->used_btf_cnt) { 17420 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 17421 * bpf_ld_imm64 instructions 17422 */ 17423 convert_pseudo_ld_imm64(env); 17424 } 17425 17426 adjust_btf_func(env); 17427 17428 err_release_maps: 17429 if (!env->prog->aux->used_maps) 17430 /* if we didn't copy map pointers into bpf_prog_info, release 17431 * them now. Otherwise free_used_maps() will release them. 17432 */ 17433 release_maps(env); 17434 if (!env->prog->aux->used_btfs) 17435 release_btfs(env); 17436 17437 /* extension progs temporarily inherit the attach_type of their targets 17438 for verification purposes, so set it back to zero before returning 17439 */ 17440 if (env->prog->type == BPF_PROG_TYPE_EXT) 17441 env->prog->expected_attach_type = 0; 17442 17443 *prog = env->prog; 17444 err_unlock: 17445 if (!is_priv) 17446 mutex_unlock(&bpf_verifier_lock); 17447 vfree(env->insn_aux_data); 17448 err_free_env: 17449 kfree(env); 17450 return ret; 17451 } 17452