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 27 #include "disasm.h" 28 29 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 30 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 31 [_id] = & _name ## _verifier_ops, 32 #define BPF_MAP_TYPE(_id, _ops) 33 #define BPF_LINK_TYPE(_id, _name) 34 #include <linux/bpf_types.h> 35 #undef BPF_PROG_TYPE 36 #undef BPF_MAP_TYPE 37 #undef BPF_LINK_TYPE 38 }; 39 40 /* bpf_check() is a static code analyzer that walks eBPF program 41 * instruction by instruction and updates register/stack state. 42 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 43 * 44 * The first pass is depth-first-search to check that the program is a DAG. 45 * It rejects the following programs: 46 * - larger than BPF_MAXINSNS insns 47 * - if loop is present (detected via back-edge) 48 * - unreachable insns exist (shouldn't be a forest. program = one function) 49 * - out of bounds or malformed jumps 50 * The second pass is all possible path descent from the 1st insn. 51 * Since it's analyzing all paths through the program, the length of the 52 * analysis is limited to 64k insn, which may be hit even if total number of 53 * insn is less then 4K, but there are too many branches that change stack/regs. 54 * Number of 'branches to be analyzed' is limited to 1k 55 * 56 * On entry to each instruction, each register has a type, and the instruction 57 * changes the types of the registers depending on instruction semantics. 58 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 59 * copied to R1. 60 * 61 * All registers are 64-bit. 62 * R0 - return register 63 * R1-R5 argument passing registers 64 * R6-R9 callee saved registers 65 * R10 - frame pointer read-only 66 * 67 * At the start of BPF program the register R1 contains a pointer to bpf_context 68 * and has type PTR_TO_CTX. 69 * 70 * Verifier tracks arithmetic operations on pointers in case: 71 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 72 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 73 * 1st insn copies R10 (which has FRAME_PTR) type into R1 74 * and 2nd arithmetic instruction is pattern matched to recognize 75 * that it wants to construct a pointer to some element within stack. 76 * So after 2nd insn, the register R1 has type PTR_TO_STACK 77 * (and -20 constant is saved for further stack bounds checking). 78 * Meaning that this reg is a pointer to stack plus known immediate constant. 79 * 80 * Most of the time the registers have SCALAR_VALUE type, which 81 * means the register has some value, but it's not a valid pointer. 82 * (like pointer plus pointer becomes SCALAR_VALUE type) 83 * 84 * When verifier sees load or store instructions the type of base register 85 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 86 * four pointer types recognized by check_mem_access() function. 87 * 88 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 89 * and the range of [ptr, ptr + map's value_size) is accessible. 90 * 91 * registers used to pass values to function calls are checked against 92 * function argument constraints. 93 * 94 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 95 * It means that the register type passed to this function must be 96 * PTR_TO_STACK and it will be used inside the function as 97 * 'pointer to map element key' 98 * 99 * For example the argument constraints for bpf_map_lookup_elem(): 100 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 101 * .arg1_type = ARG_CONST_MAP_PTR, 102 * .arg2_type = ARG_PTR_TO_MAP_KEY, 103 * 104 * ret_type says that this function returns 'pointer to map elem value or null' 105 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 106 * 2nd argument should be a pointer to stack, which will be used inside 107 * the helper function as a pointer to map element key. 108 * 109 * On the kernel side the helper function looks like: 110 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 111 * { 112 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 113 * void *key = (void *) (unsigned long) r2; 114 * void *value; 115 * 116 * here kernel can access 'key' and 'map' pointers safely, knowing that 117 * [key, key + map->key_size) bytes are valid and were initialized on 118 * the stack of eBPF program. 119 * } 120 * 121 * Corresponding eBPF program may look like: 122 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 123 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 124 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 125 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 126 * here verifier looks at prototype of map_lookup_elem() and sees: 127 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 128 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 129 * 130 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 131 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 132 * and were initialized prior to this call. 133 * If it's ok, then verifier allows this BPF_CALL insn and looks at 134 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 135 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 136 * returns either pointer to map value or NULL. 137 * 138 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 139 * insn, the register holding that pointer in the true branch changes state to 140 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 141 * branch. See check_cond_jmp_op(). 142 * 143 * After the call R0 is set to return type of the function and registers R1-R5 144 * are set to NOT_INIT to indicate that they are no longer readable. 145 * 146 * The following reference types represent a potential reference to a kernel 147 * resource which, after first being allocated, must be checked and freed by 148 * the BPF program: 149 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 150 * 151 * When the verifier sees a helper call return a reference type, it allocates a 152 * pointer id for the reference and stores it in the current function state. 153 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 154 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 155 * passes through a NULL-check conditional. For the branch wherein the state is 156 * changed to CONST_IMM, the verifier releases the reference. 157 * 158 * For each helper function that allocates a reference, such as 159 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 160 * bpf_sk_release(). When a reference type passes into the release function, 161 * the verifier also releases the reference. If any unchecked or unreleased 162 * reference remains at the end of the program, the verifier rejects it. 163 */ 164 165 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 166 struct bpf_verifier_stack_elem { 167 /* verifer state is 'st' 168 * before processing instruction 'insn_idx' 169 * and after processing instruction 'prev_insn_idx' 170 */ 171 struct bpf_verifier_state st; 172 int insn_idx; 173 int prev_insn_idx; 174 struct bpf_verifier_stack_elem *next; 175 /* length of verifier log at the time this state was pushed on stack */ 176 u32 log_pos; 177 }; 178 179 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 180 #define BPF_COMPLEXITY_LIMIT_STATES 64 181 182 #define BPF_MAP_KEY_POISON (1ULL << 63) 183 #define BPF_MAP_KEY_SEEN (1ULL << 62) 184 185 #define BPF_MAP_PTR_UNPRIV 1UL 186 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 187 POISON_POINTER_DELTA)) 188 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 189 190 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 191 { 192 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 193 } 194 195 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 196 { 197 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 198 } 199 200 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 201 const struct bpf_map *map, bool unpriv) 202 { 203 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 204 unpriv |= bpf_map_ptr_unpriv(aux); 205 aux->map_ptr_state = (unsigned long)map | 206 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 207 } 208 209 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 210 { 211 return aux->map_key_state & BPF_MAP_KEY_POISON; 212 } 213 214 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 215 { 216 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 217 } 218 219 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 220 { 221 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 222 } 223 224 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 225 { 226 bool poisoned = bpf_map_key_poisoned(aux); 227 228 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 229 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 230 } 231 232 static bool bpf_pseudo_call(const struct bpf_insn *insn) 233 { 234 return insn->code == (BPF_JMP | BPF_CALL) && 235 insn->src_reg == BPF_PSEUDO_CALL; 236 } 237 238 static bool bpf_pseudo_kfunc_call(const struct bpf_insn *insn) 239 { 240 return insn->code == (BPF_JMP | BPF_CALL) && 241 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 242 } 243 244 struct bpf_call_arg_meta { 245 struct bpf_map *map_ptr; 246 bool raw_mode; 247 bool pkt_access; 248 int regno; 249 int access_size; 250 int mem_size; 251 u64 msize_max_value; 252 int ref_obj_id; 253 int map_uid; 254 int func_id; 255 struct btf *btf; 256 u32 btf_id; 257 struct btf *ret_btf; 258 u32 ret_btf_id; 259 u32 subprogno; 260 }; 261 262 struct btf *btf_vmlinux; 263 264 static DEFINE_MUTEX(bpf_verifier_lock); 265 266 static const struct bpf_line_info * 267 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 268 { 269 const struct bpf_line_info *linfo; 270 const struct bpf_prog *prog; 271 u32 i, nr_linfo; 272 273 prog = env->prog; 274 nr_linfo = prog->aux->nr_linfo; 275 276 if (!nr_linfo || insn_off >= prog->len) 277 return NULL; 278 279 linfo = prog->aux->linfo; 280 for (i = 1; i < nr_linfo; i++) 281 if (insn_off < linfo[i].insn_off) 282 break; 283 284 return &linfo[i - 1]; 285 } 286 287 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, 288 va_list args) 289 { 290 unsigned int n; 291 292 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); 293 294 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, 295 "verifier log line truncated - local buffer too short\n"); 296 297 if (log->level == BPF_LOG_KERNEL) { 298 bool newline = n > 0 && log->kbuf[n - 1] == '\n'; 299 300 pr_err("BPF: %s%s", log->kbuf, newline ? "" : "\n"); 301 return; 302 } 303 304 n = min(log->len_total - log->len_used - 1, n); 305 log->kbuf[n] = '\0'; 306 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) 307 log->len_used += n; 308 else 309 log->ubuf = NULL; 310 } 311 312 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos) 313 { 314 char zero = 0; 315 316 if (!bpf_verifier_log_needed(log)) 317 return; 318 319 log->len_used = new_pos; 320 if (put_user(zero, log->ubuf + new_pos)) 321 log->ubuf = NULL; 322 } 323 324 /* log_level controls verbosity level of eBPF verifier. 325 * bpf_verifier_log_write() is used to dump the verification trace to the log, 326 * so the user can figure out what's wrong with the program 327 */ 328 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 329 const char *fmt, ...) 330 { 331 va_list args; 332 333 if (!bpf_verifier_log_needed(&env->log)) 334 return; 335 336 va_start(args, fmt); 337 bpf_verifier_vlog(&env->log, fmt, args); 338 va_end(args); 339 } 340 EXPORT_SYMBOL_GPL(bpf_verifier_log_write); 341 342 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 343 { 344 struct bpf_verifier_env *env = private_data; 345 va_list args; 346 347 if (!bpf_verifier_log_needed(&env->log)) 348 return; 349 350 va_start(args, fmt); 351 bpf_verifier_vlog(&env->log, fmt, args); 352 va_end(args); 353 } 354 355 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log, 356 const char *fmt, ...) 357 { 358 va_list args; 359 360 if (!bpf_verifier_log_needed(log)) 361 return; 362 363 va_start(args, fmt); 364 bpf_verifier_vlog(log, fmt, args); 365 va_end(args); 366 } 367 368 static const char *ltrim(const char *s) 369 { 370 while (isspace(*s)) 371 s++; 372 373 return s; 374 } 375 376 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 377 u32 insn_off, 378 const char *prefix_fmt, ...) 379 { 380 const struct bpf_line_info *linfo; 381 382 if (!bpf_verifier_log_needed(&env->log)) 383 return; 384 385 linfo = find_linfo(env, insn_off); 386 if (!linfo || linfo == env->prev_linfo) 387 return; 388 389 if (prefix_fmt) { 390 va_list args; 391 392 va_start(args, prefix_fmt); 393 bpf_verifier_vlog(&env->log, prefix_fmt, args); 394 va_end(args); 395 } 396 397 verbose(env, "%s\n", 398 ltrim(btf_name_by_offset(env->prog->aux->btf, 399 linfo->line_off))); 400 401 env->prev_linfo = linfo; 402 } 403 404 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 405 struct bpf_reg_state *reg, 406 struct tnum *range, const char *ctx, 407 const char *reg_name) 408 { 409 char tn_buf[48]; 410 411 verbose(env, "At %s the register %s ", ctx, reg_name); 412 if (!tnum_is_unknown(reg->var_off)) { 413 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 414 verbose(env, "has value %s", tn_buf); 415 } else { 416 verbose(env, "has unknown scalar value"); 417 } 418 tnum_strn(tn_buf, sizeof(tn_buf), *range); 419 verbose(env, " should have been in %s\n", tn_buf); 420 } 421 422 static bool type_is_pkt_pointer(enum bpf_reg_type type) 423 { 424 return type == PTR_TO_PACKET || 425 type == PTR_TO_PACKET_META; 426 } 427 428 static bool type_is_sk_pointer(enum bpf_reg_type type) 429 { 430 return type == PTR_TO_SOCKET || 431 type == PTR_TO_SOCK_COMMON || 432 type == PTR_TO_TCP_SOCK || 433 type == PTR_TO_XDP_SOCK; 434 } 435 436 static bool reg_type_not_null(enum bpf_reg_type type) 437 { 438 return type == PTR_TO_SOCKET || 439 type == PTR_TO_TCP_SOCK || 440 type == PTR_TO_MAP_VALUE || 441 type == PTR_TO_MAP_KEY || 442 type == PTR_TO_SOCK_COMMON; 443 } 444 445 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 446 { 447 return reg->type == PTR_TO_MAP_VALUE && 448 map_value_has_spin_lock(reg->map_ptr); 449 } 450 451 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type) 452 { 453 return base_type(type) == PTR_TO_SOCKET || 454 base_type(type) == PTR_TO_TCP_SOCK || 455 base_type(type) == PTR_TO_MEM; 456 } 457 458 static bool type_is_rdonly_mem(u32 type) 459 { 460 return type & MEM_RDONLY; 461 } 462 463 static bool arg_type_may_be_refcounted(enum bpf_arg_type type) 464 { 465 return type == ARG_PTR_TO_SOCK_COMMON; 466 } 467 468 static bool type_may_be_null(u32 type) 469 { 470 return type & PTR_MAYBE_NULL; 471 } 472 473 /* Determine whether the function releases some resources allocated by another 474 * function call. The first reference type argument will be assumed to be 475 * released by release_reference(). 476 */ 477 static bool is_release_function(enum bpf_func_id func_id) 478 { 479 return func_id == BPF_FUNC_sk_release || 480 func_id == BPF_FUNC_ringbuf_submit || 481 func_id == BPF_FUNC_ringbuf_discard; 482 } 483 484 static bool may_be_acquire_function(enum bpf_func_id func_id) 485 { 486 return func_id == BPF_FUNC_sk_lookup_tcp || 487 func_id == BPF_FUNC_sk_lookup_udp || 488 func_id == BPF_FUNC_skc_lookup_tcp || 489 func_id == BPF_FUNC_map_lookup_elem || 490 func_id == BPF_FUNC_ringbuf_reserve; 491 } 492 493 static bool is_acquire_function(enum bpf_func_id func_id, 494 const struct bpf_map *map) 495 { 496 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 497 498 if (func_id == BPF_FUNC_sk_lookup_tcp || 499 func_id == BPF_FUNC_sk_lookup_udp || 500 func_id == BPF_FUNC_skc_lookup_tcp || 501 func_id == BPF_FUNC_ringbuf_reserve) 502 return true; 503 504 if (func_id == BPF_FUNC_map_lookup_elem && 505 (map_type == BPF_MAP_TYPE_SOCKMAP || 506 map_type == BPF_MAP_TYPE_SOCKHASH)) 507 return true; 508 509 return false; 510 } 511 512 static bool is_ptr_cast_function(enum bpf_func_id func_id) 513 { 514 return func_id == BPF_FUNC_tcp_sock || 515 func_id == BPF_FUNC_sk_fullsock || 516 func_id == BPF_FUNC_skc_to_tcp_sock || 517 func_id == BPF_FUNC_skc_to_tcp6_sock || 518 func_id == BPF_FUNC_skc_to_udp6_sock || 519 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 520 func_id == BPF_FUNC_skc_to_tcp_request_sock; 521 } 522 523 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 524 { 525 return BPF_CLASS(insn->code) == BPF_STX && 526 BPF_MODE(insn->code) == BPF_ATOMIC && 527 insn->imm == BPF_CMPXCHG; 528 } 529 530 /* string representation of 'enum bpf_reg_type' 531 * 532 * Note that reg_type_str() can not appear more than once in a single verbose() 533 * statement. 534 */ 535 static const char *reg_type_str(struct bpf_verifier_env *env, 536 enum bpf_reg_type type) 537 { 538 char postfix[16] = {0}, prefix[16] = {0}; 539 static const char * const str[] = { 540 [NOT_INIT] = "?", 541 [SCALAR_VALUE] = "inv", 542 [PTR_TO_CTX] = "ctx", 543 [CONST_PTR_TO_MAP] = "map_ptr", 544 [PTR_TO_MAP_VALUE] = "map_value", 545 [PTR_TO_STACK] = "fp", 546 [PTR_TO_PACKET] = "pkt", 547 [PTR_TO_PACKET_META] = "pkt_meta", 548 [PTR_TO_PACKET_END] = "pkt_end", 549 [PTR_TO_FLOW_KEYS] = "flow_keys", 550 [PTR_TO_SOCKET] = "sock", 551 [PTR_TO_SOCK_COMMON] = "sock_common", 552 [PTR_TO_TCP_SOCK] = "tcp_sock", 553 [PTR_TO_TP_BUFFER] = "tp_buffer", 554 [PTR_TO_XDP_SOCK] = "xdp_sock", 555 [PTR_TO_BTF_ID] = "ptr_", 556 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_", 557 [PTR_TO_MEM] = "mem", 558 [PTR_TO_BUF] = "buf", 559 [PTR_TO_FUNC] = "func", 560 [PTR_TO_MAP_KEY] = "map_key", 561 }; 562 563 if (type & PTR_MAYBE_NULL) { 564 if (base_type(type) == PTR_TO_BTF_ID || 565 base_type(type) == PTR_TO_PERCPU_BTF_ID) 566 strncpy(postfix, "or_null_", 16); 567 else 568 strncpy(postfix, "_or_null", 16); 569 } 570 571 if (type & MEM_RDONLY) 572 strncpy(prefix, "rdonly_", 16); 573 574 snprintf(env->type_str_buf, TYPE_STR_BUF_LEN, "%s%s%s", 575 prefix, str[base_type(type)], postfix); 576 return env->type_str_buf; 577 } 578 579 static char slot_type_char[] = { 580 [STACK_INVALID] = '?', 581 [STACK_SPILL] = 'r', 582 [STACK_MISC] = 'm', 583 [STACK_ZERO] = '0', 584 }; 585 586 static void print_liveness(struct bpf_verifier_env *env, 587 enum bpf_reg_liveness live) 588 { 589 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 590 verbose(env, "_"); 591 if (live & REG_LIVE_READ) 592 verbose(env, "r"); 593 if (live & REG_LIVE_WRITTEN) 594 verbose(env, "w"); 595 if (live & REG_LIVE_DONE) 596 verbose(env, "D"); 597 } 598 599 static struct bpf_func_state *func(struct bpf_verifier_env *env, 600 const struct bpf_reg_state *reg) 601 { 602 struct bpf_verifier_state *cur = env->cur_state; 603 604 return cur->frame[reg->frameno]; 605 } 606 607 static const char *kernel_type_name(const struct btf* btf, u32 id) 608 { 609 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 610 } 611 612 static void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno) 613 { 614 env->scratched_regs |= 1U << regno; 615 } 616 617 static void mark_stack_slot_scratched(struct bpf_verifier_env *env, u32 spi) 618 { 619 env->scratched_stack_slots |= 1UL << spi; 620 } 621 622 static bool reg_scratched(const struct bpf_verifier_env *env, u32 regno) 623 { 624 return (env->scratched_regs >> regno) & 1; 625 } 626 627 static bool stack_slot_scratched(const struct bpf_verifier_env *env, u64 regno) 628 { 629 return (env->scratched_stack_slots >> regno) & 1; 630 } 631 632 static bool verifier_state_scratched(const struct bpf_verifier_env *env) 633 { 634 return env->scratched_regs || env->scratched_stack_slots; 635 } 636 637 static void mark_verifier_state_clean(struct bpf_verifier_env *env) 638 { 639 env->scratched_regs = 0U; 640 env->scratched_stack_slots = 0UL; 641 } 642 643 /* Used for printing the entire verifier state. */ 644 static void mark_verifier_state_scratched(struct bpf_verifier_env *env) 645 { 646 env->scratched_regs = ~0U; 647 env->scratched_stack_slots = ~0UL; 648 } 649 650 /* The reg state of a pointer or a bounded scalar was saved when 651 * it was spilled to the stack. 652 */ 653 static bool is_spilled_reg(const struct bpf_stack_state *stack) 654 { 655 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 656 } 657 658 static void scrub_spilled_slot(u8 *stype) 659 { 660 if (*stype != STACK_INVALID) 661 *stype = STACK_MISC; 662 } 663 664 static void print_verifier_state(struct bpf_verifier_env *env, 665 const struct bpf_func_state *state, 666 bool print_all) 667 { 668 const struct bpf_reg_state *reg; 669 enum bpf_reg_type t; 670 int i; 671 672 if (state->frameno) 673 verbose(env, " frame%d:", state->frameno); 674 for (i = 0; i < MAX_BPF_REG; i++) { 675 reg = &state->regs[i]; 676 t = reg->type; 677 if (t == NOT_INIT) 678 continue; 679 if (!print_all && !reg_scratched(env, i)) 680 continue; 681 verbose(env, " R%d", i); 682 print_liveness(env, reg->live); 683 verbose(env, "=%s", reg_type_str(env, t)); 684 if (t == SCALAR_VALUE && reg->precise) 685 verbose(env, "P"); 686 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 687 tnum_is_const(reg->var_off)) { 688 /* reg->off should be 0 for SCALAR_VALUE */ 689 verbose(env, "%lld", reg->var_off.value + reg->off); 690 } else { 691 if (base_type(t) == PTR_TO_BTF_ID || 692 base_type(t) == PTR_TO_PERCPU_BTF_ID) 693 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id)); 694 verbose(env, "(id=%d", reg->id); 695 if (reg_type_may_be_refcounted_or_null(t)) 696 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id); 697 if (t != SCALAR_VALUE) 698 verbose(env, ",off=%d", reg->off); 699 if (type_is_pkt_pointer(t)) 700 verbose(env, ",r=%d", reg->range); 701 else if (base_type(t) == CONST_PTR_TO_MAP || 702 base_type(t) == PTR_TO_MAP_KEY || 703 base_type(t) == PTR_TO_MAP_VALUE) 704 verbose(env, ",ks=%d,vs=%d", 705 reg->map_ptr->key_size, 706 reg->map_ptr->value_size); 707 if (tnum_is_const(reg->var_off)) { 708 /* Typically an immediate SCALAR_VALUE, but 709 * could be a pointer whose offset is too big 710 * for reg->off 711 */ 712 verbose(env, ",imm=%llx", reg->var_off.value); 713 } else { 714 if (reg->smin_value != reg->umin_value && 715 reg->smin_value != S64_MIN) 716 verbose(env, ",smin_value=%lld", 717 (long long)reg->smin_value); 718 if (reg->smax_value != reg->umax_value && 719 reg->smax_value != S64_MAX) 720 verbose(env, ",smax_value=%lld", 721 (long long)reg->smax_value); 722 if (reg->umin_value != 0) 723 verbose(env, ",umin_value=%llu", 724 (unsigned long long)reg->umin_value); 725 if (reg->umax_value != U64_MAX) 726 verbose(env, ",umax_value=%llu", 727 (unsigned long long)reg->umax_value); 728 if (!tnum_is_unknown(reg->var_off)) { 729 char tn_buf[48]; 730 731 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 732 verbose(env, ",var_off=%s", tn_buf); 733 } 734 if (reg->s32_min_value != reg->smin_value && 735 reg->s32_min_value != S32_MIN) 736 verbose(env, ",s32_min_value=%d", 737 (int)(reg->s32_min_value)); 738 if (reg->s32_max_value != reg->smax_value && 739 reg->s32_max_value != S32_MAX) 740 verbose(env, ",s32_max_value=%d", 741 (int)(reg->s32_max_value)); 742 if (reg->u32_min_value != reg->umin_value && 743 reg->u32_min_value != U32_MIN) 744 verbose(env, ",u32_min_value=%d", 745 (int)(reg->u32_min_value)); 746 if (reg->u32_max_value != reg->umax_value && 747 reg->u32_max_value != U32_MAX) 748 verbose(env, ",u32_max_value=%d", 749 (int)(reg->u32_max_value)); 750 } 751 verbose(env, ")"); 752 } 753 } 754 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 755 char types_buf[BPF_REG_SIZE + 1]; 756 bool valid = false; 757 int j; 758 759 for (j = 0; j < BPF_REG_SIZE; j++) { 760 if (state->stack[i].slot_type[j] != STACK_INVALID) 761 valid = true; 762 types_buf[j] = slot_type_char[ 763 state->stack[i].slot_type[j]]; 764 } 765 types_buf[BPF_REG_SIZE] = 0; 766 if (!valid) 767 continue; 768 if (!print_all && !stack_slot_scratched(env, i)) 769 continue; 770 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 771 print_liveness(env, state->stack[i].spilled_ptr.live); 772 if (is_spilled_reg(&state->stack[i])) { 773 reg = &state->stack[i].spilled_ptr; 774 t = reg->type; 775 verbose(env, "=%s", reg_type_str(env, t)); 776 if (t == SCALAR_VALUE && reg->precise) 777 verbose(env, "P"); 778 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 779 verbose(env, "%lld", reg->var_off.value + reg->off); 780 } else { 781 verbose(env, "=%s", types_buf); 782 } 783 } 784 if (state->acquired_refs && state->refs[0].id) { 785 verbose(env, " refs=%d", state->refs[0].id); 786 for (i = 1; i < state->acquired_refs; i++) 787 if (state->refs[i].id) 788 verbose(env, ",%d", state->refs[i].id); 789 } 790 if (state->in_callback_fn) 791 verbose(env, " cb"); 792 if (state->in_async_callback_fn) 793 verbose(env, " async_cb"); 794 verbose(env, "\n"); 795 mark_verifier_state_clean(env); 796 } 797 798 static inline u32 vlog_alignment(u32 pos) 799 { 800 return round_up(max(pos + BPF_LOG_MIN_ALIGNMENT / 2, BPF_LOG_ALIGNMENT), 801 BPF_LOG_MIN_ALIGNMENT) - pos - 1; 802 } 803 804 static void print_insn_state(struct bpf_verifier_env *env, 805 const struct bpf_func_state *state) 806 { 807 if (env->prev_log_len && env->prev_log_len == env->log.len_used) { 808 /* remove new line character */ 809 bpf_vlog_reset(&env->log, env->prev_log_len - 1); 810 verbose(env, "%*c;", vlog_alignment(env->prev_insn_print_len), ' '); 811 } else { 812 verbose(env, "%d:", env->insn_idx); 813 } 814 print_verifier_state(env, state, false); 815 } 816 817 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 818 * small to hold src. This is different from krealloc since we don't want to preserve 819 * the contents of dst. 820 * 821 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 822 * not be allocated. 823 */ 824 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 825 { 826 size_t bytes; 827 828 if (ZERO_OR_NULL_PTR(src)) 829 goto out; 830 831 if (unlikely(check_mul_overflow(n, size, &bytes))) 832 return NULL; 833 834 if (ksize(dst) < bytes) { 835 kfree(dst); 836 dst = kmalloc_track_caller(bytes, flags); 837 if (!dst) 838 return NULL; 839 } 840 841 memcpy(dst, src, bytes); 842 out: 843 return dst ? dst : ZERO_SIZE_PTR; 844 } 845 846 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 847 * small to hold new_n items. new items are zeroed out if the array grows. 848 * 849 * Contrary to krealloc_array, does not free arr if new_n is zero. 850 */ 851 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 852 { 853 if (!new_n || old_n == new_n) 854 goto out; 855 856 arr = krealloc_array(arr, new_n, size, GFP_KERNEL); 857 if (!arr) 858 return NULL; 859 860 if (new_n > old_n) 861 memset(arr + old_n * size, 0, (new_n - old_n) * size); 862 863 out: 864 return arr ? arr : ZERO_SIZE_PTR; 865 } 866 867 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 868 { 869 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 870 sizeof(struct bpf_reference_state), GFP_KERNEL); 871 if (!dst->refs) 872 return -ENOMEM; 873 874 dst->acquired_refs = src->acquired_refs; 875 return 0; 876 } 877 878 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 879 { 880 size_t n = src->allocated_stack / BPF_REG_SIZE; 881 882 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 883 GFP_KERNEL); 884 if (!dst->stack) 885 return -ENOMEM; 886 887 dst->allocated_stack = src->allocated_stack; 888 return 0; 889 } 890 891 static int resize_reference_state(struct bpf_func_state *state, size_t n) 892 { 893 state->refs = realloc_array(state->refs, state->acquired_refs, n, 894 sizeof(struct bpf_reference_state)); 895 if (!state->refs) 896 return -ENOMEM; 897 898 state->acquired_refs = n; 899 return 0; 900 } 901 902 static int grow_stack_state(struct bpf_func_state *state, int size) 903 { 904 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 905 906 if (old_n >= n) 907 return 0; 908 909 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 910 if (!state->stack) 911 return -ENOMEM; 912 913 state->allocated_stack = size; 914 return 0; 915 } 916 917 /* Acquire a pointer id from the env and update the state->refs to include 918 * this new pointer reference. 919 * On success, returns a valid pointer id to associate with the register 920 * On failure, returns a negative errno. 921 */ 922 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 923 { 924 struct bpf_func_state *state = cur_func(env); 925 int new_ofs = state->acquired_refs; 926 int id, err; 927 928 err = resize_reference_state(state, state->acquired_refs + 1); 929 if (err) 930 return err; 931 id = ++env->id_gen; 932 state->refs[new_ofs].id = id; 933 state->refs[new_ofs].insn_idx = insn_idx; 934 935 return id; 936 } 937 938 /* release function corresponding to acquire_reference_state(). Idempotent. */ 939 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 940 { 941 int i, last_idx; 942 943 last_idx = state->acquired_refs - 1; 944 for (i = 0; i < state->acquired_refs; i++) { 945 if (state->refs[i].id == ptr_id) { 946 if (last_idx && i != last_idx) 947 memcpy(&state->refs[i], &state->refs[last_idx], 948 sizeof(*state->refs)); 949 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 950 state->acquired_refs--; 951 return 0; 952 } 953 } 954 return -EINVAL; 955 } 956 957 static void free_func_state(struct bpf_func_state *state) 958 { 959 if (!state) 960 return; 961 kfree(state->refs); 962 kfree(state->stack); 963 kfree(state); 964 } 965 966 static void clear_jmp_history(struct bpf_verifier_state *state) 967 { 968 kfree(state->jmp_history); 969 state->jmp_history = NULL; 970 state->jmp_history_cnt = 0; 971 } 972 973 static void free_verifier_state(struct bpf_verifier_state *state, 974 bool free_self) 975 { 976 int i; 977 978 for (i = 0; i <= state->curframe; i++) { 979 free_func_state(state->frame[i]); 980 state->frame[i] = NULL; 981 } 982 clear_jmp_history(state); 983 if (free_self) 984 kfree(state); 985 } 986 987 /* copy verifier state from src to dst growing dst stack space 988 * when necessary to accommodate larger src stack 989 */ 990 static int copy_func_state(struct bpf_func_state *dst, 991 const struct bpf_func_state *src) 992 { 993 int err; 994 995 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 996 err = copy_reference_state(dst, src); 997 if (err) 998 return err; 999 return copy_stack_state(dst, src); 1000 } 1001 1002 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 1003 const struct bpf_verifier_state *src) 1004 { 1005 struct bpf_func_state *dst; 1006 int i, err; 1007 1008 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 1009 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 1010 GFP_USER); 1011 if (!dst_state->jmp_history) 1012 return -ENOMEM; 1013 dst_state->jmp_history_cnt = src->jmp_history_cnt; 1014 1015 /* if dst has more stack frames then src frame, free them */ 1016 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 1017 free_func_state(dst_state->frame[i]); 1018 dst_state->frame[i] = NULL; 1019 } 1020 dst_state->speculative = src->speculative; 1021 dst_state->curframe = src->curframe; 1022 dst_state->active_spin_lock = src->active_spin_lock; 1023 dst_state->branches = src->branches; 1024 dst_state->parent = src->parent; 1025 dst_state->first_insn_idx = src->first_insn_idx; 1026 dst_state->last_insn_idx = src->last_insn_idx; 1027 for (i = 0; i <= src->curframe; i++) { 1028 dst = dst_state->frame[i]; 1029 if (!dst) { 1030 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 1031 if (!dst) 1032 return -ENOMEM; 1033 dst_state->frame[i] = dst; 1034 } 1035 err = copy_func_state(dst, src->frame[i]); 1036 if (err) 1037 return err; 1038 } 1039 return 0; 1040 } 1041 1042 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1043 { 1044 while (st) { 1045 u32 br = --st->branches; 1046 1047 /* WARN_ON(br > 1) technically makes sense here, 1048 * but see comment in push_stack(), hence: 1049 */ 1050 WARN_ONCE((int)br < 0, 1051 "BUG update_branch_counts:branches_to_explore=%d\n", 1052 br); 1053 if (br) 1054 break; 1055 st = st->parent; 1056 } 1057 } 1058 1059 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1060 int *insn_idx, bool pop_log) 1061 { 1062 struct bpf_verifier_state *cur = env->cur_state; 1063 struct bpf_verifier_stack_elem *elem, *head = env->head; 1064 int err; 1065 1066 if (env->head == NULL) 1067 return -ENOENT; 1068 1069 if (cur) { 1070 err = copy_verifier_state(cur, &head->st); 1071 if (err) 1072 return err; 1073 } 1074 if (pop_log) 1075 bpf_vlog_reset(&env->log, head->log_pos); 1076 if (insn_idx) 1077 *insn_idx = head->insn_idx; 1078 if (prev_insn_idx) 1079 *prev_insn_idx = head->prev_insn_idx; 1080 elem = head->next; 1081 free_verifier_state(&head->st, false); 1082 kfree(head); 1083 env->head = elem; 1084 env->stack_size--; 1085 return 0; 1086 } 1087 1088 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1089 int insn_idx, int prev_insn_idx, 1090 bool speculative) 1091 { 1092 struct bpf_verifier_state *cur = env->cur_state; 1093 struct bpf_verifier_stack_elem *elem; 1094 int err; 1095 1096 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1097 if (!elem) 1098 goto err; 1099 1100 elem->insn_idx = insn_idx; 1101 elem->prev_insn_idx = prev_insn_idx; 1102 elem->next = env->head; 1103 elem->log_pos = env->log.len_used; 1104 env->head = elem; 1105 env->stack_size++; 1106 err = copy_verifier_state(&elem->st, cur); 1107 if (err) 1108 goto err; 1109 elem->st.speculative |= speculative; 1110 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1111 verbose(env, "The sequence of %d jumps is too complex.\n", 1112 env->stack_size); 1113 goto err; 1114 } 1115 if (elem->st.parent) { 1116 ++elem->st.parent->branches; 1117 /* WARN_ON(branches > 2) technically makes sense here, 1118 * but 1119 * 1. speculative states will bump 'branches' for non-branch 1120 * instructions 1121 * 2. is_state_visited() heuristics may decide not to create 1122 * a new state for a sequence of branches and all such current 1123 * and cloned states will be pointing to a single parent state 1124 * which might have large 'branches' count. 1125 */ 1126 } 1127 return &elem->st; 1128 err: 1129 free_verifier_state(env->cur_state, true); 1130 env->cur_state = NULL; 1131 /* pop all elements and return */ 1132 while (!pop_stack(env, NULL, NULL, false)); 1133 return NULL; 1134 } 1135 1136 #define CALLER_SAVED_REGS 6 1137 static const int caller_saved[CALLER_SAVED_REGS] = { 1138 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1139 }; 1140 1141 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1142 struct bpf_reg_state *reg); 1143 1144 /* This helper doesn't clear reg->id */ 1145 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1146 { 1147 reg->var_off = tnum_const(imm); 1148 reg->smin_value = (s64)imm; 1149 reg->smax_value = (s64)imm; 1150 reg->umin_value = imm; 1151 reg->umax_value = imm; 1152 1153 reg->s32_min_value = (s32)imm; 1154 reg->s32_max_value = (s32)imm; 1155 reg->u32_min_value = (u32)imm; 1156 reg->u32_max_value = (u32)imm; 1157 } 1158 1159 /* Mark the unknown part of a register (variable offset or scalar value) as 1160 * known to have the value @imm. 1161 */ 1162 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1163 { 1164 /* Clear id, off, and union(map_ptr, range) */ 1165 memset(((u8 *)reg) + sizeof(reg->type), 0, 1166 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1167 ___mark_reg_known(reg, imm); 1168 } 1169 1170 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1171 { 1172 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1173 reg->s32_min_value = (s32)imm; 1174 reg->s32_max_value = (s32)imm; 1175 reg->u32_min_value = (u32)imm; 1176 reg->u32_max_value = (u32)imm; 1177 } 1178 1179 /* Mark the 'variable offset' part of a register as zero. This should be 1180 * used only on registers holding a pointer type. 1181 */ 1182 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1183 { 1184 __mark_reg_known(reg, 0); 1185 } 1186 1187 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1188 { 1189 __mark_reg_known(reg, 0); 1190 reg->type = SCALAR_VALUE; 1191 } 1192 1193 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1194 struct bpf_reg_state *regs, u32 regno) 1195 { 1196 if (WARN_ON(regno >= MAX_BPF_REG)) { 1197 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1198 /* Something bad happened, let's kill all regs */ 1199 for (regno = 0; regno < MAX_BPF_REG; regno++) 1200 __mark_reg_not_init(env, regs + regno); 1201 return; 1202 } 1203 __mark_reg_known_zero(regs + regno); 1204 } 1205 1206 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1207 { 1208 if (base_type(reg->type) == PTR_TO_MAP_VALUE) { 1209 const struct bpf_map *map = reg->map_ptr; 1210 1211 if (map->inner_map_meta) { 1212 reg->type = CONST_PTR_TO_MAP; 1213 reg->map_ptr = map->inner_map_meta; 1214 /* transfer reg's id which is unique for every map_lookup_elem 1215 * as UID of the inner map. 1216 */ 1217 if (map_value_has_timer(map->inner_map_meta)) 1218 reg->map_uid = reg->id; 1219 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1220 reg->type = PTR_TO_XDP_SOCK; 1221 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1222 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1223 reg->type = PTR_TO_SOCKET; 1224 } else { 1225 reg->type = PTR_TO_MAP_VALUE; 1226 } 1227 return; 1228 } 1229 1230 reg->type &= ~PTR_MAYBE_NULL; 1231 } 1232 1233 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1234 { 1235 return type_is_pkt_pointer(reg->type); 1236 } 1237 1238 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1239 { 1240 return reg_is_pkt_pointer(reg) || 1241 reg->type == PTR_TO_PACKET_END; 1242 } 1243 1244 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1245 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1246 enum bpf_reg_type which) 1247 { 1248 /* The register can already have a range from prior markings. 1249 * This is fine as long as it hasn't been advanced from its 1250 * origin. 1251 */ 1252 return reg->type == which && 1253 reg->id == 0 && 1254 reg->off == 0 && 1255 tnum_equals_const(reg->var_off, 0); 1256 } 1257 1258 /* Reset the min/max bounds of a register */ 1259 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1260 { 1261 reg->smin_value = S64_MIN; 1262 reg->smax_value = S64_MAX; 1263 reg->umin_value = 0; 1264 reg->umax_value = U64_MAX; 1265 1266 reg->s32_min_value = S32_MIN; 1267 reg->s32_max_value = S32_MAX; 1268 reg->u32_min_value = 0; 1269 reg->u32_max_value = U32_MAX; 1270 } 1271 1272 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1273 { 1274 reg->smin_value = S64_MIN; 1275 reg->smax_value = S64_MAX; 1276 reg->umin_value = 0; 1277 reg->umax_value = U64_MAX; 1278 } 1279 1280 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1281 { 1282 reg->s32_min_value = S32_MIN; 1283 reg->s32_max_value = S32_MAX; 1284 reg->u32_min_value = 0; 1285 reg->u32_max_value = U32_MAX; 1286 } 1287 1288 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1289 { 1290 struct tnum var32_off = tnum_subreg(reg->var_off); 1291 1292 /* min signed is max(sign bit) | min(other bits) */ 1293 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1294 var32_off.value | (var32_off.mask & S32_MIN)); 1295 /* max signed is min(sign bit) | max(other bits) */ 1296 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1297 var32_off.value | (var32_off.mask & S32_MAX)); 1298 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1299 reg->u32_max_value = min(reg->u32_max_value, 1300 (u32)(var32_off.value | var32_off.mask)); 1301 } 1302 1303 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1304 { 1305 /* min signed is max(sign bit) | min(other bits) */ 1306 reg->smin_value = max_t(s64, reg->smin_value, 1307 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1308 /* max signed is min(sign bit) | max(other bits) */ 1309 reg->smax_value = min_t(s64, reg->smax_value, 1310 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1311 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1312 reg->umax_value = min(reg->umax_value, 1313 reg->var_off.value | reg->var_off.mask); 1314 } 1315 1316 static void __update_reg_bounds(struct bpf_reg_state *reg) 1317 { 1318 __update_reg32_bounds(reg); 1319 __update_reg64_bounds(reg); 1320 } 1321 1322 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1323 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1324 { 1325 /* Learn sign from signed bounds. 1326 * If we cannot cross the sign boundary, then signed and unsigned bounds 1327 * are the same, so combine. This works even in the negative case, e.g. 1328 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1329 */ 1330 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 1331 reg->s32_min_value = reg->u32_min_value = 1332 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1333 reg->s32_max_value = reg->u32_max_value = 1334 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1335 return; 1336 } 1337 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1338 * boundary, so we must be careful. 1339 */ 1340 if ((s32)reg->u32_max_value >= 0) { 1341 /* Positive. We can't learn anything from the smin, but smax 1342 * is positive, hence safe. 1343 */ 1344 reg->s32_min_value = reg->u32_min_value; 1345 reg->s32_max_value = reg->u32_max_value = 1346 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1347 } else if ((s32)reg->u32_min_value < 0) { 1348 /* Negative. We can't learn anything from the smax, but smin 1349 * is negative, hence safe. 1350 */ 1351 reg->s32_min_value = reg->u32_min_value = 1352 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1353 reg->s32_max_value = reg->u32_max_value; 1354 } 1355 } 1356 1357 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 1358 { 1359 /* Learn sign from signed bounds. 1360 * If we cannot cross the sign boundary, then signed and unsigned bounds 1361 * are the same, so combine. This works even in the negative case, e.g. 1362 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1363 */ 1364 if (reg->smin_value >= 0 || reg->smax_value < 0) { 1365 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1366 reg->umin_value); 1367 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1368 reg->umax_value); 1369 return; 1370 } 1371 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1372 * boundary, so we must be careful. 1373 */ 1374 if ((s64)reg->umax_value >= 0) { 1375 /* Positive. We can't learn anything from the smin, but smax 1376 * is positive, hence safe. 1377 */ 1378 reg->smin_value = reg->umin_value; 1379 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1380 reg->umax_value); 1381 } else if ((s64)reg->umin_value < 0) { 1382 /* Negative. We can't learn anything from the smax, but smin 1383 * is negative, hence safe. 1384 */ 1385 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1386 reg->umin_value); 1387 reg->smax_value = reg->umax_value; 1388 } 1389 } 1390 1391 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 1392 { 1393 __reg32_deduce_bounds(reg); 1394 __reg64_deduce_bounds(reg); 1395 } 1396 1397 /* Attempts to improve var_off based on unsigned min/max information */ 1398 static void __reg_bound_offset(struct bpf_reg_state *reg) 1399 { 1400 struct tnum var64_off = tnum_intersect(reg->var_off, 1401 tnum_range(reg->umin_value, 1402 reg->umax_value)); 1403 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off), 1404 tnum_range(reg->u32_min_value, 1405 reg->u32_max_value)); 1406 1407 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 1408 } 1409 1410 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 1411 { 1412 reg->umin_value = reg->u32_min_value; 1413 reg->umax_value = reg->u32_max_value; 1414 /* Attempt to pull 32-bit signed bounds into 64-bit bounds 1415 * but must be positive otherwise set to worse case bounds 1416 * and refine later from tnum. 1417 */ 1418 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0) 1419 reg->smax_value = reg->s32_max_value; 1420 else 1421 reg->smax_value = U32_MAX; 1422 if (reg->s32_min_value >= 0) 1423 reg->smin_value = reg->s32_min_value; 1424 else 1425 reg->smin_value = 0; 1426 } 1427 1428 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 1429 { 1430 /* special case when 64-bit register has upper 32-bit register 1431 * zeroed. Typically happens after zext or <<32, >>32 sequence 1432 * allowing us to use 32-bit bounds directly, 1433 */ 1434 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 1435 __reg_assign_32_into_64(reg); 1436 } else { 1437 /* Otherwise the best we can do is push lower 32bit known and 1438 * unknown bits into register (var_off set from jmp logic) 1439 * then learn as much as possible from the 64-bit tnum 1440 * known and unknown bits. The previous smin/smax bounds are 1441 * invalid here because of jmp32 compare so mark them unknown 1442 * so they do not impact tnum bounds calculation. 1443 */ 1444 __mark_reg64_unbounded(reg); 1445 __update_reg_bounds(reg); 1446 } 1447 1448 /* Intersecting with the old var_off might have improved our bounds 1449 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1450 * then new var_off is (0; 0x7f...fc) which improves our umax. 1451 */ 1452 __reg_deduce_bounds(reg); 1453 __reg_bound_offset(reg); 1454 __update_reg_bounds(reg); 1455 } 1456 1457 static bool __reg64_bound_s32(s64 a) 1458 { 1459 return a >= S32_MIN && a <= S32_MAX; 1460 } 1461 1462 static bool __reg64_bound_u32(u64 a) 1463 { 1464 return a >= U32_MIN && a <= U32_MAX; 1465 } 1466 1467 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 1468 { 1469 __mark_reg32_unbounded(reg); 1470 1471 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 1472 reg->s32_min_value = (s32)reg->smin_value; 1473 reg->s32_max_value = (s32)reg->smax_value; 1474 } 1475 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 1476 reg->u32_min_value = (u32)reg->umin_value; 1477 reg->u32_max_value = (u32)reg->umax_value; 1478 } 1479 1480 /* Intersecting with the old var_off might have improved our bounds 1481 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1482 * then new var_off is (0; 0x7f...fc) which improves our umax. 1483 */ 1484 __reg_deduce_bounds(reg); 1485 __reg_bound_offset(reg); 1486 __update_reg_bounds(reg); 1487 } 1488 1489 /* Mark a register as having a completely unknown (scalar) value. */ 1490 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1491 struct bpf_reg_state *reg) 1492 { 1493 /* 1494 * Clear type, id, off, and union(map_ptr, range) and 1495 * padding between 'type' and union 1496 */ 1497 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 1498 reg->type = SCALAR_VALUE; 1499 reg->var_off = tnum_unknown; 1500 reg->frameno = 0; 1501 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable; 1502 __mark_reg_unbounded(reg); 1503 } 1504 1505 static void mark_reg_unknown(struct bpf_verifier_env *env, 1506 struct bpf_reg_state *regs, u32 regno) 1507 { 1508 if (WARN_ON(regno >= MAX_BPF_REG)) { 1509 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 1510 /* Something bad happened, let's kill all regs except FP */ 1511 for (regno = 0; regno < BPF_REG_FP; regno++) 1512 __mark_reg_not_init(env, regs + regno); 1513 return; 1514 } 1515 __mark_reg_unknown(env, regs + regno); 1516 } 1517 1518 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1519 struct bpf_reg_state *reg) 1520 { 1521 __mark_reg_unknown(env, reg); 1522 reg->type = NOT_INIT; 1523 } 1524 1525 static void mark_reg_not_init(struct bpf_verifier_env *env, 1526 struct bpf_reg_state *regs, u32 regno) 1527 { 1528 if (WARN_ON(regno >= MAX_BPF_REG)) { 1529 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 1530 /* Something bad happened, let's kill all regs except FP */ 1531 for (regno = 0; regno < BPF_REG_FP; regno++) 1532 __mark_reg_not_init(env, regs + regno); 1533 return; 1534 } 1535 __mark_reg_not_init(env, regs + regno); 1536 } 1537 1538 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 1539 struct bpf_reg_state *regs, u32 regno, 1540 enum bpf_reg_type reg_type, 1541 struct btf *btf, u32 btf_id) 1542 { 1543 if (reg_type == SCALAR_VALUE) { 1544 mark_reg_unknown(env, regs, regno); 1545 return; 1546 } 1547 mark_reg_known_zero(env, regs, regno); 1548 regs[regno].type = PTR_TO_BTF_ID; 1549 regs[regno].btf = btf; 1550 regs[regno].btf_id = btf_id; 1551 } 1552 1553 #define DEF_NOT_SUBREG (0) 1554 static void init_reg_state(struct bpf_verifier_env *env, 1555 struct bpf_func_state *state) 1556 { 1557 struct bpf_reg_state *regs = state->regs; 1558 int i; 1559 1560 for (i = 0; i < MAX_BPF_REG; i++) { 1561 mark_reg_not_init(env, regs, i); 1562 regs[i].live = REG_LIVE_NONE; 1563 regs[i].parent = NULL; 1564 regs[i].subreg_def = DEF_NOT_SUBREG; 1565 } 1566 1567 /* frame pointer */ 1568 regs[BPF_REG_FP].type = PTR_TO_STACK; 1569 mark_reg_known_zero(env, regs, BPF_REG_FP); 1570 regs[BPF_REG_FP].frameno = state->frameno; 1571 } 1572 1573 #define BPF_MAIN_FUNC (-1) 1574 static void init_func_state(struct bpf_verifier_env *env, 1575 struct bpf_func_state *state, 1576 int callsite, int frameno, int subprogno) 1577 { 1578 state->callsite = callsite; 1579 state->frameno = frameno; 1580 state->subprogno = subprogno; 1581 init_reg_state(env, state); 1582 mark_verifier_state_scratched(env); 1583 } 1584 1585 /* Similar to push_stack(), but for async callbacks */ 1586 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 1587 int insn_idx, int prev_insn_idx, 1588 int subprog) 1589 { 1590 struct bpf_verifier_stack_elem *elem; 1591 struct bpf_func_state *frame; 1592 1593 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1594 if (!elem) 1595 goto err; 1596 1597 elem->insn_idx = insn_idx; 1598 elem->prev_insn_idx = prev_insn_idx; 1599 elem->next = env->head; 1600 elem->log_pos = env->log.len_used; 1601 env->head = elem; 1602 env->stack_size++; 1603 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1604 verbose(env, 1605 "The sequence of %d jumps is too complex for async cb.\n", 1606 env->stack_size); 1607 goto err; 1608 } 1609 /* Unlike push_stack() do not copy_verifier_state(). 1610 * The caller state doesn't matter. 1611 * This is async callback. It starts in a fresh stack. 1612 * Initialize it similar to do_check_common(). 1613 */ 1614 elem->st.branches = 1; 1615 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 1616 if (!frame) 1617 goto err; 1618 init_func_state(env, frame, 1619 BPF_MAIN_FUNC /* callsite */, 1620 0 /* frameno within this callchain */, 1621 subprog /* subprog number within this prog */); 1622 elem->st.frame[0] = frame; 1623 return &elem->st; 1624 err: 1625 free_verifier_state(env->cur_state, true); 1626 env->cur_state = NULL; 1627 /* pop all elements and return */ 1628 while (!pop_stack(env, NULL, NULL, false)); 1629 return NULL; 1630 } 1631 1632 1633 enum reg_arg_type { 1634 SRC_OP, /* register is used as source operand */ 1635 DST_OP, /* register is used as destination operand */ 1636 DST_OP_NO_MARK /* same as above, check only, don't mark */ 1637 }; 1638 1639 static int cmp_subprogs(const void *a, const void *b) 1640 { 1641 return ((struct bpf_subprog_info *)a)->start - 1642 ((struct bpf_subprog_info *)b)->start; 1643 } 1644 1645 static int find_subprog(struct bpf_verifier_env *env, int off) 1646 { 1647 struct bpf_subprog_info *p; 1648 1649 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 1650 sizeof(env->subprog_info[0]), cmp_subprogs); 1651 if (!p) 1652 return -ENOENT; 1653 return p - env->subprog_info; 1654 1655 } 1656 1657 static int add_subprog(struct bpf_verifier_env *env, int off) 1658 { 1659 int insn_cnt = env->prog->len; 1660 int ret; 1661 1662 if (off >= insn_cnt || off < 0) { 1663 verbose(env, "call to invalid destination\n"); 1664 return -EINVAL; 1665 } 1666 ret = find_subprog(env, off); 1667 if (ret >= 0) 1668 return ret; 1669 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 1670 verbose(env, "too many subprograms\n"); 1671 return -E2BIG; 1672 } 1673 /* determine subprog starts. The end is one before the next starts */ 1674 env->subprog_info[env->subprog_cnt++].start = off; 1675 sort(env->subprog_info, env->subprog_cnt, 1676 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 1677 return env->subprog_cnt - 1; 1678 } 1679 1680 #define MAX_KFUNC_DESCS 256 1681 #define MAX_KFUNC_BTFS 256 1682 1683 struct bpf_kfunc_desc { 1684 struct btf_func_model func_model; 1685 u32 func_id; 1686 s32 imm; 1687 u16 offset; 1688 }; 1689 1690 struct bpf_kfunc_btf { 1691 struct btf *btf; 1692 struct module *module; 1693 u16 offset; 1694 }; 1695 1696 struct bpf_kfunc_desc_tab { 1697 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 1698 u32 nr_descs; 1699 }; 1700 1701 struct bpf_kfunc_btf_tab { 1702 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 1703 u32 nr_descs; 1704 }; 1705 1706 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 1707 { 1708 const struct bpf_kfunc_desc *d0 = a; 1709 const struct bpf_kfunc_desc *d1 = b; 1710 1711 /* func_id is not greater than BTF_MAX_TYPE */ 1712 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 1713 } 1714 1715 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 1716 { 1717 const struct bpf_kfunc_btf *d0 = a; 1718 const struct bpf_kfunc_btf *d1 = b; 1719 1720 return d0->offset - d1->offset; 1721 } 1722 1723 static const struct bpf_kfunc_desc * 1724 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 1725 { 1726 struct bpf_kfunc_desc desc = { 1727 .func_id = func_id, 1728 .offset = offset, 1729 }; 1730 struct bpf_kfunc_desc_tab *tab; 1731 1732 tab = prog->aux->kfunc_tab; 1733 return bsearch(&desc, tab->descs, tab->nr_descs, 1734 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 1735 } 1736 1737 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 1738 s16 offset, struct module **btf_modp) 1739 { 1740 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 1741 struct bpf_kfunc_btf_tab *tab; 1742 struct bpf_kfunc_btf *b; 1743 struct module *mod; 1744 struct btf *btf; 1745 int btf_fd; 1746 1747 tab = env->prog->aux->kfunc_btf_tab; 1748 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 1749 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 1750 if (!b) { 1751 if (tab->nr_descs == MAX_KFUNC_BTFS) { 1752 verbose(env, "too many different module BTFs\n"); 1753 return ERR_PTR(-E2BIG); 1754 } 1755 1756 if (bpfptr_is_null(env->fd_array)) { 1757 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 1758 return ERR_PTR(-EPROTO); 1759 } 1760 1761 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 1762 offset * sizeof(btf_fd), 1763 sizeof(btf_fd))) 1764 return ERR_PTR(-EFAULT); 1765 1766 btf = btf_get_by_fd(btf_fd); 1767 if (IS_ERR(btf)) { 1768 verbose(env, "invalid module BTF fd specified\n"); 1769 return btf; 1770 } 1771 1772 if (!btf_is_module(btf)) { 1773 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 1774 btf_put(btf); 1775 return ERR_PTR(-EINVAL); 1776 } 1777 1778 mod = btf_try_get_module(btf); 1779 if (!mod) { 1780 btf_put(btf); 1781 return ERR_PTR(-ENXIO); 1782 } 1783 1784 b = &tab->descs[tab->nr_descs++]; 1785 b->btf = btf; 1786 b->module = mod; 1787 b->offset = offset; 1788 1789 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 1790 kfunc_btf_cmp_by_off, NULL); 1791 } 1792 if (btf_modp) 1793 *btf_modp = b->module; 1794 return b->btf; 1795 } 1796 1797 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 1798 { 1799 if (!tab) 1800 return; 1801 1802 while (tab->nr_descs--) { 1803 module_put(tab->descs[tab->nr_descs].module); 1804 btf_put(tab->descs[tab->nr_descs].btf); 1805 } 1806 kfree(tab); 1807 } 1808 1809 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, 1810 u32 func_id, s16 offset, 1811 struct module **btf_modp) 1812 { 1813 if (offset) { 1814 if (offset < 0) { 1815 /* In the future, this can be allowed to increase limit 1816 * of fd index into fd_array, interpreted as u16. 1817 */ 1818 verbose(env, "negative offset disallowed for kernel module function call\n"); 1819 return ERR_PTR(-EINVAL); 1820 } 1821 1822 return __find_kfunc_desc_btf(env, offset, btf_modp); 1823 } 1824 return btf_vmlinux ?: ERR_PTR(-ENOENT); 1825 } 1826 1827 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 1828 { 1829 const struct btf_type *func, *func_proto; 1830 struct bpf_kfunc_btf_tab *btf_tab; 1831 struct bpf_kfunc_desc_tab *tab; 1832 struct bpf_prog_aux *prog_aux; 1833 struct bpf_kfunc_desc *desc; 1834 const char *func_name; 1835 struct btf *desc_btf; 1836 unsigned long addr; 1837 int err; 1838 1839 prog_aux = env->prog->aux; 1840 tab = prog_aux->kfunc_tab; 1841 btf_tab = prog_aux->kfunc_btf_tab; 1842 if (!tab) { 1843 if (!btf_vmlinux) { 1844 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 1845 return -ENOTSUPP; 1846 } 1847 1848 if (!env->prog->jit_requested) { 1849 verbose(env, "JIT is required for calling kernel function\n"); 1850 return -ENOTSUPP; 1851 } 1852 1853 if (!bpf_jit_supports_kfunc_call()) { 1854 verbose(env, "JIT does not support calling kernel function\n"); 1855 return -ENOTSUPP; 1856 } 1857 1858 if (!env->prog->gpl_compatible) { 1859 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 1860 return -EINVAL; 1861 } 1862 1863 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 1864 if (!tab) 1865 return -ENOMEM; 1866 prog_aux->kfunc_tab = tab; 1867 } 1868 1869 /* func_id == 0 is always invalid, but instead of returning an error, be 1870 * conservative and wait until the code elimination pass before returning 1871 * error, so that invalid calls that get pruned out can be in BPF programs 1872 * loaded from userspace. It is also required that offset be untouched 1873 * for such calls. 1874 */ 1875 if (!func_id && !offset) 1876 return 0; 1877 1878 if (!btf_tab && offset) { 1879 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 1880 if (!btf_tab) 1881 return -ENOMEM; 1882 prog_aux->kfunc_btf_tab = btf_tab; 1883 } 1884 1885 desc_btf = find_kfunc_desc_btf(env, func_id, offset, NULL); 1886 if (IS_ERR(desc_btf)) { 1887 verbose(env, "failed to find BTF for kernel function\n"); 1888 return PTR_ERR(desc_btf); 1889 } 1890 1891 if (find_kfunc_desc(env->prog, func_id, offset)) 1892 return 0; 1893 1894 if (tab->nr_descs == MAX_KFUNC_DESCS) { 1895 verbose(env, "too many different kernel function calls\n"); 1896 return -E2BIG; 1897 } 1898 1899 func = btf_type_by_id(desc_btf, func_id); 1900 if (!func || !btf_type_is_func(func)) { 1901 verbose(env, "kernel btf_id %u is not a function\n", 1902 func_id); 1903 return -EINVAL; 1904 } 1905 func_proto = btf_type_by_id(desc_btf, func->type); 1906 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 1907 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 1908 func_id); 1909 return -EINVAL; 1910 } 1911 1912 func_name = btf_name_by_offset(desc_btf, func->name_off); 1913 addr = kallsyms_lookup_name(func_name); 1914 if (!addr) { 1915 verbose(env, "cannot find address for kernel function %s\n", 1916 func_name); 1917 return -EINVAL; 1918 } 1919 1920 desc = &tab->descs[tab->nr_descs++]; 1921 desc->func_id = func_id; 1922 desc->imm = BPF_CALL_IMM(addr); 1923 desc->offset = offset; 1924 err = btf_distill_func_proto(&env->log, desc_btf, 1925 func_proto, func_name, 1926 &desc->func_model); 1927 if (!err) 1928 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 1929 kfunc_desc_cmp_by_id_off, NULL); 1930 return err; 1931 } 1932 1933 static int kfunc_desc_cmp_by_imm(const void *a, const void *b) 1934 { 1935 const struct bpf_kfunc_desc *d0 = a; 1936 const struct bpf_kfunc_desc *d1 = b; 1937 1938 if (d0->imm > d1->imm) 1939 return 1; 1940 else if (d0->imm < d1->imm) 1941 return -1; 1942 return 0; 1943 } 1944 1945 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog) 1946 { 1947 struct bpf_kfunc_desc_tab *tab; 1948 1949 tab = prog->aux->kfunc_tab; 1950 if (!tab) 1951 return; 1952 1953 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 1954 kfunc_desc_cmp_by_imm, NULL); 1955 } 1956 1957 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 1958 { 1959 return !!prog->aux->kfunc_tab; 1960 } 1961 1962 const struct btf_func_model * 1963 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 1964 const struct bpf_insn *insn) 1965 { 1966 const struct bpf_kfunc_desc desc = { 1967 .imm = insn->imm, 1968 }; 1969 const struct bpf_kfunc_desc *res; 1970 struct bpf_kfunc_desc_tab *tab; 1971 1972 tab = prog->aux->kfunc_tab; 1973 res = bsearch(&desc, tab->descs, tab->nr_descs, 1974 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm); 1975 1976 return res ? &res->func_model : NULL; 1977 } 1978 1979 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 1980 { 1981 struct bpf_subprog_info *subprog = env->subprog_info; 1982 struct bpf_insn *insn = env->prog->insnsi; 1983 int i, ret, insn_cnt = env->prog->len; 1984 1985 /* Add entry function. */ 1986 ret = add_subprog(env, 0); 1987 if (ret) 1988 return ret; 1989 1990 for (i = 0; i < insn_cnt; i++, insn++) { 1991 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 1992 !bpf_pseudo_kfunc_call(insn)) 1993 continue; 1994 1995 if (!env->bpf_capable) { 1996 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 1997 return -EPERM; 1998 } 1999 2000 if (bpf_pseudo_func(insn) || bpf_pseudo_call(insn)) 2001 ret = add_subprog(env, i + insn->imm + 1); 2002 else 2003 ret = add_kfunc_call(env, insn->imm, insn->off); 2004 2005 if (ret < 0) 2006 return ret; 2007 } 2008 2009 /* Add a fake 'exit' subprog which could simplify subprog iteration 2010 * logic. 'subprog_cnt' should not be increased. 2011 */ 2012 subprog[env->subprog_cnt].start = insn_cnt; 2013 2014 if (env->log.level & BPF_LOG_LEVEL2) 2015 for (i = 0; i < env->subprog_cnt; i++) 2016 verbose(env, "func#%d @%d\n", i, subprog[i].start); 2017 2018 return 0; 2019 } 2020 2021 static int check_subprogs(struct bpf_verifier_env *env) 2022 { 2023 int i, subprog_start, subprog_end, off, cur_subprog = 0; 2024 struct bpf_subprog_info *subprog = env->subprog_info; 2025 struct bpf_insn *insn = env->prog->insnsi; 2026 int insn_cnt = env->prog->len; 2027 2028 /* now check that all jumps are within the same subprog */ 2029 subprog_start = subprog[cur_subprog].start; 2030 subprog_end = subprog[cur_subprog + 1].start; 2031 for (i = 0; i < insn_cnt; i++) { 2032 u8 code = insn[i].code; 2033 2034 if (code == (BPF_JMP | BPF_CALL) && 2035 insn[i].imm == BPF_FUNC_tail_call && 2036 insn[i].src_reg != BPF_PSEUDO_CALL) 2037 subprog[cur_subprog].has_tail_call = true; 2038 if (BPF_CLASS(code) == BPF_LD && 2039 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2040 subprog[cur_subprog].has_ld_abs = true; 2041 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2042 goto next; 2043 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2044 goto next; 2045 off = i + insn[i].off + 1; 2046 if (off < subprog_start || off >= subprog_end) { 2047 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2048 return -EINVAL; 2049 } 2050 next: 2051 if (i == subprog_end - 1) { 2052 /* to avoid fall-through from one subprog into another 2053 * the last insn of the subprog should be either exit 2054 * or unconditional jump back 2055 */ 2056 if (code != (BPF_JMP | BPF_EXIT) && 2057 code != (BPF_JMP | BPF_JA)) { 2058 verbose(env, "last insn is not an exit or jmp\n"); 2059 return -EINVAL; 2060 } 2061 subprog_start = subprog_end; 2062 cur_subprog++; 2063 if (cur_subprog < env->subprog_cnt) 2064 subprog_end = subprog[cur_subprog + 1].start; 2065 } 2066 } 2067 return 0; 2068 } 2069 2070 /* Parentage chain of this register (or stack slot) should take care of all 2071 * issues like callee-saved registers, stack slot allocation time, etc. 2072 */ 2073 static int mark_reg_read(struct bpf_verifier_env *env, 2074 const struct bpf_reg_state *state, 2075 struct bpf_reg_state *parent, u8 flag) 2076 { 2077 bool writes = parent == state->parent; /* Observe write marks */ 2078 int cnt = 0; 2079 2080 while (parent) { 2081 /* if read wasn't screened by an earlier write ... */ 2082 if (writes && state->live & REG_LIVE_WRITTEN) 2083 break; 2084 if (parent->live & REG_LIVE_DONE) { 2085 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2086 reg_type_str(env, parent->type), 2087 parent->var_off.value, parent->off); 2088 return -EFAULT; 2089 } 2090 /* The first condition is more likely to be true than the 2091 * second, checked it first. 2092 */ 2093 if ((parent->live & REG_LIVE_READ) == flag || 2094 parent->live & REG_LIVE_READ64) 2095 /* The parentage chain never changes and 2096 * this parent was already marked as LIVE_READ. 2097 * There is no need to keep walking the chain again and 2098 * keep re-marking all parents as LIVE_READ. 2099 * This case happens when the same register is read 2100 * multiple times without writes into it in-between. 2101 * Also, if parent has the stronger REG_LIVE_READ64 set, 2102 * then no need to set the weak REG_LIVE_READ32. 2103 */ 2104 break; 2105 /* ... then we depend on parent's value */ 2106 parent->live |= flag; 2107 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 2108 if (flag == REG_LIVE_READ64) 2109 parent->live &= ~REG_LIVE_READ32; 2110 state = parent; 2111 parent = state->parent; 2112 writes = true; 2113 cnt++; 2114 } 2115 2116 if (env->longest_mark_read_walk < cnt) 2117 env->longest_mark_read_walk = cnt; 2118 return 0; 2119 } 2120 2121 /* This function is supposed to be used by the following 32-bit optimization 2122 * code only. It returns TRUE if the source or destination register operates 2123 * on 64-bit, otherwise return FALSE. 2124 */ 2125 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 2126 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 2127 { 2128 u8 code, class, op; 2129 2130 code = insn->code; 2131 class = BPF_CLASS(code); 2132 op = BPF_OP(code); 2133 if (class == BPF_JMP) { 2134 /* BPF_EXIT for "main" will reach here. Return TRUE 2135 * conservatively. 2136 */ 2137 if (op == BPF_EXIT) 2138 return true; 2139 if (op == BPF_CALL) { 2140 /* BPF to BPF call will reach here because of marking 2141 * caller saved clobber with DST_OP_NO_MARK for which we 2142 * don't care the register def because they are anyway 2143 * marked as NOT_INIT already. 2144 */ 2145 if (insn->src_reg == BPF_PSEUDO_CALL) 2146 return false; 2147 /* Helper call will reach here because of arg type 2148 * check, conservatively return TRUE. 2149 */ 2150 if (t == SRC_OP) 2151 return true; 2152 2153 return false; 2154 } 2155 } 2156 2157 if (class == BPF_ALU64 || class == BPF_JMP || 2158 /* BPF_END always use BPF_ALU class. */ 2159 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 2160 return true; 2161 2162 if (class == BPF_ALU || class == BPF_JMP32) 2163 return false; 2164 2165 if (class == BPF_LDX) { 2166 if (t != SRC_OP) 2167 return BPF_SIZE(code) == BPF_DW; 2168 /* LDX source must be ptr. */ 2169 return true; 2170 } 2171 2172 if (class == BPF_STX) { 2173 /* BPF_STX (including atomic variants) has multiple source 2174 * operands, one of which is a ptr. Check whether the caller is 2175 * asking about it. 2176 */ 2177 if (t == SRC_OP && reg->type != SCALAR_VALUE) 2178 return true; 2179 return BPF_SIZE(code) == BPF_DW; 2180 } 2181 2182 if (class == BPF_LD) { 2183 u8 mode = BPF_MODE(code); 2184 2185 /* LD_IMM64 */ 2186 if (mode == BPF_IMM) 2187 return true; 2188 2189 /* Both LD_IND and LD_ABS return 32-bit data. */ 2190 if (t != SRC_OP) 2191 return false; 2192 2193 /* Implicit ctx ptr. */ 2194 if (regno == BPF_REG_6) 2195 return true; 2196 2197 /* Explicit source could be any width. */ 2198 return true; 2199 } 2200 2201 if (class == BPF_ST) 2202 /* The only source register for BPF_ST is a ptr. */ 2203 return true; 2204 2205 /* Conservatively return true at default. */ 2206 return true; 2207 } 2208 2209 /* Return the regno defined by the insn, or -1. */ 2210 static int insn_def_regno(const struct bpf_insn *insn) 2211 { 2212 switch (BPF_CLASS(insn->code)) { 2213 case BPF_JMP: 2214 case BPF_JMP32: 2215 case BPF_ST: 2216 return -1; 2217 case BPF_STX: 2218 if (BPF_MODE(insn->code) == BPF_ATOMIC && 2219 (insn->imm & BPF_FETCH)) { 2220 if (insn->imm == BPF_CMPXCHG) 2221 return BPF_REG_0; 2222 else 2223 return insn->src_reg; 2224 } else { 2225 return -1; 2226 } 2227 default: 2228 return insn->dst_reg; 2229 } 2230 } 2231 2232 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 2233 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 2234 { 2235 int dst_reg = insn_def_regno(insn); 2236 2237 if (dst_reg == -1) 2238 return false; 2239 2240 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 2241 } 2242 2243 static void mark_insn_zext(struct bpf_verifier_env *env, 2244 struct bpf_reg_state *reg) 2245 { 2246 s32 def_idx = reg->subreg_def; 2247 2248 if (def_idx == DEF_NOT_SUBREG) 2249 return; 2250 2251 env->insn_aux_data[def_idx - 1].zext_dst = true; 2252 /* The dst will be zero extended, so won't be sub-register anymore. */ 2253 reg->subreg_def = DEF_NOT_SUBREG; 2254 } 2255 2256 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 2257 enum reg_arg_type t) 2258 { 2259 struct bpf_verifier_state *vstate = env->cur_state; 2260 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2261 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 2262 struct bpf_reg_state *reg, *regs = state->regs; 2263 bool rw64; 2264 2265 if (regno >= MAX_BPF_REG) { 2266 verbose(env, "R%d is invalid\n", regno); 2267 return -EINVAL; 2268 } 2269 2270 mark_reg_scratched(env, regno); 2271 2272 reg = ®s[regno]; 2273 rw64 = is_reg64(env, insn, regno, reg, t); 2274 if (t == SRC_OP) { 2275 /* check whether register used as source operand can be read */ 2276 if (reg->type == NOT_INIT) { 2277 verbose(env, "R%d !read_ok\n", regno); 2278 return -EACCES; 2279 } 2280 /* We don't need to worry about FP liveness because it's read-only */ 2281 if (regno == BPF_REG_FP) 2282 return 0; 2283 2284 if (rw64) 2285 mark_insn_zext(env, reg); 2286 2287 return mark_reg_read(env, reg, reg->parent, 2288 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 2289 } else { 2290 /* check whether register used as dest operand can be written to */ 2291 if (regno == BPF_REG_FP) { 2292 verbose(env, "frame pointer is read only\n"); 2293 return -EACCES; 2294 } 2295 reg->live |= REG_LIVE_WRITTEN; 2296 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 2297 if (t == DST_OP) 2298 mark_reg_unknown(env, regs, regno); 2299 } 2300 return 0; 2301 } 2302 2303 /* for any branch, call, exit record the history of jmps in the given state */ 2304 static int push_jmp_history(struct bpf_verifier_env *env, 2305 struct bpf_verifier_state *cur) 2306 { 2307 u32 cnt = cur->jmp_history_cnt; 2308 struct bpf_idx_pair *p; 2309 2310 cnt++; 2311 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER); 2312 if (!p) 2313 return -ENOMEM; 2314 p[cnt - 1].idx = env->insn_idx; 2315 p[cnt - 1].prev_idx = env->prev_insn_idx; 2316 cur->jmp_history = p; 2317 cur->jmp_history_cnt = cnt; 2318 return 0; 2319 } 2320 2321 /* Backtrack one insn at a time. If idx is not at the top of recorded 2322 * history then previous instruction came from straight line execution. 2323 */ 2324 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 2325 u32 *history) 2326 { 2327 u32 cnt = *history; 2328 2329 if (cnt && st->jmp_history[cnt - 1].idx == i) { 2330 i = st->jmp_history[cnt - 1].prev_idx; 2331 (*history)--; 2332 } else { 2333 i--; 2334 } 2335 return i; 2336 } 2337 2338 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 2339 { 2340 const struct btf_type *func; 2341 struct btf *desc_btf; 2342 2343 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 2344 return NULL; 2345 2346 desc_btf = find_kfunc_desc_btf(data, insn->imm, insn->off, NULL); 2347 if (IS_ERR(desc_btf)) 2348 return "<error>"; 2349 2350 func = btf_type_by_id(desc_btf, insn->imm); 2351 return btf_name_by_offset(desc_btf, func->name_off); 2352 } 2353 2354 /* For given verifier state backtrack_insn() is called from the last insn to 2355 * the first insn. Its purpose is to compute a bitmask of registers and 2356 * stack slots that needs precision in the parent verifier state. 2357 */ 2358 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 2359 u32 *reg_mask, u64 *stack_mask) 2360 { 2361 const struct bpf_insn_cbs cbs = { 2362 .cb_call = disasm_kfunc_name, 2363 .cb_print = verbose, 2364 .private_data = env, 2365 }; 2366 struct bpf_insn *insn = env->prog->insnsi + idx; 2367 u8 class = BPF_CLASS(insn->code); 2368 u8 opcode = BPF_OP(insn->code); 2369 u8 mode = BPF_MODE(insn->code); 2370 u32 dreg = 1u << insn->dst_reg; 2371 u32 sreg = 1u << insn->src_reg; 2372 u32 spi; 2373 2374 if (insn->code == 0) 2375 return 0; 2376 if (env->log.level & BPF_LOG_LEVEL2) { 2377 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask); 2378 verbose(env, "%d: ", idx); 2379 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 2380 } 2381 2382 if (class == BPF_ALU || class == BPF_ALU64) { 2383 if (!(*reg_mask & dreg)) 2384 return 0; 2385 if (opcode == BPF_MOV) { 2386 if (BPF_SRC(insn->code) == BPF_X) { 2387 /* dreg = sreg 2388 * dreg needs precision after this insn 2389 * sreg needs precision before this insn 2390 */ 2391 *reg_mask &= ~dreg; 2392 *reg_mask |= sreg; 2393 } else { 2394 /* dreg = K 2395 * dreg needs precision after this insn. 2396 * Corresponding register is already marked 2397 * as precise=true in this verifier state. 2398 * No further markings in parent are necessary 2399 */ 2400 *reg_mask &= ~dreg; 2401 } 2402 } else { 2403 if (BPF_SRC(insn->code) == BPF_X) { 2404 /* dreg += sreg 2405 * both dreg and sreg need precision 2406 * before this insn 2407 */ 2408 *reg_mask |= sreg; 2409 } /* else dreg += K 2410 * dreg still needs precision before this insn 2411 */ 2412 } 2413 } else if (class == BPF_LDX) { 2414 if (!(*reg_mask & dreg)) 2415 return 0; 2416 *reg_mask &= ~dreg; 2417 2418 /* scalars can only be spilled into stack w/o losing precision. 2419 * Load from any other memory can be zero extended. 2420 * The desire to keep that precision is already indicated 2421 * by 'precise' mark in corresponding register of this state. 2422 * No further tracking necessary. 2423 */ 2424 if (insn->src_reg != BPF_REG_FP) 2425 return 0; 2426 if (BPF_SIZE(insn->code) != BPF_DW) 2427 return 0; 2428 2429 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 2430 * that [fp - off] slot contains scalar that needs to be 2431 * tracked with precision 2432 */ 2433 spi = (-insn->off - 1) / BPF_REG_SIZE; 2434 if (spi >= 64) { 2435 verbose(env, "BUG spi %d\n", spi); 2436 WARN_ONCE(1, "verifier backtracking bug"); 2437 return -EFAULT; 2438 } 2439 *stack_mask |= 1ull << spi; 2440 } else if (class == BPF_STX || class == BPF_ST) { 2441 if (*reg_mask & dreg) 2442 /* stx & st shouldn't be using _scalar_ dst_reg 2443 * to access memory. It means backtracking 2444 * encountered a case of pointer subtraction. 2445 */ 2446 return -ENOTSUPP; 2447 /* scalars can only be spilled into stack */ 2448 if (insn->dst_reg != BPF_REG_FP) 2449 return 0; 2450 if (BPF_SIZE(insn->code) != BPF_DW) 2451 return 0; 2452 spi = (-insn->off - 1) / BPF_REG_SIZE; 2453 if (spi >= 64) { 2454 verbose(env, "BUG spi %d\n", spi); 2455 WARN_ONCE(1, "verifier backtracking bug"); 2456 return -EFAULT; 2457 } 2458 if (!(*stack_mask & (1ull << spi))) 2459 return 0; 2460 *stack_mask &= ~(1ull << spi); 2461 if (class == BPF_STX) 2462 *reg_mask |= sreg; 2463 } else if (class == BPF_JMP || class == BPF_JMP32) { 2464 if (opcode == BPF_CALL) { 2465 if (insn->src_reg == BPF_PSEUDO_CALL) 2466 return -ENOTSUPP; 2467 /* regular helper call sets R0 */ 2468 *reg_mask &= ~1; 2469 if (*reg_mask & 0x3f) { 2470 /* if backtracing was looking for registers R1-R5 2471 * they should have been found already. 2472 */ 2473 verbose(env, "BUG regs %x\n", *reg_mask); 2474 WARN_ONCE(1, "verifier backtracking bug"); 2475 return -EFAULT; 2476 } 2477 } else if (opcode == BPF_EXIT) { 2478 return -ENOTSUPP; 2479 } 2480 } else if (class == BPF_LD) { 2481 if (!(*reg_mask & dreg)) 2482 return 0; 2483 *reg_mask &= ~dreg; 2484 /* It's ld_imm64 or ld_abs or ld_ind. 2485 * For ld_imm64 no further tracking of precision 2486 * into parent is necessary 2487 */ 2488 if (mode == BPF_IND || mode == BPF_ABS) 2489 /* to be analyzed */ 2490 return -ENOTSUPP; 2491 } 2492 return 0; 2493 } 2494 2495 /* the scalar precision tracking algorithm: 2496 * . at the start all registers have precise=false. 2497 * . scalar ranges are tracked as normal through alu and jmp insns. 2498 * . once precise value of the scalar register is used in: 2499 * . ptr + scalar alu 2500 * . if (scalar cond K|scalar) 2501 * . helper_call(.., scalar, ...) where ARG_CONST is expected 2502 * backtrack through the verifier states and mark all registers and 2503 * stack slots with spilled constants that these scalar regisers 2504 * should be precise. 2505 * . during state pruning two registers (or spilled stack slots) 2506 * are equivalent if both are not precise. 2507 * 2508 * Note the verifier cannot simply walk register parentage chain, 2509 * since many different registers and stack slots could have been 2510 * used to compute single precise scalar. 2511 * 2512 * The approach of starting with precise=true for all registers and then 2513 * backtrack to mark a register as not precise when the verifier detects 2514 * that program doesn't care about specific value (e.g., when helper 2515 * takes register as ARG_ANYTHING parameter) is not safe. 2516 * 2517 * It's ok to walk single parentage chain of the verifier states. 2518 * It's possible that this backtracking will go all the way till 1st insn. 2519 * All other branches will be explored for needing precision later. 2520 * 2521 * The backtracking needs to deal with cases like: 2522 * 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) 2523 * r9 -= r8 2524 * r5 = r9 2525 * if r5 > 0x79f goto pc+7 2526 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 2527 * r5 += 1 2528 * ... 2529 * call bpf_perf_event_output#25 2530 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 2531 * 2532 * and this case: 2533 * r6 = 1 2534 * call foo // uses callee's r6 inside to compute r0 2535 * r0 += r6 2536 * if r0 == 0 goto 2537 * 2538 * to track above reg_mask/stack_mask needs to be independent for each frame. 2539 * 2540 * Also if parent's curframe > frame where backtracking started, 2541 * the verifier need to mark registers in both frames, otherwise callees 2542 * may incorrectly prune callers. This is similar to 2543 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 2544 * 2545 * For now backtracking falls back into conservative marking. 2546 */ 2547 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 2548 struct bpf_verifier_state *st) 2549 { 2550 struct bpf_func_state *func; 2551 struct bpf_reg_state *reg; 2552 int i, j; 2553 2554 /* big hammer: mark all scalars precise in this path. 2555 * pop_stack may still get !precise scalars. 2556 */ 2557 for (; st; st = st->parent) 2558 for (i = 0; i <= st->curframe; i++) { 2559 func = st->frame[i]; 2560 for (j = 0; j < BPF_REG_FP; j++) { 2561 reg = &func->regs[j]; 2562 if (reg->type != SCALAR_VALUE) 2563 continue; 2564 reg->precise = true; 2565 } 2566 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 2567 if (!is_spilled_reg(&func->stack[j])) 2568 continue; 2569 reg = &func->stack[j].spilled_ptr; 2570 if (reg->type != SCALAR_VALUE) 2571 continue; 2572 reg->precise = true; 2573 } 2574 } 2575 } 2576 2577 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno, 2578 int spi) 2579 { 2580 struct bpf_verifier_state *st = env->cur_state; 2581 int first_idx = st->first_insn_idx; 2582 int last_idx = env->insn_idx; 2583 struct bpf_func_state *func; 2584 struct bpf_reg_state *reg; 2585 u32 reg_mask = regno >= 0 ? 1u << regno : 0; 2586 u64 stack_mask = spi >= 0 ? 1ull << spi : 0; 2587 bool skip_first = true; 2588 bool new_marks = false; 2589 int i, err; 2590 2591 if (!env->bpf_capable) 2592 return 0; 2593 2594 func = st->frame[st->curframe]; 2595 if (regno >= 0) { 2596 reg = &func->regs[regno]; 2597 if (reg->type != SCALAR_VALUE) { 2598 WARN_ONCE(1, "backtracing misuse"); 2599 return -EFAULT; 2600 } 2601 if (!reg->precise) 2602 new_marks = true; 2603 else 2604 reg_mask = 0; 2605 reg->precise = true; 2606 } 2607 2608 while (spi >= 0) { 2609 if (!is_spilled_reg(&func->stack[spi])) { 2610 stack_mask = 0; 2611 break; 2612 } 2613 reg = &func->stack[spi].spilled_ptr; 2614 if (reg->type != SCALAR_VALUE) { 2615 stack_mask = 0; 2616 break; 2617 } 2618 if (!reg->precise) 2619 new_marks = true; 2620 else 2621 stack_mask = 0; 2622 reg->precise = true; 2623 break; 2624 } 2625 2626 if (!new_marks) 2627 return 0; 2628 if (!reg_mask && !stack_mask) 2629 return 0; 2630 for (;;) { 2631 DECLARE_BITMAP(mask, 64); 2632 u32 history = st->jmp_history_cnt; 2633 2634 if (env->log.level & BPF_LOG_LEVEL2) 2635 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx); 2636 for (i = last_idx;;) { 2637 if (skip_first) { 2638 err = 0; 2639 skip_first = false; 2640 } else { 2641 err = backtrack_insn(env, i, ®_mask, &stack_mask); 2642 } 2643 if (err == -ENOTSUPP) { 2644 mark_all_scalars_precise(env, st); 2645 return 0; 2646 } else if (err) { 2647 return err; 2648 } 2649 if (!reg_mask && !stack_mask) 2650 /* Found assignment(s) into tracked register in this state. 2651 * Since this state is already marked, just return. 2652 * Nothing to be tracked further in the parent state. 2653 */ 2654 return 0; 2655 if (i == first_idx) 2656 break; 2657 i = get_prev_insn_idx(st, i, &history); 2658 if (i >= env->prog->len) { 2659 /* This can happen if backtracking reached insn 0 2660 * and there are still reg_mask or stack_mask 2661 * to backtrack. 2662 * It means the backtracking missed the spot where 2663 * particular register was initialized with a constant. 2664 */ 2665 verbose(env, "BUG backtracking idx %d\n", i); 2666 WARN_ONCE(1, "verifier backtracking bug"); 2667 return -EFAULT; 2668 } 2669 } 2670 st = st->parent; 2671 if (!st) 2672 break; 2673 2674 new_marks = false; 2675 func = st->frame[st->curframe]; 2676 bitmap_from_u64(mask, reg_mask); 2677 for_each_set_bit(i, mask, 32) { 2678 reg = &func->regs[i]; 2679 if (reg->type != SCALAR_VALUE) { 2680 reg_mask &= ~(1u << i); 2681 continue; 2682 } 2683 if (!reg->precise) 2684 new_marks = true; 2685 reg->precise = true; 2686 } 2687 2688 bitmap_from_u64(mask, stack_mask); 2689 for_each_set_bit(i, mask, 64) { 2690 if (i >= func->allocated_stack / BPF_REG_SIZE) { 2691 /* the sequence of instructions: 2692 * 2: (bf) r3 = r10 2693 * 3: (7b) *(u64 *)(r3 -8) = r0 2694 * 4: (79) r4 = *(u64 *)(r10 -8) 2695 * doesn't contain jmps. It's backtracked 2696 * as a single block. 2697 * During backtracking insn 3 is not recognized as 2698 * stack access, so at the end of backtracking 2699 * stack slot fp-8 is still marked in stack_mask. 2700 * However the parent state may not have accessed 2701 * fp-8 and it's "unallocated" stack space. 2702 * In such case fallback to conservative. 2703 */ 2704 mark_all_scalars_precise(env, st); 2705 return 0; 2706 } 2707 2708 if (!is_spilled_reg(&func->stack[i])) { 2709 stack_mask &= ~(1ull << i); 2710 continue; 2711 } 2712 reg = &func->stack[i].spilled_ptr; 2713 if (reg->type != SCALAR_VALUE) { 2714 stack_mask &= ~(1ull << i); 2715 continue; 2716 } 2717 if (!reg->precise) 2718 new_marks = true; 2719 reg->precise = true; 2720 } 2721 if (env->log.level & BPF_LOG_LEVEL2) { 2722 verbose(env, "parent %s regs=%x stack=%llx marks:", 2723 new_marks ? "didn't have" : "already had", 2724 reg_mask, stack_mask); 2725 print_verifier_state(env, func, true); 2726 } 2727 2728 if (!reg_mask && !stack_mask) 2729 break; 2730 if (!new_marks) 2731 break; 2732 2733 last_idx = st->last_insn_idx; 2734 first_idx = st->first_insn_idx; 2735 } 2736 return 0; 2737 } 2738 2739 static int mark_chain_precision(struct bpf_verifier_env *env, int regno) 2740 { 2741 return __mark_chain_precision(env, regno, -1); 2742 } 2743 2744 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi) 2745 { 2746 return __mark_chain_precision(env, -1, spi); 2747 } 2748 2749 static bool is_spillable_regtype(enum bpf_reg_type type) 2750 { 2751 switch (base_type(type)) { 2752 case PTR_TO_MAP_VALUE: 2753 case PTR_TO_STACK: 2754 case PTR_TO_CTX: 2755 case PTR_TO_PACKET: 2756 case PTR_TO_PACKET_META: 2757 case PTR_TO_PACKET_END: 2758 case PTR_TO_FLOW_KEYS: 2759 case CONST_PTR_TO_MAP: 2760 case PTR_TO_SOCKET: 2761 case PTR_TO_SOCK_COMMON: 2762 case PTR_TO_TCP_SOCK: 2763 case PTR_TO_XDP_SOCK: 2764 case PTR_TO_BTF_ID: 2765 case PTR_TO_BUF: 2766 case PTR_TO_PERCPU_BTF_ID: 2767 case PTR_TO_MEM: 2768 case PTR_TO_FUNC: 2769 case PTR_TO_MAP_KEY: 2770 return true; 2771 default: 2772 return false; 2773 } 2774 } 2775 2776 /* Does this register contain a constant zero? */ 2777 static bool register_is_null(struct bpf_reg_state *reg) 2778 { 2779 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 2780 } 2781 2782 static bool register_is_const(struct bpf_reg_state *reg) 2783 { 2784 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 2785 } 2786 2787 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 2788 { 2789 return tnum_is_unknown(reg->var_off) && 2790 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 2791 reg->umin_value == 0 && reg->umax_value == U64_MAX && 2792 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 2793 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 2794 } 2795 2796 static bool register_is_bounded(struct bpf_reg_state *reg) 2797 { 2798 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 2799 } 2800 2801 static bool __is_pointer_value(bool allow_ptr_leaks, 2802 const struct bpf_reg_state *reg) 2803 { 2804 if (allow_ptr_leaks) 2805 return false; 2806 2807 return reg->type != SCALAR_VALUE; 2808 } 2809 2810 static void save_register_state(struct bpf_func_state *state, 2811 int spi, struct bpf_reg_state *reg, 2812 int size) 2813 { 2814 int i; 2815 2816 state->stack[spi].spilled_ptr = *reg; 2817 if (size == BPF_REG_SIZE) 2818 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2819 2820 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 2821 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 2822 2823 /* size < 8 bytes spill */ 2824 for (; i; i--) 2825 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 2826 } 2827 2828 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 2829 * stack boundary and alignment are checked in check_mem_access() 2830 */ 2831 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 2832 /* stack frame we're writing to */ 2833 struct bpf_func_state *state, 2834 int off, int size, int value_regno, 2835 int insn_idx) 2836 { 2837 struct bpf_func_state *cur; /* state of the current function */ 2838 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 2839 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg; 2840 struct bpf_reg_state *reg = NULL; 2841 2842 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 2843 if (err) 2844 return err; 2845 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 2846 * so it's aligned access and [off, off + size) are within stack limits 2847 */ 2848 if (!env->allow_ptr_leaks && 2849 state->stack[spi].slot_type[0] == STACK_SPILL && 2850 size != BPF_REG_SIZE) { 2851 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 2852 return -EACCES; 2853 } 2854 2855 cur = env->cur_state->frame[env->cur_state->curframe]; 2856 if (value_regno >= 0) 2857 reg = &cur->regs[value_regno]; 2858 if (!env->bypass_spec_v4) { 2859 bool sanitize = reg && is_spillable_regtype(reg->type); 2860 2861 for (i = 0; i < size; i++) { 2862 if (state->stack[spi].slot_type[i] == STACK_INVALID) { 2863 sanitize = true; 2864 break; 2865 } 2866 } 2867 2868 if (sanitize) 2869 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 2870 } 2871 2872 mark_stack_slot_scratched(env, spi); 2873 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 2874 !register_is_null(reg) && env->bpf_capable) { 2875 if (dst_reg != BPF_REG_FP) { 2876 /* The backtracking logic can only recognize explicit 2877 * stack slot address like [fp - 8]. Other spill of 2878 * scalar via different register has to be conservative. 2879 * Backtrack from here and mark all registers as precise 2880 * that contributed into 'reg' being a constant. 2881 */ 2882 err = mark_chain_precision(env, value_regno); 2883 if (err) 2884 return err; 2885 } 2886 save_register_state(state, spi, reg, size); 2887 } else if (reg && is_spillable_regtype(reg->type)) { 2888 /* register containing pointer is being spilled into stack */ 2889 if (size != BPF_REG_SIZE) { 2890 verbose_linfo(env, insn_idx, "; "); 2891 verbose(env, "invalid size of register spill\n"); 2892 return -EACCES; 2893 } 2894 if (state != cur && reg->type == PTR_TO_STACK) { 2895 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 2896 return -EINVAL; 2897 } 2898 save_register_state(state, spi, reg, size); 2899 } else { 2900 u8 type = STACK_MISC; 2901 2902 /* regular write of data into stack destroys any spilled ptr */ 2903 state->stack[spi].spilled_ptr.type = NOT_INIT; 2904 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */ 2905 if (is_spilled_reg(&state->stack[spi])) 2906 for (i = 0; i < BPF_REG_SIZE; i++) 2907 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 2908 2909 /* only mark the slot as written if all 8 bytes were written 2910 * otherwise read propagation may incorrectly stop too soon 2911 * when stack slots are partially written. 2912 * This heuristic means that read propagation will be 2913 * conservative, since it will add reg_live_read marks 2914 * to stack slots all the way to first state when programs 2915 * writes+reads less than 8 bytes 2916 */ 2917 if (size == BPF_REG_SIZE) 2918 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2919 2920 /* when we zero initialize stack slots mark them as such */ 2921 if (reg && register_is_null(reg)) { 2922 /* backtracking doesn't work for STACK_ZERO yet. */ 2923 err = mark_chain_precision(env, value_regno); 2924 if (err) 2925 return err; 2926 type = STACK_ZERO; 2927 } 2928 2929 /* Mark slots affected by this stack write. */ 2930 for (i = 0; i < size; i++) 2931 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 2932 type; 2933 } 2934 return 0; 2935 } 2936 2937 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 2938 * known to contain a variable offset. 2939 * This function checks whether the write is permitted and conservatively 2940 * tracks the effects of the write, considering that each stack slot in the 2941 * dynamic range is potentially written to. 2942 * 2943 * 'off' includes 'regno->off'. 2944 * 'value_regno' can be -1, meaning that an unknown value is being written to 2945 * the stack. 2946 * 2947 * Spilled pointers in range are not marked as written because we don't know 2948 * what's going to be actually written. This means that read propagation for 2949 * future reads cannot be terminated by this write. 2950 * 2951 * For privileged programs, uninitialized stack slots are considered 2952 * initialized by this write (even though we don't know exactly what offsets 2953 * are going to be written to). The idea is that we don't want the verifier to 2954 * reject future reads that access slots written to through variable offsets. 2955 */ 2956 static int check_stack_write_var_off(struct bpf_verifier_env *env, 2957 /* func where register points to */ 2958 struct bpf_func_state *state, 2959 int ptr_regno, int off, int size, 2960 int value_regno, int insn_idx) 2961 { 2962 struct bpf_func_state *cur; /* state of the current function */ 2963 int min_off, max_off; 2964 int i, err; 2965 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 2966 bool writing_zero = false; 2967 /* set if the fact that we're writing a zero is used to let any 2968 * stack slots remain STACK_ZERO 2969 */ 2970 bool zero_used = false; 2971 2972 cur = env->cur_state->frame[env->cur_state->curframe]; 2973 ptr_reg = &cur->regs[ptr_regno]; 2974 min_off = ptr_reg->smin_value + off; 2975 max_off = ptr_reg->smax_value + off + size; 2976 if (value_regno >= 0) 2977 value_reg = &cur->regs[value_regno]; 2978 if (value_reg && register_is_null(value_reg)) 2979 writing_zero = true; 2980 2981 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 2982 if (err) 2983 return err; 2984 2985 2986 /* Variable offset writes destroy any spilled pointers in range. */ 2987 for (i = min_off; i < max_off; i++) { 2988 u8 new_type, *stype; 2989 int slot, spi; 2990 2991 slot = -i - 1; 2992 spi = slot / BPF_REG_SIZE; 2993 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 2994 mark_stack_slot_scratched(env, spi); 2995 2996 if (!env->allow_ptr_leaks 2997 && *stype != NOT_INIT 2998 && *stype != SCALAR_VALUE) { 2999 /* Reject the write if there's are spilled pointers in 3000 * range. If we didn't reject here, the ptr status 3001 * would be erased below (even though not all slots are 3002 * actually overwritten), possibly opening the door to 3003 * leaks. 3004 */ 3005 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 3006 insn_idx, i); 3007 return -EINVAL; 3008 } 3009 3010 /* Erase all spilled pointers. */ 3011 state->stack[spi].spilled_ptr.type = NOT_INIT; 3012 3013 /* Update the slot type. */ 3014 new_type = STACK_MISC; 3015 if (writing_zero && *stype == STACK_ZERO) { 3016 new_type = STACK_ZERO; 3017 zero_used = true; 3018 } 3019 /* If the slot is STACK_INVALID, we check whether it's OK to 3020 * pretend that it will be initialized by this write. The slot 3021 * might not actually be written to, and so if we mark it as 3022 * initialized future reads might leak uninitialized memory. 3023 * For privileged programs, we will accept such reads to slots 3024 * that may or may not be written because, if we're reject 3025 * them, the error would be too confusing. 3026 */ 3027 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 3028 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3029 insn_idx, i); 3030 return -EINVAL; 3031 } 3032 *stype = new_type; 3033 } 3034 if (zero_used) { 3035 /* backtracking doesn't work for STACK_ZERO yet. */ 3036 err = mark_chain_precision(env, value_regno); 3037 if (err) 3038 return err; 3039 } 3040 return 0; 3041 } 3042 3043 /* When register 'dst_regno' is assigned some values from stack[min_off, 3044 * max_off), we set the register's type according to the types of the 3045 * respective stack slots. If all the stack values are known to be zeros, then 3046 * so is the destination reg. Otherwise, the register is considered to be 3047 * SCALAR. This function does not deal with register filling; the caller must 3048 * ensure that all spilled registers in the stack range have been marked as 3049 * read. 3050 */ 3051 static void mark_reg_stack_read(struct bpf_verifier_env *env, 3052 /* func where src register points to */ 3053 struct bpf_func_state *ptr_state, 3054 int min_off, int max_off, int dst_regno) 3055 { 3056 struct bpf_verifier_state *vstate = env->cur_state; 3057 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3058 int i, slot, spi; 3059 u8 *stype; 3060 int zeros = 0; 3061 3062 for (i = min_off; i < max_off; i++) { 3063 slot = -i - 1; 3064 spi = slot / BPF_REG_SIZE; 3065 stype = ptr_state->stack[spi].slot_type; 3066 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 3067 break; 3068 zeros++; 3069 } 3070 if (zeros == max_off - min_off) { 3071 /* any access_size read into register is zero extended, 3072 * so the whole register == const_zero 3073 */ 3074 __mark_reg_const_zero(&state->regs[dst_regno]); 3075 /* backtracking doesn't support STACK_ZERO yet, 3076 * so mark it precise here, so that later 3077 * backtracking can stop here. 3078 * Backtracking may not need this if this register 3079 * doesn't participate in pointer adjustment. 3080 * Forward propagation of precise flag is not 3081 * necessary either. This mark is only to stop 3082 * backtracking. Any register that contributed 3083 * to const 0 was marked precise before spill. 3084 */ 3085 state->regs[dst_regno].precise = true; 3086 } else { 3087 /* have read misc data from the stack */ 3088 mark_reg_unknown(env, state->regs, dst_regno); 3089 } 3090 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3091 } 3092 3093 /* Read the stack at 'off' and put the results into the register indicated by 3094 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3095 * spilled reg. 3096 * 3097 * 'dst_regno' can be -1, meaning that the read value is not going to a 3098 * register. 3099 * 3100 * The access is assumed to be within the current stack bounds. 3101 */ 3102 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3103 /* func where src register points to */ 3104 struct bpf_func_state *reg_state, 3105 int off, int size, int dst_regno) 3106 { 3107 struct bpf_verifier_state *vstate = env->cur_state; 3108 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3109 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3110 struct bpf_reg_state *reg; 3111 u8 *stype, type; 3112 3113 stype = reg_state->stack[spi].slot_type; 3114 reg = ®_state->stack[spi].spilled_ptr; 3115 3116 if (is_spilled_reg(®_state->stack[spi])) { 3117 u8 spill_size = 1; 3118 3119 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3120 spill_size++; 3121 3122 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3123 if (reg->type != SCALAR_VALUE) { 3124 verbose_linfo(env, env->insn_idx, "; "); 3125 verbose(env, "invalid size of register fill\n"); 3126 return -EACCES; 3127 } 3128 3129 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3130 if (dst_regno < 0) 3131 return 0; 3132 3133 if (!(off % BPF_REG_SIZE) && size == spill_size) { 3134 /* The earlier check_reg_arg() has decided the 3135 * subreg_def for this insn. Save it first. 3136 */ 3137 s32 subreg_def = state->regs[dst_regno].subreg_def; 3138 3139 state->regs[dst_regno] = *reg; 3140 state->regs[dst_regno].subreg_def = subreg_def; 3141 } else { 3142 for (i = 0; i < size; i++) { 3143 type = stype[(slot - i) % BPF_REG_SIZE]; 3144 if (type == STACK_SPILL) 3145 continue; 3146 if (type == STACK_MISC) 3147 continue; 3148 verbose(env, "invalid read from stack off %d+%d size %d\n", 3149 off, i, size); 3150 return -EACCES; 3151 } 3152 mark_reg_unknown(env, state->regs, dst_regno); 3153 } 3154 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3155 return 0; 3156 } 3157 3158 if (dst_regno >= 0) { 3159 /* restore register state from stack */ 3160 state->regs[dst_regno] = *reg; 3161 /* mark reg as written since spilled pointer state likely 3162 * has its liveness marks cleared by is_state_visited() 3163 * which resets stack/reg liveness for state transitions 3164 */ 3165 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3166 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3167 /* If dst_regno==-1, the caller is asking us whether 3168 * it is acceptable to use this value as a SCALAR_VALUE 3169 * (e.g. for XADD). 3170 * We must not allow unprivileged callers to do that 3171 * with spilled pointers. 3172 */ 3173 verbose(env, "leaking pointer from stack off %d\n", 3174 off); 3175 return -EACCES; 3176 } 3177 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3178 } else { 3179 for (i = 0; i < size; i++) { 3180 type = stype[(slot - i) % BPF_REG_SIZE]; 3181 if (type == STACK_MISC) 3182 continue; 3183 if (type == STACK_ZERO) 3184 continue; 3185 verbose(env, "invalid read from stack off %d+%d size %d\n", 3186 off, i, size); 3187 return -EACCES; 3188 } 3189 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3190 if (dst_regno >= 0) 3191 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3192 } 3193 return 0; 3194 } 3195 3196 enum stack_access_src { 3197 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3198 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3199 }; 3200 3201 static int check_stack_range_initialized(struct bpf_verifier_env *env, 3202 int regno, int off, int access_size, 3203 bool zero_size_allowed, 3204 enum stack_access_src type, 3205 struct bpf_call_arg_meta *meta); 3206 3207 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3208 { 3209 return cur_regs(env) + regno; 3210 } 3211 3212 /* Read the stack at 'ptr_regno + off' and put the result into the register 3213 * 'dst_regno'. 3214 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 3215 * but not its variable offset. 3216 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3217 * 3218 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3219 * filling registers (i.e. reads of spilled register cannot be detected when 3220 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3221 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 3222 * offset; for a fixed offset check_stack_read_fixed_off should be used 3223 * instead. 3224 */ 3225 static int check_stack_read_var_off(struct bpf_verifier_env *env, 3226 int ptr_regno, int off, int size, int dst_regno) 3227 { 3228 /* The state of the source register. */ 3229 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3230 struct bpf_func_state *ptr_state = func(env, reg); 3231 int err; 3232 int min_off, max_off; 3233 3234 /* Note that we pass a NULL meta, so raw access will not be permitted. 3235 */ 3236 err = check_stack_range_initialized(env, ptr_regno, off, size, 3237 false, ACCESS_DIRECT, NULL); 3238 if (err) 3239 return err; 3240 3241 min_off = reg->smin_value + off; 3242 max_off = reg->smax_value + off; 3243 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 3244 return 0; 3245 } 3246 3247 /* check_stack_read dispatches to check_stack_read_fixed_off or 3248 * check_stack_read_var_off. 3249 * 3250 * The caller must ensure that the offset falls within the allocated stack 3251 * bounds. 3252 * 3253 * 'dst_regno' is a register which will receive the value from the stack. It 3254 * can be -1, meaning that the read value is not going to a register. 3255 */ 3256 static int check_stack_read(struct bpf_verifier_env *env, 3257 int ptr_regno, int off, int size, 3258 int dst_regno) 3259 { 3260 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3261 struct bpf_func_state *state = func(env, reg); 3262 int err; 3263 /* Some accesses are only permitted with a static offset. */ 3264 bool var_off = !tnum_is_const(reg->var_off); 3265 3266 /* The offset is required to be static when reads don't go to a 3267 * register, in order to not leak pointers (see 3268 * check_stack_read_fixed_off). 3269 */ 3270 if (dst_regno < 0 && var_off) { 3271 char tn_buf[48]; 3272 3273 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3274 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 3275 tn_buf, off, size); 3276 return -EACCES; 3277 } 3278 /* Variable offset is prohibited for unprivileged mode for simplicity 3279 * since it requires corresponding support in Spectre masking for stack 3280 * ALU. See also retrieve_ptr_limit(). 3281 */ 3282 if (!env->bypass_spec_v1 && var_off) { 3283 char tn_buf[48]; 3284 3285 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3286 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 3287 ptr_regno, tn_buf); 3288 return -EACCES; 3289 } 3290 3291 if (!var_off) { 3292 off += reg->var_off.value; 3293 err = check_stack_read_fixed_off(env, state, off, size, 3294 dst_regno); 3295 } else { 3296 /* Variable offset stack reads need more conservative handling 3297 * than fixed offset ones. Note that dst_regno >= 0 on this 3298 * branch. 3299 */ 3300 err = check_stack_read_var_off(env, ptr_regno, off, size, 3301 dst_regno); 3302 } 3303 return err; 3304 } 3305 3306 3307 /* check_stack_write dispatches to check_stack_write_fixed_off or 3308 * check_stack_write_var_off. 3309 * 3310 * 'ptr_regno' is the register used as a pointer into the stack. 3311 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 3312 * 'value_regno' is the register whose value we're writing to the stack. It can 3313 * be -1, meaning that we're not writing from a register. 3314 * 3315 * The caller must ensure that the offset falls within the maximum stack size. 3316 */ 3317 static int check_stack_write(struct bpf_verifier_env *env, 3318 int ptr_regno, int off, int size, 3319 int value_regno, int insn_idx) 3320 { 3321 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3322 struct bpf_func_state *state = func(env, reg); 3323 int err; 3324 3325 if (tnum_is_const(reg->var_off)) { 3326 off += reg->var_off.value; 3327 err = check_stack_write_fixed_off(env, state, off, size, 3328 value_regno, insn_idx); 3329 } else { 3330 /* Variable offset stack reads need more conservative handling 3331 * than fixed offset ones. 3332 */ 3333 err = check_stack_write_var_off(env, state, 3334 ptr_regno, off, size, 3335 value_regno, insn_idx); 3336 } 3337 return err; 3338 } 3339 3340 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 3341 int off, int size, enum bpf_access_type type) 3342 { 3343 struct bpf_reg_state *regs = cur_regs(env); 3344 struct bpf_map *map = regs[regno].map_ptr; 3345 u32 cap = bpf_map_flags_to_cap(map); 3346 3347 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 3348 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 3349 map->value_size, off, size); 3350 return -EACCES; 3351 } 3352 3353 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 3354 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 3355 map->value_size, off, size); 3356 return -EACCES; 3357 } 3358 3359 return 0; 3360 } 3361 3362 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 3363 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 3364 int off, int size, u32 mem_size, 3365 bool zero_size_allowed) 3366 { 3367 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 3368 struct bpf_reg_state *reg; 3369 3370 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 3371 return 0; 3372 3373 reg = &cur_regs(env)[regno]; 3374 switch (reg->type) { 3375 case PTR_TO_MAP_KEY: 3376 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 3377 mem_size, off, size); 3378 break; 3379 case PTR_TO_MAP_VALUE: 3380 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 3381 mem_size, off, size); 3382 break; 3383 case PTR_TO_PACKET: 3384 case PTR_TO_PACKET_META: 3385 case PTR_TO_PACKET_END: 3386 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 3387 off, size, regno, reg->id, off, mem_size); 3388 break; 3389 case PTR_TO_MEM: 3390 default: 3391 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 3392 mem_size, off, size); 3393 } 3394 3395 return -EACCES; 3396 } 3397 3398 /* check read/write into a memory region with possible variable offset */ 3399 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 3400 int off, int size, u32 mem_size, 3401 bool zero_size_allowed) 3402 { 3403 struct bpf_verifier_state *vstate = env->cur_state; 3404 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3405 struct bpf_reg_state *reg = &state->regs[regno]; 3406 int err; 3407 3408 /* We may have adjusted the register pointing to memory region, so we 3409 * need to try adding each of min_value and max_value to off 3410 * to make sure our theoretical access will be safe. 3411 * 3412 * The minimum value is only important with signed 3413 * comparisons where we can't assume the floor of a 3414 * value is 0. If we are using signed variables for our 3415 * index'es we need to make sure that whatever we use 3416 * will have a set floor within our range. 3417 */ 3418 if (reg->smin_value < 0 && 3419 (reg->smin_value == S64_MIN || 3420 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 3421 reg->smin_value + off < 0)) { 3422 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3423 regno); 3424 return -EACCES; 3425 } 3426 err = __check_mem_access(env, regno, reg->smin_value + off, size, 3427 mem_size, zero_size_allowed); 3428 if (err) { 3429 verbose(env, "R%d min value is outside of the allowed memory range\n", 3430 regno); 3431 return err; 3432 } 3433 3434 /* If we haven't set a max value then we need to bail since we can't be 3435 * sure we won't do bad things. 3436 * If reg->umax_value + off could overflow, treat that as unbounded too. 3437 */ 3438 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 3439 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 3440 regno); 3441 return -EACCES; 3442 } 3443 err = __check_mem_access(env, regno, reg->umax_value + off, size, 3444 mem_size, zero_size_allowed); 3445 if (err) { 3446 verbose(env, "R%d max value is outside of the allowed memory range\n", 3447 regno); 3448 return err; 3449 } 3450 3451 return 0; 3452 } 3453 3454 /* check read/write into a map element with possible variable offset */ 3455 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 3456 int off, int size, bool zero_size_allowed) 3457 { 3458 struct bpf_verifier_state *vstate = env->cur_state; 3459 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3460 struct bpf_reg_state *reg = &state->regs[regno]; 3461 struct bpf_map *map = reg->map_ptr; 3462 int err; 3463 3464 err = check_mem_region_access(env, regno, off, size, map->value_size, 3465 zero_size_allowed); 3466 if (err) 3467 return err; 3468 3469 if (map_value_has_spin_lock(map)) { 3470 u32 lock = map->spin_lock_off; 3471 3472 /* if any part of struct bpf_spin_lock can be touched by 3473 * load/store reject this program. 3474 * To check that [x1, x2) overlaps with [y1, y2) 3475 * it is sufficient to check x1 < y2 && y1 < x2. 3476 */ 3477 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) && 3478 lock < reg->umax_value + off + size) { 3479 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n"); 3480 return -EACCES; 3481 } 3482 } 3483 if (map_value_has_timer(map)) { 3484 u32 t = map->timer_off; 3485 3486 if (reg->smin_value + off < t + sizeof(struct bpf_timer) && 3487 t < reg->umax_value + off + size) { 3488 verbose(env, "bpf_timer cannot be accessed directly by load/store\n"); 3489 return -EACCES; 3490 } 3491 } 3492 return err; 3493 } 3494 3495 #define MAX_PACKET_OFF 0xffff 3496 3497 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog) 3498 { 3499 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type; 3500 } 3501 3502 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 3503 const struct bpf_call_arg_meta *meta, 3504 enum bpf_access_type t) 3505 { 3506 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 3507 3508 switch (prog_type) { 3509 /* Program types only with direct read access go here! */ 3510 case BPF_PROG_TYPE_LWT_IN: 3511 case BPF_PROG_TYPE_LWT_OUT: 3512 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 3513 case BPF_PROG_TYPE_SK_REUSEPORT: 3514 case BPF_PROG_TYPE_FLOW_DISSECTOR: 3515 case BPF_PROG_TYPE_CGROUP_SKB: 3516 if (t == BPF_WRITE) 3517 return false; 3518 fallthrough; 3519 3520 /* Program types with direct read + write access go here! */ 3521 case BPF_PROG_TYPE_SCHED_CLS: 3522 case BPF_PROG_TYPE_SCHED_ACT: 3523 case BPF_PROG_TYPE_XDP: 3524 case BPF_PROG_TYPE_LWT_XMIT: 3525 case BPF_PROG_TYPE_SK_SKB: 3526 case BPF_PROG_TYPE_SK_MSG: 3527 if (meta) 3528 return meta->pkt_access; 3529 3530 env->seen_direct_write = true; 3531 return true; 3532 3533 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 3534 if (t == BPF_WRITE) 3535 env->seen_direct_write = true; 3536 3537 return true; 3538 3539 default: 3540 return false; 3541 } 3542 } 3543 3544 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 3545 int size, bool zero_size_allowed) 3546 { 3547 struct bpf_reg_state *regs = cur_regs(env); 3548 struct bpf_reg_state *reg = ®s[regno]; 3549 int err; 3550 3551 /* We may have added a variable offset to the packet pointer; but any 3552 * reg->range we have comes after that. We are only checking the fixed 3553 * offset. 3554 */ 3555 3556 /* We don't allow negative numbers, because we aren't tracking enough 3557 * detail to prove they're safe. 3558 */ 3559 if (reg->smin_value < 0) { 3560 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3561 regno); 3562 return -EACCES; 3563 } 3564 3565 err = reg->range < 0 ? -EINVAL : 3566 __check_mem_access(env, regno, off, size, reg->range, 3567 zero_size_allowed); 3568 if (err) { 3569 verbose(env, "R%d offset is outside of the packet\n", regno); 3570 return err; 3571 } 3572 3573 /* __check_mem_access has made sure "off + size - 1" is within u16. 3574 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 3575 * otherwise find_good_pkt_pointers would have refused to set range info 3576 * that __check_mem_access would have rejected this pkt access. 3577 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 3578 */ 3579 env->prog->aux->max_pkt_offset = 3580 max_t(u32, env->prog->aux->max_pkt_offset, 3581 off + reg->umax_value + size - 1); 3582 3583 return err; 3584 } 3585 3586 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 3587 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 3588 enum bpf_access_type t, enum bpf_reg_type *reg_type, 3589 struct btf **btf, u32 *btf_id) 3590 { 3591 struct bpf_insn_access_aux info = { 3592 .reg_type = *reg_type, 3593 .log = &env->log, 3594 }; 3595 3596 if (env->ops->is_valid_access && 3597 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 3598 /* A non zero info.ctx_field_size indicates that this field is a 3599 * candidate for later verifier transformation to load the whole 3600 * field and then apply a mask when accessed with a narrower 3601 * access than actual ctx access size. A zero info.ctx_field_size 3602 * will only allow for whole field access and rejects any other 3603 * type of narrower access. 3604 */ 3605 *reg_type = info.reg_type; 3606 3607 if (base_type(*reg_type) == PTR_TO_BTF_ID) { 3608 *btf = info.btf; 3609 *btf_id = info.btf_id; 3610 } else { 3611 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 3612 } 3613 /* remember the offset of last byte accessed in ctx */ 3614 if (env->prog->aux->max_ctx_offset < off + size) 3615 env->prog->aux->max_ctx_offset = off + size; 3616 return 0; 3617 } 3618 3619 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 3620 return -EACCES; 3621 } 3622 3623 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 3624 int size) 3625 { 3626 if (size < 0 || off < 0 || 3627 (u64)off + size > sizeof(struct bpf_flow_keys)) { 3628 verbose(env, "invalid access to flow keys off=%d size=%d\n", 3629 off, size); 3630 return -EACCES; 3631 } 3632 return 0; 3633 } 3634 3635 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 3636 u32 regno, int off, int size, 3637 enum bpf_access_type t) 3638 { 3639 struct bpf_reg_state *regs = cur_regs(env); 3640 struct bpf_reg_state *reg = ®s[regno]; 3641 struct bpf_insn_access_aux info = {}; 3642 bool valid; 3643 3644 if (reg->smin_value < 0) { 3645 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3646 regno); 3647 return -EACCES; 3648 } 3649 3650 switch (reg->type) { 3651 case PTR_TO_SOCK_COMMON: 3652 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 3653 break; 3654 case PTR_TO_SOCKET: 3655 valid = bpf_sock_is_valid_access(off, size, t, &info); 3656 break; 3657 case PTR_TO_TCP_SOCK: 3658 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 3659 break; 3660 case PTR_TO_XDP_SOCK: 3661 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 3662 break; 3663 default: 3664 valid = false; 3665 } 3666 3667 3668 if (valid) { 3669 env->insn_aux_data[insn_idx].ctx_field_size = 3670 info.ctx_field_size; 3671 return 0; 3672 } 3673 3674 verbose(env, "R%d invalid %s access off=%d size=%d\n", 3675 regno, reg_type_str(env, reg->type), off, size); 3676 3677 return -EACCES; 3678 } 3679 3680 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 3681 { 3682 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 3683 } 3684 3685 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 3686 { 3687 const struct bpf_reg_state *reg = reg_state(env, regno); 3688 3689 return reg->type == PTR_TO_CTX; 3690 } 3691 3692 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 3693 { 3694 const struct bpf_reg_state *reg = reg_state(env, regno); 3695 3696 return type_is_sk_pointer(reg->type); 3697 } 3698 3699 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 3700 { 3701 const struct bpf_reg_state *reg = reg_state(env, regno); 3702 3703 return type_is_pkt_pointer(reg->type); 3704 } 3705 3706 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 3707 { 3708 const struct bpf_reg_state *reg = reg_state(env, regno); 3709 3710 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 3711 return reg->type == PTR_TO_FLOW_KEYS; 3712 } 3713 3714 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 3715 const struct bpf_reg_state *reg, 3716 int off, int size, bool strict) 3717 { 3718 struct tnum reg_off; 3719 int ip_align; 3720 3721 /* Byte size accesses are always allowed. */ 3722 if (!strict || size == 1) 3723 return 0; 3724 3725 /* For platforms that do not have a Kconfig enabling 3726 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 3727 * NET_IP_ALIGN is universally set to '2'. And on platforms 3728 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 3729 * to this code only in strict mode where we want to emulate 3730 * the NET_IP_ALIGN==2 checking. Therefore use an 3731 * unconditional IP align value of '2'. 3732 */ 3733 ip_align = 2; 3734 3735 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 3736 if (!tnum_is_aligned(reg_off, size)) { 3737 char tn_buf[48]; 3738 3739 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3740 verbose(env, 3741 "misaligned packet access off %d+%s+%d+%d size %d\n", 3742 ip_align, tn_buf, reg->off, off, size); 3743 return -EACCES; 3744 } 3745 3746 return 0; 3747 } 3748 3749 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 3750 const struct bpf_reg_state *reg, 3751 const char *pointer_desc, 3752 int off, int size, bool strict) 3753 { 3754 struct tnum reg_off; 3755 3756 /* Byte size accesses are always allowed. */ 3757 if (!strict || size == 1) 3758 return 0; 3759 3760 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 3761 if (!tnum_is_aligned(reg_off, size)) { 3762 char tn_buf[48]; 3763 3764 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3765 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 3766 pointer_desc, tn_buf, reg->off, off, size); 3767 return -EACCES; 3768 } 3769 3770 return 0; 3771 } 3772 3773 static int check_ptr_alignment(struct bpf_verifier_env *env, 3774 const struct bpf_reg_state *reg, int off, 3775 int size, bool strict_alignment_once) 3776 { 3777 bool strict = env->strict_alignment || strict_alignment_once; 3778 const char *pointer_desc = ""; 3779 3780 switch (reg->type) { 3781 case PTR_TO_PACKET: 3782 case PTR_TO_PACKET_META: 3783 /* Special case, because of NET_IP_ALIGN. Given metadata sits 3784 * right in front, treat it the very same way. 3785 */ 3786 return check_pkt_ptr_alignment(env, reg, off, size, strict); 3787 case PTR_TO_FLOW_KEYS: 3788 pointer_desc = "flow keys "; 3789 break; 3790 case PTR_TO_MAP_KEY: 3791 pointer_desc = "key "; 3792 break; 3793 case PTR_TO_MAP_VALUE: 3794 pointer_desc = "value "; 3795 break; 3796 case PTR_TO_CTX: 3797 pointer_desc = "context "; 3798 break; 3799 case PTR_TO_STACK: 3800 pointer_desc = "stack "; 3801 /* The stack spill tracking logic in check_stack_write_fixed_off() 3802 * and check_stack_read_fixed_off() relies on stack accesses being 3803 * aligned. 3804 */ 3805 strict = true; 3806 break; 3807 case PTR_TO_SOCKET: 3808 pointer_desc = "sock "; 3809 break; 3810 case PTR_TO_SOCK_COMMON: 3811 pointer_desc = "sock_common "; 3812 break; 3813 case PTR_TO_TCP_SOCK: 3814 pointer_desc = "tcp_sock "; 3815 break; 3816 case PTR_TO_XDP_SOCK: 3817 pointer_desc = "xdp_sock "; 3818 break; 3819 default: 3820 break; 3821 } 3822 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 3823 strict); 3824 } 3825 3826 static int update_stack_depth(struct bpf_verifier_env *env, 3827 const struct bpf_func_state *func, 3828 int off) 3829 { 3830 u16 stack = env->subprog_info[func->subprogno].stack_depth; 3831 3832 if (stack >= -off) 3833 return 0; 3834 3835 /* update known max for given subprogram */ 3836 env->subprog_info[func->subprogno].stack_depth = -off; 3837 return 0; 3838 } 3839 3840 /* starting from main bpf function walk all instructions of the function 3841 * and recursively walk all callees that given function can call. 3842 * Ignore jump and exit insns. 3843 * Since recursion is prevented by check_cfg() this algorithm 3844 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 3845 */ 3846 static int check_max_stack_depth(struct bpf_verifier_env *env) 3847 { 3848 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 3849 struct bpf_subprog_info *subprog = env->subprog_info; 3850 struct bpf_insn *insn = env->prog->insnsi; 3851 bool tail_call_reachable = false; 3852 int ret_insn[MAX_CALL_FRAMES]; 3853 int ret_prog[MAX_CALL_FRAMES]; 3854 int j; 3855 3856 process_func: 3857 /* protect against potential stack overflow that might happen when 3858 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 3859 * depth for such case down to 256 so that the worst case scenario 3860 * would result in 8k stack size (32 which is tailcall limit * 256 = 3861 * 8k). 3862 * 3863 * To get the idea what might happen, see an example: 3864 * func1 -> sub rsp, 128 3865 * subfunc1 -> sub rsp, 256 3866 * tailcall1 -> add rsp, 256 3867 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 3868 * subfunc2 -> sub rsp, 64 3869 * subfunc22 -> sub rsp, 128 3870 * tailcall2 -> add rsp, 128 3871 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 3872 * 3873 * tailcall will unwind the current stack frame but it will not get rid 3874 * of caller's stack as shown on the example above. 3875 */ 3876 if (idx && subprog[idx].has_tail_call && depth >= 256) { 3877 verbose(env, 3878 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 3879 depth); 3880 return -EACCES; 3881 } 3882 /* round up to 32-bytes, since this is granularity 3883 * of interpreter stack size 3884 */ 3885 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 3886 if (depth > MAX_BPF_STACK) { 3887 verbose(env, "combined stack size of %d calls is %d. Too large\n", 3888 frame + 1, depth); 3889 return -EACCES; 3890 } 3891 continue_func: 3892 subprog_end = subprog[idx + 1].start; 3893 for (; i < subprog_end; i++) { 3894 int next_insn; 3895 3896 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 3897 continue; 3898 /* remember insn and function to return to */ 3899 ret_insn[frame] = i + 1; 3900 ret_prog[frame] = idx; 3901 3902 /* find the callee */ 3903 next_insn = i + insn[i].imm + 1; 3904 idx = find_subprog(env, next_insn); 3905 if (idx < 0) { 3906 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 3907 next_insn); 3908 return -EFAULT; 3909 } 3910 if (subprog[idx].is_async_cb) { 3911 if (subprog[idx].has_tail_call) { 3912 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 3913 return -EFAULT; 3914 } 3915 /* async callbacks don't increase bpf prog stack size */ 3916 continue; 3917 } 3918 i = next_insn; 3919 3920 if (subprog[idx].has_tail_call) 3921 tail_call_reachable = true; 3922 3923 frame++; 3924 if (frame >= MAX_CALL_FRAMES) { 3925 verbose(env, "the call stack of %d frames is too deep !\n", 3926 frame); 3927 return -E2BIG; 3928 } 3929 goto process_func; 3930 } 3931 /* if tail call got detected across bpf2bpf calls then mark each of the 3932 * currently present subprog frames as tail call reachable subprogs; 3933 * this info will be utilized by JIT so that we will be preserving the 3934 * tail call counter throughout bpf2bpf calls combined with tailcalls 3935 */ 3936 if (tail_call_reachable) 3937 for (j = 0; j < frame; j++) 3938 subprog[ret_prog[j]].tail_call_reachable = true; 3939 if (subprog[0].tail_call_reachable) 3940 env->prog->aux->tail_call_reachable = true; 3941 3942 /* end of for() loop means the last insn of the 'subprog' 3943 * was reached. Doesn't matter whether it was JA or EXIT 3944 */ 3945 if (frame == 0) 3946 return 0; 3947 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 3948 frame--; 3949 i = ret_insn[frame]; 3950 idx = ret_prog[frame]; 3951 goto continue_func; 3952 } 3953 3954 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 3955 static int get_callee_stack_depth(struct bpf_verifier_env *env, 3956 const struct bpf_insn *insn, int idx) 3957 { 3958 int start = idx + insn->imm + 1, subprog; 3959 3960 subprog = find_subprog(env, start); 3961 if (subprog < 0) { 3962 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 3963 start); 3964 return -EFAULT; 3965 } 3966 return env->subprog_info[subprog].stack_depth; 3967 } 3968 #endif 3969 3970 int check_ctx_reg(struct bpf_verifier_env *env, 3971 const struct bpf_reg_state *reg, int regno) 3972 { 3973 /* Access to ctx or passing it to a helper is only allowed in 3974 * its original, unmodified form. 3975 */ 3976 3977 if (reg->off) { 3978 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n", 3979 regno, reg->off); 3980 return -EACCES; 3981 } 3982 3983 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3984 char tn_buf[48]; 3985 3986 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3987 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf); 3988 return -EACCES; 3989 } 3990 3991 return 0; 3992 } 3993 3994 static int __check_buffer_access(struct bpf_verifier_env *env, 3995 const char *buf_info, 3996 const struct bpf_reg_state *reg, 3997 int regno, int off, int size) 3998 { 3999 if (off < 0) { 4000 verbose(env, 4001 "R%d invalid %s buffer access: off=%d, size=%d\n", 4002 regno, buf_info, off, size); 4003 return -EACCES; 4004 } 4005 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4006 char tn_buf[48]; 4007 4008 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4009 verbose(env, 4010 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 4011 regno, off, tn_buf); 4012 return -EACCES; 4013 } 4014 4015 return 0; 4016 } 4017 4018 static int check_tp_buffer_access(struct bpf_verifier_env *env, 4019 const struct bpf_reg_state *reg, 4020 int regno, int off, int size) 4021 { 4022 int err; 4023 4024 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 4025 if (err) 4026 return err; 4027 4028 if (off + size > env->prog->aux->max_tp_access) 4029 env->prog->aux->max_tp_access = off + size; 4030 4031 return 0; 4032 } 4033 4034 static int check_buffer_access(struct bpf_verifier_env *env, 4035 const struct bpf_reg_state *reg, 4036 int regno, int off, int size, 4037 bool zero_size_allowed, 4038 const char *buf_info, 4039 u32 *max_access) 4040 { 4041 int err; 4042 4043 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 4044 if (err) 4045 return err; 4046 4047 if (off + size > *max_access) 4048 *max_access = off + size; 4049 4050 return 0; 4051 } 4052 4053 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 4054 static void zext_32_to_64(struct bpf_reg_state *reg) 4055 { 4056 reg->var_off = tnum_subreg(reg->var_off); 4057 __reg_assign_32_into_64(reg); 4058 } 4059 4060 /* truncate register to smaller size (in bytes) 4061 * must be called with size < BPF_REG_SIZE 4062 */ 4063 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 4064 { 4065 u64 mask; 4066 4067 /* clear high bits in bit representation */ 4068 reg->var_off = tnum_cast(reg->var_off, size); 4069 4070 /* fix arithmetic bounds */ 4071 mask = ((u64)1 << (size * 8)) - 1; 4072 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 4073 reg->umin_value &= mask; 4074 reg->umax_value &= mask; 4075 } else { 4076 reg->umin_value = 0; 4077 reg->umax_value = mask; 4078 } 4079 reg->smin_value = reg->umin_value; 4080 reg->smax_value = reg->umax_value; 4081 4082 /* If size is smaller than 32bit register the 32bit register 4083 * values are also truncated so we push 64-bit bounds into 4084 * 32-bit bounds. Above were truncated < 32-bits already. 4085 */ 4086 if (size >= 4) 4087 return; 4088 __reg_combine_64_into_32(reg); 4089 } 4090 4091 static bool bpf_map_is_rdonly(const struct bpf_map *map) 4092 { 4093 /* A map is considered read-only if the following condition are true: 4094 * 4095 * 1) BPF program side cannot change any of the map content. The 4096 * BPF_F_RDONLY_PROG flag is throughout the lifetime of a map 4097 * and was set at map creation time. 4098 * 2) The map value(s) have been initialized from user space by a 4099 * loader and then "frozen", such that no new map update/delete 4100 * operations from syscall side are possible for the rest of 4101 * the map's lifetime from that point onwards. 4102 * 3) Any parallel/pending map update/delete operations from syscall 4103 * side have been completed. Only after that point, it's safe to 4104 * assume that map value(s) are immutable. 4105 */ 4106 return (map->map_flags & BPF_F_RDONLY_PROG) && 4107 READ_ONCE(map->frozen) && 4108 !bpf_map_write_active(map); 4109 } 4110 4111 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 4112 { 4113 void *ptr; 4114 u64 addr; 4115 int err; 4116 4117 err = map->ops->map_direct_value_addr(map, &addr, off); 4118 if (err) 4119 return err; 4120 ptr = (void *)(long)addr + off; 4121 4122 switch (size) { 4123 case sizeof(u8): 4124 *val = (u64)*(u8 *)ptr; 4125 break; 4126 case sizeof(u16): 4127 *val = (u64)*(u16 *)ptr; 4128 break; 4129 case sizeof(u32): 4130 *val = (u64)*(u32 *)ptr; 4131 break; 4132 case sizeof(u64): 4133 *val = *(u64 *)ptr; 4134 break; 4135 default: 4136 return -EINVAL; 4137 } 4138 return 0; 4139 } 4140 4141 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 4142 struct bpf_reg_state *regs, 4143 int regno, int off, int size, 4144 enum bpf_access_type atype, 4145 int value_regno) 4146 { 4147 struct bpf_reg_state *reg = regs + regno; 4148 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 4149 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 4150 u32 btf_id; 4151 int ret; 4152 4153 if (off < 0) { 4154 verbose(env, 4155 "R%d is ptr_%s invalid negative access: off=%d\n", 4156 regno, tname, off); 4157 return -EACCES; 4158 } 4159 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4160 char tn_buf[48]; 4161 4162 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4163 verbose(env, 4164 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 4165 regno, tname, off, tn_buf); 4166 return -EACCES; 4167 } 4168 4169 if (env->ops->btf_struct_access) { 4170 ret = env->ops->btf_struct_access(&env->log, reg->btf, t, 4171 off, size, atype, &btf_id); 4172 } else { 4173 if (atype != BPF_READ) { 4174 verbose(env, "only read is supported\n"); 4175 return -EACCES; 4176 } 4177 4178 ret = btf_struct_access(&env->log, reg->btf, t, off, size, 4179 atype, &btf_id); 4180 } 4181 4182 if (ret < 0) 4183 return ret; 4184 4185 if (atype == BPF_READ && value_regno >= 0) 4186 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id); 4187 4188 return 0; 4189 } 4190 4191 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 4192 struct bpf_reg_state *regs, 4193 int regno, int off, int size, 4194 enum bpf_access_type atype, 4195 int value_regno) 4196 { 4197 struct bpf_reg_state *reg = regs + regno; 4198 struct bpf_map *map = reg->map_ptr; 4199 const struct btf_type *t; 4200 const char *tname; 4201 u32 btf_id; 4202 int ret; 4203 4204 if (!btf_vmlinux) { 4205 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 4206 return -ENOTSUPP; 4207 } 4208 4209 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 4210 verbose(env, "map_ptr access not supported for map type %d\n", 4211 map->map_type); 4212 return -ENOTSUPP; 4213 } 4214 4215 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 4216 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 4217 4218 if (!env->allow_ptr_to_map_access) { 4219 verbose(env, 4220 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 4221 tname); 4222 return -EPERM; 4223 } 4224 4225 if (off < 0) { 4226 verbose(env, "R%d is %s invalid negative access: off=%d\n", 4227 regno, tname, off); 4228 return -EACCES; 4229 } 4230 4231 if (atype != BPF_READ) { 4232 verbose(env, "only read from %s is supported\n", tname); 4233 return -EACCES; 4234 } 4235 4236 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id); 4237 if (ret < 0) 4238 return ret; 4239 4240 if (value_regno >= 0) 4241 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id); 4242 4243 return 0; 4244 } 4245 4246 /* Check that the stack access at the given offset is within bounds. The 4247 * maximum valid offset is -1. 4248 * 4249 * The minimum valid offset is -MAX_BPF_STACK for writes, and 4250 * -state->allocated_stack for reads. 4251 */ 4252 static int check_stack_slot_within_bounds(int off, 4253 struct bpf_func_state *state, 4254 enum bpf_access_type t) 4255 { 4256 int min_valid_off; 4257 4258 if (t == BPF_WRITE) 4259 min_valid_off = -MAX_BPF_STACK; 4260 else 4261 min_valid_off = -state->allocated_stack; 4262 4263 if (off < min_valid_off || off > -1) 4264 return -EACCES; 4265 return 0; 4266 } 4267 4268 /* Check that the stack access at 'regno + off' falls within the maximum stack 4269 * bounds. 4270 * 4271 * 'off' includes `regno->offset`, but not its dynamic part (if any). 4272 */ 4273 static int check_stack_access_within_bounds( 4274 struct bpf_verifier_env *env, 4275 int regno, int off, int access_size, 4276 enum stack_access_src src, enum bpf_access_type type) 4277 { 4278 struct bpf_reg_state *regs = cur_regs(env); 4279 struct bpf_reg_state *reg = regs + regno; 4280 struct bpf_func_state *state = func(env, reg); 4281 int min_off, max_off; 4282 int err; 4283 char *err_extra; 4284 4285 if (src == ACCESS_HELPER) 4286 /* We don't know if helpers are reading or writing (or both). */ 4287 err_extra = " indirect access to"; 4288 else if (type == BPF_READ) 4289 err_extra = " read from"; 4290 else 4291 err_extra = " write to"; 4292 4293 if (tnum_is_const(reg->var_off)) { 4294 min_off = reg->var_off.value + off; 4295 if (access_size > 0) 4296 max_off = min_off + access_size - 1; 4297 else 4298 max_off = min_off; 4299 } else { 4300 if (reg->smax_value >= BPF_MAX_VAR_OFF || 4301 reg->smin_value <= -BPF_MAX_VAR_OFF) { 4302 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 4303 err_extra, regno); 4304 return -EACCES; 4305 } 4306 min_off = reg->smin_value + off; 4307 if (access_size > 0) 4308 max_off = reg->smax_value + off + access_size - 1; 4309 else 4310 max_off = min_off; 4311 } 4312 4313 err = check_stack_slot_within_bounds(min_off, state, type); 4314 if (!err) 4315 err = check_stack_slot_within_bounds(max_off, state, type); 4316 4317 if (err) { 4318 if (tnum_is_const(reg->var_off)) { 4319 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 4320 err_extra, regno, off, access_size); 4321 } else { 4322 char tn_buf[48]; 4323 4324 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4325 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 4326 err_extra, regno, tn_buf, access_size); 4327 } 4328 } 4329 return err; 4330 } 4331 4332 /* check whether memory at (regno + off) is accessible for t = (read | write) 4333 * if t==write, value_regno is a register which value is stored into memory 4334 * if t==read, value_regno is a register which will receive the value from memory 4335 * if t==write && value_regno==-1, some unknown value is stored into memory 4336 * if t==read && value_regno==-1, don't care what we read from memory 4337 */ 4338 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 4339 int off, int bpf_size, enum bpf_access_type t, 4340 int value_regno, bool strict_alignment_once) 4341 { 4342 struct bpf_reg_state *regs = cur_regs(env); 4343 struct bpf_reg_state *reg = regs + regno; 4344 struct bpf_func_state *state; 4345 int size, err = 0; 4346 4347 size = bpf_size_to_bytes(bpf_size); 4348 if (size < 0) 4349 return size; 4350 4351 /* alignment checks will add in reg->off themselves */ 4352 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 4353 if (err) 4354 return err; 4355 4356 /* for access checks, reg->off is just part of off */ 4357 off += reg->off; 4358 4359 if (reg->type == PTR_TO_MAP_KEY) { 4360 if (t == BPF_WRITE) { 4361 verbose(env, "write to change key R%d not allowed\n", regno); 4362 return -EACCES; 4363 } 4364 4365 err = check_mem_region_access(env, regno, off, size, 4366 reg->map_ptr->key_size, false); 4367 if (err) 4368 return err; 4369 if (value_regno >= 0) 4370 mark_reg_unknown(env, regs, value_regno); 4371 } else if (reg->type == PTR_TO_MAP_VALUE) { 4372 if (t == BPF_WRITE && value_regno >= 0 && 4373 is_pointer_value(env, value_regno)) { 4374 verbose(env, "R%d leaks addr into map\n", value_regno); 4375 return -EACCES; 4376 } 4377 err = check_map_access_type(env, regno, off, size, t); 4378 if (err) 4379 return err; 4380 err = check_map_access(env, regno, off, size, false); 4381 if (!err && t == BPF_READ && value_regno >= 0) { 4382 struct bpf_map *map = reg->map_ptr; 4383 4384 /* if map is read-only, track its contents as scalars */ 4385 if (tnum_is_const(reg->var_off) && 4386 bpf_map_is_rdonly(map) && 4387 map->ops->map_direct_value_addr) { 4388 int map_off = off + reg->var_off.value; 4389 u64 val = 0; 4390 4391 err = bpf_map_direct_read(map, map_off, size, 4392 &val); 4393 if (err) 4394 return err; 4395 4396 regs[value_regno].type = SCALAR_VALUE; 4397 __mark_reg_known(®s[value_regno], val); 4398 } else { 4399 mark_reg_unknown(env, regs, value_regno); 4400 } 4401 } 4402 } else if (base_type(reg->type) == PTR_TO_MEM) { 4403 bool rdonly_mem = type_is_rdonly_mem(reg->type); 4404 4405 if (type_may_be_null(reg->type)) { 4406 verbose(env, "R%d invalid mem access '%s'\n", regno, 4407 reg_type_str(env, reg->type)); 4408 return -EACCES; 4409 } 4410 4411 if (t == BPF_WRITE && rdonly_mem) { 4412 verbose(env, "R%d cannot write into %s\n", 4413 regno, reg_type_str(env, reg->type)); 4414 return -EACCES; 4415 } 4416 4417 if (t == BPF_WRITE && value_regno >= 0 && 4418 is_pointer_value(env, value_regno)) { 4419 verbose(env, "R%d leaks addr into mem\n", value_regno); 4420 return -EACCES; 4421 } 4422 4423 err = check_mem_region_access(env, regno, off, size, 4424 reg->mem_size, false); 4425 if (!err && value_regno >= 0 && (t == BPF_READ || rdonly_mem)) 4426 mark_reg_unknown(env, regs, value_regno); 4427 } else if (reg->type == PTR_TO_CTX) { 4428 enum bpf_reg_type reg_type = SCALAR_VALUE; 4429 struct btf *btf = NULL; 4430 u32 btf_id = 0; 4431 4432 if (t == BPF_WRITE && value_regno >= 0 && 4433 is_pointer_value(env, value_regno)) { 4434 verbose(env, "R%d leaks addr into ctx\n", value_regno); 4435 return -EACCES; 4436 } 4437 4438 err = check_ctx_reg(env, reg, regno); 4439 if (err < 0) 4440 return err; 4441 4442 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, &btf_id); 4443 if (err) 4444 verbose_linfo(env, insn_idx, "; "); 4445 if (!err && t == BPF_READ && value_regno >= 0) { 4446 /* ctx access returns either a scalar, or a 4447 * PTR_TO_PACKET[_META,_END]. In the latter 4448 * case, we know the offset is zero. 4449 */ 4450 if (reg_type == SCALAR_VALUE) { 4451 mark_reg_unknown(env, regs, value_regno); 4452 } else { 4453 mark_reg_known_zero(env, regs, 4454 value_regno); 4455 if (type_may_be_null(reg_type)) 4456 regs[value_regno].id = ++env->id_gen; 4457 /* A load of ctx field could have different 4458 * actual load size with the one encoded in the 4459 * insn. When the dst is PTR, it is for sure not 4460 * a sub-register. 4461 */ 4462 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 4463 if (base_type(reg_type) == PTR_TO_BTF_ID) { 4464 regs[value_regno].btf = btf; 4465 regs[value_regno].btf_id = btf_id; 4466 } 4467 } 4468 regs[value_regno].type = reg_type; 4469 } 4470 4471 } else if (reg->type == PTR_TO_STACK) { 4472 /* Basic bounds checks. */ 4473 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 4474 if (err) 4475 return err; 4476 4477 state = func(env, reg); 4478 err = update_stack_depth(env, state, off); 4479 if (err) 4480 return err; 4481 4482 if (t == BPF_READ) 4483 err = check_stack_read(env, regno, off, size, 4484 value_regno); 4485 else 4486 err = check_stack_write(env, regno, off, size, 4487 value_regno, insn_idx); 4488 } else if (reg_is_pkt_pointer(reg)) { 4489 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 4490 verbose(env, "cannot write into packet\n"); 4491 return -EACCES; 4492 } 4493 if (t == BPF_WRITE && value_regno >= 0 && 4494 is_pointer_value(env, value_regno)) { 4495 verbose(env, "R%d leaks addr into packet\n", 4496 value_regno); 4497 return -EACCES; 4498 } 4499 err = check_packet_access(env, regno, off, size, false); 4500 if (!err && t == BPF_READ && value_regno >= 0) 4501 mark_reg_unknown(env, regs, value_regno); 4502 } else if (reg->type == PTR_TO_FLOW_KEYS) { 4503 if (t == BPF_WRITE && value_regno >= 0 && 4504 is_pointer_value(env, value_regno)) { 4505 verbose(env, "R%d leaks addr into flow keys\n", 4506 value_regno); 4507 return -EACCES; 4508 } 4509 4510 err = check_flow_keys_access(env, off, size); 4511 if (!err && t == BPF_READ && value_regno >= 0) 4512 mark_reg_unknown(env, regs, value_regno); 4513 } else if (type_is_sk_pointer(reg->type)) { 4514 if (t == BPF_WRITE) { 4515 verbose(env, "R%d cannot write into %s\n", 4516 regno, reg_type_str(env, reg->type)); 4517 return -EACCES; 4518 } 4519 err = check_sock_access(env, insn_idx, regno, off, size, t); 4520 if (!err && value_regno >= 0) 4521 mark_reg_unknown(env, regs, value_regno); 4522 } else if (reg->type == PTR_TO_TP_BUFFER) { 4523 err = check_tp_buffer_access(env, reg, regno, off, size); 4524 if (!err && t == BPF_READ && value_regno >= 0) 4525 mark_reg_unknown(env, regs, value_regno); 4526 } else if (reg->type == PTR_TO_BTF_ID) { 4527 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 4528 value_regno); 4529 } else if (reg->type == CONST_PTR_TO_MAP) { 4530 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 4531 value_regno); 4532 } else if (base_type(reg->type) == PTR_TO_BUF) { 4533 bool rdonly_mem = type_is_rdonly_mem(reg->type); 4534 const char *buf_info; 4535 u32 *max_access; 4536 4537 if (rdonly_mem) { 4538 if (t == BPF_WRITE) { 4539 verbose(env, "R%d cannot write into %s\n", 4540 regno, reg_type_str(env, reg->type)); 4541 return -EACCES; 4542 } 4543 buf_info = "rdonly"; 4544 max_access = &env->prog->aux->max_rdonly_access; 4545 } else { 4546 buf_info = "rdwr"; 4547 max_access = &env->prog->aux->max_rdwr_access; 4548 } 4549 4550 err = check_buffer_access(env, reg, regno, off, size, false, 4551 buf_info, max_access); 4552 4553 if (!err && value_regno >= 0 && (rdonly_mem || t == BPF_READ)) 4554 mark_reg_unknown(env, regs, value_regno); 4555 } else { 4556 verbose(env, "R%d invalid mem access '%s'\n", regno, 4557 reg_type_str(env, reg->type)); 4558 return -EACCES; 4559 } 4560 4561 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 4562 regs[value_regno].type == SCALAR_VALUE) { 4563 /* b/h/w load zero-extends, mark upper bits as known 0 */ 4564 coerce_reg_to_size(®s[value_regno], size); 4565 } 4566 return err; 4567 } 4568 4569 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 4570 { 4571 int load_reg; 4572 int err; 4573 4574 switch (insn->imm) { 4575 case BPF_ADD: 4576 case BPF_ADD | BPF_FETCH: 4577 case BPF_AND: 4578 case BPF_AND | BPF_FETCH: 4579 case BPF_OR: 4580 case BPF_OR | BPF_FETCH: 4581 case BPF_XOR: 4582 case BPF_XOR | BPF_FETCH: 4583 case BPF_XCHG: 4584 case BPF_CMPXCHG: 4585 break; 4586 default: 4587 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 4588 return -EINVAL; 4589 } 4590 4591 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 4592 verbose(env, "invalid atomic operand size\n"); 4593 return -EINVAL; 4594 } 4595 4596 /* check src1 operand */ 4597 err = check_reg_arg(env, insn->src_reg, SRC_OP); 4598 if (err) 4599 return err; 4600 4601 /* check src2 operand */ 4602 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 4603 if (err) 4604 return err; 4605 4606 if (insn->imm == BPF_CMPXCHG) { 4607 /* Check comparison of R0 with memory location */ 4608 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 4609 if (err) 4610 return err; 4611 } 4612 4613 if (is_pointer_value(env, insn->src_reg)) { 4614 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 4615 return -EACCES; 4616 } 4617 4618 if (is_ctx_reg(env, insn->dst_reg) || 4619 is_pkt_reg(env, insn->dst_reg) || 4620 is_flow_key_reg(env, insn->dst_reg) || 4621 is_sk_reg(env, insn->dst_reg)) { 4622 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 4623 insn->dst_reg, 4624 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 4625 return -EACCES; 4626 } 4627 4628 if (insn->imm & BPF_FETCH) { 4629 if (insn->imm == BPF_CMPXCHG) 4630 load_reg = BPF_REG_0; 4631 else 4632 load_reg = insn->src_reg; 4633 4634 /* check and record load of old value */ 4635 err = check_reg_arg(env, load_reg, DST_OP); 4636 if (err) 4637 return err; 4638 } else { 4639 /* This instruction accesses a memory location but doesn't 4640 * actually load it into a register. 4641 */ 4642 load_reg = -1; 4643 } 4644 4645 /* check whether we can read the memory */ 4646 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 4647 BPF_SIZE(insn->code), BPF_READ, load_reg, true); 4648 if (err) 4649 return err; 4650 4651 /* check whether we can write into the same memory */ 4652 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 4653 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 4654 if (err) 4655 return err; 4656 4657 return 0; 4658 } 4659 4660 /* When register 'regno' is used to read the stack (either directly or through 4661 * a helper function) make sure that it's within stack boundary and, depending 4662 * on the access type, that all elements of the stack are initialized. 4663 * 4664 * 'off' includes 'regno->off', but not its dynamic part (if any). 4665 * 4666 * All registers that have been spilled on the stack in the slots within the 4667 * read offsets are marked as read. 4668 */ 4669 static int check_stack_range_initialized( 4670 struct bpf_verifier_env *env, int regno, int off, 4671 int access_size, bool zero_size_allowed, 4672 enum stack_access_src type, struct bpf_call_arg_meta *meta) 4673 { 4674 struct bpf_reg_state *reg = reg_state(env, regno); 4675 struct bpf_func_state *state = func(env, reg); 4676 int err, min_off, max_off, i, j, slot, spi; 4677 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 4678 enum bpf_access_type bounds_check_type; 4679 /* Some accesses can write anything into the stack, others are 4680 * read-only. 4681 */ 4682 bool clobber = false; 4683 4684 if (access_size == 0 && !zero_size_allowed) { 4685 verbose(env, "invalid zero-sized read\n"); 4686 return -EACCES; 4687 } 4688 4689 if (type == ACCESS_HELPER) { 4690 /* The bounds checks for writes are more permissive than for 4691 * reads. However, if raw_mode is not set, we'll do extra 4692 * checks below. 4693 */ 4694 bounds_check_type = BPF_WRITE; 4695 clobber = true; 4696 } else { 4697 bounds_check_type = BPF_READ; 4698 } 4699 err = check_stack_access_within_bounds(env, regno, off, access_size, 4700 type, bounds_check_type); 4701 if (err) 4702 return err; 4703 4704 4705 if (tnum_is_const(reg->var_off)) { 4706 min_off = max_off = reg->var_off.value + off; 4707 } else { 4708 /* Variable offset is prohibited for unprivileged mode for 4709 * simplicity since it requires corresponding support in 4710 * Spectre masking for stack ALU. 4711 * See also retrieve_ptr_limit(). 4712 */ 4713 if (!env->bypass_spec_v1) { 4714 char tn_buf[48]; 4715 4716 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4717 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 4718 regno, err_extra, tn_buf); 4719 return -EACCES; 4720 } 4721 /* Only initialized buffer on stack is allowed to be accessed 4722 * with variable offset. With uninitialized buffer it's hard to 4723 * guarantee that whole memory is marked as initialized on 4724 * helper return since specific bounds are unknown what may 4725 * cause uninitialized stack leaking. 4726 */ 4727 if (meta && meta->raw_mode) 4728 meta = NULL; 4729 4730 min_off = reg->smin_value + off; 4731 max_off = reg->smax_value + off; 4732 } 4733 4734 if (meta && meta->raw_mode) { 4735 meta->access_size = access_size; 4736 meta->regno = regno; 4737 return 0; 4738 } 4739 4740 for (i = min_off; i < max_off + access_size; i++) { 4741 u8 *stype; 4742 4743 slot = -i - 1; 4744 spi = slot / BPF_REG_SIZE; 4745 if (state->allocated_stack <= slot) 4746 goto err; 4747 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4748 if (*stype == STACK_MISC) 4749 goto mark; 4750 if (*stype == STACK_ZERO) { 4751 if (clobber) { 4752 /* helper can write anything into the stack */ 4753 *stype = STACK_MISC; 4754 } 4755 goto mark; 4756 } 4757 4758 if (is_spilled_reg(&state->stack[spi]) && 4759 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID) 4760 goto mark; 4761 4762 if (is_spilled_reg(&state->stack[spi]) && 4763 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 4764 env->allow_ptr_leaks)) { 4765 if (clobber) { 4766 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 4767 for (j = 0; j < BPF_REG_SIZE; j++) 4768 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 4769 } 4770 goto mark; 4771 } 4772 4773 err: 4774 if (tnum_is_const(reg->var_off)) { 4775 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 4776 err_extra, regno, min_off, i - min_off, access_size); 4777 } else { 4778 char tn_buf[48]; 4779 4780 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4781 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 4782 err_extra, regno, tn_buf, i - min_off, access_size); 4783 } 4784 return -EACCES; 4785 mark: 4786 /* reading any byte out of 8-byte 'spill_slot' will cause 4787 * the whole slot to be marked as 'read' 4788 */ 4789 mark_reg_read(env, &state->stack[spi].spilled_ptr, 4790 state->stack[spi].spilled_ptr.parent, 4791 REG_LIVE_READ64); 4792 } 4793 return update_stack_depth(env, state, min_off); 4794 } 4795 4796 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 4797 int access_size, bool zero_size_allowed, 4798 struct bpf_call_arg_meta *meta) 4799 { 4800 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4801 const char *buf_info; 4802 u32 *max_access; 4803 4804 switch (base_type(reg->type)) { 4805 case PTR_TO_PACKET: 4806 case PTR_TO_PACKET_META: 4807 return check_packet_access(env, regno, reg->off, access_size, 4808 zero_size_allowed); 4809 case PTR_TO_MAP_KEY: 4810 return check_mem_region_access(env, regno, reg->off, access_size, 4811 reg->map_ptr->key_size, false); 4812 case PTR_TO_MAP_VALUE: 4813 if (check_map_access_type(env, regno, reg->off, access_size, 4814 meta && meta->raw_mode ? BPF_WRITE : 4815 BPF_READ)) 4816 return -EACCES; 4817 return check_map_access(env, regno, reg->off, access_size, 4818 zero_size_allowed); 4819 case PTR_TO_MEM: 4820 return check_mem_region_access(env, regno, reg->off, 4821 access_size, reg->mem_size, 4822 zero_size_allowed); 4823 case PTR_TO_BUF: 4824 if (type_is_rdonly_mem(reg->type)) { 4825 if (meta && meta->raw_mode) 4826 return -EACCES; 4827 4828 buf_info = "rdonly"; 4829 max_access = &env->prog->aux->max_rdonly_access; 4830 } else { 4831 buf_info = "rdwr"; 4832 max_access = &env->prog->aux->max_rdwr_access; 4833 } 4834 return check_buffer_access(env, reg, regno, reg->off, 4835 access_size, zero_size_allowed, 4836 buf_info, max_access); 4837 case PTR_TO_STACK: 4838 return check_stack_range_initialized( 4839 env, 4840 regno, reg->off, access_size, 4841 zero_size_allowed, ACCESS_HELPER, meta); 4842 default: /* scalar_value or invalid ptr */ 4843 /* Allow zero-byte read from NULL, regardless of pointer type */ 4844 if (zero_size_allowed && access_size == 0 && 4845 register_is_null(reg)) 4846 return 0; 4847 4848 verbose(env, "R%d type=%s ", regno, 4849 reg_type_str(env, reg->type)); 4850 verbose(env, "expected=%s\n", reg_type_str(env, PTR_TO_STACK)); 4851 return -EACCES; 4852 } 4853 } 4854 4855 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4856 u32 regno, u32 mem_size) 4857 { 4858 if (register_is_null(reg)) 4859 return 0; 4860 4861 if (type_may_be_null(reg->type)) { 4862 /* Assuming that the register contains a value check if the memory 4863 * access is safe. Temporarily save and restore the register's state as 4864 * the conversion shouldn't be visible to a caller. 4865 */ 4866 const struct bpf_reg_state saved_reg = *reg; 4867 int rv; 4868 4869 mark_ptr_not_null_reg(reg); 4870 rv = check_helper_mem_access(env, regno, mem_size, true, NULL); 4871 *reg = saved_reg; 4872 return rv; 4873 } 4874 4875 return check_helper_mem_access(env, regno, mem_size, true, NULL); 4876 } 4877 4878 /* Implementation details: 4879 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL 4880 * Two bpf_map_lookups (even with the same key) will have different reg->id. 4881 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after 4882 * value_or_null->value transition, since the verifier only cares about 4883 * the range of access to valid map value pointer and doesn't care about actual 4884 * address of the map element. 4885 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 4886 * reg->id > 0 after value_or_null->value transition. By doing so 4887 * two bpf_map_lookups will be considered two different pointers that 4888 * point to different bpf_spin_locks. 4889 * The verifier allows taking only one bpf_spin_lock at a time to avoid 4890 * dead-locks. 4891 * Since only one bpf_spin_lock is allowed the checks are simpler than 4892 * reg_is_refcounted() logic. The verifier needs to remember only 4893 * one spin_lock instead of array of acquired_refs. 4894 * cur_state->active_spin_lock remembers which map value element got locked 4895 * and clears it after bpf_spin_unlock. 4896 */ 4897 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 4898 bool is_lock) 4899 { 4900 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4901 struct bpf_verifier_state *cur = env->cur_state; 4902 bool is_const = tnum_is_const(reg->var_off); 4903 struct bpf_map *map = reg->map_ptr; 4904 u64 val = reg->var_off.value; 4905 4906 if (!is_const) { 4907 verbose(env, 4908 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 4909 regno); 4910 return -EINVAL; 4911 } 4912 if (!map->btf) { 4913 verbose(env, 4914 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 4915 map->name); 4916 return -EINVAL; 4917 } 4918 if (!map_value_has_spin_lock(map)) { 4919 if (map->spin_lock_off == -E2BIG) 4920 verbose(env, 4921 "map '%s' has more than one 'struct bpf_spin_lock'\n", 4922 map->name); 4923 else if (map->spin_lock_off == -ENOENT) 4924 verbose(env, 4925 "map '%s' doesn't have 'struct bpf_spin_lock'\n", 4926 map->name); 4927 else 4928 verbose(env, 4929 "map '%s' is not a struct type or bpf_spin_lock is mangled\n", 4930 map->name); 4931 return -EINVAL; 4932 } 4933 if (map->spin_lock_off != val + reg->off) { 4934 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n", 4935 val + reg->off); 4936 return -EINVAL; 4937 } 4938 if (is_lock) { 4939 if (cur->active_spin_lock) { 4940 verbose(env, 4941 "Locking two bpf_spin_locks are not allowed\n"); 4942 return -EINVAL; 4943 } 4944 cur->active_spin_lock = reg->id; 4945 } else { 4946 if (!cur->active_spin_lock) { 4947 verbose(env, "bpf_spin_unlock without taking a lock\n"); 4948 return -EINVAL; 4949 } 4950 if (cur->active_spin_lock != reg->id) { 4951 verbose(env, "bpf_spin_unlock of different lock\n"); 4952 return -EINVAL; 4953 } 4954 cur->active_spin_lock = 0; 4955 } 4956 return 0; 4957 } 4958 4959 static int process_timer_func(struct bpf_verifier_env *env, int regno, 4960 struct bpf_call_arg_meta *meta) 4961 { 4962 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4963 bool is_const = tnum_is_const(reg->var_off); 4964 struct bpf_map *map = reg->map_ptr; 4965 u64 val = reg->var_off.value; 4966 4967 if (!is_const) { 4968 verbose(env, 4969 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 4970 regno); 4971 return -EINVAL; 4972 } 4973 if (!map->btf) { 4974 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 4975 map->name); 4976 return -EINVAL; 4977 } 4978 if (!map_value_has_timer(map)) { 4979 if (map->timer_off == -E2BIG) 4980 verbose(env, 4981 "map '%s' has more than one 'struct bpf_timer'\n", 4982 map->name); 4983 else if (map->timer_off == -ENOENT) 4984 verbose(env, 4985 "map '%s' doesn't have 'struct bpf_timer'\n", 4986 map->name); 4987 else 4988 verbose(env, 4989 "map '%s' is not a struct type or bpf_timer is mangled\n", 4990 map->name); 4991 return -EINVAL; 4992 } 4993 if (map->timer_off != val + reg->off) { 4994 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 4995 val + reg->off, map->timer_off); 4996 return -EINVAL; 4997 } 4998 if (meta->map_ptr) { 4999 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 5000 return -EFAULT; 5001 } 5002 meta->map_uid = reg->map_uid; 5003 meta->map_ptr = map; 5004 return 0; 5005 } 5006 5007 static bool arg_type_is_mem_ptr(enum bpf_arg_type type) 5008 { 5009 return base_type(type) == ARG_PTR_TO_MEM || 5010 base_type(type) == ARG_PTR_TO_UNINIT_MEM; 5011 } 5012 5013 static bool arg_type_is_mem_size(enum bpf_arg_type type) 5014 { 5015 return type == ARG_CONST_SIZE || 5016 type == ARG_CONST_SIZE_OR_ZERO; 5017 } 5018 5019 static bool arg_type_is_alloc_size(enum bpf_arg_type type) 5020 { 5021 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO; 5022 } 5023 5024 static bool arg_type_is_int_ptr(enum bpf_arg_type type) 5025 { 5026 return type == ARG_PTR_TO_INT || 5027 type == ARG_PTR_TO_LONG; 5028 } 5029 5030 static int int_ptr_type_to_size(enum bpf_arg_type type) 5031 { 5032 if (type == ARG_PTR_TO_INT) 5033 return sizeof(u32); 5034 else if (type == ARG_PTR_TO_LONG) 5035 return sizeof(u64); 5036 5037 return -EINVAL; 5038 } 5039 5040 static int resolve_map_arg_type(struct bpf_verifier_env *env, 5041 const struct bpf_call_arg_meta *meta, 5042 enum bpf_arg_type *arg_type) 5043 { 5044 if (!meta->map_ptr) { 5045 /* kernel subsystem misconfigured verifier */ 5046 verbose(env, "invalid map_ptr to access map->type\n"); 5047 return -EACCES; 5048 } 5049 5050 switch (meta->map_ptr->map_type) { 5051 case BPF_MAP_TYPE_SOCKMAP: 5052 case BPF_MAP_TYPE_SOCKHASH: 5053 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 5054 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 5055 } else { 5056 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 5057 return -EINVAL; 5058 } 5059 break; 5060 case BPF_MAP_TYPE_BLOOM_FILTER: 5061 if (meta->func_id == BPF_FUNC_map_peek_elem) 5062 *arg_type = ARG_PTR_TO_MAP_VALUE; 5063 break; 5064 default: 5065 break; 5066 } 5067 return 0; 5068 } 5069 5070 struct bpf_reg_types { 5071 const enum bpf_reg_type types[10]; 5072 u32 *btf_id; 5073 }; 5074 5075 static const struct bpf_reg_types map_key_value_types = { 5076 .types = { 5077 PTR_TO_STACK, 5078 PTR_TO_PACKET, 5079 PTR_TO_PACKET_META, 5080 PTR_TO_MAP_KEY, 5081 PTR_TO_MAP_VALUE, 5082 }, 5083 }; 5084 5085 static const struct bpf_reg_types sock_types = { 5086 .types = { 5087 PTR_TO_SOCK_COMMON, 5088 PTR_TO_SOCKET, 5089 PTR_TO_TCP_SOCK, 5090 PTR_TO_XDP_SOCK, 5091 }, 5092 }; 5093 5094 #ifdef CONFIG_NET 5095 static const struct bpf_reg_types btf_id_sock_common_types = { 5096 .types = { 5097 PTR_TO_SOCK_COMMON, 5098 PTR_TO_SOCKET, 5099 PTR_TO_TCP_SOCK, 5100 PTR_TO_XDP_SOCK, 5101 PTR_TO_BTF_ID, 5102 }, 5103 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5104 }; 5105 #endif 5106 5107 static const struct bpf_reg_types mem_types = { 5108 .types = { 5109 PTR_TO_STACK, 5110 PTR_TO_PACKET, 5111 PTR_TO_PACKET_META, 5112 PTR_TO_MAP_KEY, 5113 PTR_TO_MAP_VALUE, 5114 PTR_TO_MEM, 5115 PTR_TO_BUF, 5116 }, 5117 }; 5118 5119 static const struct bpf_reg_types int_ptr_types = { 5120 .types = { 5121 PTR_TO_STACK, 5122 PTR_TO_PACKET, 5123 PTR_TO_PACKET_META, 5124 PTR_TO_MAP_KEY, 5125 PTR_TO_MAP_VALUE, 5126 }, 5127 }; 5128 5129 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 5130 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 5131 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 5132 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } }; 5133 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 5134 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } }; 5135 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } }; 5136 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } }; 5137 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 5138 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 5139 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 5140 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 5141 5142 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 5143 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types, 5144 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types, 5145 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types, 5146 [ARG_CONST_SIZE] = &scalar_types, 5147 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 5148 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 5149 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 5150 [ARG_PTR_TO_CTX] = &context_types, 5151 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 5152 #ifdef CONFIG_NET 5153 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 5154 #endif 5155 [ARG_PTR_TO_SOCKET] = &fullsock_types, 5156 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 5157 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 5158 [ARG_PTR_TO_MEM] = &mem_types, 5159 [ARG_PTR_TO_UNINIT_MEM] = &mem_types, 5160 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types, 5161 [ARG_PTR_TO_INT] = &int_ptr_types, 5162 [ARG_PTR_TO_LONG] = &int_ptr_types, 5163 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 5164 [ARG_PTR_TO_FUNC] = &func_ptr_types, 5165 [ARG_PTR_TO_STACK] = &stack_ptr_types, 5166 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 5167 [ARG_PTR_TO_TIMER] = &timer_types, 5168 }; 5169 5170 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 5171 enum bpf_arg_type arg_type, 5172 const u32 *arg_btf_id) 5173 { 5174 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5175 enum bpf_reg_type expected, type = reg->type; 5176 const struct bpf_reg_types *compatible; 5177 int i, j; 5178 5179 compatible = compatible_reg_types[base_type(arg_type)]; 5180 if (!compatible) { 5181 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 5182 return -EFAULT; 5183 } 5184 5185 /* ARG_PTR_TO_MEM + RDONLY is compatible with PTR_TO_MEM and PTR_TO_MEM + RDONLY, 5186 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM and NOT with PTR_TO_MEM + RDONLY 5187 * 5188 * Same for MAYBE_NULL: 5189 * 5190 * ARG_PTR_TO_MEM + MAYBE_NULL is compatible with PTR_TO_MEM and PTR_TO_MEM + MAYBE_NULL, 5191 * but ARG_PTR_TO_MEM is compatible only with PTR_TO_MEM but NOT with PTR_TO_MEM + MAYBE_NULL 5192 * 5193 * Therefore we fold these flags depending on the arg_type before comparison. 5194 */ 5195 if (arg_type & MEM_RDONLY) 5196 type &= ~MEM_RDONLY; 5197 if (arg_type & PTR_MAYBE_NULL) 5198 type &= ~PTR_MAYBE_NULL; 5199 5200 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 5201 expected = compatible->types[i]; 5202 if (expected == NOT_INIT) 5203 break; 5204 5205 if (type == expected) 5206 goto found; 5207 } 5208 5209 verbose(env, "R%d type=%s expected=", regno, reg_type_str(env, reg->type)); 5210 for (j = 0; j + 1 < i; j++) 5211 verbose(env, "%s, ", reg_type_str(env, compatible->types[j])); 5212 verbose(env, "%s\n", reg_type_str(env, compatible->types[j])); 5213 return -EACCES; 5214 5215 found: 5216 if (reg->type == PTR_TO_BTF_ID) { 5217 if (!arg_btf_id) { 5218 if (!compatible->btf_id) { 5219 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 5220 return -EFAULT; 5221 } 5222 arg_btf_id = compatible->btf_id; 5223 } 5224 5225 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5226 btf_vmlinux, *arg_btf_id)) { 5227 verbose(env, "R%d is of type %s but %s is expected\n", 5228 regno, kernel_type_name(reg->btf, reg->btf_id), 5229 kernel_type_name(btf_vmlinux, *arg_btf_id)); 5230 return -EACCES; 5231 } 5232 5233 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5234 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n", 5235 regno); 5236 return -EACCES; 5237 } 5238 } 5239 5240 return 0; 5241 } 5242 5243 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 5244 struct bpf_call_arg_meta *meta, 5245 const struct bpf_func_proto *fn) 5246 { 5247 u32 regno = BPF_REG_1 + arg; 5248 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5249 enum bpf_arg_type arg_type = fn->arg_type[arg]; 5250 enum bpf_reg_type type = reg->type; 5251 int err = 0; 5252 5253 if (arg_type == ARG_DONTCARE) 5254 return 0; 5255 5256 err = check_reg_arg(env, regno, SRC_OP); 5257 if (err) 5258 return err; 5259 5260 if (arg_type == ARG_ANYTHING) { 5261 if (is_pointer_value(env, regno)) { 5262 verbose(env, "R%d leaks addr into helper function\n", 5263 regno); 5264 return -EACCES; 5265 } 5266 return 0; 5267 } 5268 5269 if (type_is_pkt_pointer(type) && 5270 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 5271 verbose(env, "helper access to the packet is not allowed\n"); 5272 return -EACCES; 5273 } 5274 5275 if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE || 5276 base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) { 5277 err = resolve_map_arg_type(env, meta, &arg_type); 5278 if (err) 5279 return err; 5280 } 5281 5282 if (register_is_null(reg) && type_may_be_null(arg_type)) 5283 /* A NULL register has a SCALAR_VALUE type, so skip 5284 * type checking. 5285 */ 5286 goto skip_type_check; 5287 5288 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]); 5289 if (err) 5290 return err; 5291 5292 if (type == PTR_TO_CTX) { 5293 err = check_ctx_reg(env, reg, regno); 5294 if (err < 0) 5295 return err; 5296 } 5297 5298 skip_type_check: 5299 if (reg->ref_obj_id) { 5300 if (meta->ref_obj_id) { 5301 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 5302 regno, reg->ref_obj_id, 5303 meta->ref_obj_id); 5304 return -EFAULT; 5305 } 5306 meta->ref_obj_id = reg->ref_obj_id; 5307 } 5308 5309 if (arg_type == ARG_CONST_MAP_PTR) { 5310 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 5311 if (meta->map_ptr) { 5312 /* Use map_uid (which is unique id of inner map) to reject: 5313 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 5314 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 5315 * if (inner_map1 && inner_map2) { 5316 * timer = bpf_map_lookup_elem(inner_map1); 5317 * if (timer) 5318 * // mismatch would have been allowed 5319 * bpf_timer_init(timer, inner_map2); 5320 * } 5321 * 5322 * Comparing map_ptr is enough to distinguish normal and outer maps. 5323 */ 5324 if (meta->map_ptr != reg->map_ptr || 5325 meta->map_uid != reg->map_uid) { 5326 verbose(env, 5327 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 5328 meta->map_uid, reg->map_uid); 5329 return -EINVAL; 5330 } 5331 } 5332 meta->map_ptr = reg->map_ptr; 5333 meta->map_uid = reg->map_uid; 5334 } else if (arg_type == ARG_PTR_TO_MAP_KEY) { 5335 /* bpf_map_xxx(..., map_ptr, ..., key) call: 5336 * check that [key, key + map->key_size) are within 5337 * stack limits and initialized 5338 */ 5339 if (!meta->map_ptr) { 5340 /* in function declaration map_ptr must come before 5341 * map_key, so that it's verified and known before 5342 * we have to check map_key here. Otherwise it means 5343 * that kernel subsystem misconfigured verifier 5344 */ 5345 verbose(env, "invalid map_ptr to access map->key\n"); 5346 return -EACCES; 5347 } 5348 err = check_helper_mem_access(env, regno, 5349 meta->map_ptr->key_size, false, 5350 NULL); 5351 } else if (base_type(arg_type) == ARG_PTR_TO_MAP_VALUE || 5352 base_type(arg_type) == ARG_PTR_TO_UNINIT_MAP_VALUE) { 5353 if (type_may_be_null(arg_type) && register_is_null(reg)) 5354 return 0; 5355 5356 /* bpf_map_xxx(..., map_ptr, ..., value) call: 5357 * check [value, value + map->value_size) validity 5358 */ 5359 if (!meta->map_ptr) { 5360 /* kernel subsystem misconfigured verifier */ 5361 verbose(env, "invalid map_ptr to access map->value\n"); 5362 return -EACCES; 5363 } 5364 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE); 5365 err = check_helper_mem_access(env, regno, 5366 meta->map_ptr->value_size, false, 5367 meta); 5368 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) { 5369 if (!reg->btf_id) { 5370 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 5371 return -EACCES; 5372 } 5373 meta->ret_btf = reg->btf; 5374 meta->ret_btf_id = reg->btf_id; 5375 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) { 5376 if (meta->func_id == BPF_FUNC_spin_lock) { 5377 if (process_spin_lock(env, regno, true)) 5378 return -EACCES; 5379 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 5380 if (process_spin_lock(env, regno, false)) 5381 return -EACCES; 5382 } else { 5383 verbose(env, "verifier internal error\n"); 5384 return -EFAULT; 5385 } 5386 } else if (arg_type == ARG_PTR_TO_TIMER) { 5387 if (process_timer_func(env, regno, meta)) 5388 return -EACCES; 5389 } else if (arg_type == ARG_PTR_TO_FUNC) { 5390 meta->subprogno = reg->subprogno; 5391 } else if (arg_type_is_mem_ptr(arg_type)) { 5392 /* The access to this pointer is only checked when we hit the 5393 * next is_mem_size argument below. 5394 */ 5395 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM); 5396 } else if (arg_type_is_mem_size(arg_type)) { 5397 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); 5398 5399 /* This is used to refine r0 return value bounds for helpers 5400 * that enforce this value as an upper bound on return values. 5401 * See do_refine_retval_range() for helpers that can refine 5402 * the return value. C type of helper is u32 so we pull register 5403 * bound from umax_value however, if negative verifier errors 5404 * out. Only upper bounds can be learned because retval is an 5405 * int type and negative retvals are allowed. 5406 */ 5407 meta->msize_max_value = reg->umax_value; 5408 5409 /* The register is SCALAR_VALUE; the access check 5410 * happens using its boundaries. 5411 */ 5412 if (!tnum_is_const(reg->var_off)) 5413 /* For unprivileged variable accesses, disable raw 5414 * mode so that the program is required to 5415 * initialize all the memory that the helper could 5416 * just partially fill up. 5417 */ 5418 meta = NULL; 5419 5420 if (reg->smin_value < 0) { 5421 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 5422 regno); 5423 return -EACCES; 5424 } 5425 5426 if (reg->umin_value == 0) { 5427 err = check_helper_mem_access(env, regno - 1, 0, 5428 zero_size_allowed, 5429 meta); 5430 if (err) 5431 return err; 5432 } 5433 5434 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 5435 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 5436 regno); 5437 return -EACCES; 5438 } 5439 err = check_helper_mem_access(env, regno - 1, 5440 reg->umax_value, 5441 zero_size_allowed, meta); 5442 if (!err) 5443 err = mark_chain_precision(env, regno); 5444 } else if (arg_type_is_alloc_size(arg_type)) { 5445 if (!tnum_is_const(reg->var_off)) { 5446 verbose(env, "R%d is not a known constant'\n", 5447 regno); 5448 return -EACCES; 5449 } 5450 meta->mem_size = reg->var_off.value; 5451 } else if (arg_type_is_int_ptr(arg_type)) { 5452 int size = int_ptr_type_to_size(arg_type); 5453 5454 err = check_helper_mem_access(env, regno, size, false, meta); 5455 if (err) 5456 return err; 5457 err = check_ptr_alignment(env, reg, 0, size, true); 5458 } else if (arg_type == ARG_PTR_TO_CONST_STR) { 5459 struct bpf_map *map = reg->map_ptr; 5460 int map_off; 5461 u64 map_addr; 5462 char *str_ptr; 5463 5464 if (!bpf_map_is_rdonly(map)) { 5465 verbose(env, "R%d does not point to a readonly map'\n", regno); 5466 return -EACCES; 5467 } 5468 5469 if (!tnum_is_const(reg->var_off)) { 5470 verbose(env, "R%d is not a constant address'\n", regno); 5471 return -EACCES; 5472 } 5473 5474 if (!map->ops->map_direct_value_addr) { 5475 verbose(env, "no direct value access support for this map type\n"); 5476 return -EACCES; 5477 } 5478 5479 err = check_map_access(env, regno, reg->off, 5480 map->value_size - reg->off, false); 5481 if (err) 5482 return err; 5483 5484 map_off = reg->off + reg->var_off.value; 5485 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 5486 if (err) { 5487 verbose(env, "direct value access on string failed\n"); 5488 return err; 5489 } 5490 5491 str_ptr = (char *)(long)(map_addr); 5492 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 5493 verbose(env, "string is not zero-terminated\n"); 5494 return -EINVAL; 5495 } 5496 } 5497 5498 return err; 5499 } 5500 5501 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 5502 { 5503 enum bpf_attach_type eatype = env->prog->expected_attach_type; 5504 enum bpf_prog_type type = resolve_prog_type(env->prog); 5505 5506 if (func_id != BPF_FUNC_map_update_elem) 5507 return false; 5508 5509 /* It's not possible to get access to a locked struct sock in these 5510 * contexts, so updating is safe. 5511 */ 5512 switch (type) { 5513 case BPF_PROG_TYPE_TRACING: 5514 if (eatype == BPF_TRACE_ITER) 5515 return true; 5516 break; 5517 case BPF_PROG_TYPE_SOCKET_FILTER: 5518 case BPF_PROG_TYPE_SCHED_CLS: 5519 case BPF_PROG_TYPE_SCHED_ACT: 5520 case BPF_PROG_TYPE_XDP: 5521 case BPF_PROG_TYPE_SK_REUSEPORT: 5522 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5523 case BPF_PROG_TYPE_SK_LOOKUP: 5524 return true; 5525 default: 5526 break; 5527 } 5528 5529 verbose(env, "cannot update sockmap in this context\n"); 5530 return false; 5531 } 5532 5533 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 5534 { 5535 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64); 5536 } 5537 5538 static int check_map_func_compatibility(struct bpf_verifier_env *env, 5539 struct bpf_map *map, int func_id) 5540 { 5541 if (!map) 5542 return 0; 5543 5544 /* We need a two way check, first is from map perspective ... */ 5545 switch (map->map_type) { 5546 case BPF_MAP_TYPE_PROG_ARRAY: 5547 if (func_id != BPF_FUNC_tail_call) 5548 goto error; 5549 break; 5550 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 5551 if (func_id != BPF_FUNC_perf_event_read && 5552 func_id != BPF_FUNC_perf_event_output && 5553 func_id != BPF_FUNC_skb_output && 5554 func_id != BPF_FUNC_perf_event_read_value && 5555 func_id != BPF_FUNC_xdp_output) 5556 goto error; 5557 break; 5558 case BPF_MAP_TYPE_RINGBUF: 5559 if (func_id != BPF_FUNC_ringbuf_output && 5560 func_id != BPF_FUNC_ringbuf_reserve && 5561 func_id != BPF_FUNC_ringbuf_query) 5562 goto error; 5563 break; 5564 case BPF_MAP_TYPE_STACK_TRACE: 5565 if (func_id != BPF_FUNC_get_stackid) 5566 goto error; 5567 break; 5568 case BPF_MAP_TYPE_CGROUP_ARRAY: 5569 if (func_id != BPF_FUNC_skb_under_cgroup && 5570 func_id != BPF_FUNC_current_task_under_cgroup) 5571 goto error; 5572 break; 5573 case BPF_MAP_TYPE_CGROUP_STORAGE: 5574 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 5575 if (func_id != BPF_FUNC_get_local_storage) 5576 goto error; 5577 break; 5578 case BPF_MAP_TYPE_DEVMAP: 5579 case BPF_MAP_TYPE_DEVMAP_HASH: 5580 if (func_id != BPF_FUNC_redirect_map && 5581 func_id != BPF_FUNC_map_lookup_elem) 5582 goto error; 5583 break; 5584 /* Restrict bpf side of cpumap and xskmap, open when use-cases 5585 * appear. 5586 */ 5587 case BPF_MAP_TYPE_CPUMAP: 5588 if (func_id != BPF_FUNC_redirect_map) 5589 goto error; 5590 break; 5591 case BPF_MAP_TYPE_XSKMAP: 5592 if (func_id != BPF_FUNC_redirect_map && 5593 func_id != BPF_FUNC_map_lookup_elem) 5594 goto error; 5595 break; 5596 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 5597 case BPF_MAP_TYPE_HASH_OF_MAPS: 5598 if (func_id != BPF_FUNC_map_lookup_elem) 5599 goto error; 5600 break; 5601 case BPF_MAP_TYPE_SOCKMAP: 5602 if (func_id != BPF_FUNC_sk_redirect_map && 5603 func_id != BPF_FUNC_sock_map_update && 5604 func_id != BPF_FUNC_map_delete_elem && 5605 func_id != BPF_FUNC_msg_redirect_map && 5606 func_id != BPF_FUNC_sk_select_reuseport && 5607 func_id != BPF_FUNC_map_lookup_elem && 5608 !may_update_sockmap(env, func_id)) 5609 goto error; 5610 break; 5611 case BPF_MAP_TYPE_SOCKHASH: 5612 if (func_id != BPF_FUNC_sk_redirect_hash && 5613 func_id != BPF_FUNC_sock_hash_update && 5614 func_id != BPF_FUNC_map_delete_elem && 5615 func_id != BPF_FUNC_msg_redirect_hash && 5616 func_id != BPF_FUNC_sk_select_reuseport && 5617 func_id != BPF_FUNC_map_lookup_elem && 5618 !may_update_sockmap(env, func_id)) 5619 goto error; 5620 break; 5621 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 5622 if (func_id != BPF_FUNC_sk_select_reuseport) 5623 goto error; 5624 break; 5625 case BPF_MAP_TYPE_QUEUE: 5626 case BPF_MAP_TYPE_STACK: 5627 if (func_id != BPF_FUNC_map_peek_elem && 5628 func_id != BPF_FUNC_map_pop_elem && 5629 func_id != BPF_FUNC_map_push_elem) 5630 goto error; 5631 break; 5632 case BPF_MAP_TYPE_SK_STORAGE: 5633 if (func_id != BPF_FUNC_sk_storage_get && 5634 func_id != BPF_FUNC_sk_storage_delete) 5635 goto error; 5636 break; 5637 case BPF_MAP_TYPE_INODE_STORAGE: 5638 if (func_id != BPF_FUNC_inode_storage_get && 5639 func_id != BPF_FUNC_inode_storage_delete) 5640 goto error; 5641 break; 5642 case BPF_MAP_TYPE_TASK_STORAGE: 5643 if (func_id != BPF_FUNC_task_storage_get && 5644 func_id != BPF_FUNC_task_storage_delete) 5645 goto error; 5646 break; 5647 case BPF_MAP_TYPE_BLOOM_FILTER: 5648 if (func_id != BPF_FUNC_map_peek_elem && 5649 func_id != BPF_FUNC_map_push_elem) 5650 goto error; 5651 break; 5652 default: 5653 break; 5654 } 5655 5656 /* ... and second from the function itself. */ 5657 switch (func_id) { 5658 case BPF_FUNC_tail_call: 5659 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 5660 goto error; 5661 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 5662 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 5663 return -EINVAL; 5664 } 5665 break; 5666 case BPF_FUNC_perf_event_read: 5667 case BPF_FUNC_perf_event_output: 5668 case BPF_FUNC_perf_event_read_value: 5669 case BPF_FUNC_skb_output: 5670 case BPF_FUNC_xdp_output: 5671 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 5672 goto error; 5673 break; 5674 case BPF_FUNC_ringbuf_output: 5675 case BPF_FUNC_ringbuf_reserve: 5676 case BPF_FUNC_ringbuf_query: 5677 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 5678 goto error; 5679 break; 5680 case BPF_FUNC_get_stackid: 5681 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 5682 goto error; 5683 break; 5684 case BPF_FUNC_current_task_under_cgroup: 5685 case BPF_FUNC_skb_under_cgroup: 5686 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 5687 goto error; 5688 break; 5689 case BPF_FUNC_redirect_map: 5690 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 5691 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 5692 map->map_type != BPF_MAP_TYPE_CPUMAP && 5693 map->map_type != BPF_MAP_TYPE_XSKMAP) 5694 goto error; 5695 break; 5696 case BPF_FUNC_sk_redirect_map: 5697 case BPF_FUNC_msg_redirect_map: 5698 case BPF_FUNC_sock_map_update: 5699 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 5700 goto error; 5701 break; 5702 case BPF_FUNC_sk_redirect_hash: 5703 case BPF_FUNC_msg_redirect_hash: 5704 case BPF_FUNC_sock_hash_update: 5705 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 5706 goto error; 5707 break; 5708 case BPF_FUNC_get_local_storage: 5709 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 5710 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 5711 goto error; 5712 break; 5713 case BPF_FUNC_sk_select_reuseport: 5714 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 5715 map->map_type != BPF_MAP_TYPE_SOCKMAP && 5716 map->map_type != BPF_MAP_TYPE_SOCKHASH) 5717 goto error; 5718 break; 5719 case BPF_FUNC_map_pop_elem: 5720 if (map->map_type != BPF_MAP_TYPE_QUEUE && 5721 map->map_type != BPF_MAP_TYPE_STACK) 5722 goto error; 5723 break; 5724 case BPF_FUNC_map_peek_elem: 5725 case BPF_FUNC_map_push_elem: 5726 if (map->map_type != BPF_MAP_TYPE_QUEUE && 5727 map->map_type != BPF_MAP_TYPE_STACK && 5728 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 5729 goto error; 5730 break; 5731 case BPF_FUNC_sk_storage_get: 5732 case BPF_FUNC_sk_storage_delete: 5733 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 5734 goto error; 5735 break; 5736 case BPF_FUNC_inode_storage_get: 5737 case BPF_FUNC_inode_storage_delete: 5738 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 5739 goto error; 5740 break; 5741 case BPF_FUNC_task_storage_get: 5742 case BPF_FUNC_task_storage_delete: 5743 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 5744 goto error; 5745 break; 5746 default: 5747 break; 5748 } 5749 5750 return 0; 5751 error: 5752 verbose(env, "cannot pass map_type %d into func %s#%d\n", 5753 map->map_type, func_id_name(func_id), func_id); 5754 return -EINVAL; 5755 } 5756 5757 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 5758 { 5759 int count = 0; 5760 5761 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 5762 count++; 5763 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 5764 count++; 5765 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 5766 count++; 5767 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 5768 count++; 5769 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 5770 count++; 5771 5772 /* We only support one arg being in raw mode at the moment, 5773 * which is sufficient for the helper functions we have 5774 * right now. 5775 */ 5776 return count <= 1; 5777 } 5778 5779 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr, 5780 enum bpf_arg_type arg_next) 5781 { 5782 return (arg_type_is_mem_ptr(arg_curr) && 5783 !arg_type_is_mem_size(arg_next)) || 5784 (!arg_type_is_mem_ptr(arg_curr) && 5785 arg_type_is_mem_size(arg_next)); 5786 } 5787 5788 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 5789 { 5790 /* bpf_xxx(..., buf, len) call will access 'len' 5791 * bytes from memory 'buf'. Both arg types need 5792 * to be paired, so make sure there's no buggy 5793 * helper function specification. 5794 */ 5795 if (arg_type_is_mem_size(fn->arg1_type) || 5796 arg_type_is_mem_ptr(fn->arg5_type) || 5797 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) || 5798 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) || 5799 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) || 5800 check_args_pair_invalid(fn->arg4_type, fn->arg5_type)) 5801 return false; 5802 5803 return true; 5804 } 5805 5806 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id) 5807 { 5808 int count = 0; 5809 5810 if (arg_type_may_be_refcounted(fn->arg1_type)) 5811 count++; 5812 if (arg_type_may_be_refcounted(fn->arg2_type)) 5813 count++; 5814 if (arg_type_may_be_refcounted(fn->arg3_type)) 5815 count++; 5816 if (arg_type_may_be_refcounted(fn->arg4_type)) 5817 count++; 5818 if (arg_type_may_be_refcounted(fn->arg5_type)) 5819 count++; 5820 5821 /* A reference acquiring function cannot acquire 5822 * another refcounted ptr. 5823 */ 5824 if (may_be_acquire_function(func_id) && count) 5825 return false; 5826 5827 /* We only support one arg being unreferenced at the moment, 5828 * which is sufficient for the helper functions we have right now. 5829 */ 5830 return count <= 1; 5831 } 5832 5833 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 5834 { 5835 int i; 5836 5837 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 5838 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i]) 5839 return false; 5840 5841 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i]) 5842 return false; 5843 } 5844 5845 return true; 5846 } 5847 5848 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 5849 { 5850 return check_raw_mode_ok(fn) && 5851 check_arg_pair_ok(fn) && 5852 check_btf_id_ok(fn) && 5853 check_refcount_ok(fn, func_id) ? 0 : -EINVAL; 5854 } 5855 5856 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 5857 * are now invalid, so turn them into unknown SCALAR_VALUE. 5858 */ 5859 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env, 5860 struct bpf_func_state *state) 5861 { 5862 struct bpf_reg_state *regs = state->regs, *reg; 5863 int i; 5864 5865 for (i = 0; i < MAX_BPF_REG; i++) 5866 if (reg_is_pkt_pointer_any(®s[i])) 5867 mark_reg_unknown(env, regs, i); 5868 5869 bpf_for_each_spilled_reg(i, state, reg) { 5870 if (!reg) 5871 continue; 5872 if (reg_is_pkt_pointer_any(reg)) 5873 __mark_reg_unknown(env, reg); 5874 } 5875 } 5876 5877 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 5878 { 5879 struct bpf_verifier_state *vstate = env->cur_state; 5880 int i; 5881 5882 for (i = 0; i <= vstate->curframe; i++) 5883 __clear_all_pkt_pointers(env, vstate->frame[i]); 5884 } 5885 5886 enum { 5887 AT_PKT_END = -1, 5888 BEYOND_PKT_END = -2, 5889 }; 5890 5891 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 5892 { 5893 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5894 struct bpf_reg_state *reg = &state->regs[regn]; 5895 5896 if (reg->type != PTR_TO_PACKET) 5897 /* PTR_TO_PACKET_META is not supported yet */ 5898 return; 5899 5900 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 5901 * How far beyond pkt_end it goes is unknown. 5902 * if (!range_open) it's the case of pkt >= pkt_end 5903 * if (range_open) it's the case of pkt > pkt_end 5904 * hence this pointer is at least 1 byte bigger than pkt_end 5905 */ 5906 if (range_open) 5907 reg->range = BEYOND_PKT_END; 5908 else 5909 reg->range = AT_PKT_END; 5910 } 5911 5912 static void release_reg_references(struct bpf_verifier_env *env, 5913 struct bpf_func_state *state, 5914 int ref_obj_id) 5915 { 5916 struct bpf_reg_state *regs = state->regs, *reg; 5917 int i; 5918 5919 for (i = 0; i < MAX_BPF_REG; i++) 5920 if (regs[i].ref_obj_id == ref_obj_id) 5921 mark_reg_unknown(env, regs, i); 5922 5923 bpf_for_each_spilled_reg(i, state, reg) { 5924 if (!reg) 5925 continue; 5926 if (reg->ref_obj_id == ref_obj_id) 5927 __mark_reg_unknown(env, reg); 5928 } 5929 } 5930 5931 /* The pointer with the specified id has released its reference to kernel 5932 * resources. Identify all copies of the same pointer and clear the reference. 5933 */ 5934 static int release_reference(struct bpf_verifier_env *env, 5935 int ref_obj_id) 5936 { 5937 struct bpf_verifier_state *vstate = env->cur_state; 5938 int err; 5939 int i; 5940 5941 err = release_reference_state(cur_func(env), ref_obj_id); 5942 if (err) 5943 return err; 5944 5945 for (i = 0; i <= vstate->curframe; i++) 5946 release_reg_references(env, vstate->frame[i], ref_obj_id); 5947 5948 return 0; 5949 } 5950 5951 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 5952 struct bpf_reg_state *regs) 5953 { 5954 int i; 5955 5956 /* after the call registers r0 - r5 were scratched */ 5957 for (i = 0; i < CALLER_SAVED_REGS; i++) { 5958 mark_reg_not_init(env, regs, caller_saved[i]); 5959 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 5960 } 5961 } 5962 5963 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 5964 struct bpf_func_state *caller, 5965 struct bpf_func_state *callee, 5966 int insn_idx); 5967 5968 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 5969 int *insn_idx, int subprog, 5970 set_callee_state_fn set_callee_state_cb) 5971 { 5972 struct bpf_verifier_state *state = env->cur_state; 5973 struct bpf_func_info_aux *func_info_aux; 5974 struct bpf_func_state *caller, *callee; 5975 int err; 5976 bool is_global = false; 5977 5978 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 5979 verbose(env, "the call stack of %d frames is too deep\n", 5980 state->curframe + 2); 5981 return -E2BIG; 5982 } 5983 5984 caller = state->frame[state->curframe]; 5985 if (state->frame[state->curframe + 1]) { 5986 verbose(env, "verifier bug. Frame %d already allocated\n", 5987 state->curframe + 1); 5988 return -EFAULT; 5989 } 5990 5991 func_info_aux = env->prog->aux->func_info_aux; 5992 if (func_info_aux) 5993 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 5994 err = btf_check_subprog_arg_match(env, subprog, caller->regs); 5995 if (err == -EFAULT) 5996 return err; 5997 if (is_global) { 5998 if (err) { 5999 verbose(env, "Caller passes invalid args into func#%d\n", 6000 subprog); 6001 return err; 6002 } else { 6003 if (env->log.level & BPF_LOG_LEVEL) 6004 verbose(env, 6005 "Func#%d is global and valid. Skipping.\n", 6006 subprog); 6007 clear_caller_saved_regs(env, caller->regs); 6008 6009 /* All global functions return a 64-bit SCALAR_VALUE */ 6010 mark_reg_unknown(env, caller->regs, BPF_REG_0); 6011 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 6012 6013 /* continue with next insn after call */ 6014 return 0; 6015 } 6016 } 6017 6018 if (insn->code == (BPF_JMP | BPF_CALL) && 6019 insn->imm == BPF_FUNC_timer_set_callback) { 6020 struct bpf_verifier_state *async_cb; 6021 6022 /* there is no real recursion here. timer callbacks are async */ 6023 env->subprog_info[subprog].is_async_cb = true; 6024 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 6025 *insn_idx, subprog); 6026 if (!async_cb) 6027 return -EFAULT; 6028 callee = async_cb->frame[0]; 6029 callee->async_entry_cnt = caller->async_entry_cnt + 1; 6030 6031 /* Convert bpf_timer_set_callback() args into timer callback args */ 6032 err = set_callee_state_cb(env, caller, callee, *insn_idx); 6033 if (err) 6034 return err; 6035 6036 clear_caller_saved_regs(env, caller->regs); 6037 mark_reg_unknown(env, caller->regs, BPF_REG_0); 6038 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 6039 /* continue with next insn after call */ 6040 return 0; 6041 } 6042 6043 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 6044 if (!callee) 6045 return -ENOMEM; 6046 state->frame[state->curframe + 1] = callee; 6047 6048 /* callee cannot access r0, r6 - r9 for reading and has to write 6049 * into its own stack before reading from it. 6050 * callee can read/write into caller's stack 6051 */ 6052 init_func_state(env, callee, 6053 /* remember the callsite, it will be used by bpf_exit */ 6054 *insn_idx /* callsite */, 6055 state->curframe + 1 /* frameno within this callchain */, 6056 subprog /* subprog number within this prog */); 6057 6058 /* Transfer references to the callee */ 6059 err = copy_reference_state(callee, caller); 6060 if (err) 6061 return err; 6062 6063 err = set_callee_state_cb(env, caller, callee, *insn_idx); 6064 if (err) 6065 return err; 6066 6067 clear_caller_saved_regs(env, caller->regs); 6068 6069 /* only increment it after check_reg_arg() finished */ 6070 state->curframe++; 6071 6072 /* and go analyze first insn of the callee */ 6073 *insn_idx = env->subprog_info[subprog].start - 1; 6074 6075 if (env->log.level & BPF_LOG_LEVEL) { 6076 verbose(env, "caller:\n"); 6077 print_verifier_state(env, caller, true); 6078 verbose(env, "callee:\n"); 6079 print_verifier_state(env, callee, true); 6080 } 6081 return 0; 6082 } 6083 6084 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 6085 struct bpf_func_state *caller, 6086 struct bpf_func_state *callee) 6087 { 6088 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 6089 * void *callback_ctx, u64 flags); 6090 * callback_fn(struct bpf_map *map, void *key, void *value, 6091 * void *callback_ctx); 6092 */ 6093 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 6094 6095 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 6096 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 6097 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 6098 6099 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 6100 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 6101 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 6102 6103 /* pointer to stack or null */ 6104 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 6105 6106 /* unused */ 6107 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 6108 return 0; 6109 } 6110 6111 static int set_callee_state(struct bpf_verifier_env *env, 6112 struct bpf_func_state *caller, 6113 struct bpf_func_state *callee, int insn_idx) 6114 { 6115 int i; 6116 6117 /* copy r1 - r5 args that callee can access. The copy includes parent 6118 * pointers, which connects us up to the liveness chain 6119 */ 6120 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 6121 callee->regs[i] = caller->regs[i]; 6122 return 0; 6123 } 6124 6125 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 6126 int *insn_idx) 6127 { 6128 int subprog, target_insn; 6129 6130 target_insn = *insn_idx + insn->imm + 1; 6131 subprog = find_subprog(env, target_insn); 6132 if (subprog < 0) { 6133 verbose(env, "verifier bug. No program starts at insn %d\n", 6134 target_insn); 6135 return -EFAULT; 6136 } 6137 6138 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 6139 } 6140 6141 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 6142 struct bpf_func_state *caller, 6143 struct bpf_func_state *callee, 6144 int insn_idx) 6145 { 6146 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 6147 struct bpf_map *map; 6148 int err; 6149 6150 if (bpf_map_ptr_poisoned(insn_aux)) { 6151 verbose(env, "tail_call abusing map_ptr\n"); 6152 return -EINVAL; 6153 } 6154 6155 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 6156 if (!map->ops->map_set_for_each_callback_args || 6157 !map->ops->map_for_each_callback) { 6158 verbose(env, "callback function not allowed for map\n"); 6159 return -ENOTSUPP; 6160 } 6161 6162 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 6163 if (err) 6164 return err; 6165 6166 callee->in_callback_fn = true; 6167 return 0; 6168 } 6169 6170 static int set_loop_callback_state(struct bpf_verifier_env *env, 6171 struct bpf_func_state *caller, 6172 struct bpf_func_state *callee, 6173 int insn_idx) 6174 { 6175 /* bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, 6176 * u64 flags); 6177 * callback_fn(u32 index, void *callback_ctx); 6178 */ 6179 callee->regs[BPF_REG_1].type = SCALAR_VALUE; 6180 callee->regs[BPF_REG_2] = caller->regs[BPF_REG_3]; 6181 6182 /* unused */ 6183 __mark_reg_not_init(env, &callee->regs[BPF_REG_3]); 6184 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 6185 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 6186 6187 callee->in_callback_fn = true; 6188 return 0; 6189 } 6190 6191 static int set_timer_callback_state(struct bpf_verifier_env *env, 6192 struct bpf_func_state *caller, 6193 struct bpf_func_state *callee, 6194 int insn_idx) 6195 { 6196 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 6197 6198 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 6199 * callback_fn(struct bpf_map *map, void *key, void *value); 6200 */ 6201 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 6202 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 6203 callee->regs[BPF_REG_1].map_ptr = map_ptr; 6204 6205 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 6206 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 6207 callee->regs[BPF_REG_2].map_ptr = map_ptr; 6208 6209 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 6210 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 6211 callee->regs[BPF_REG_3].map_ptr = map_ptr; 6212 6213 /* unused */ 6214 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 6215 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 6216 callee->in_async_callback_fn = true; 6217 return 0; 6218 } 6219 6220 static int set_find_vma_callback_state(struct bpf_verifier_env *env, 6221 struct bpf_func_state *caller, 6222 struct bpf_func_state *callee, 6223 int insn_idx) 6224 { 6225 /* bpf_find_vma(struct task_struct *task, u64 addr, 6226 * void *callback_fn, void *callback_ctx, u64 flags) 6227 * (callback_fn)(struct task_struct *task, 6228 * struct vm_area_struct *vma, void *callback_ctx); 6229 */ 6230 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 6231 6232 callee->regs[BPF_REG_2].type = PTR_TO_BTF_ID; 6233 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 6234 callee->regs[BPF_REG_2].btf = btf_vmlinux; 6235 callee->regs[BPF_REG_2].btf_id = btf_tracing_ids[BTF_TRACING_TYPE_VMA], 6236 6237 /* pointer to stack or null */ 6238 callee->regs[BPF_REG_3] = caller->regs[BPF_REG_4]; 6239 6240 /* unused */ 6241 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 6242 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 6243 callee->in_callback_fn = true; 6244 return 0; 6245 } 6246 6247 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 6248 { 6249 struct bpf_verifier_state *state = env->cur_state; 6250 struct bpf_func_state *caller, *callee; 6251 struct bpf_reg_state *r0; 6252 int err; 6253 6254 callee = state->frame[state->curframe]; 6255 r0 = &callee->regs[BPF_REG_0]; 6256 if (r0->type == PTR_TO_STACK) { 6257 /* technically it's ok to return caller's stack pointer 6258 * (or caller's caller's pointer) back to the caller, 6259 * since these pointers are valid. Only current stack 6260 * pointer will be invalid as soon as function exits, 6261 * but let's be conservative 6262 */ 6263 verbose(env, "cannot return stack pointer to the caller\n"); 6264 return -EINVAL; 6265 } 6266 6267 state->curframe--; 6268 caller = state->frame[state->curframe]; 6269 if (callee->in_callback_fn) { 6270 /* enforce R0 return value range [0, 1]. */ 6271 struct tnum range = tnum_range(0, 1); 6272 6273 if (r0->type != SCALAR_VALUE) { 6274 verbose(env, "R0 not a scalar value\n"); 6275 return -EACCES; 6276 } 6277 if (!tnum_in(range, r0->var_off)) { 6278 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 6279 return -EINVAL; 6280 } 6281 } else { 6282 /* return to the caller whatever r0 had in the callee */ 6283 caller->regs[BPF_REG_0] = *r0; 6284 } 6285 6286 /* Transfer references to the caller */ 6287 err = copy_reference_state(caller, callee); 6288 if (err) 6289 return err; 6290 6291 *insn_idx = callee->callsite + 1; 6292 if (env->log.level & BPF_LOG_LEVEL) { 6293 verbose(env, "returning from callee:\n"); 6294 print_verifier_state(env, callee, true); 6295 verbose(env, "to caller at %d:\n", *insn_idx); 6296 print_verifier_state(env, caller, true); 6297 } 6298 /* clear everything in the callee */ 6299 free_func_state(callee); 6300 state->frame[state->curframe + 1] = NULL; 6301 return 0; 6302 } 6303 6304 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 6305 int func_id, 6306 struct bpf_call_arg_meta *meta) 6307 { 6308 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 6309 6310 if (ret_type != RET_INTEGER || 6311 (func_id != BPF_FUNC_get_stack && 6312 func_id != BPF_FUNC_get_task_stack && 6313 func_id != BPF_FUNC_probe_read_str && 6314 func_id != BPF_FUNC_probe_read_kernel_str && 6315 func_id != BPF_FUNC_probe_read_user_str)) 6316 return; 6317 6318 ret_reg->smax_value = meta->msize_max_value; 6319 ret_reg->s32_max_value = meta->msize_max_value; 6320 ret_reg->smin_value = -MAX_ERRNO; 6321 ret_reg->s32_min_value = -MAX_ERRNO; 6322 __reg_deduce_bounds(ret_reg); 6323 __reg_bound_offset(ret_reg); 6324 __update_reg_bounds(ret_reg); 6325 } 6326 6327 static int 6328 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 6329 int func_id, int insn_idx) 6330 { 6331 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 6332 struct bpf_map *map = meta->map_ptr; 6333 6334 if (func_id != BPF_FUNC_tail_call && 6335 func_id != BPF_FUNC_map_lookup_elem && 6336 func_id != BPF_FUNC_map_update_elem && 6337 func_id != BPF_FUNC_map_delete_elem && 6338 func_id != BPF_FUNC_map_push_elem && 6339 func_id != BPF_FUNC_map_pop_elem && 6340 func_id != BPF_FUNC_map_peek_elem && 6341 func_id != BPF_FUNC_for_each_map_elem && 6342 func_id != BPF_FUNC_redirect_map) 6343 return 0; 6344 6345 if (map == NULL) { 6346 verbose(env, "kernel subsystem misconfigured verifier\n"); 6347 return -EINVAL; 6348 } 6349 6350 /* In case of read-only, some additional restrictions 6351 * need to be applied in order to prevent altering the 6352 * state of the map from program side. 6353 */ 6354 if ((map->map_flags & BPF_F_RDONLY_PROG) && 6355 (func_id == BPF_FUNC_map_delete_elem || 6356 func_id == BPF_FUNC_map_update_elem || 6357 func_id == BPF_FUNC_map_push_elem || 6358 func_id == BPF_FUNC_map_pop_elem)) { 6359 verbose(env, "write into map forbidden\n"); 6360 return -EACCES; 6361 } 6362 6363 if (!BPF_MAP_PTR(aux->map_ptr_state)) 6364 bpf_map_ptr_store(aux, meta->map_ptr, 6365 !meta->map_ptr->bypass_spec_v1); 6366 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 6367 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 6368 !meta->map_ptr->bypass_spec_v1); 6369 return 0; 6370 } 6371 6372 static int 6373 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 6374 int func_id, int insn_idx) 6375 { 6376 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 6377 struct bpf_reg_state *regs = cur_regs(env), *reg; 6378 struct bpf_map *map = meta->map_ptr; 6379 struct tnum range; 6380 u64 val; 6381 int err; 6382 6383 if (func_id != BPF_FUNC_tail_call) 6384 return 0; 6385 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 6386 verbose(env, "kernel subsystem misconfigured verifier\n"); 6387 return -EINVAL; 6388 } 6389 6390 range = tnum_range(0, map->max_entries - 1); 6391 reg = ®s[BPF_REG_3]; 6392 6393 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) { 6394 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 6395 return 0; 6396 } 6397 6398 err = mark_chain_precision(env, BPF_REG_3); 6399 if (err) 6400 return err; 6401 6402 val = reg->var_off.value; 6403 if (bpf_map_key_unseen(aux)) 6404 bpf_map_key_store(aux, val); 6405 else if (!bpf_map_key_poisoned(aux) && 6406 bpf_map_key_immediate(aux) != val) 6407 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 6408 return 0; 6409 } 6410 6411 static int check_reference_leak(struct bpf_verifier_env *env) 6412 { 6413 struct bpf_func_state *state = cur_func(env); 6414 int i; 6415 6416 for (i = 0; i < state->acquired_refs; i++) { 6417 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 6418 state->refs[i].id, state->refs[i].insn_idx); 6419 } 6420 return state->acquired_refs ? -EINVAL : 0; 6421 } 6422 6423 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 6424 struct bpf_reg_state *regs) 6425 { 6426 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 6427 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 6428 struct bpf_map *fmt_map = fmt_reg->map_ptr; 6429 int err, fmt_map_off, num_args; 6430 u64 fmt_addr; 6431 char *fmt; 6432 6433 /* data must be an array of u64 */ 6434 if (data_len_reg->var_off.value % 8) 6435 return -EINVAL; 6436 num_args = data_len_reg->var_off.value / 8; 6437 6438 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 6439 * and map_direct_value_addr is set. 6440 */ 6441 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 6442 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 6443 fmt_map_off); 6444 if (err) { 6445 verbose(env, "verifier bug\n"); 6446 return -EFAULT; 6447 } 6448 fmt = (char *)(long)fmt_addr + fmt_map_off; 6449 6450 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 6451 * can focus on validating the format specifiers. 6452 */ 6453 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args); 6454 if (err < 0) 6455 verbose(env, "Invalid format string\n"); 6456 6457 return err; 6458 } 6459 6460 static int check_get_func_ip(struct bpf_verifier_env *env) 6461 { 6462 enum bpf_prog_type type = resolve_prog_type(env->prog); 6463 int func_id = BPF_FUNC_get_func_ip; 6464 6465 if (type == BPF_PROG_TYPE_TRACING) { 6466 if (!bpf_prog_has_trampoline(env->prog)) { 6467 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 6468 func_id_name(func_id), func_id); 6469 return -ENOTSUPP; 6470 } 6471 return 0; 6472 } else if (type == BPF_PROG_TYPE_KPROBE) { 6473 return 0; 6474 } 6475 6476 verbose(env, "func %s#%d not supported for program type %d\n", 6477 func_id_name(func_id), func_id, type); 6478 return -ENOTSUPP; 6479 } 6480 6481 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 6482 int *insn_idx_p) 6483 { 6484 const struct bpf_func_proto *fn = NULL; 6485 enum bpf_return_type ret_type; 6486 enum bpf_type_flag ret_flag; 6487 struct bpf_reg_state *regs; 6488 struct bpf_call_arg_meta meta; 6489 int insn_idx = *insn_idx_p; 6490 bool changes_data; 6491 int i, err, func_id; 6492 6493 /* find function prototype */ 6494 func_id = insn->imm; 6495 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 6496 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 6497 func_id); 6498 return -EINVAL; 6499 } 6500 6501 if (env->ops->get_func_proto) 6502 fn = env->ops->get_func_proto(func_id, env->prog); 6503 if (!fn) { 6504 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 6505 func_id); 6506 return -EINVAL; 6507 } 6508 6509 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 6510 if (!env->prog->gpl_compatible && fn->gpl_only) { 6511 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 6512 return -EINVAL; 6513 } 6514 6515 if (fn->allowed && !fn->allowed(env->prog)) { 6516 verbose(env, "helper call is not allowed in probe\n"); 6517 return -EINVAL; 6518 } 6519 6520 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 6521 changes_data = bpf_helper_changes_pkt_data(fn->func); 6522 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 6523 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 6524 func_id_name(func_id), func_id); 6525 return -EINVAL; 6526 } 6527 6528 memset(&meta, 0, sizeof(meta)); 6529 meta.pkt_access = fn->pkt_access; 6530 6531 err = check_func_proto(fn, func_id); 6532 if (err) { 6533 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 6534 func_id_name(func_id), func_id); 6535 return err; 6536 } 6537 6538 meta.func_id = func_id; 6539 /* check args */ 6540 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 6541 err = check_func_arg(env, i, &meta, fn); 6542 if (err) 6543 return err; 6544 } 6545 6546 err = record_func_map(env, &meta, func_id, insn_idx); 6547 if (err) 6548 return err; 6549 6550 err = record_func_key(env, &meta, func_id, insn_idx); 6551 if (err) 6552 return err; 6553 6554 /* Mark slots with STACK_MISC in case of raw mode, stack offset 6555 * is inferred from register state. 6556 */ 6557 for (i = 0; i < meta.access_size; i++) { 6558 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 6559 BPF_WRITE, -1, false); 6560 if (err) 6561 return err; 6562 } 6563 6564 if (is_release_function(func_id)) { 6565 err = release_reference(env, meta.ref_obj_id); 6566 if (err) { 6567 verbose(env, "func %s#%d reference has not been acquired before\n", 6568 func_id_name(func_id), func_id); 6569 return err; 6570 } 6571 } 6572 6573 regs = cur_regs(env); 6574 6575 switch (func_id) { 6576 case BPF_FUNC_tail_call: 6577 err = check_reference_leak(env); 6578 if (err) { 6579 verbose(env, "tail_call would lead to reference leak\n"); 6580 return err; 6581 } 6582 break; 6583 case BPF_FUNC_get_local_storage: 6584 /* check that flags argument in get_local_storage(map, flags) is 0, 6585 * this is required because get_local_storage() can't return an error. 6586 */ 6587 if (!register_is_null(®s[BPF_REG_2])) { 6588 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 6589 return -EINVAL; 6590 } 6591 break; 6592 case BPF_FUNC_for_each_map_elem: 6593 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 6594 set_map_elem_callback_state); 6595 break; 6596 case BPF_FUNC_timer_set_callback: 6597 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 6598 set_timer_callback_state); 6599 break; 6600 case BPF_FUNC_find_vma: 6601 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 6602 set_find_vma_callback_state); 6603 break; 6604 case BPF_FUNC_snprintf: 6605 err = check_bpf_snprintf_call(env, regs); 6606 break; 6607 case BPF_FUNC_loop: 6608 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 6609 set_loop_callback_state); 6610 break; 6611 } 6612 6613 if (err) 6614 return err; 6615 6616 /* reset caller saved regs */ 6617 for (i = 0; i < CALLER_SAVED_REGS; i++) { 6618 mark_reg_not_init(env, regs, caller_saved[i]); 6619 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 6620 } 6621 6622 /* helper call returns 64-bit value. */ 6623 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 6624 6625 /* update return register (already marked as written above) */ 6626 ret_type = fn->ret_type; 6627 ret_flag = type_flag(fn->ret_type); 6628 if (ret_type == RET_INTEGER) { 6629 /* sets type to SCALAR_VALUE */ 6630 mark_reg_unknown(env, regs, BPF_REG_0); 6631 } else if (ret_type == RET_VOID) { 6632 regs[BPF_REG_0].type = NOT_INIT; 6633 } else if (base_type(ret_type) == RET_PTR_TO_MAP_VALUE) { 6634 /* There is no offset yet applied, variable or fixed */ 6635 mark_reg_known_zero(env, regs, BPF_REG_0); 6636 /* remember map_ptr, so that check_map_access() 6637 * can check 'value_size' boundary of memory access 6638 * to map element returned from bpf_map_lookup_elem() 6639 */ 6640 if (meta.map_ptr == NULL) { 6641 verbose(env, 6642 "kernel subsystem misconfigured verifier\n"); 6643 return -EINVAL; 6644 } 6645 regs[BPF_REG_0].map_ptr = meta.map_ptr; 6646 regs[BPF_REG_0].map_uid = meta.map_uid; 6647 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE | ret_flag; 6648 if (!type_may_be_null(ret_type) && 6649 map_value_has_spin_lock(meta.map_ptr)) { 6650 regs[BPF_REG_0].id = ++env->id_gen; 6651 } 6652 } else if (base_type(ret_type) == RET_PTR_TO_SOCKET) { 6653 mark_reg_known_zero(env, regs, BPF_REG_0); 6654 regs[BPF_REG_0].type = PTR_TO_SOCKET | ret_flag; 6655 } else if (base_type(ret_type) == RET_PTR_TO_SOCK_COMMON) { 6656 mark_reg_known_zero(env, regs, BPF_REG_0); 6657 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON | ret_flag; 6658 } else if (base_type(ret_type) == RET_PTR_TO_TCP_SOCK) { 6659 mark_reg_known_zero(env, regs, BPF_REG_0); 6660 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK | ret_flag; 6661 } else if (base_type(ret_type) == RET_PTR_TO_ALLOC_MEM) { 6662 mark_reg_known_zero(env, regs, BPF_REG_0); 6663 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 6664 regs[BPF_REG_0].mem_size = meta.mem_size; 6665 } else if (base_type(ret_type) == RET_PTR_TO_MEM_OR_BTF_ID) { 6666 const struct btf_type *t; 6667 6668 mark_reg_known_zero(env, regs, BPF_REG_0); 6669 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 6670 if (!btf_type_is_struct(t)) { 6671 u32 tsize; 6672 const struct btf_type *ret; 6673 const char *tname; 6674 6675 /* resolve the type size of ksym. */ 6676 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 6677 if (IS_ERR(ret)) { 6678 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 6679 verbose(env, "unable to resolve the size of type '%s': %ld\n", 6680 tname, PTR_ERR(ret)); 6681 return -EINVAL; 6682 } 6683 regs[BPF_REG_0].type = PTR_TO_MEM | ret_flag; 6684 regs[BPF_REG_0].mem_size = tsize; 6685 } else { 6686 /* MEM_RDONLY may be carried from ret_flag, but it 6687 * doesn't apply on PTR_TO_BTF_ID. Fold it, otherwise 6688 * it will confuse the check of PTR_TO_BTF_ID in 6689 * check_mem_access(). 6690 */ 6691 ret_flag &= ~MEM_RDONLY; 6692 6693 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 6694 regs[BPF_REG_0].btf = meta.ret_btf; 6695 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 6696 } 6697 } else if (base_type(ret_type) == RET_PTR_TO_BTF_ID) { 6698 int ret_btf_id; 6699 6700 mark_reg_known_zero(env, regs, BPF_REG_0); 6701 regs[BPF_REG_0].type = PTR_TO_BTF_ID | ret_flag; 6702 ret_btf_id = *fn->ret_btf_id; 6703 if (ret_btf_id == 0) { 6704 verbose(env, "invalid return type %u of func %s#%d\n", 6705 base_type(ret_type), func_id_name(func_id), 6706 func_id); 6707 return -EINVAL; 6708 } 6709 /* current BPF helper definitions are only coming from 6710 * built-in code with type IDs from vmlinux BTF 6711 */ 6712 regs[BPF_REG_0].btf = btf_vmlinux; 6713 regs[BPF_REG_0].btf_id = ret_btf_id; 6714 } else { 6715 verbose(env, "unknown return type %u of func %s#%d\n", 6716 base_type(ret_type), func_id_name(func_id), func_id); 6717 return -EINVAL; 6718 } 6719 6720 if (type_may_be_null(regs[BPF_REG_0].type)) 6721 regs[BPF_REG_0].id = ++env->id_gen; 6722 6723 if (is_ptr_cast_function(func_id)) { 6724 /* For release_reference() */ 6725 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 6726 } else if (is_acquire_function(func_id, meta.map_ptr)) { 6727 int id = acquire_reference_state(env, insn_idx); 6728 6729 if (id < 0) 6730 return id; 6731 /* For mark_ptr_or_null_reg() */ 6732 regs[BPF_REG_0].id = id; 6733 /* For release_reference() */ 6734 regs[BPF_REG_0].ref_obj_id = id; 6735 } 6736 6737 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 6738 6739 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 6740 if (err) 6741 return err; 6742 6743 if ((func_id == BPF_FUNC_get_stack || 6744 func_id == BPF_FUNC_get_task_stack) && 6745 !env->prog->has_callchain_buf) { 6746 const char *err_str; 6747 6748 #ifdef CONFIG_PERF_EVENTS 6749 err = get_callchain_buffers(sysctl_perf_event_max_stack); 6750 err_str = "cannot get callchain buffer for func %s#%d\n"; 6751 #else 6752 err = -ENOTSUPP; 6753 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 6754 #endif 6755 if (err) { 6756 verbose(env, err_str, func_id_name(func_id), func_id); 6757 return err; 6758 } 6759 6760 env->prog->has_callchain_buf = true; 6761 } 6762 6763 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 6764 env->prog->call_get_stack = true; 6765 6766 if (func_id == BPF_FUNC_get_func_ip) { 6767 if (check_get_func_ip(env)) 6768 return -ENOTSUPP; 6769 env->prog->call_get_func_ip = true; 6770 } 6771 6772 if (changes_data) 6773 clear_all_pkt_pointers(env); 6774 return 0; 6775 } 6776 6777 /* mark_btf_func_reg_size() is used when the reg size is determined by 6778 * the BTF func_proto's return value size and argument. 6779 */ 6780 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 6781 size_t reg_size) 6782 { 6783 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 6784 6785 if (regno == BPF_REG_0) { 6786 /* Function return value */ 6787 reg->live |= REG_LIVE_WRITTEN; 6788 reg->subreg_def = reg_size == sizeof(u64) ? 6789 DEF_NOT_SUBREG : env->insn_idx + 1; 6790 } else { 6791 /* Function argument */ 6792 if (reg_size == sizeof(u64)) { 6793 mark_insn_zext(env, reg); 6794 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 6795 } else { 6796 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 6797 } 6798 } 6799 } 6800 6801 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn) 6802 { 6803 const struct btf_type *t, *func, *func_proto, *ptr_type; 6804 struct bpf_reg_state *regs = cur_regs(env); 6805 const char *func_name, *ptr_type_name; 6806 u32 i, nargs, func_id, ptr_type_id; 6807 struct module *btf_mod = NULL; 6808 const struct btf_param *args; 6809 struct btf *desc_btf; 6810 int err; 6811 6812 /* skip for now, but return error when we find this in fixup_kfunc_call */ 6813 if (!insn->imm) 6814 return 0; 6815 6816 desc_btf = find_kfunc_desc_btf(env, insn->imm, insn->off, &btf_mod); 6817 if (IS_ERR(desc_btf)) 6818 return PTR_ERR(desc_btf); 6819 6820 func_id = insn->imm; 6821 func = btf_type_by_id(desc_btf, func_id); 6822 func_name = btf_name_by_offset(desc_btf, func->name_off); 6823 func_proto = btf_type_by_id(desc_btf, func->type); 6824 6825 if (!env->ops->check_kfunc_call || 6826 !env->ops->check_kfunc_call(func_id, btf_mod)) { 6827 verbose(env, "calling kernel function %s is not allowed\n", 6828 func_name); 6829 return -EACCES; 6830 } 6831 6832 /* Check the arguments */ 6833 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs); 6834 if (err) 6835 return err; 6836 6837 for (i = 0; i < CALLER_SAVED_REGS; i++) 6838 mark_reg_not_init(env, regs, caller_saved[i]); 6839 6840 /* Check return type */ 6841 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL); 6842 if (btf_type_is_scalar(t)) { 6843 mark_reg_unknown(env, regs, BPF_REG_0); 6844 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 6845 } else if (btf_type_is_ptr(t)) { 6846 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, 6847 &ptr_type_id); 6848 if (!btf_type_is_struct(ptr_type)) { 6849 ptr_type_name = btf_name_by_offset(desc_btf, 6850 ptr_type->name_off); 6851 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n", 6852 func_name, btf_type_str(ptr_type), 6853 ptr_type_name); 6854 return -EINVAL; 6855 } 6856 mark_reg_known_zero(env, regs, BPF_REG_0); 6857 regs[BPF_REG_0].btf = desc_btf; 6858 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 6859 regs[BPF_REG_0].btf_id = ptr_type_id; 6860 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 6861 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */ 6862 6863 nargs = btf_type_vlen(func_proto); 6864 args = (const struct btf_param *)(func_proto + 1); 6865 for (i = 0; i < nargs; i++) { 6866 u32 regno = i + 1; 6867 6868 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 6869 if (btf_type_is_ptr(t)) 6870 mark_btf_func_reg_size(env, regno, sizeof(void *)); 6871 else 6872 /* scalar. ensured by btf_check_kfunc_arg_match() */ 6873 mark_btf_func_reg_size(env, regno, t->size); 6874 } 6875 6876 return 0; 6877 } 6878 6879 static bool signed_add_overflows(s64 a, s64 b) 6880 { 6881 /* Do the add in u64, where overflow is well-defined */ 6882 s64 res = (s64)((u64)a + (u64)b); 6883 6884 if (b < 0) 6885 return res > a; 6886 return res < a; 6887 } 6888 6889 static bool signed_add32_overflows(s32 a, s32 b) 6890 { 6891 /* Do the add in u32, where overflow is well-defined */ 6892 s32 res = (s32)((u32)a + (u32)b); 6893 6894 if (b < 0) 6895 return res > a; 6896 return res < a; 6897 } 6898 6899 static bool signed_sub_overflows(s64 a, s64 b) 6900 { 6901 /* Do the sub in u64, where overflow is well-defined */ 6902 s64 res = (s64)((u64)a - (u64)b); 6903 6904 if (b < 0) 6905 return res < a; 6906 return res > a; 6907 } 6908 6909 static bool signed_sub32_overflows(s32 a, s32 b) 6910 { 6911 /* Do the sub in u32, where overflow is well-defined */ 6912 s32 res = (s32)((u32)a - (u32)b); 6913 6914 if (b < 0) 6915 return res < a; 6916 return res > a; 6917 } 6918 6919 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 6920 const struct bpf_reg_state *reg, 6921 enum bpf_reg_type type) 6922 { 6923 bool known = tnum_is_const(reg->var_off); 6924 s64 val = reg->var_off.value; 6925 s64 smin = reg->smin_value; 6926 6927 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 6928 verbose(env, "math between %s pointer and %lld is not allowed\n", 6929 reg_type_str(env, type), val); 6930 return false; 6931 } 6932 6933 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 6934 verbose(env, "%s pointer offset %d is not allowed\n", 6935 reg_type_str(env, type), reg->off); 6936 return false; 6937 } 6938 6939 if (smin == S64_MIN) { 6940 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 6941 reg_type_str(env, type)); 6942 return false; 6943 } 6944 6945 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 6946 verbose(env, "value %lld makes %s pointer be out of bounds\n", 6947 smin, reg_type_str(env, type)); 6948 return false; 6949 } 6950 6951 return true; 6952 } 6953 6954 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 6955 { 6956 return &env->insn_aux_data[env->insn_idx]; 6957 } 6958 6959 enum { 6960 REASON_BOUNDS = -1, 6961 REASON_TYPE = -2, 6962 REASON_PATHS = -3, 6963 REASON_LIMIT = -4, 6964 REASON_STACK = -5, 6965 }; 6966 6967 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 6968 u32 *alu_limit, bool mask_to_left) 6969 { 6970 u32 max = 0, ptr_limit = 0; 6971 6972 switch (ptr_reg->type) { 6973 case PTR_TO_STACK: 6974 /* Offset 0 is out-of-bounds, but acceptable start for the 6975 * left direction, see BPF_REG_FP. Also, unknown scalar 6976 * offset where we would need to deal with min/max bounds is 6977 * currently prohibited for unprivileged. 6978 */ 6979 max = MAX_BPF_STACK + mask_to_left; 6980 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 6981 break; 6982 case PTR_TO_MAP_VALUE: 6983 max = ptr_reg->map_ptr->value_size; 6984 ptr_limit = (mask_to_left ? 6985 ptr_reg->smin_value : 6986 ptr_reg->umax_value) + ptr_reg->off; 6987 break; 6988 default: 6989 return REASON_TYPE; 6990 } 6991 6992 if (ptr_limit >= max) 6993 return REASON_LIMIT; 6994 *alu_limit = ptr_limit; 6995 return 0; 6996 } 6997 6998 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 6999 const struct bpf_insn *insn) 7000 { 7001 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 7002 } 7003 7004 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 7005 u32 alu_state, u32 alu_limit) 7006 { 7007 /* If we arrived here from different branches with different 7008 * state or limits to sanitize, then this won't work. 7009 */ 7010 if (aux->alu_state && 7011 (aux->alu_state != alu_state || 7012 aux->alu_limit != alu_limit)) 7013 return REASON_PATHS; 7014 7015 /* Corresponding fixup done in do_misc_fixups(). */ 7016 aux->alu_state = alu_state; 7017 aux->alu_limit = alu_limit; 7018 return 0; 7019 } 7020 7021 static int sanitize_val_alu(struct bpf_verifier_env *env, 7022 struct bpf_insn *insn) 7023 { 7024 struct bpf_insn_aux_data *aux = cur_aux(env); 7025 7026 if (can_skip_alu_sanitation(env, insn)) 7027 return 0; 7028 7029 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 7030 } 7031 7032 static bool sanitize_needed(u8 opcode) 7033 { 7034 return opcode == BPF_ADD || opcode == BPF_SUB; 7035 } 7036 7037 struct bpf_sanitize_info { 7038 struct bpf_insn_aux_data aux; 7039 bool mask_to_left; 7040 }; 7041 7042 static struct bpf_verifier_state * 7043 sanitize_speculative_path(struct bpf_verifier_env *env, 7044 const struct bpf_insn *insn, 7045 u32 next_idx, u32 curr_idx) 7046 { 7047 struct bpf_verifier_state *branch; 7048 struct bpf_reg_state *regs; 7049 7050 branch = push_stack(env, next_idx, curr_idx, true); 7051 if (branch && insn) { 7052 regs = branch->frame[branch->curframe]->regs; 7053 if (BPF_SRC(insn->code) == BPF_K) { 7054 mark_reg_unknown(env, regs, insn->dst_reg); 7055 } else if (BPF_SRC(insn->code) == BPF_X) { 7056 mark_reg_unknown(env, regs, insn->dst_reg); 7057 mark_reg_unknown(env, regs, insn->src_reg); 7058 } 7059 } 7060 return branch; 7061 } 7062 7063 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 7064 struct bpf_insn *insn, 7065 const struct bpf_reg_state *ptr_reg, 7066 const struct bpf_reg_state *off_reg, 7067 struct bpf_reg_state *dst_reg, 7068 struct bpf_sanitize_info *info, 7069 const bool commit_window) 7070 { 7071 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 7072 struct bpf_verifier_state *vstate = env->cur_state; 7073 bool off_is_imm = tnum_is_const(off_reg->var_off); 7074 bool off_is_neg = off_reg->smin_value < 0; 7075 bool ptr_is_dst_reg = ptr_reg == dst_reg; 7076 u8 opcode = BPF_OP(insn->code); 7077 u32 alu_state, alu_limit; 7078 struct bpf_reg_state tmp; 7079 bool ret; 7080 int err; 7081 7082 if (can_skip_alu_sanitation(env, insn)) 7083 return 0; 7084 7085 /* We already marked aux for masking from non-speculative 7086 * paths, thus we got here in the first place. We only care 7087 * to explore bad access from here. 7088 */ 7089 if (vstate->speculative) 7090 goto do_sim; 7091 7092 if (!commit_window) { 7093 if (!tnum_is_const(off_reg->var_off) && 7094 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 7095 return REASON_BOUNDS; 7096 7097 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 7098 (opcode == BPF_SUB && !off_is_neg); 7099 } 7100 7101 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 7102 if (err < 0) 7103 return err; 7104 7105 if (commit_window) { 7106 /* In commit phase we narrow the masking window based on 7107 * the observed pointer move after the simulated operation. 7108 */ 7109 alu_state = info->aux.alu_state; 7110 alu_limit = abs(info->aux.alu_limit - alu_limit); 7111 } else { 7112 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 7113 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 7114 alu_state |= ptr_is_dst_reg ? 7115 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 7116 7117 /* Limit pruning on unknown scalars to enable deep search for 7118 * potential masking differences from other program paths. 7119 */ 7120 if (!off_is_imm) 7121 env->explore_alu_limits = true; 7122 } 7123 7124 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 7125 if (err < 0) 7126 return err; 7127 do_sim: 7128 /* If we're in commit phase, we're done here given we already 7129 * pushed the truncated dst_reg into the speculative verification 7130 * stack. 7131 * 7132 * Also, when register is a known constant, we rewrite register-based 7133 * operation to immediate-based, and thus do not need masking (and as 7134 * a consequence, do not need to simulate the zero-truncation either). 7135 */ 7136 if (commit_window || off_is_imm) 7137 return 0; 7138 7139 /* Simulate and find potential out-of-bounds access under 7140 * speculative execution from truncation as a result of 7141 * masking when off was not within expected range. If off 7142 * sits in dst, then we temporarily need to move ptr there 7143 * to simulate dst (== 0) +/-= ptr. Needed, for example, 7144 * for cases where we use K-based arithmetic in one direction 7145 * and truncated reg-based in the other in order to explore 7146 * bad access. 7147 */ 7148 if (!ptr_is_dst_reg) { 7149 tmp = *dst_reg; 7150 *dst_reg = *ptr_reg; 7151 } 7152 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 7153 env->insn_idx); 7154 if (!ptr_is_dst_reg && ret) 7155 *dst_reg = tmp; 7156 return !ret ? REASON_STACK : 0; 7157 } 7158 7159 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 7160 { 7161 struct bpf_verifier_state *vstate = env->cur_state; 7162 7163 /* If we simulate paths under speculation, we don't update the 7164 * insn as 'seen' such that when we verify unreachable paths in 7165 * the non-speculative domain, sanitize_dead_code() can still 7166 * rewrite/sanitize them. 7167 */ 7168 if (!vstate->speculative) 7169 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 7170 } 7171 7172 static int sanitize_err(struct bpf_verifier_env *env, 7173 const struct bpf_insn *insn, int reason, 7174 const struct bpf_reg_state *off_reg, 7175 const struct bpf_reg_state *dst_reg) 7176 { 7177 static const char *err = "pointer arithmetic with it prohibited for !root"; 7178 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 7179 u32 dst = insn->dst_reg, src = insn->src_reg; 7180 7181 switch (reason) { 7182 case REASON_BOUNDS: 7183 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 7184 off_reg == dst_reg ? dst : src, err); 7185 break; 7186 case REASON_TYPE: 7187 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 7188 off_reg == dst_reg ? src : dst, err); 7189 break; 7190 case REASON_PATHS: 7191 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 7192 dst, op, err); 7193 break; 7194 case REASON_LIMIT: 7195 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 7196 dst, op, err); 7197 break; 7198 case REASON_STACK: 7199 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 7200 dst, err); 7201 break; 7202 default: 7203 verbose(env, "verifier internal error: unknown reason (%d)\n", 7204 reason); 7205 break; 7206 } 7207 7208 return -EACCES; 7209 } 7210 7211 /* check that stack access falls within stack limits and that 'reg' doesn't 7212 * have a variable offset. 7213 * 7214 * Variable offset is prohibited for unprivileged mode for simplicity since it 7215 * requires corresponding support in Spectre masking for stack ALU. See also 7216 * retrieve_ptr_limit(). 7217 * 7218 * 7219 * 'off' includes 'reg->off'. 7220 */ 7221 static int check_stack_access_for_ptr_arithmetic( 7222 struct bpf_verifier_env *env, 7223 int regno, 7224 const struct bpf_reg_state *reg, 7225 int off) 7226 { 7227 if (!tnum_is_const(reg->var_off)) { 7228 char tn_buf[48]; 7229 7230 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7231 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 7232 regno, tn_buf, off); 7233 return -EACCES; 7234 } 7235 7236 if (off >= 0 || off < -MAX_BPF_STACK) { 7237 verbose(env, "R%d stack pointer arithmetic goes out of range, " 7238 "prohibited for !root; off=%d\n", regno, off); 7239 return -EACCES; 7240 } 7241 7242 return 0; 7243 } 7244 7245 static int sanitize_check_bounds(struct bpf_verifier_env *env, 7246 const struct bpf_insn *insn, 7247 const struct bpf_reg_state *dst_reg) 7248 { 7249 u32 dst = insn->dst_reg; 7250 7251 /* For unprivileged we require that resulting offset must be in bounds 7252 * in order to be able to sanitize access later on. 7253 */ 7254 if (env->bypass_spec_v1) 7255 return 0; 7256 7257 switch (dst_reg->type) { 7258 case PTR_TO_STACK: 7259 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 7260 dst_reg->off + dst_reg->var_off.value)) 7261 return -EACCES; 7262 break; 7263 case PTR_TO_MAP_VALUE: 7264 if (check_map_access(env, dst, dst_reg->off, 1, false)) { 7265 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 7266 "prohibited for !root\n", dst); 7267 return -EACCES; 7268 } 7269 break; 7270 default: 7271 break; 7272 } 7273 7274 return 0; 7275 } 7276 7277 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 7278 * Caller should also handle BPF_MOV case separately. 7279 * If we return -EACCES, caller may want to try again treating pointer as a 7280 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 7281 */ 7282 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 7283 struct bpf_insn *insn, 7284 const struct bpf_reg_state *ptr_reg, 7285 const struct bpf_reg_state *off_reg) 7286 { 7287 struct bpf_verifier_state *vstate = env->cur_state; 7288 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7289 struct bpf_reg_state *regs = state->regs, *dst_reg; 7290 bool known = tnum_is_const(off_reg->var_off); 7291 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 7292 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 7293 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 7294 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 7295 struct bpf_sanitize_info info = {}; 7296 u8 opcode = BPF_OP(insn->code); 7297 u32 dst = insn->dst_reg; 7298 int ret; 7299 7300 dst_reg = ®s[dst]; 7301 7302 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 7303 smin_val > smax_val || umin_val > umax_val) { 7304 /* Taint dst register if offset had invalid bounds derived from 7305 * e.g. dead branches. 7306 */ 7307 __mark_reg_unknown(env, dst_reg); 7308 return 0; 7309 } 7310 7311 if (BPF_CLASS(insn->code) != BPF_ALU64) { 7312 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 7313 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 7314 __mark_reg_unknown(env, dst_reg); 7315 return 0; 7316 } 7317 7318 verbose(env, 7319 "R%d 32-bit pointer arithmetic prohibited\n", 7320 dst); 7321 return -EACCES; 7322 } 7323 7324 if (ptr_reg->type & PTR_MAYBE_NULL) { 7325 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 7326 dst, reg_type_str(env, ptr_reg->type)); 7327 return -EACCES; 7328 } 7329 7330 switch (base_type(ptr_reg->type)) { 7331 case CONST_PTR_TO_MAP: 7332 /* smin_val represents the known value */ 7333 if (known && smin_val == 0 && opcode == BPF_ADD) 7334 break; 7335 fallthrough; 7336 case PTR_TO_PACKET_END: 7337 case PTR_TO_SOCKET: 7338 case PTR_TO_SOCK_COMMON: 7339 case PTR_TO_TCP_SOCK: 7340 case PTR_TO_XDP_SOCK: 7341 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 7342 dst, reg_type_str(env, ptr_reg->type)); 7343 return -EACCES; 7344 default: 7345 break; 7346 } 7347 7348 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 7349 * The id may be overwritten later if we create a new variable offset. 7350 */ 7351 dst_reg->type = ptr_reg->type; 7352 dst_reg->id = ptr_reg->id; 7353 7354 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 7355 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 7356 return -EINVAL; 7357 7358 /* pointer types do not carry 32-bit bounds at the moment. */ 7359 __mark_reg32_unbounded(dst_reg); 7360 7361 if (sanitize_needed(opcode)) { 7362 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 7363 &info, false); 7364 if (ret < 0) 7365 return sanitize_err(env, insn, ret, off_reg, dst_reg); 7366 } 7367 7368 switch (opcode) { 7369 case BPF_ADD: 7370 /* We can take a fixed offset as long as it doesn't overflow 7371 * the s32 'off' field 7372 */ 7373 if (known && (ptr_reg->off + smin_val == 7374 (s64)(s32)(ptr_reg->off + smin_val))) { 7375 /* pointer += K. Accumulate it into fixed offset */ 7376 dst_reg->smin_value = smin_ptr; 7377 dst_reg->smax_value = smax_ptr; 7378 dst_reg->umin_value = umin_ptr; 7379 dst_reg->umax_value = umax_ptr; 7380 dst_reg->var_off = ptr_reg->var_off; 7381 dst_reg->off = ptr_reg->off + smin_val; 7382 dst_reg->raw = ptr_reg->raw; 7383 break; 7384 } 7385 /* A new variable offset is created. Note that off_reg->off 7386 * == 0, since it's a scalar. 7387 * dst_reg gets the pointer type and since some positive 7388 * integer value was added to the pointer, give it a new 'id' 7389 * if it's a PTR_TO_PACKET. 7390 * this creates a new 'base' pointer, off_reg (variable) gets 7391 * added into the variable offset, and we copy the fixed offset 7392 * from ptr_reg. 7393 */ 7394 if (signed_add_overflows(smin_ptr, smin_val) || 7395 signed_add_overflows(smax_ptr, smax_val)) { 7396 dst_reg->smin_value = S64_MIN; 7397 dst_reg->smax_value = S64_MAX; 7398 } else { 7399 dst_reg->smin_value = smin_ptr + smin_val; 7400 dst_reg->smax_value = smax_ptr + smax_val; 7401 } 7402 if (umin_ptr + umin_val < umin_ptr || 7403 umax_ptr + umax_val < umax_ptr) { 7404 dst_reg->umin_value = 0; 7405 dst_reg->umax_value = U64_MAX; 7406 } else { 7407 dst_reg->umin_value = umin_ptr + umin_val; 7408 dst_reg->umax_value = umax_ptr + umax_val; 7409 } 7410 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 7411 dst_reg->off = ptr_reg->off; 7412 dst_reg->raw = ptr_reg->raw; 7413 if (reg_is_pkt_pointer(ptr_reg)) { 7414 dst_reg->id = ++env->id_gen; 7415 /* something was added to pkt_ptr, set range to zero */ 7416 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 7417 } 7418 break; 7419 case BPF_SUB: 7420 if (dst_reg == off_reg) { 7421 /* scalar -= pointer. Creates an unknown scalar */ 7422 verbose(env, "R%d tried to subtract pointer from scalar\n", 7423 dst); 7424 return -EACCES; 7425 } 7426 /* We don't allow subtraction from FP, because (according to 7427 * test_verifier.c test "invalid fp arithmetic", JITs might not 7428 * be able to deal with it. 7429 */ 7430 if (ptr_reg->type == PTR_TO_STACK) { 7431 verbose(env, "R%d subtraction from stack pointer prohibited\n", 7432 dst); 7433 return -EACCES; 7434 } 7435 if (known && (ptr_reg->off - smin_val == 7436 (s64)(s32)(ptr_reg->off - smin_val))) { 7437 /* pointer -= K. Subtract it from fixed offset */ 7438 dst_reg->smin_value = smin_ptr; 7439 dst_reg->smax_value = smax_ptr; 7440 dst_reg->umin_value = umin_ptr; 7441 dst_reg->umax_value = umax_ptr; 7442 dst_reg->var_off = ptr_reg->var_off; 7443 dst_reg->id = ptr_reg->id; 7444 dst_reg->off = ptr_reg->off - smin_val; 7445 dst_reg->raw = ptr_reg->raw; 7446 break; 7447 } 7448 /* A new variable offset is created. If the subtrahend is known 7449 * nonnegative, then any reg->range we had before is still good. 7450 */ 7451 if (signed_sub_overflows(smin_ptr, smax_val) || 7452 signed_sub_overflows(smax_ptr, smin_val)) { 7453 /* Overflow possible, we know nothing */ 7454 dst_reg->smin_value = S64_MIN; 7455 dst_reg->smax_value = S64_MAX; 7456 } else { 7457 dst_reg->smin_value = smin_ptr - smax_val; 7458 dst_reg->smax_value = smax_ptr - smin_val; 7459 } 7460 if (umin_ptr < umax_val) { 7461 /* Overflow possible, we know nothing */ 7462 dst_reg->umin_value = 0; 7463 dst_reg->umax_value = U64_MAX; 7464 } else { 7465 /* Cannot overflow (as long as bounds are consistent) */ 7466 dst_reg->umin_value = umin_ptr - umax_val; 7467 dst_reg->umax_value = umax_ptr - umin_val; 7468 } 7469 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 7470 dst_reg->off = ptr_reg->off; 7471 dst_reg->raw = ptr_reg->raw; 7472 if (reg_is_pkt_pointer(ptr_reg)) { 7473 dst_reg->id = ++env->id_gen; 7474 /* something was added to pkt_ptr, set range to zero */ 7475 if (smin_val < 0) 7476 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 7477 } 7478 break; 7479 case BPF_AND: 7480 case BPF_OR: 7481 case BPF_XOR: 7482 /* bitwise ops on pointers are troublesome, prohibit. */ 7483 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 7484 dst, bpf_alu_string[opcode >> 4]); 7485 return -EACCES; 7486 default: 7487 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 7488 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 7489 dst, bpf_alu_string[opcode >> 4]); 7490 return -EACCES; 7491 } 7492 7493 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 7494 return -EINVAL; 7495 7496 __update_reg_bounds(dst_reg); 7497 __reg_deduce_bounds(dst_reg); 7498 __reg_bound_offset(dst_reg); 7499 7500 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 7501 return -EACCES; 7502 if (sanitize_needed(opcode)) { 7503 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 7504 &info, true); 7505 if (ret < 0) 7506 return sanitize_err(env, insn, ret, off_reg, dst_reg); 7507 } 7508 7509 return 0; 7510 } 7511 7512 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 7513 struct bpf_reg_state *src_reg) 7514 { 7515 s32 smin_val = src_reg->s32_min_value; 7516 s32 smax_val = src_reg->s32_max_value; 7517 u32 umin_val = src_reg->u32_min_value; 7518 u32 umax_val = src_reg->u32_max_value; 7519 7520 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 7521 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 7522 dst_reg->s32_min_value = S32_MIN; 7523 dst_reg->s32_max_value = S32_MAX; 7524 } else { 7525 dst_reg->s32_min_value += smin_val; 7526 dst_reg->s32_max_value += smax_val; 7527 } 7528 if (dst_reg->u32_min_value + umin_val < umin_val || 7529 dst_reg->u32_max_value + umax_val < umax_val) { 7530 dst_reg->u32_min_value = 0; 7531 dst_reg->u32_max_value = U32_MAX; 7532 } else { 7533 dst_reg->u32_min_value += umin_val; 7534 dst_reg->u32_max_value += umax_val; 7535 } 7536 } 7537 7538 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 7539 struct bpf_reg_state *src_reg) 7540 { 7541 s64 smin_val = src_reg->smin_value; 7542 s64 smax_val = src_reg->smax_value; 7543 u64 umin_val = src_reg->umin_value; 7544 u64 umax_val = src_reg->umax_value; 7545 7546 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 7547 signed_add_overflows(dst_reg->smax_value, smax_val)) { 7548 dst_reg->smin_value = S64_MIN; 7549 dst_reg->smax_value = S64_MAX; 7550 } else { 7551 dst_reg->smin_value += smin_val; 7552 dst_reg->smax_value += smax_val; 7553 } 7554 if (dst_reg->umin_value + umin_val < umin_val || 7555 dst_reg->umax_value + umax_val < umax_val) { 7556 dst_reg->umin_value = 0; 7557 dst_reg->umax_value = U64_MAX; 7558 } else { 7559 dst_reg->umin_value += umin_val; 7560 dst_reg->umax_value += umax_val; 7561 } 7562 } 7563 7564 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 7565 struct bpf_reg_state *src_reg) 7566 { 7567 s32 smin_val = src_reg->s32_min_value; 7568 s32 smax_val = src_reg->s32_max_value; 7569 u32 umin_val = src_reg->u32_min_value; 7570 u32 umax_val = src_reg->u32_max_value; 7571 7572 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 7573 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 7574 /* Overflow possible, we know nothing */ 7575 dst_reg->s32_min_value = S32_MIN; 7576 dst_reg->s32_max_value = S32_MAX; 7577 } else { 7578 dst_reg->s32_min_value -= smax_val; 7579 dst_reg->s32_max_value -= smin_val; 7580 } 7581 if (dst_reg->u32_min_value < umax_val) { 7582 /* Overflow possible, we know nothing */ 7583 dst_reg->u32_min_value = 0; 7584 dst_reg->u32_max_value = U32_MAX; 7585 } else { 7586 /* Cannot overflow (as long as bounds are consistent) */ 7587 dst_reg->u32_min_value -= umax_val; 7588 dst_reg->u32_max_value -= umin_val; 7589 } 7590 } 7591 7592 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 7593 struct bpf_reg_state *src_reg) 7594 { 7595 s64 smin_val = src_reg->smin_value; 7596 s64 smax_val = src_reg->smax_value; 7597 u64 umin_val = src_reg->umin_value; 7598 u64 umax_val = src_reg->umax_value; 7599 7600 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 7601 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 7602 /* Overflow possible, we know nothing */ 7603 dst_reg->smin_value = S64_MIN; 7604 dst_reg->smax_value = S64_MAX; 7605 } else { 7606 dst_reg->smin_value -= smax_val; 7607 dst_reg->smax_value -= smin_val; 7608 } 7609 if (dst_reg->umin_value < umax_val) { 7610 /* Overflow possible, we know nothing */ 7611 dst_reg->umin_value = 0; 7612 dst_reg->umax_value = U64_MAX; 7613 } else { 7614 /* Cannot overflow (as long as bounds are consistent) */ 7615 dst_reg->umin_value -= umax_val; 7616 dst_reg->umax_value -= umin_val; 7617 } 7618 } 7619 7620 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 7621 struct bpf_reg_state *src_reg) 7622 { 7623 s32 smin_val = src_reg->s32_min_value; 7624 u32 umin_val = src_reg->u32_min_value; 7625 u32 umax_val = src_reg->u32_max_value; 7626 7627 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 7628 /* Ain't nobody got time to multiply that sign */ 7629 __mark_reg32_unbounded(dst_reg); 7630 return; 7631 } 7632 /* Both values are positive, so we can work with unsigned and 7633 * copy the result to signed (unless it exceeds S32_MAX). 7634 */ 7635 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 7636 /* Potential overflow, we know nothing */ 7637 __mark_reg32_unbounded(dst_reg); 7638 return; 7639 } 7640 dst_reg->u32_min_value *= umin_val; 7641 dst_reg->u32_max_value *= umax_val; 7642 if (dst_reg->u32_max_value > S32_MAX) { 7643 /* Overflow possible, we know nothing */ 7644 dst_reg->s32_min_value = S32_MIN; 7645 dst_reg->s32_max_value = S32_MAX; 7646 } else { 7647 dst_reg->s32_min_value = dst_reg->u32_min_value; 7648 dst_reg->s32_max_value = dst_reg->u32_max_value; 7649 } 7650 } 7651 7652 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 7653 struct bpf_reg_state *src_reg) 7654 { 7655 s64 smin_val = src_reg->smin_value; 7656 u64 umin_val = src_reg->umin_value; 7657 u64 umax_val = src_reg->umax_value; 7658 7659 if (smin_val < 0 || dst_reg->smin_value < 0) { 7660 /* Ain't nobody got time to multiply that sign */ 7661 __mark_reg64_unbounded(dst_reg); 7662 return; 7663 } 7664 /* Both values are positive, so we can work with unsigned and 7665 * copy the result to signed (unless it exceeds S64_MAX). 7666 */ 7667 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 7668 /* Potential overflow, we know nothing */ 7669 __mark_reg64_unbounded(dst_reg); 7670 return; 7671 } 7672 dst_reg->umin_value *= umin_val; 7673 dst_reg->umax_value *= umax_val; 7674 if (dst_reg->umax_value > S64_MAX) { 7675 /* Overflow possible, we know nothing */ 7676 dst_reg->smin_value = S64_MIN; 7677 dst_reg->smax_value = S64_MAX; 7678 } else { 7679 dst_reg->smin_value = dst_reg->umin_value; 7680 dst_reg->smax_value = dst_reg->umax_value; 7681 } 7682 } 7683 7684 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 7685 struct bpf_reg_state *src_reg) 7686 { 7687 bool src_known = tnum_subreg_is_const(src_reg->var_off); 7688 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 7689 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 7690 s32 smin_val = src_reg->s32_min_value; 7691 u32 umax_val = src_reg->u32_max_value; 7692 7693 if (src_known && dst_known) { 7694 __mark_reg32_known(dst_reg, var32_off.value); 7695 return; 7696 } 7697 7698 /* We get our minimum from the var_off, since that's inherently 7699 * bitwise. Our maximum is the minimum of the operands' maxima. 7700 */ 7701 dst_reg->u32_min_value = var32_off.value; 7702 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 7703 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 7704 /* Lose signed bounds when ANDing negative numbers, 7705 * ain't nobody got time for that. 7706 */ 7707 dst_reg->s32_min_value = S32_MIN; 7708 dst_reg->s32_max_value = S32_MAX; 7709 } else { 7710 /* ANDing two positives gives a positive, so safe to 7711 * cast result into s64. 7712 */ 7713 dst_reg->s32_min_value = dst_reg->u32_min_value; 7714 dst_reg->s32_max_value = dst_reg->u32_max_value; 7715 } 7716 } 7717 7718 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 7719 struct bpf_reg_state *src_reg) 7720 { 7721 bool src_known = tnum_is_const(src_reg->var_off); 7722 bool dst_known = tnum_is_const(dst_reg->var_off); 7723 s64 smin_val = src_reg->smin_value; 7724 u64 umax_val = src_reg->umax_value; 7725 7726 if (src_known && dst_known) { 7727 __mark_reg_known(dst_reg, dst_reg->var_off.value); 7728 return; 7729 } 7730 7731 /* We get our minimum from the var_off, since that's inherently 7732 * bitwise. Our maximum is the minimum of the operands' maxima. 7733 */ 7734 dst_reg->umin_value = dst_reg->var_off.value; 7735 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 7736 if (dst_reg->smin_value < 0 || smin_val < 0) { 7737 /* Lose signed bounds when ANDing negative numbers, 7738 * ain't nobody got time for that. 7739 */ 7740 dst_reg->smin_value = S64_MIN; 7741 dst_reg->smax_value = S64_MAX; 7742 } else { 7743 /* ANDing two positives gives a positive, so safe to 7744 * cast result into s64. 7745 */ 7746 dst_reg->smin_value = dst_reg->umin_value; 7747 dst_reg->smax_value = dst_reg->umax_value; 7748 } 7749 /* We may learn something more from the var_off */ 7750 __update_reg_bounds(dst_reg); 7751 } 7752 7753 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 7754 struct bpf_reg_state *src_reg) 7755 { 7756 bool src_known = tnum_subreg_is_const(src_reg->var_off); 7757 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 7758 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 7759 s32 smin_val = src_reg->s32_min_value; 7760 u32 umin_val = src_reg->u32_min_value; 7761 7762 if (src_known && dst_known) { 7763 __mark_reg32_known(dst_reg, var32_off.value); 7764 return; 7765 } 7766 7767 /* We get our maximum from the var_off, and our minimum is the 7768 * maximum of the operands' minima 7769 */ 7770 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 7771 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 7772 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 7773 /* Lose signed bounds when ORing negative numbers, 7774 * ain't nobody got time for that. 7775 */ 7776 dst_reg->s32_min_value = S32_MIN; 7777 dst_reg->s32_max_value = S32_MAX; 7778 } else { 7779 /* ORing two positives gives a positive, so safe to 7780 * cast result into s64. 7781 */ 7782 dst_reg->s32_min_value = dst_reg->u32_min_value; 7783 dst_reg->s32_max_value = dst_reg->u32_max_value; 7784 } 7785 } 7786 7787 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 7788 struct bpf_reg_state *src_reg) 7789 { 7790 bool src_known = tnum_is_const(src_reg->var_off); 7791 bool dst_known = tnum_is_const(dst_reg->var_off); 7792 s64 smin_val = src_reg->smin_value; 7793 u64 umin_val = src_reg->umin_value; 7794 7795 if (src_known && dst_known) { 7796 __mark_reg_known(dst_reg, dst_reg->var_off.value); 7797 return; 7798 } 7799 7800 /* We get our maximum from the var_off, and our minimum is the 7801 * maximum of the operands' minima 7802 */ 7803 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 7804 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 7805 if (dst_reg->smin_value < 0 || smin_val < 0) { 7806 /* Lose signed bounds when ORing negative numbers, 7807 * ain't nobody got time for that. 7808 */ 7809 dst_reg->smin_value = S64_MIN; 7810 dst_reg->smax_value = S64_MAX; 7811 } else { 7812 /* ORing two positives gives a positive, so safe to 7813 * cast result into s64. 7814 */ 7815 dst_reg->smin_value = dst_reg->umin_value; 7816 dst_reg->smax_value = dst_reg->umax_value; 7817 } 7818 /* We may learn something more from the var_off */ 7819 __update_reg_bounds(dst_reg); 7820 } 7821 7822 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 7823 struct bpf_reg_state *src_reg) 7824 { 7825 bool src_known = tnum_subreg_is_const(src_reg->var_off); 7826 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 7827 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 7828 s32 smin_val = src_reg->s32_min_value; 7829 7830 if (src_known && dst_known) { 7831 __mark_reg32_known(dst_reg, var32_off.value); 7832 return; 7833 } 7834 7835 /* We get both minimum and maximum from the var32_off. */ 7836 dst_reg->u32_min_value = var32_off.value; 7837 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 7838 7839 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 7840 /* XORing two positive sign numbers gives a positive, 7841 * so safe to cast u32 result into s32. 7842 */ 7843 dst_reg->s32_min_value = dst_reg->u32_min_value; 7844 dst_reg->s32_max_value = dst_reg->u32_max_value; 7845 } else { 7846 dst_reg->s32_min_value = S32_MIN; 7847 dst_reg->s32_max_value = S32_MAX; 7848 } 7849 } 7850 7851 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 7852 struct bpf_reg_state *src_reg) 7853 { 7854 bool src_known = tnum_is_const(src_reg->var_off); 7855 bool dst_known = tnum_is_const(dst_reg->var_off); 7856 s64 smin_val = src_reg->smin_value; 7857 7858 if (src_known && dst_known) { 7859 /* dst_reg->var_off.value has been updated earlier */ 7860 __mark_reg_known(dst_reg, dst_reg->var_off.value); 7861 return; 7862 } 7863 7864 /* We get both minimum and maximum from the var_off. */ 7865 dst_reg->umin_value = dst_reg->var_off.value; 7866 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 7867 7868 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 7869 /* XORing two positive sign numbers gives a positive, 7870 * so safe to cast u64 result into s64. 7871 */ 7872 dst_reg->smin_value = dst_reg->umin_value; 7873 dst_reg->smax_value = dst_reg->umax_value; 7874 } else { 7875 dst_reg->smin_value = S64_MIN; 7876 dst_reg->smax_value = S64_MAX; 7877 } 7878 7879 __update_reg_bounds(dst_reg); 7880 } 7881 7882 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 7883 u64 umin_val, u64 umax_val) 7884 { 7885 /* We lose all sign bit information (except what we can pick 7886 * up from var_off) 7887 */ 7888 dst_reg->s32_min_value = S32_MIN; 7889 dst_reg->s32_max_value = S32_MAX; 7890 /* If we might shift our top bit out, then we know nothing */ 7891 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 7892 dst_reg->u32_min_value = 0; 7893 dst_reg->u32_max_value = U32_MAX; 7894 } else { 7895 dst_reg->u32_min_value <<= umin_val; 7896 dst_reg->u32_max_value <<= umax_val; 7897 } 7898 } 7899 7900 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 7901 struct bpf_reg_state *src_reg) 7902 { 7903 u32 umax_val = src_reg->u32_max_value; 7904 u32 umin_val = src_reg->u32_min_value; 7905 /* u32 alu operation will zext upper bits */ 7906 struct tnum subreg = tnum_subreg(dst_reg->var_off); 7907 7908 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 7909 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 7910 /* Not required but being careful mark reg64 bounds as unknown so 7911 * that we are forced to pick them up from tnum and zext later and 7912 * if some path skips this step we are still safe. 7913 */ 7914 __mark_reg64_unbounded(dst_reg); 7915 __update_reg32_bounds(dst_reg); 7916 } 7917 7918 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 7919 u64 umin_val, u64 umax_val) 7920 { 7921 /* Special case <<32 because it is a common compiler pattern to sign 7922 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 7923 * positive we know this shift will also be positive so we can track 7924 * bounds correctly. Otherwise we lose all sign bit information except 7925 * what we can pick up from var_off. Perhaps we can generalize this 7926 * later to shifts of any length. 7927 */ 7928 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 7929 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 7930 else 7931 dst_reg->smax_value = S64_MAX; 7932 7933 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 7934 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 7935 else 7936 dst_reg->smin_value = S64_MIN; 7937 7938 /* If we might shift our top bit out, then we know nothing */ 7939 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 7940 dst_reg->umin_value = 0; 7941 dst_reg->umax_value = U64_MAX; 7942 } else { 7943 dst_reg->umin_value <<= umin_val; 7944 dst_reg->umax_value <<= umax_val; 7945 } 7946 } 7947 7948 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 7949 struct bpf_reg_state *src_reg) 7950 { 7951 u64 umax_val = src_reg->umax_value; 7952 u64 umin_val = src_reg->umin_value; 7953 7954 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 7955 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 7956 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 7957 7958 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 7959 /* We may learn something more from the var_off */ 7960 __update_reg_bounds(dst_reg); 7961 } 7962 7963 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 7964 struct bpf_reg_state *src_reg) 7965 { 7966 struct tnum subreg = tnum_subreg(dst_reg->var_off); 7967 u32 umax_val = src_reg->u32_max_value; 7968 u32 umin_val = src_reg->u32_min_value; 7969 7970 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 7971 * be negative, then either: 7972 * 1) src_reg might be zero, so the sign bit of the result is 7973 * unknown, so we lose our signed bounds 7974 * 2) it's known negative, thus the unsigned bounds capture the 7975 * signed bounds 7976 * 3) the signed bounds cross zero, so they tell us nothing 7977 * about the result 7978 * If the value in dst_reg is known nonnegative, then again the 7979 * unsigned bounds capture the signed bounds. 7980 * Thus, in all cases it suffices to blow away our signed bounds 7981 * and rely on inferring new ones from the unsigned bounds and 7982 * var_off of the result. 7983 */ 7984 dst_reg->s32_min_value = S32_MIN; 7985 dst_reg->s32_max_value = S32_MAX; 7986 7987 dst_reg->var_off = tnum_rshift(subreg, umin_val); 7988 dst_reg->u32_min_value >>= umax_val; 7989 dst_reg->u32_max_value >>= umin_val; 7990 7991 __mark_reg64_unbounded(dst_reg); 7992 __update_reg32_bounds(dst_reg); 7993 } 7994 7995 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 7996 struct bpf_reg_state *src_reg) 7997 { 7998 u64 umax_val = src_reg->umax_value; 7999 u64 umin_val = src_reg->umin_value; 8000 8001 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 8002 * be negative, then either: 8003 * 1) src_reg might be zero, so the sign bit of the result is 8004 * unknown, so we lose our signed bounds 8005 * 2) it's known negative, thus the unsigned bounds capture the 8006 * signed bounds 8007 * 3) the signed bounds cross zero, so they tell us nothing 8008 * about the result 8009 * If the value in dst_reg is known nonnegative, then again the 8010 * unsigned bounds capture the signed bounds. 8011 * Thus, in all cases it suffices to blow away our signed bounds 8012 * and rely on inferring new ones from the unsigned bounds and 8013 * var_off of the result. 8014 */ 8015 dst_reg->smin_value = S64_MIN; 8016 dst_reg->smax_value = S64_MAX; 8017 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 8018 dst_reg->umin_value >>= umax_val; 8019 dst_reg->umax_value >>= umin_val; 8020 8021 /* Its not easy to operate on alu32 bounds here because it depends 8022 * on bits being shifted in. Take easy way out and mark unbounded 8023 * so we can recalculate later from tnum. 8024 */ 8025 __mark_reg32_unbounded(dst_reg); 8026 __update_reg_bounds(dst_reg); 8027 } 8028 8029 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 8030 struct bpf_reg_state *src_reg) 8031 { 8032 u64 umin_val = src_reg->u32_min_value; 8033 8034 /* Upon reaching here, src_known is true and 8035 * umax_val is equal to umin_val. 8036 */ 8037 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 8038 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 8039 8040 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 8041 8042 /* blow away the dst_reg umin_value/umax_value and rely on 8043 * dst_reg var_off to refine the result. 8044 */ 8045 dst_reg->u32_min_value = 0; 8046 dst_reg->u32_max_value = U32_MAX; 8047 8048 __mark_reg64_unbounded(dst_reg); 8049 __update_reg32_bounds(dst_reg); 8050 } 8051 8052 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 8053 struct bpf_reg_state *src_reg) 8054 { 8055 u64 umin_val = src_reg->umin_value; 8056 8057 /* Upon reaching here, src_known is true and umax_val is equal 8058 * to umin_val. 8059 */ 8060 dst_reg->smin_value >>= umin_val; 8061 dst_reg->smax_value >>= umin_val; 8062 8063 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 8064 8065 /* blow away the dst_reg umin_value/umax_value and rely on 8066 * dst_reg var_off to refine the result. 8067 */ 8068 dst_reg->umin_value = 0; 8069 dst_reg->umax_value = U64_MAX; 8070 8071 /* Its not easy to operate on alu32 bounds here because it depends 8072 * on bits being shifted in from upper 32-bits. Take easy way out 8073 * and mark unbounded so we can recalculate later from tnum. 8074 */ 8075 __mark_reg32_unbounded(dst_reg); 8076 __update_reg_bounds(dst_reg); 8077 } 8078 8079 /* WARNING: This function does calculations on 64-bit values, but the actual 8080 * execution may occur on 32-bit values. Therefore, things like bitshifts 8081 * need extra checks in the 32-bit case. 8082 */ 8083 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 8084 struct bpf_insn *insn, 8085 struct bpf_reg_state *dst_reg, 8086 struct bpf_reg_state src_reg) 8087 { 8088 struct bpf_reg_state *regs = cur_regs(env); 8089 u8 opcode = BPF_OP(insn->code); 8090 bool src_known; 8091 s64 smin_val, smax_val; 8092 u64 umin_val, umax_val; 8093 s32 s32_min_val, s32_max_val; 8094 u32 u32_min_val, u32_max_val; 8095 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 8096 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 8097 int ret; 8098 8099 smin_val = src_reg.smin_value; 8100 smax_val = src_reg.smax_value; 8101 umin_val = src_reg.umin_value; 8102 umax_val = src_reg.umax_value; 8103 8104 s32_min_val = src_reg.s32_min_value; 8105 s32_max_val = src_reg.s32_max_value; 8106 u32_min_val = src_reg.u32_min_value; 8107 u32_max_val = src_reg.u32_max_value; 8108 8109 if (alu32) { 8110 src_known = tnum_subreg_is_const(src_reg.var_off); 8111 if ((src_known && 8112 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 8113 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 8114 /* Taint dst register if offset had invalid bounds 8115 * derived from e.g. dead branches. 8116 */ 8117 __mark_reg_unknown(env, dst_reg); 8118 return 0; 8119 } 8120 } else { 8121 src_known = tnum_is_const(src_reg.var_off); 8122 if ((src_known && 8123 (smin_val != smax_val || umin_val != umax_val)) || 8124 smin_val > smax_val || umin_val > umax_val) { 8125 /* Taint dst register if offset had invalid bounds 8126 * derived from e.g. dead branches. 8127 */ 8128 __mark_reg_unknown(env, dst_reg); 8129 return 0; 8130 } 8131 } 8132 8133 if (!src_known && 8134 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 8135 __mark_reg_unknown(env, dst_reg); 8136 return 0; 8137 } 8138 8139 if (sanitize_needed(opcode)) { 8140 ret = sanitize_val_alu(env, insn); 8141 if (ret < 0) 8142 return sanitize_err(env, insn, ret, NULL, NULL); 8143 } 8144 8145 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 8146 * There are two classes of instructions: The first class we track both 8147 * alu32 and alu64 sign/unsigned bounds independently this provides the 8148 * greatest amount of precision when alu operations are mixed with jmp32 8149 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 8150 * and BPF_OR. This is possible because these ops have fairly easy to 8151 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 8152 * See alu32 verifier tests for examples. The second class of 8153 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 8154 * with regards to tracking sign/unsigned bounds because the bits may 8155 * cross subreg boundaries in the alu64 case. When this happens we mark 8156 * the reg unbounded in the subreg bound space and use the resulting 8157 * tnum to calculate an approximation of the sign/unsigned bounds. 8158 */ 8159 switch (opcode) { 8160 case BPF_ADD: 8161 scalar32_min_max_add(dst_reg, &src_reg); 8162 scalar_min_max_add(dst_reg, &src_reg); 8163 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 8164 break; 8165 case BPF_SUB: 8166 scalar32_min_max_sub(dst_reg, &src_reg); 8167 scalar_min_max_sub(dst_reg, &src_reg); 8168 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 8169 break; 8170 case BPF_MUL: 8171 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 8172 scalar32_min_max_mul(dst_reg, &src_reg); 8173 scalar_min_max_mul(dst_reg, &src_reg); 8174 break; 8175 case BPF_AND: 8176 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 8177 scalar32_min_max_and(dst_reg, &src_reg); 8178 scalar_min_max_and(dst_reg, &src_reg); 8179 break; 8180 case BPF_OR: 8181 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 8182 scalar32_min_max_or(dst_reg, &src_reg); 8183 scalar_min_max_or(dst_reg, &src_reg); 8184 break; 8185 case BPF_XOR: 8186 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 8187 scalar32_min_max_xor(dst_reg, &src_reg); 8188 scalar_min_max_xor(dst_reg, &src_reg); 8189 break; 8190 case BPF_LSH: 8191 if (umax_val >= insn_bitness) { 8192 /* Shifts greater than 31 or 63 are undefined. 8193 * This includes shifts by a negative number. 8194 */ 8195 mark_reg_unknown(env, regs, insn->dst_reg); 8196 break; 8197 } 8198 if (alu32) 8199 scalar32_min_max_lsh(dst_reg, &src_reg); 8200 else 8201 scalar_min_max_lsh(dst_reg, &src_reg); 8202 break; 8203 case BPF_RSH: 8204 if (umax_val >= insn_bitness) { 8205 /* Shifts greater than 31 or 63 are undefined. 8206 * This includes shifts by a negative number. 8207 */ 8208 mark_reg_unknown(env, regs, insn->dst_reg); 8209 break; 8210 } 8211 if (alu32) 8212 scalar32_min_max_rsh(dst_reg, &src_reg); 8213 else 8214 scalar_min_max_rsh(dst_reg, &src_reg); 8215 break; 8216 case BPF_ARSH: 8217 if (umax_val >= insn_bitness) { 8218 /* Shifts greater than 31 or 63 are undefined. 8219 * This includes shifts by a negative number. 8220 */ 8221 mark_reg_unknown(env, regs, insn->dst_reg); 8222 break; 8223 } 8224 if (alu32) 8225 scalar32_min_max_arsh(dst_reg, &src_reg); 8226 else 8227 scalar_min_max_arsh(dst_reg, &src_reg); 8228 break; 8229 default: 8230 mark_reg_unknown(env, regs, insn->dst_reg); 8231 break; 8232 } 8233 8234 /* ALU32 ops are zero extended into 64bit register */ 8235 if (alu32) 8236 zext_32_to_64(dst_reg); 8237 8238 __update_reg_bounds(dst_reg); 8239 __reg_deduce_bounds(dst_reg); 8240 __reg_bound_offset(dst_reg); 8241 return 0; 8242 } 8243 8244 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 8245 * and var_off. 8246 */ 8247 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 8248 struct bpf_insn *insn) 8249 { 8250 struct bpf_verifier_state *vstate = env->cur_state; 8251 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8252 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 8253 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 8254 u8 opcode = BPF_OP(insn->code); 8255 int err; 8256 8257 dst_reg = ®s[insn->dst_reg]; 8258 src_reg = NULL; 8259 if (dst_reg->type != SCALAR_VALUE) 8260 ptr_reg = dst_reg; 8261 else 8262 /* Make sure ID is cleared otherwise dst_reg min/max could be 8263 * incorrectly propagated into other registers by find_equal_scalars() 8264 */ 8265 dst_reg->id = 0; 8266 if (BPF_SRC(insn->code) == BPF_X) { 8267 src_reg = ®s[insn->src_reg]; 8268 if (src_reg->type != SCALAR_VALUE) { 8269 if (dst_reg->type != SCALAR_VALUE) { 8270 /* Combining two pointers by any ALU op yields 8271 * an arbitrary scalar. Disallow all math except 8272 * pointer subtraction 8273 */ 8274 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 8275 mark_reg_unknown(env, regs, insn->dst_reg); 8276 return 0; 8277 } 8278 verbose(env, "R%d pointer %s pointer prohibited\n", 8279 insn->dst_reg, 8280 bpf_alu_string[opcode >> 4]); 8281 return -EACCES; 8282 } else { 8283 /* scalar += pointer 8284 * This is legal, but we have to reverse our 8285 * src/dest handling in computing the range 8286 */ 8287 err = mark_chain_precision(env, insn->dst_reg); 8288 if (err) 8289 return err; 8290 return adjust_ptr_min_max_vals(env, insn, 8291 src_reg, dst_reg); 8292 } 8293 } else if (ptr_reg) { 8294 /* pointer += scalar */ 8295 err = mark_chain_precision(env, insn->src_reg); 8296 if (err) 8297 return err; 8298 return adjust_ptr_min_max_vals(env, insn, 8299 dst_reg, src_reg); 8300 } 8301 } else { 8302 /* Pretend the src is a reg with a known value, since we only 8303 * need to be able to read from this state. 8304 */ 8305 off_reg.type = SCALAR_VALUE; 8306 __mark_reg_known(&off_reg, insn->imm); 8307 src_reg = &off_reg; 8308 if (ptr_reg) /* pointer += K */ 8309 return adjust_ptr_min_max_vals(env, insn, 8310 ptr_reg, src_reg); 8311 } 8312 8313 /* Got here implies adding two SCALAR_VALUEs */ 8314 if (WARN_ON_ONCE(ptr_reg)) { 8315 print_verifier_state(env, state, true); 8316 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 8317 return -EINVAL; 8318 } 8319 if (WARN_ON(!src_reg)) { 8320 print_verifier_state(env, state, true); 8321 verbose(env, "verifier internal error: no src_reg\n"); 8322 return -EINVAL; 8323 } 8324 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 8325 } 8326 8327 /* check validity of 32-bit and 64-bit arithmetic operations */ 8328 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 8329 { 8330 struct bpf_reg_state *regs = cur_regs(env); 8331 u8 opcode = BPF_OP(insn->code); 8332 int err; 8333 8334 if (opcode == BPF_END || opcode == BPF_NEG) { 8335 if (opcode == BPF_NEG) { 8336 if (BPF_SRC(insn->code) != 0 || 8337 insn->src_reg != BPF_REG_0 || 8338 insn->off != 0 || insn->imm != 0) { 8339 verbose(env, "BPF_NEG uses reserved fields\n"); 8340 return -EINVAL; 8341 } 8342 } else { 8343 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 8344 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 8345 BPF_CLASS(insn->code) == BPF_ALU64) { 8346 verbose(env, "BPF_END uses reserved fields\n"); 8347 return -EINVAL; 8348 } 8349 } 8350 8351 /* check src operand */ 8352 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8353 if (err) 8354 return err; 8355 8356 if (is_pointer_value(env, insn->dst_reg)) { 8357 verbose(env, "R%d pointer arithmetic prohibited\n", 8358 insn->dst_reg); 8359 return -EACCES; 8360 } 8361 8362 /* check dest operand */ 8363 err = check_reg_arg(env, insn->dst_reg, DST_OP); 8364 if (err) 8365 return err; 8366 8367 } else if (opcode == BPF_MOV) { 8368 8369 if (BPF_SRC(insn->code) == BPF_X) { 8370 if (insn->imm != 0 || insn->off != 0) { 8371 verbose(env, "BPF_MOV uses reserved fields\n"); 8372 return -EINVAL; 8373 } 8374 8375 /* check src operand */ 8376 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8377 if (err) 8378 return err; 8379 } else { 8380 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 8381 verbose(env, "BPF_MOV uses reserved fields\n"); 8382 return -EINVAL; 8383 } 8384 } 8385 8386 /* check dest operand, mark as required later */ 8387 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 8388 if (err) 8389 return err; 8390 8391 if (BPF_SRC(insn->code) == BPF_X) { 8392 struct bpf_reg_state *src_reg = regs + insn->src_reg; 8393 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 8394 8395 if (BPF_CLASS(insn->code) == BPF_ALU64) { 8396 /* case: R1 = R2 8397 * copy register state to dest reg 8398 */ 8399 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 8400 /* Assign src and dst registers the same ID 8401 * that will be used by find_equal_scalars() 8402 * to propagate min/max range. 8403 */ 8404 src_reg->id = ++env->id_gen; 8405 *dst_reg = *src_reg; 8406 dst_reg->live |= REG_LIVE_WRITTEN; 8407 dst_reg->subreg_def = DEF_NOT_SUBREG; 8408 } else { 8409 /* R1 = (u32) R2 */ 8410 if (is_pointer_value(env, insn->src_reg)) { 8411 verbose(env, 8412 "R%d partial copy of pointer\n", 8413 insn->src_reg); 8414 return -EACCES; 8415 } else if (src_reg->type == SCALAR_VALUE) { 8416 *dst_reg = *src_reg; 8417 /* Make sure ID is cleared otherwise 8418 * dst_reg min/max could be incorrectly 8419 * propagated into src_reg by find_equal_scalars() 8420 */ 8421 dst_reg->id = 0; 8422 dst_reg->live |= REG_LIVE_WRITTEN; 8423 dst_reg->subreg_def = env->insn_idx + 1; 8424 } else { 8425 mark_reg_unknown(env, regs, 8426 insn->dst_reg); 8427 } 8428 zext_32_to_64(dst_reg); 8429 } 8430 } else { 8431 /* case: R = imm 8432 * remember the value we stored into this reg 8433 */ 8434 /* clear any state __mark_reg_known doesn't set */ 8435 mark_reg_unknown(env, regs, insn->dst_reg); 8436 regs[insn->dst_reg].type = SCALAR_VALUE; 8437 if (BPF_CLASS(insn->code) == BPF_ALU64) { 8438 __mark_reg_known(regs + insn->dst_reg, 8439 insn->imm); 8440 } else { 8441 __mark_reg_known(regs + insn->dst_reg, 8442 (u32)insn->imm); 8443 } 8444 } 8445 8446 } else if (opcode > BPF_END) { 8447 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 8448 return -EINVAL; 8449 8450 } else { /* all other ALU ops: and, sub, xor, add, ... */ 8451 8452 if (BPF_SRC(insn->code) == BPF_X) { 8453 if (insn->imm != 0 || insn->off != 0) { 8454 verbose(env, "BPF_ALU uses reserved fields\n"); 8455 return -EINVAL; 8456 } 8457 /* check src1 operand */ 8458 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8459 if (err) 8460 return err; 8461 } else { 8462 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 8463 verbose(env, "BPF_ALU uses reserved fields\n"); 8464 return -EINVAL; 8465 } 8466 } 8467 8468 /* check src2 operand */ 8469 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8470 if (err) 8471 return err; 8472 8473 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 8474 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 8475 verbose(env, "div by zero\n"); 8476 return -EINVAL; 8477 } 8478 8479 if ((opcode == BPF_LSH || opcode == BPF_RSH || 8480 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 8481 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 8482 8483 if (insn->imm < 0 || insn->imm >= size) { 8484 verbose(env, "invalid shift %d\n", insn->imm); 8485 return -EINVAL; 8486 } 8487 } 8488 8489 /* check dest operand */ 8490 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 8491 if (err) 8492 return err; 8493 8494 return adjust_reg_min_max_vals(env, insn); 8495 } 8496 8497 return 0; 8498 } 8499 8500 static void __find_good_pkt_pointers(struct bpf_func_state *state, 8501 struct bpf_reg_state *dst_reg, 8502 enum bpf_reg_type type, int new_range) 8503 { 8504 struct bpf_reg_state *reg; 8505 int i; 8506 8507 for (i = 0; i < MAX_BPF_REG; i++) { 8508 reg = &state->regs[i]; 8509 if (reg->type == type && reg->id == dst_reg->id) 8510 /* keep the maximum range already checked */ 8511 reg->range = max(reg->range, new_range); 8512 } 8513 8514 bpf_for_each_spilled_reg(i, state, reg) { 8515 if (!reg) 8516 continue; 8517 if (reg->type == type && reg->id == dst_reg->id) 8518 reg->range = max(reg->range, new_range); 8519 } 8520 } 8521 8522 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 8523 struct bpf_reg_state *dst_reg, 8524 enum bpf_reg_type type, 8525 bool range_right_open) 8526 { 8527 int new_range, i; 8528 8529 if (dst_reg->off < 0 || 8530 (dst_reg->off == 0 && range_right_open)) 8531 /* This doesn't give us any range */ 8532 return; 8533 8534 if (dst_reg->umax_value > MAX_PACKET_OFF || 8535 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 8536 /* Risk of overflow. For instance, ptr + (1<<63) may be less 8537 * than pkt_end, but that's because it's also less than pkt. 8538 */ 8539 return; 8540 8541 new_range = dst_reg->off; 8542 if (range_right_open) 8543 new_range++; 8544 8545 /* Examples for register markings: 8546 * 8547 * pkt_data in dst register: 8548 * 8549 * r2 = r3; 8550 * r2 += 8; 8551 * if (r2 > pkt_end) goto <handle exception> 8552 * <access okay> 8553 * 8554 * r2 = r3; 8555 * r2 += 8; 8556 * if (r2 < pkt_end) goto <access okay> 8557 * <handle exception> 8558 * 8559 * Where: 8560 * r2 == dst_reg, pkt_end == src_reg 8561 * r2=pkt(id=n,off=8,r=0) 8562 * r3=pkt(id=n,off=0,r=0) 8563 * 8564 * pkt_data in src register: 8565 * 8566 * r2 = r3; 8567 * r2 += 8; 8568 * if (pkt_end >= r2) goto <access okay> 8569 * <handle exception> 8570 * 8571 * r2 = r3; 8572 * r2 += 8; 8573 * if (pkt_end <= r2) goto <handle exception> 8574 * <access okay> 8575 * 8576 * Where: 8577 * pkt_end == dst_reg, r2 == src_reg 8578 * r2=pkt(id=n,off=8,r=0) 8579 * r3=pkt(id=n,off=0,r=0) 8580 * 8581 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 8582 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 8583 * and [r3, r3 + 8-1) respectively is safe to access depending on 8584 * the check. 8585 */ 8586 8587 /* If our ids match, then we must have the same max_value. And we 8588 * don't care about the other reg's fixed offset, since if it's too big 8589 * the range won't allow anything. 8590 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 8591 */ 8592 for (i = 0; i <= vstate->curframe; i++) 8593 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type, 8594 new_range); 8595 } 8596 8597 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 8598 { 8599 struct tnum subreg = tnum_subreg(reg->var_off); 8600 s32 sval = (s32)val; 8601 8602 switch (opcode) { 8603 case BPF_JEQ: 8604 if (tnum_is_const(subreg)) 8605 return !!tnum_equals_const(subreg, val); 8606 break; 8607 case BPF_JNE: 8608 if (tnum_is_const(subreg)) 8609 return !tnum_equals_const(subreg, val); 8610 break; 8611 case BPF_JSET: 8612 if ((~subreg.mask & subreg.value) & val) 8613 return 1; 8614 if (!((subreg.mask | subreg.value) & val)) 8615 return 0; 8616 break; 8617 case BPF_JGT: 8618 if (reg->u32_min_value > val) 8619 return 1; 8620 else if (reg->u32_max_value <= val) 8621 return 0; 8622 break; 8623 case BPF_JSGT: 8624 if (reg->s32_min_value > sval) 8625 return 1; 8626 else if (reg->s32_max_value <= sval) 8627 return 0; 8628 break; 8629 case BPF_JLT: 8630 if (reg->u32_max_value < val) 8631 return 1; 8632 else if (reg->u32_min_value >= val) 8633 return 0; 8634 break; 8635 case BPF_JSLT: 8636 if (reg->s32_max_value < sval) 8637 return 1; 8638 else if (reg->s32_min_value >= sval) 8639 return 0; 8640 break; 8641 case BPF_JGE: 8642 if (reg->u32_min_value >= val) 8643 return 1; 8644 else if (reg->u32_max_value < val) 8645 return 0; 8646 break; 8647 case BPF_JSGE: 8648 if (reg->s32_min_value >= sval) 8649 return 1; 8650 else if (reg->s32_max_value < sval) 8651 return 0; 8652 break; 8653 case BPF_JLE: 8654 if (reg->u32_max_value <= val) 8655 return 1; 8656 else if (reg->u32_min_value > val) 8657 return 0; 8658 break; 8659 case BPF_JSLE: 8660 if (reg->s32_max_value <= sval) 8661 return 1; 8662 else if (reg->s32_min_value > sval) 8663 return 0; 8664 break; 8665 } 8666 8667 return -1; 8668 } 8669 8670 8671 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 8672 { 8673 s64 sval = (s64)val; 8674 8675 switch (opcode) { 8676 case BPF_JEQ: 8677 if (tnum_is_const(reg->var_off)) 8678 return !!tnum_equals_const(reg->var_off, val); 8679 break; 8680 case BPF_JNE: 8681 if (tnum_is_const(reg->var_off)) 8682 return !tnum_equals_const(reg->var_off, val); 8683 break; 8684 case BPF_JSET: 8685 if ((~reg->var_off.mask & reg->var_off.value) & val) 8686 return 1; 8687 if (!((reg->var_off.mask | reg->var_off.value) & val)) 8688 return 0; 8689 break; 8690 case BPF_JGT: 8691 if (reg->umin_value > val) 8692 return 1; 8693 else if (reg->umax_value <= val) 8694 return 0; 8695 break; 8696 case BPF_JSGT: 8697 if (reg->smin_value > sval) 8698 return 1; 8699 else if (reg->smax_value <= sval) 8700 return 0; 8701 break; 8702 case BPF_JLT: 8703 if (reg->umax_value < val) 8704 return 1; 8705 else if (reg->umin_value >= val) 8706 return 0; 8707 break; 8708 case BPF_JSLT: 8709 if (reg->smax_value < sval) 8710 return 1; 8711 else if (reg->smin_value >= sval) 8712 return 0; 8713 break; 8714 case BPF_JGE: 8715 if (reg->umin_value >= val) 8716 return 1; 8717 else if (reg->umax_value < val) 8718 return 0; 8719 break; 8720 case BPF_JSGE: 8721 if (reg->smin_value >= sval) 8722 return 1; 8723 else if (reg->smax_value < sval) 8724 return 0; 8725 break; 8726 case BPF_JLE: 8727 if (reg->umax_value <= val) 8728 return 1; 8729 else if (reg->umin_value > val) 8730 return 0; 8731 break; 8732 case BPF_JSLE: 8733 if (reg->smax_value <= sval) 8734 return 1; 8735 else if (reg->smin_value > sval) 8736 return 0; 8737 break; 8738 } 8739 8740 return -1; 8741 } 8742 8743 /* compute branch direction of the expression "if (reg opcode val) goto target;" 8744 * and return: 8745 * 1 - branch will be taken and "goto target" will be executed 8746 * 0 - branch will not be taken and fall-through to next insn 8747 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 8748 * range [0,10] 8749 */ 8750 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 8751 bool is_jmp32) 8752 { 8753 if (__is_pointer_value(false, reg)) { 8754 if (!reg_type_not_null(reg->type)) 8755 return -1; 8756 8757 /* If pointer is valid tests against zero will fail so we can 8758 * use this to direct branch taken. 8759 */ 8760 if (val != 0) 8761 return -1; 8762 8763 switch (opcode) { 8764 case BPF_JEQ: 8765 return 0; 8766 case BPF_JNE: 8767 return 1; 8768 default: 8769 return -1; 8770 } 8771 } 8772 8773 if (is_jmp32) 8774 return is_branch32_taken(reg, val, opcode); 8775 return is_branch64_taken(reg, val, opcode); 8776 } 8777 8778 static int flip_opcode(u32 opcode) 8779 { 8780 /* How can we transform "a <op> b" into "b <op> a"? */ 8781 static const u8 opcode_flip[16] = { 8782 /* these stay the same */ 8783 [BPF_JEQ >> 4] = BPF_JEQ, 8784 [BPF_JNE >> 4] = BPF_JNE, 8785 [BPF_JSET >> 4] = BPF_JSET, 8786 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 8787 [BPF_JGE >> 4] = BPF_JLE, 8788 [BPF_JGT >> 4] = BPF_JLT, 8789 [BPF_JLE >> 4] = BPF_JGE, 8790 [BPF_JLT >> 4] = BPF_JGT, 8791 [BPF_JSGE >> 4] = BPF_JSLE, 8792 [BPF_JSGT >> 4] = BPF_JSLT, 8793 [BPF_JSLE >> 4] = BPF_JSGE, 8794 [BPF_JSLT >> 4] = BPF_JSGT 8795 }; 8796 return opcode_flip[opcode >> 4]; 8797 } 8798 8799 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 8800 struct bpf_reg_state *src_reg, 8801 u8 opcode) 8802 { 8803 struct bpf_reg_state *pkt; 8804 8805 if (src_reg->type == PTR_TO_PACKET_END) { 8806 pkt = dst_reg; 8807 } else if (dst_reg->type == PTR_TO_PACKET_END) { 8808 pkt = src_reg; 8809 opcode = flip_opcode(opcode); 8810 } else { 8811 return -1; 8812 } 8813 8814 if (pkt->range >= 0) 8815 return -1; 8816 8817 switch (opcode) { 8818 case BPF_JLE: 8819 /* pkt <= pkt_end */ 8820 fallthrough; 8821 case BPF_JGT: 8822 /* pkt > pkt_end */ 8823 if (pkt->range == BEYOND_PKT_END) 8824 /* pkt has at last one extra byte beyond pkt_end */ 8825 return opcode == BPF_JGT; 8826 break; 8827 case BPF_JLT: 8828 /* pkt < pkt_end */ 8829 fallthrough; 8830 case BPF_JGE: 8831 /* pkt >= pkt_end */ 8832 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 8833 return opcode == BPF_JGE; 8834 break; 8835 } 8836 return -1; 8837 } 8838 8839 /* Adjusts the register min/max values in the case that the dst_reg is the 8840 * variable register that we are working on, and src_reg is a constant or we're 8841 * simply doing a BPF_K check. 8842 * In JEQ/JNE cases we also adjust the var_off values. 8843 */ 8844 static void reg_set_min_max(struct bpf_reg_state *true_reg, 8845 struct bpf_reg_state *false_reg, 8846 u64 val, u32 val32, 8847 u8 opcode, bool is_jmp32) 8848 { 8849 struct tnum false_32off = tnum_subreg(false_reg->var_off); 8850 struct tnum false_64off = false_reg->var_off; 8851 struct tnum true_32off = tnum_subreg(true_reg->var_off); 8852 struct tnum true_64off = true_reg->var_off; 8853 s64 sval = (s64)val; 8854 s32 sval32 = (s32)val32; 8855 8856 /* If the dst_reg is a pointer, we can't learn anything about its 8857 * variable offset from the compare (unless src_reg were a pointer into 8858 * the same object, but we don't bother with that. 8859 * Since false_reg and true_reg have the same type by construction, we 8860 * only need to check one of them for pointerness. 8861 */ 8862 if (__is_pointer_value(false, false_reg)) 8863 return; 8864 8865 switch (opcode) { 8866 case BPF_JEQ: 8867 case BPF_JNE: 8868 { 8869 struct bpf_reg_state *reg = 8870 opcode == BPF_JEQ ? true_reg : false_reg; 8871 8872 /* JEQ/JNE comparison doesn't change the register equivalence. 8873 * r1 = r2; 8874 * if (r1 == 42) goto label; 8875 * ... 8876 * label: // here both r1 and r2 are known to be 42. 8877 * 8878 * Hence when marking register as known preserve it's ID. 8879 */ 8880 if (is_jmp32) 8881 __mark_reg32_known(reg, val32); 8882 else 8883 ___mark_reg_known(reg, val); 8884 break; 8885 } 8886 case BPF_JSET: 8887 if (is_jmp32) { 8888 false_32off = tnum_and(false_32off, tnum_const(~val32)); 8889 if (is_power_of_2(val32)) 8890 true_32off = tnum_or(true_32off, 8891 tnum_const(val32)); 8892 } else { 8893 false_64off = tnum_and(false_64off, tnum_const(~val)); 8894 if (is_power_of_2(val)) 8895 true_64off = tnum_or(true_64off, 8896 tnum_const(val)); 8897 } 8898 break; 8899 case BPF_JGE: 8900 case BPF_JGT: 8901 { 8902 if (is_jmp32) { 8903 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 8904 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 8905 8906 false_reg->u32_max_value = min(false_reg->u32_max_value, 8907 false_umax); 8908 true_reg->u32_min_value = max(true_reg->u32_min_value, 8909 true_umin); 8910 } else { 8911 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 8912 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 8913 8914 false_reg->umax_value = min(false_reg->umax_value, false_umax); 8915 true_reg->umin_value = max(true_reg->umin_value, true_umin); 8916 } 8917 break; 8918 } 8919 case BPF_JSGE: 8920 case BPF_JSGT: 8921 { 8922 if (is_jmp32) { 8923 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 8924 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 8925 8926 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 8927 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 8928 } else { 8929 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 8930 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 8931 8932 false_reg->smax_value = min(false_reg->smax_value, false_smax); 8933 true_reg->smin_value = max(true_reg->smin_value, true_smin); 8934 } 8935 break; 8936 } 8937 case BPF_JLE: 8938 case BPF_JLT: 8939 { 8940 if (is_jmp32) { 8941 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 8942 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 8943 8944 false_reg->u32_min_value = max(false_reg->u32_min_value, 8945 false_umin); 8946 true_reg->u32_max_value = min(true_reg->u32_max_value, 8947 true_umax); 8948 } else { 8949 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 8950 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 8951 8952 false_reg->umin_value = max(false_reg->umin_value, false_umin); 8953 true_reg->umax_value = min(true_reg->umax_value, true_umax); 8954 } 8955 break; 8956 } 8957 case BPF_JSLE: 8958 case BPF_JSLT: 8959 { 8960 if (is_jmp32) { 8961 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 8962 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 8963 8964 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 8965 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 8966 } else { 8967 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 8968 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 8969 8970 false_reg->smin_value = max(false_reg->smin_value, false_smin); 8971 true_reg->smax_value = min(true_reg->smax_value, true_smax); 8972 } 8973 break; 8974 } 8975 default: 8976 return; 8977 } 8978 8979 if (is_jmp32) { 8980 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 8981 tnum_subreg(false_32off)); 8982 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 8983 tnum_subreg(true_32off)); 8984 __reg_combine_32_into_64(false_reg); 8985 __reg_combine_32_into_64(true_reg); 8986 } else { 8987 false_reg->var_off = false_64off; 8988 true_reg->var_off = true_64off; 8989 __reg_combine_64_into_32(false_reg); 8990 __reg_combine_64_into_32(true_reg); 8991 } 8992 } 8993 8994 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 8995 * the variable reg. 8996 */ 8997 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 8998 struct bpf_reg_state *false_reg, 8999 u64 val, u32 val32, 9000 u8 opcode, bool is_jmp32) 9001 { 9002 opcode = flip_opcode(opcode); 9003 /* This uses zero as "not present in table"; luckily the zero opcode, 9004 * BPF_JA, can't get here. 9005 */ 9006 if (opcode) 9007 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 9008 } 9009 9010 /* Regs are known to be equal, so intersect their min/max/var_off */ 9011 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 9012 struct bpf_reg_state *dst_reg) 9013 { 9014 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 9015 dst_reg->umin_value); 9016 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 9017 dst_reg->umax_value); 9018 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 9019 dst_reg->smin_value); 9020 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 9021 dst_reg->smax_value); 9022 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 9023 dst_reg->var_off); 9024 /* We might have learned new bounds from the var_off. */ 9025 __update_reg_bounds(src_reg); 9026 __update_reg_bounds(dst_reg); 9027 /* We might have learned something about the sign bit. */ 9028 __reg_deduce_bounds(src_reg); 9029 __reg_deduce_bounds(dst_reg); 9030 /* We might have learned some bits from the bounds. */ 9031 __reg_bound_offset(src_reg); 9032 __reg_bound_offset(dst_reg); 9033 /* Intersecting with the old var_off might have improved our bounds 9034 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 9035 * then new var_off is (0; 0x7f...fc) which improves our umax. 9036 */ 9037 __update_reg_bounds(src_reg); 9038 __update_reg_bounds(dst_reg); 9039 } 9040 9041 static void reg_combine_min_max(struct bpf_reg_state *true_src, 9042 struct bpf_reg_state *true_dst, 9043 struct bpf_reg_state *false_src, 9044 struct bpf_reg_state *false_dst, 9045 u8 opcode) 9046 { 9047 switch (opcode) { 9048 case BPF_JEQ: 9049 __reg_combine_min_max(true_src, true_dst); 9050 break; 9051 case BPF_JNE: 9052 __reg_combine_min_max(false_src, false_dst); 9053 break; 9054 } 9055 } 9056 9057 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 9058 struct bpf_reg_state *reg, u32 id, 9059 bool is_null) 9060 { 9061 if (type_may_be_null(reg->type) && reg->id == id && 9062 !WARN_ON_ONCE(!reg->id)) { 9063 /* Old offset (both fixed and variable parts) should 9064 * have been known-zero, because we don't allow pointer 9065 * arithmetic on pointers that might be NULL. 9066 */ 9067 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || 9068 !tnum_equals_const(reg->var_off, 0) || 9069 reg->off)) { 9070 __mark_reg_known_zero(reg); 9071 reg->off = 0; 9072 } 9073 if (is_null) { 9074 reg->type = SCALAR_VALUE; 9075 /* We don't need id and ref_obj_id from this point 9076 * onwards anymore, thus we should better reset it, 9077 * so that state pruning has chances to take effect. 9078 */ 9079 reg->id = 0; 9080 reg->ref_obj_id = 0; 9081 9082 return; 9083 } 9084 9085 mark_ptr_not_null_reg(reg); 9086 9087 if (!reg_may_point_to_spin_lock(reg)) { 9088 /* For not-NULL ptr, reg->ref_obj_id will be reset 9089 * in release_reg_references(). 9090 * 9091 * reg->id is still used by spin_lock ptr. Other 9092 * than spin_lock ptr type, reg->id can be reset. 9093 */ 9094 reg->id = 0; 9095 } 9096 } 9097 } 9098 9099 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id, 9100 bool is_null) 9101 { 9102 struct bpf_reg_state *reg; 9103 int i; 9104 9105 for (i = 0; i < MAX_BPF_REG; i++) 9106 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null); 9107 9108 bpf_for_each_spilled_reg(i, state, reg) { 9109 if (!reg) 9110 continue; 9111 mark_ptr_or_null_reg(state, reg, id, is_null); 9112 } 9113 } 9114 9115 /* The logic is similar to find_good_pkt_pointers(), both could eventually 9116 * be folded together at some point. 9117 */ 9118 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 9119 bool is_null) 9120 { 9121 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9122 struct bpf_reg_state *regs = state->regs; 9123 u32 ref_obj_id = regs[regno].ref_obj_id; 9124 u32 id = regs[regno].id; 9125 int i; 9126 9127 if (ref_obj_id && ref_obj_id == id && is_null) 9128 /* regs[regno] is in the " == NULL" branch. 9129 * No one could have freed the reference state before 9130 * doing the NULL check. 9131 */ 9132 WARN_ON_ONCE(release_reference_state(state, id)); 9133 9134 for (i = 0; i <= vstate->curframe; i++) 9135 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null); 9136 } 9137 9138 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 9139 struct bpf_reg_state *dst_reg, 9140 struct bpf_reg_state *src_reg, 9141 struct bpf_verifier_state *this_branch, 9142 struct bpf_verifier_state *other_branch) 9143 { 9144 if (BPF_SRC(insn->code) != BPF_X) 9145 return false; 9146 9147 /* Pointers are always 64-bit. */ 9148 if (BPF_CLASS(insn->code) == BPF_JMP32) 9149 return false; 9150 9151 switch (BPF_OP(insn->code)) { 9152 case BPF_JGT: 9153 if ((dst_reg->type == PTR_TO_PACKET && 9154 src_reg->type == PTR_TO_PACKET_END) || 9155 (dst_reg->type == PTR_TO_PACKET_META && 9156 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 9157 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 9158 find_good_pkt_pointers(this_branch, dst_reg, 9159 dst_reg->type, false); 9160 mark_pkt_end(other_branch, insn->dst_reg, true); 9161 } else if ((dst_reg->type == PTR_TO_PACKET_END && 9162 src_reg->type == PTR_TO_PACKET) || 9163 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 9164 src_reg->type == PTR_TO_PACKET_META)) { 9165 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 9166 find_good_pkt_pointers(other_branch, src_reg, 9167 src_reg->type, true); 9168 mark_pkt_end(this_branch, insn->src_reg, false); 9169 } else { 9170 return false; 9171 } 9172 break; 9173 case BPF_JLT: 9174 if ((dst_reg->type == PTR_TO_PACKET && 9175 src_reg->type == PTR_TO_PACKET_END) || 9176 (dst_reg->type == PTR_TO_PACKET_META && 9177 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 9178 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 9179 find_good_pkt_pointers(other_branch, dst_reg, 9180 dst_reg->type, true); 9181 mark_pkt_end(this_branch, insn->dst_reg, false); 9182 } else if ((dst_reg->type == PTR_TO_PACKET_END && 9183 src_reg->type == PTR_TO_PACKET) || 9184 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 9185 src_reg->type == PTR_TO_PACKET_META)) { 9186 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 9187 find_good_pkt_pointers(this_branch, src_reg, 9188 src_reg->type, false); 9189 mark_pkt_end(other_branch, insn->src_reg, true); 9190 } else { 9191 return false; 9192 } 9193 break; 9194 case BPF_JGE: 9195 if ((dst_reg->type == PTR_TO_PACKET && 9196 src_reg->type == PTR_TO_PACKET_END) || 9197 (dst_reg->type == PTR_TO_PACKET_META && 9198 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 9199 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 9200 find_good_pkt_pointers(this_branch, dst_reg, 9201 dst_reg->type, true); 9202 mark_pkt_end(other_branch, insn->dst_reg, false); 9203 } else if ((dst_reg->type == PTR_TO_PACKET_END && 9204 src_reg->type == PTR_TO_PACKET) || 9205 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 9206 src_reg->type == PTR_TO_PACKET_META)) { 9207 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 9208 find_good_pkt_pointers(other_branch, src_reg, 9209 src_reg->type, false); 9210 mark_pkt_end(this_branch, insn->src_reg, true); 9211 } else { 9212 return false; 9213 } 9214 break; 9215 case BPF_JLE: 9216 if ((dst_reg->type == PTR_TO_PACKET && 9217 src_reg->type == PTR_TO_PACKET_END) || 9218 (dst_reg->type == PTR_TO_PACKET_META && 9219 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 9220 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 9221 find_good_pkt_pointers(other_branch, dst_reg, 9222 dst_reg->type, false); 9223 mark_pkt_end(this_branch, insn->dst_reg, true); 9224 } else if ((dst_reg->type == PTR_TO_PACKET_END && 9225 src_reg->type == PTR_TO_PACKET) || 9226 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 9227 src_reg->type == PTR_TO_PACKET_META)) { 9228 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 9229 find_good_pkt_pointers(this_branch, src_reg, 9230 src_reg->type, true); 9231 mark_pkt_end(other_branch, insn->src_reg, false); 9232 } else { 9233 return false; 9234 } 9235 break; 9236 default: 9237 return false; 9238 } 9239 9240 return true; 9241 } 9242 9243 static void find_equal_scalars(struct bpf_verifier_state *vstate, 9244 struct bpf_reg_state *known_reg) 9245 { 9246 struct bpf_func_state *state; 9247 struct bpf_reg_state *reg; 9248 int i, j; 9249 9250 for (i = 0; i <= vstate->curframe; i++) { 9251 state = vstate->frame[i]; 9252 for (j = 0; j < MAX_BPF_REG; j++) { 9253 reg = &state->regs[j]; 9254 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 9255 *reg = *known_reg; 9256 } 9257 9258 bpf_for_each_spilled_reg(j, state, reg) { 9259 if (!reg) 9260 continue; 9261 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 9262 *reg = *known_reg; 9263 } 9264 } 9265 } 9266 9267 static int check_cond_jmp_op(struct bpf_verifier_env *env, 9268 struct bpf_insn *insn, int *insn_idx) 9269 { 9270 struct bpf_verifier_state *this_branch = env->cur_state; 9271 struct bpf_verifier_state *other_branch; 9272 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 9273 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 9274 u8 opcode = BPF_OP(insn->code); 9275 bool is_jmp32; 9276 int pred = -1; 9277 int err; 9278 9279 /* Only conditional jumps are expected to reach here. */ 9280 if (opcode == BPF_JA || opcode > BPF_JSLE) { 9281 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 9282 return -EINVAL; 9283 } 9284 9285 if (BPF_SRC(insn->code) == BPF_X) { 9286 if (insn->imm != 0) { 9287 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 9288 return -EINVAL; 9289 } 9290 9291 /* check src1 operand */ 9292 err = check_reg_arg(env, insn->src_reg, SRC_OP); 9293 if (err) 9294 return err; 9295 9296 if (is_pointer_value(env, insn->src_reg)) { 9297 verbose(env, "R%d pointer comparison prohibited\n", 9298 insn->src_reg); 9299 return -EACCES; 9300 } 9301 src_reg = ®s[insn->src_reg]; 9302 } else { 9303 if (insn->src_reg != BPF_REG_0) { 9304 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 9305 return -EINVAL; 9306 } 9307 } 9308 9309 /* check src2 operand */ 9310 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 9311 if (err) 9312 return err; 9313 9314 dst_reg = ®s[insn->dst_reg]; 9315 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 9316 9317 if (BPF_SRC(insn->code) == BPF_K) { 9318 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 9319 } else if (src_reg->type == SCALAR_VALUE && 9320 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 9321 pred = is_branch_taken(dst_reg, 9322 tnum_subreg(src_reg->var_off).value, 9323 opcode, 9324 is_jmp32); 9325 } else if (src_reg->type == SCALAR_VALUE && 9326 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 9327 pred = is_branch_taken(dst_reg, 9328 src_reg->var_off.value, 9329 opcode, 9330 is_jmp32); 9331 } else if (reg_is_pkt_pointer_any(dst_reg) && 9332 reg_is_pkt_pointer_any(src_reg) && 9333 !is_jmp32) { 9334 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 9335 } 9336 9337 if (pred >= 0) { 9338 /* If we get here with a dst_reg pointer type it is because 9339 * above is_branch_taken() special cased the 0 comparison. 9340 */ 9341 if (!__is_pointer_value(false, dst_reg)) 9342 err = mark_chain_precision(env, insn->dst_reg); 9343 if (BPF_SRC(insn->code) == BPF_X && !err && 9344 !__is_pointer_value(false, src_reg)) 9345 err = mark_chain_precision(env, insn->src_reg); 9346 if (err) 9347 return err; 9348 } 9349 9350 if (pred == 1) { 9351 /* Only follow the goto, ignore fall-through. If needed, push 9352 * the fall-through branch for simulation under speculative 9353 * execution. 9354 */ 9355 if (!env->bypass_spec_v1 && 9356 !sanitize_speculative_path(env, insn, *insn_idx + 1, 9357 *insn_idx)) 9358 return -EFAULT; 9359 *insn_idx += insn->off; 9360 return 0; 9361 } else if (pred == 0) { 9362 /* Only follow the fall-through branch, since that's where the 9363 * program will go. If needed, push the goto branch for 9364 * simulation under speculative execution. 9365 */ 9366 if (!env->bypass_spec_v1 && 9367 !sanitize_speculative_path(env, insn, 9368 *insn_idx + insn->off + 1, 9369 *insn_idx)) 9370 return -EFAULT; 9371 return 0; 9372 } 9373 9374 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 9375 false); 9376 if (!other_branch) 9377 return -EFAULT; 9378 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 9379 9380 /* detect if we are comparing against a constant value so we can adjust 9381 * our min/max values for our dst register. 9382 * this is only legit if both are scalars (or pointers to the same 9383 * object, I suppose, but we don't support that right now), because 9384 * otherwise the different base pointers mean the offsets aren't 9385 * comparable. 9386 */ 9387 if (BPF_SRC(insn->code) == BPF_X) { 9388 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 9389 9390 if (dst_reg->type == SCALAR_VALUE && 9391 src_reg->type == SCALAR_VALUE) { 9392 if (tnum_is_const(src_reg->var_off) || 9393 (is_jmp32 && 9394 tnum_is_const(tnum_subreg(src_reg->var_off)))) 9395 reg_set_min_max(&other_branch_regs[insn->dst_reg], 9396 dst_reg, 9397 src_reg->var_off.value, 9398 tnum_subreg(src_reg->var_off).value, 9399 opcode, is_jmp32); 9400 else if (tnum_is_const(dst_reg->var_off) || 9401 (is_jmp32 && 9402 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 9403 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 9404 src_reg, 9405 dst_reg->var_off.value, 9406 tnum_subreg(dst_reg->var_off).value, 9407 opcode, is_jmp32); 9408 else if (!is_jmp32 && 9409 (opcode == BPF_JEQ || opcode == BPF_JNE)) 9410 /* Comparing for equality, we can combine knowledge */ 9411 reg_combine_min_max(&other_branch_regs[insn->src_reg], 9412 &other_branch_regs[insn->dst_reg], 9413 src_reg, dst_reg, opcode); 9414 if (src_reg->id && 9415 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 9416 find_equal_scalars(this_branch, src_reg); 9417 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 9418 } 9419 9420 } 9421 } else if (dst_reg->type == SCALAR_VALUE) { 9422 reg_set_min_max(&other_branch_regs[insn->dst_reg], 9423 dst_reg, insn->imm, (u32)insn->imm, 9424 opcode, is_jmp32); 9425 } 9426 9427 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 9428 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 9429 find_equal_scalars(this_branch, dst_reg); 9430 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 9431 } 9432 9433 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 9434 * NOTE: these optimizations below are related with pointer comparison 9435 * which will never be JMP32. 9436 */ 9437 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 9438 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 9439 type_may_be_null(dst_reg->type)) { 9440 /* Mark all identical registers in each branch as either 9441 * safe or unknown depending R == 0 or R != 0 conditional. 9442 */ 9443 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 9444 opcode == BPF_JNE); 9445 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 9446 opcode == BPF_JEQ); 9447 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 9448 this_branch, other_branch) && 9449 is_pointer_value(env, insn->dst_reg)) { 9450 verbose(env, "R%d pointer comparison prohibited\n", 9451 insn->dst_reg); 9452 return -EACCES; 9453 } 9454 if (env->log.level & BPF_LOG_LEVEL) 9455 print_insn_state(env, this_branch->frame[this_branch->curframe]); 9456 return 0; 9457 } 9458 9459 /* verify BPF_LD_IMM64 instruction */ 9460 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 9461 { 9462 struct bpf_insn_aux_data *aux = cur_aux(env); 9463 struct bpf_reg_state *regs = cur_regs(env); 9464 struct bpf_reg_state *dst_reg; 9465 struct bpf_map *map; 9466 int err; 9467 9468 if (BPF_SIZE(insn->code) != BPF_DW) { 9469 verbose(env, "invalid BPF_LD_IMM insn\n"); 9470 return -EINVAL; 9471 } 9472 if (insn->off != 0) { 9473 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 9474 return -EINVAL; 9475 } 9476 9477 err = check_reg_arg(env, insn->dst_reg, DST_OP); 9478 if (err) 9479 return err; 9480 9481 dst_reg = ®s[insn->dst_reg]; 9482 if (insn->src_reg == 0) { 9483 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 9484 9485 dst_reg->type = SCALAR_VALUE; 9486 __mark_reg_known(®s[insn->dst_reg], imm); 9487 return 0; 9488 } 9489 9490 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 9491 mark_reg_known_zero(env, regs, insn->dst_reg); 9492 9493 dst_reg->type = aux->btf_var.reg_type; 9494 switch (base_type(dst_reg->type)) { 9495 case PTR_TO_MEM: 9496 dst_reg->mem_size = aux->btf_var.mem_size; 9497 break; 9498 case PTR_TO_BTF_ID: 9499 case PTR_TO_PERCPU_BTF_ID: 9500 dst_reg->btf = aux->btf_var.btf; 9501 dst_reg->btf_id = aux->btf_var.btf_id; 9502 break; 9503 default: 9504 verbose(env, "bpf verifier is misconfigured\n"); 9505 return -EFAULT; 9506 } 9507 return 0; 9508 } 9509 9510 if (insn->src_reg == BPF_PSEUDO_FUNC) { 9511 struct bpf_prog_aux *aux = env->prog->aux; 9512 u32 subprogno = find_subprog(env, 9513 env->insn_idx + insn->imm + 1); 9514 9515 if (!aux->func_info) { 9516 verbose(env, "missing btf func_info\n"); 9517 return -EINVAL; 9518 } 9519 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 9520 verbose(env, "callback function not static\n"); 9521 return -EINVAL; 9522 } 9523 9524 dst_reg->type = PTR_TO_FUNC; 9525 dst_reg->subprogno = subprogno; 9526 return 0; 9527 } 9528 9529 map = env->used_maps[aux->map_index]; 9530 mark_reg_known_zero(env, regs, insn->dst_reg); 9531 dst_reg->map_ptr = map; 9532 9533 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 9534 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 9535 dst_reg->type = PTR_TO_MAP_VALUE; 9536 dst_reg->off = aux->map_off; 9537 if (map_value_has_spin_lock(map)) 9538 dst_reg->id = ++env->id_gen; 9539 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 9540 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 9541 dst_reg->type = CONST_PTR_TO_MAP; 9542 } else { 9543 verbose(env, "bpf verifier is misconfigured\n"); 9544 return -EINVAL; 9545 } 9546 9547 return 0; 9548 } 9549 9550 static bool may_access_skb(enum bpf_prog_type type) 9551 { 9552 switch (type) { 9553 case BPF_PROG_TYPE_SOCKET_FILTER: 9554 case BPF_PROG_TYPE_SCHED_CLS: 9555 case BPF_PROG_TYPE_SCHED_ACT: 9556 return true; 9557 default: 9558 return false; 9559 } 9560 } 9561 9562 /* verify safety of LD_ABS|LD_IND instructions: 9563 * - they can only appear in the programs where ctx == skb 9564 * - since they are wrappers of function calls, they scratch R1-R5 registers, 9565 * preserve R6-R9, and store return value into R0 9566 * 9567 * Implicit input: 9568 * ctx == skb == R6 == CTX 9569 * 9570 * Explicit input: 9571 * SRC == any register 9572 * IMM == 32-bit immediate 9573 * 9574 * Output: 9575 * R0 - 8/16/32-bit skb data converted to cpu endianness 9576 */ 9577 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 9578 { 9579 struct bpf_reg_state *regs = cur_regs(env); 9580 static const int ctx_reg = BPF_REG_6; 9581 u8 mode = BPF_MODE(insn->code); 9582 int i, err; 9583 9584 if (!may_access_skb(resolve_prog_type(env->prog))) { 9585 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 9586 return -EINVAL; 9587 } 9588 9589 if (!env->ops->gen_ld_abs) { 9590 verbose(env, "bpf verifier is misconfigured\n"); 9591 return -EINVAL; 9592 } 9593 9594 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 9595 BPF_SIZE(insn->code) == BPF_DW || 9596 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 9597 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 9598 return -EINVAL; 9599 } 9600 9601 /* check whether implicit source operand (register R6) is readable */ 9602 err = check_reg_arg(env, ctx_reg, SRC_OP); 9603 if (err) 9604 return err; 9605 9606 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 9607 * gen_ld_abs() may terminate the program at runtime, leading to 9608 * reference leak. 9609 */ 9610 err = check_reference_leak(env); 9611 if (err) { 9612 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 9613 return err; 9614 } 9615 9616 if (env->cur_state->active_spin_lock) { 9617 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 9618 return -EINVAL; 9619 } 9620 9621 if (regs[ctx_reg].type != PTR_TO_CTX) { 9622 verbose(env, 9623 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 9624 return -EINVAL; 9625 } 9626 9627 if (mode == BPF_IND) { 9628 /* check explicit source operand */ 9629 err = check_reg_arg(env, insn->src_reg, SRC_OP); 9630 if (err) 9631 return err; 9632 } 9633 9634 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg); 9635 if (err < 0) 9636 return err; 9637 9638 /* reset caller saved regs to unreadable */ 9639 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9640 mark_reg_not_init(env, regs, caller_saved[i]); 9641 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9642 } 9643 9644 /* mark destination R0 register as readable, since it contains 9645 * the value fetched from the packet. 9646 * Already marked as written above. 9647 */ 9648 mark_reg_unknown(env, regs, BPF_REG_0); 9649 /* ld_abs load up to 32-bit skb data. */ 9650 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 9651 return 0; 9652 } 9653 9654 static int check_return_code(struct bpf_verifier_env *env) 9655 { 9656 struct tnum enforce_attach_type_range = tnum_unknown; 9657 const struct bpf_prog *prog = env->prog; 9658 struct bpf_reg_state *reg; 9659 struct tnum range = tnum_range(0, 1); 9660 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9661 int err; 9662 struct bpf_func_state *frame = env->cur_state->frame[0]; 9663 const bool is_subprog = frame->subprogno; 9664 9665 /* LSM and struct_ops func-ptr's return type could be "void" */ 9666 if (!is_subprog && 9667 (prog_type == BPF_PROG_TYPE_STRUCT_OPS || 9668 prog_type == BPF_PROG_TYPE_LSM) && 9669 !prog->aux->attach_func_proto->type) 9670 return 0; 9671 9672 /* eBPF calling convention is such that R0 is used 9673 * to return the value from eBPF program. 9674 * Make sure that it's readable at this time 9675 * of bpf_exit, which means that program wrote 9676 * something into it earlier 9677 */ 9678 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 9679 if (err) 9680 return err; 9681 9682 if (is_pointer_value(env, BPF_REG_0)) { 9683 verbose(env, "R0 leaks addr as return value\n"); 9684 return -EACCES; 9685 } 9686 9687 reg = cur_regs(env) + BPF_REG_0; 9688 9689 if (frame->in_async_callback_fn) { 9690 /* enforce return zero from async callbacks like timer */ 9691 if (reg->type != SCALAR_VALUE) { 9692 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 9693 reg_type_str(env, reg->type)); 9694 return -EINVAL; 9695 } 9696 9697 if (!tnum_in(tnum_const(0), reg->var_off)) { 9698 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 9699 return -EINVAL; 9700 } 9701 return 0; 9702 } 9703 9704 if (is_subprog) { 9705 if (reg->type != SCALAR_VALUE) { 9706 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 9707 reg_type_str(env, reg->type)); 9708 return -EINVAL; 9709 } 9710 return 0; 9711 } 9712 9713 switch (prog_type) { 9714 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 9715 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 9716 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 9717 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 9718 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 9719 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 9720 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 9721 range = tnum_range(1, 1); 9722 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 9723 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 9724 range = tnum_range(0, 3); 9725 break; 9726 case BPF_PROG_TYPE_CGROUP_SKB: 9727 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 9728 range = tnum_range(0, 3); 9729 enforce_attach_type_range = tnum_range(2, 3); 9730 } 9731 break; 9732 case BPF_PROG_TYPE_CGROUP_SOCK: 9733 case BPF_PROG_TYPE_SOCK_OPS: 9734 case BPF_PROG_TYPE_CGROUP_DEVICE: 9735 case BPF_PROG_TYPE_CGROUP_SYSCTL: 9736 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 9737 break; 9738 case BPF_PROG_TYPE_RAW_TRACEPOINT: 9739 if (!env->prog->aux->attach_btf_id) 9740 return 0; 9741 range = tnum_const(0); 9742 break; 9743 case BPF_PROG_TYPE_TRACING: 9744 switch (env->prog->expected_attach_type) { 9745 case BPF_TRACE_FENTRY: 9746 case BPF_TRACE_FEXIT: 9747 range = tnum_const(0); 9748 break; 9749 case BPF_TRACE_RAW_TP: 9750 case BPF_MODIFY_RETURN: 9751 return 0; 9752 case BPF_TRACE_ITER: 9753 break; 9754 default: 9755 return -ENOTSUPP; 9756 } 9757 break; 9758 case BPF_PROG_TYPE_SK_LOOKUP: 9759 range = tnum_range(SK_DROP, SK_PASS); 9760 break; 9761 case BPF_PROG_TYPE_EXT: 9762 /* freplace program can return anything as its return value 9763 * depends on the to-be-replaced kernel func or bpf program. 9764 */ 9765 default: 9766 return 0; 9767 } 9768 9769 if (reg->type != SCALAR_VALUE) { 9770 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 9771 reg_type_str(env, reg->type)); 9772 return -EINVAL; 9773 } 9774 9775 if (!tnum_in(range, reg->var_off)) { 9776 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 9777 return -EINVAL; 9778 } 9779 9780 if (!tnum_is_unknown(enforce_attach_type_range) && 9781 tnum_in(enforce_attach_type_range, reg->var_off)) 9782 env->prog->enforce_expected_attach_type = 1; 9783 return 0; 9784 } 9785 9786 /* non-recursive DFS pseudo code 9787 * 1 procedure DFS-iterative(G,v): 9788 * 2 label v as discovered 9789 * 3 let S be a stack 9790 * 4 S.push(v) 9791 * 5 while S is not empty 9792 * 6 t <- S.pop() 9793 * 7 if t is what we're looking for: 9794 * 8 return t 9795 * 9 for all edges e in G.adjacentEdges(t) do 9796 * 10 if edge e is already labelled 9797 * 11 continue with the next edge 9798 * 12 w <- G.adjacentVertex(t,e) 9799 * 13 if vertex w is not discovered and not explored 9800 * 14 label e as tree-edge 9801 * 15 label w as discovered 9802 * 16 S.push(w) 9803 * 17 continue at 5 9804 * 18 else if vertex w is discovered 9805 * 19 label e as back-edge 9806 * 20 else 9807 * 21 // vertex w is explored 9808 * 22 label e as forward- or cross-edge 9809 * 23 label t as explored 9810 * 24 S.pop() 9811 * 9812 * convention: 9813 * 0x10 - discovered 9814 * 0x11 - discovered and fall-through edge labelled 9815 * 0x12 - discovered and fall-through and branch edges labelled 9816 * 0x20 - explored 9817 */ 9818 9819 enum { 9820 DISCOVERED = 0x10, 9821 EXPLORED = 0x20, 9822 FALLTHROUGH = 1, 9823 BRANCH = 2, 9824 }; 9825 9826 static u32 state_htab_size(struct bpf_verifier_env *env) 9827 { 9828 return env->prog->len; 9829 } 9830 9831 static struct bpf_verifier_state_list **explored_state( 9832 struct bpf_verifier_env *env, 9833 int idx) 9834 { 9835 struct bpf_verifier_state *cur = env->cur_state; 9836 struct bpf_func_state *state = cur->frame[cur->curframe]; 9837 9838 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 9839 } 9840 9841 static void init_explored_state(struct bpf_verifier_env *env, int idx) 9842 { 9843 env->insn_aux_data[idx].prune_point = true; 9844 } 9845 9846 enum { 9847 DONE_EXPLORING = 0, 9848 KEEP_EXPLORING = 1, 9849 }; 9850 9851 /* t, w, e - match pseudo-code above: 9852 * t - index of current instruction 9853 * w - next instruction 9854 * e - edge 9855 */ 9856 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 9857 bool loop_ok) 9858 { 9859 int *insn_stack = env->cfg.insn_stack; 9860 int *insn_state = env->cfg.insn_state; 9861 9862 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 9863 return DONE_EXPLORING; 9864 9865 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 9866 return DONE_EXPLORING; 9867 9868 if (w < 0 || w >= env->prog->len) { 9869 verbose_linfo(env, t, "%d: ", t); 9870 verbose(env, "jump out of range from insn %d to %d\n", t, w); 9871 return -EINVAL; 9872 } 9873 9874 if (e == BRANCH) 9875 /* mark branch target for state pruning */ 9876 init_explored_state(env, w); 9877 9878 if (insn_state[w] == 0) { 9879 /* tree-edge */ 9880 insn_state[t] = DISCOVERED | e; 9881 insn_state[w] = DISCOVERED; 9882 if (env->cfg.cur_stack >= env->prog->len) 9883 return -E2BIG; 9884 insn_stack[env->cfg.cur_stack++] = w; 9885 return KEEP_EXPLORING; 9886 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 9887 if (loop_ok && env->bpf_capable) 9888 return DONE_EXPLORING; 9889 verbose_linfo(env, t, "%d: ", t); 9890 verbose_linfo(env, w, "%d: ", w); 9891 verbose(env, "back-edge from insn %d to %d\n", t, w); 9892 return -EINVAL; 9893 } else if (insn_state[w] == EXPLORED) { 9894 /* forward- or cross-edge */ 9895 insn_state[t] = DISCOVERED | e; 9896 } else { 9897 verbose(env, "insn state internal bug\n"); 9898 return -EFAULT; 9899 } 9900 return DONE_EXPLORING; 9901 } 9902 9903 static int visit_func_call_insn(int t, int insn_cnt, 9904 struct bpf_insn *insns, 9905 struct bpf_verifier_env *env, 9906 bool visit_callee) 9907 { 9908 int ret; 9909 9910 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 9911 if (ret) 9912 return ret; 9913 9914 if (t + 1 < insn_cnt) 9915 init_explored_state(env, t + 1); 9916 if (visit_callee) { 9917 init_explored_state(env, t); 9918 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 9919 /* It's ok to allow recursion from CFG point of 9920 * view. __check_func_call() will do the actual 9921 * check. 9922 */ 9923 bpf_pseudo_func(insns + t)); 9924 } 9925 return ret; 9926 } 9927 9928 /* Visits the instruction at index t and returns one of the following: 9929 * < 0 - an error occurred 9930 * DONE_EXPLORING - the instruction was fully explored 9931 * KEEP_EXPLORING - there is still work to be done before it is fully explored 9932 */ 9933 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env) 9934 { 9935 struct bpf_insn *insns = env->prog->insnsi; 9936 int ret; 9937 9938 if (bpf_pseudo_func(insns + t)) 9939 return visit_func_call_insn(t, insn_cnt, insns, env, true); 9940 9941 /* All non-branch instructions have a single fall-through edge. */ 9942 if (BPF_CLASS(insns[t].code) != BPF_JMP && 9943 BPF_CLASS(insns[t].code) != BPF_JMP32) 9944 return push_insn(t, t + 1, FALLTHROUGH, env, false); 9945 9946 switch (BPF_OP(insns[t].code)) { 9947 case BPF_EXIT: 9948 return DONE_EXPLORING; 9949 9950 case BPF_CALL: 9951 if (insns[t].imm == BPF_FUNC_timer_set_callback) 9952 /* Mark this call insn to trigger is_state_visited() check 9953 * before call itself is processed by __check_func_call(). 9954 * Otherwise new async state will be pushed for further 9955 * exploration. 9956 */ 9957 init_explored_state(env, t); 9958 return visit_func_call_insn(t, insn_cnt, insns, env, 9959 insns[t].src_reg == BPF_PSEUDO_CALL); 9960 9961 case BPF_JA: 9962 if (BPF_SRC(insns[t].code) != BPF_K) 9963 return -EINVAL; 9964 9965 /* unconditional jump with single edge */ 9966 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env, 9967 true); 9968 if (ret) 9969 return ret; 9970 9971 /* unconditional jmp is not a good pruning point, 9972 * but it's marked, since backtracking needs 9973 * to record jmp history in is_state_visited(). 9974 */ 9975 init_explored_state(env, t + insns[t].off + 1); 9976 /* tell verifier to check for equivalent states 9977 * after every call and jump 9978 */ 9979 if (t + 1 < insn_cnt) 9980 init_explored_state(env, t + 1); 9981 9982 return ret; 9983 9984 default: 9985 /* conditional jump with two edges */ 9986 init_explored_state(env, t); 9987 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 9988 if (ret) 9989 return ret; 9990 9991 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true); 9992 } 9993 } 9994 9995 /* non-recursive depth-first-search to detect loops in BPF program 9996 * loop == back-edge in directed graph 9997 */ 9998 static int check_cfg(struct bpf_verifier_env *env) 9999 { 10000 int insn_cnt = env->prog->len; 10001 int *insn_stack, *insn_state; 10002 int ret = 0; 10003 int i; 10004 10005 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 10006 if (!insn_state) 10007 return -ENOMEM; 10008 10009 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 10010 if (!insn_stack) { 10011 kvfree(insn_state); 10012 return -ENOMEM; 10013 } 10014 10015 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 10016 insn_stack[0] = 0; /* 0 is the first instruction */ 10017 env->cfg.cur_stack = 1; 10018 10019 while (env->cfg.cur_stack > 0) { 10020 int t = insn_stack[env->cfg.cur_stack - 1]; 10021 10022 ret = visit_insn(t, insn_cnt, env); 10023 switch (ret) { 10024 case DONE_EXPLORING: 10025 insn_state[t] = EXPLORED; 10026 env->cfg.cur_stack--; 10027 break; 10028 case KEEP_EXPLORING: 10029 break; 10030 default: 10031 if (ret > 0) { 10032 verbose(env, "visit_insn internal bug\n"); 10033 ret = -EFAULT; 10034 } 10035 goto err_free; 10036 } 10037 } 10038 10039 if (env->cfg.cur_stack < 0) { 10040 verbose(env, "pop stack internal bug\n"); 10041 ret = -EFAULT; 10042 goto err_free; 10043 } 10044 10045 for (i = 0; i < insn_cnt; i++) { 10046 if (insn_state[i] != EXPLORED) { 10047 verbose(env, "unreachable insn %d\n", i); 10048 ret = -EINVAL; 10049 goto err_free; 10050 } 10051 } 10052 ret = 0; /* cfg looks good */ 10053 10054 err_free: 10055 kvfree(insn_state); 10056 kvfree(insn_stack); 10057 env->cfg.insn_state = env->cfg.insn_stack = NULL; 10058 return ret; 10059 } 10060 10061 static int check_abnormal_return(struct bpf_verifier_env *env) 10062 { 10063 int i; 10064 10065 for (i = 1; i < env->subprog_cnt; i++) { 10066 if (env->subprog_info[i].has_ld_abs) { 10067 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 10068 return -EINVAL; 10069 } 10070 if (env->subprog_info[i].has_tail_call) { 10071 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 10072 return -EINVAL; 10073 } 10074 } 10075 return 0; 10076 } 10077 10078 /* The minimum supported BTF func info size */ 10079 #define MIN_BPF_FUNCINFO_SIZE 8 10080 #define MAX_FUNCINFO_REC_SIZE 252 10081 10082 static int check_btf_func(struct bpf_verifier_env *env, 10083 const union bpf_attr *attr, 10084 bpfptr_t uattr) 10085 { 10086 const struct btf_type *type, *func_proto, *ret_type; 10087 u32 i, nfuncs, urec_size, min_size; 10088 u32 krec_size = sizeof(struct bpf_func_info); 10089 struct bpf_func_info *krecord; 10090 struct bpf_func_info_aux *info_aux = NULL; 10091 struct bpf_prog *prog; 10092 const struct btf *btf; 10093 bpfptr_t urecord; 10094 u32 prev_offset = 0; 10095 bool scalar_return; 10096 int ret = -ENOMEM; 10097 10098 nfuncs = attr->func_info_cnt; 10099 if (!nfuncs) { 10100 if (check_abnormal_return(env)) 10101 return -EINVAL; 10102 return 0; 10103 } 10104 10105 if (nfuncs != env->subprog_cnt) { 10106 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 10107 return -EINVAL; 10108 } 10109 10110 urec_size = attr->func_info_rec_size; 10111 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 10112 urec_size > MAX_FUNCINFO_REC_SIZE || 10113 urec_size % sizeof(u32)) { 10114 verbose(env, "invalid func info rec size %u\n", urec_size); 10115 return -EINVAL; 10116 } 10117 10118 prog = env->prog; 10119 btf = prog->aux->btf; 10120 10121 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 10122 min_size = min_t(u32, krec_size, urec_size); 10123 10124 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 10125 if (!krecord) 10126 return -ENOMEM; 10127 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 10128 if (!info_aux) 10129 goto err_free; 10130 10131 for (i = 0; i < nfuncs; i++) { 10132 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 10133 if (ret) { 10134 if (ret == -E2BIG) { 10135 verbose(env, "nonzero tailing record in func info"); 10136 /* set the size kernel expects so loader can zero 10137 * out the rest of the record. 10138 */ 10139 if (copy_to_bpfptr_offset(uattr, 10140 offsetof(union bpf_attr, func_info_rec_size), 10141 &min_size, sizeof(min_size))) 10142 ret = -EFAULT; 10143 } 10144 goto err_free; 10145 } 10146 10147 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 10148 ret = -EFAULT; 10149 goto err_free; 10150 } 10151 10152 /* check insn_off */ 10153 ret = -EINVAL; 10154 if (i == 0) { 10155 if (krecord[i].insn_off) { 10156 verbose(env, 10157 "nonzero insn_off %u for the first func info record", 10158 krecord[i].insn_off); 10159 goto err_free; 10160 } 10161 } else if (krecord[i].insn_off <= prev_offset) { 10162 verbose(env, 10163 "same or smaller insn offset (%u) than previous func info record (%u)", 10164 krecord[i].insn_off, prev_offset); 10165 goto err_free; 10166 } 10167 10168 if (env->subprog_info[i].start != krecord[i].insn_off) { 10169 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 10170 goto err_free; 10171 } 10172 10173 /* check type_id */ 10174 type = btf_type_by_id(btf, krecord[i].type_id); 10175 if (!type || !btf_type_is_func(type)) { 10176 verbose(env, "invalid type id %d in func info", 10177 krecord[i].type_id); 10178 goto err_free; 10179 } 10180 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 10181 10182 func_proto = btf_type_by_id(btf, type->type); 10183 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 10184 /* btf_func_check() already verified it during BTF load */ 10185 goto err_free; 10186 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 10187 scalar_return = 10188 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type); 10189 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 10190 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 10191 goto err_free; 10192 } 10193 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 10194 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 10195 goto err_free; 10196 } 10197 10198 prev_offset = krecord[i].insn_off; 10199 bpfptr_add(&urecord, urec_size); 10200 } 10201 10202 prog->aux->func_info = krecord; 10203 prog->aux->func_info_cnt = nfuncs; 10204 prog->aux->func_info_aux = info_aux; 10205 return 0; 10206 10207 err_free: 10208 kvfree(krecord); 10209 kfree(info_aux); 10210 return ret; 10211 } 10212 10213 static void adjust_btf_func(struct bpf_verifier_env *env) 10214 { 10215 struct bpf_prog_aux *aux = env->prog->aux; 10216 int i; 10217 10218 if (!aux->func_info) 10219 return; 10220 10221 for (i = 0; i < env->subprog_cnt; i++) 10222 aux->func_info[i].insn_off = env->subprog_info[i].start; 10223 } 10224 10225 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \ 10226 sizeof(((struct bpf_line_info *)(0))->line_col)) 10227 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 10228 10229 static int check_btf_line(struct bpf_verifier_env *env, 10230 const union bpf_attr *attr, 10231 bpfptr_t uattr) 10232 { 10233 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 10234 struct bpf_subprog_info *sub; 10235 struct bpf_line_info *linfo; 10236 struct bpf_prog *prog; 10237 const struct btf *btf; 10238 bpfptr_t ulinfo; 10239 int err; 10240 10241 nr_linfo = attr->line_info_cnt; 10242 if (!nr_linfo) 10243 return 0; 10244 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 10245 return -EINVAL; 10246 10247 rec_size = attr->line_info_rec_size; 10248 if (rec_size < MIN_BPF_LINEINFO_SIZE || 10249 rec_size > MAX_LINEINFO_REC_SIZE || 10250 rec_size & (sizeof(u32) - 1)) 10251 return -EINVAL; 10252 10253 /* Need to zero it in case the userspace may 10254 * pass in a smaller bpf_line_info object. 10255 */ 10256 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 10257 GFP_KERNEL | __GFP_NOWARN); 10258 if (!linfo) 10259 return -ENOMEM; 10260 10261 prog = env->prog; 10262 btf = prog->aux->btf; 10263 10264 s = 0; 10265 sub = env->subprog_info; 10266 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 10267 expected_size = sizeof(struct bpf_line_info); 10268 ncopy = min_t(u32, expected_size, rec_size); 10269 for (i = 0; i < nr_linfo; i++) { 10270 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 10271 if (err) { 10272 if (err == -E2BIG) { 10273 verbose(env, "nonzero tailing record in line_info"); 10274 if (copy_to_bpfptr_offset(uattr, 10275 offsetof(union bpf_attr, line_info_rec_size), 10276 &expected_size, sizeof(expected_size))) 10277 err = -EFAULT; 10278 } 10279 goto err_free; 10280 } 10281 10282 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 10283 err = -EFAULT; 10284 goto err_free; 10285 } 10286 10287 /* 10288 * Check insn_off to ensure 10289 * 1) strictly increasing AND 10290 * 2) bounded by prog->len 10291 * 10292 * The linfo[0].insn_off == 0 check logically falls into 10293 * the later "missing bpf_line_info for func..." case 10294 * because the first linfo[0].insn_off must be the 10295 * first sub also and the first sub must have 10296 * subprog_info[0].start == 0. 10297 */ 10298 if ((i && linfo[i].insn_off <= prev_offset) || 10299 linfo[i].insn_off >= prog->len) { 10300 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 10301 i, linfo[i].insn_off, prev_offset, 10302 prog->len); 10303 err = -EINVAL; 10304 goto err_free; 10305 } 10306 10307 if (!prog->insnsi[linfo[i].insn_off].code) { 10308 verbose(env, 10309 "Invalid insn code at line_info[%u].insn_off\n", 10310 i); 10311 err = -EINVAL; 10312 goto err_free; 10313 } 10314 10315 if (!btf_name_by_offset(btf, linfo[i].line_off) || 10316 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 10317 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 10318 err = -EINVAL; 10319 goto err_free; 10320 } 10321 10322 if (s != env->subprog_cnt) { 10323 if (linfo[i].insn_off == sub[s].start) { 10324 sub[s].linfo_idx = i; 10325 s++; 10326 } else if (sub[s].start < linfo[i].insn_off) { 10327 verbose(env, "missing bpf_line_info for func#%u\n", s); 10328 err = -EINVAL; 10329 goto err_free; 10330 } 10331 } 10332 10333 prev_offset = linfo[i].insn_off; 10334 bpfptr_add(&ulinfo, rec_size); 10335 } 10336 10337 if (s != env->subprog_cnt) { 10338 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 10339 env->subprog_cnt - s, s); 10340 err = -EINVAL; 10341 goto err_free; 10342 } 10343 10344 prog->aux->linfo = linfo; 10345 prog->aux->nr_linfo = nr_linfo; 10346 10347 return 0; 10348 10349 err_free: 10350 kvfree(linfo); 10351 return err; 10352 } 10353 10354 #define MIN_CORE_RELO_SIZE sizeof(struct bpf_core_relo) 10355 #define MAX_CORE_RELO_SIZE MAX_FUNCINFO_REC_SIZE 10356 10357 static int check_core_relo(struct bpf_verifier_env *env, 10358 const union bpf_attr *attr, 10359 bpfptr_t uattr) 10360 { 10361 u32 i, nr_core_relo, ncopy, expected_size, rec_size; 10362 struct bpf_core_relo core_relo = {}; 10363 struct bpf_prog *prog = env->prog; 10364 const struct btf *btf = prog->aux->btf; 10365 struct bpf_core_ctx ctx = { 10366 .log = &env->log, 10367 .btf = btf, 10368 }; 10369 bpfptr_t u_core_relo; 10370 int err; 10371 10372 nr_core_relo = attr->core_relo_cnt; 10373 if (!nr_core_relo) 10374 return 0; 10375 if (nr_core_relo > INT_MAX / sizeof(struct bpf_core_relo)) 10376 return -EINVAL; 10377 10378 rec_size = attr->core_relo_rec_size; 10379 if (rec_size < MIN_CORE_RELO_SIZE || 10380 rec_size > MAX_CORE_RELO_SIZE || 10381 rec_size % sizeof(u32)) 10382 return -EINVAL; 10383 10384 u_core_relo = make_bpfptr(attr->core_relos, uattr.is_kernel); 10385 expected_size = sizeof(struct bpf_core_relo); 10386 ncopy = min_t(u32, expected_size, rec_size); 10387 10388 /* Unlike func_info and line_info, copy and apply each CO-RE 10389 * relocation record one at a time. 10390 */ 10391 for (i = 0; i < nr_core_relo; i++) { 10392 /* future proofing when sizeof(bpf_core_relo) changes */ 10393 err = bpf_check_uarg_tail_zero(u_core_relo, expected_size, rec_size); 10394 if (err) { 10395 if (err == -E2BIG) { 10396 verbose(env, "nonzero tailing record in core_relo"); 10397 if (copy_to_bpfptr_offset(uattr, 10398 offsetof(union bpf_attr, core_relo_rec_size), 10399 &expected_size, sizeof(expected_size))) 10400 err = -EFAULT; 10401 } 10402 break; 10403 } 10404 10405 if (copy_from_bpfptr(&core_relo, u_core_relo, ncopy)) { 10406 err = -EFAULT; 10407 break; 10408 } 10409 10410 if (core_relo.insn_off % 8 || core_relo.insn_off / 8 >= prog->len) { 10411 verbose(env, "Invalid core_relo[%u].insn_off:%u prog->len:%u\n", 10412 i, core_relo.insn_off, prog->len); 10413 err = -EINVAL; 10414 break; 10415 } 10416 10417 err = bpf_core_apply(&ctx, &core_relo, i, 10418 &prog->insnsi[core_relo.insn_off / 8]); 10419 if (err) 10420 break; 10421 bpfptr_add(&u_core_relo, rec_size); 10422 } 10423 return err; 10424 } 10425 10426 static int check_btf_info(struct bpf_verifier_env *env, 10427 const union bpf_attr *attr, 10428 bpfptr_t uattr) 10429 { 10430 struct btf *btf; 10431 int err; 10432 10433 if (!attr->func_info_cnt && !attr->line_info_cnt) { 10434 if (check_abnormal_return(env)) 10435 return -EINVAL; 10436 return 0; 10437 } 10438 10439 btf = btf_get_by_fd(attr->prog_btf_fd); 10440 if (IS_ERR(btf)) 10441 return PTR_ERR(btf); 10442 if (btf_is_kernel(btf)) { 10443 btf_put(btf); 10444 return -EACCES; 10445 } 10446 env->prog->aux->btf = btf; 10447 10448 err = check_btf_func(env, attr, uattr); 10449 if (err) 10450 return err; 10451 10452 err = check_btf_line(env, attr, uattr); 10453 if (err) 10454 return err; 10455 10456 err = check_core_relo(env, attr, uattr); 10457 if (err) 10458 return err; 10459 10460 return 0; 10461 } 10462 10463 /* check %cur's range satisfies %old's */ 10464 static bool range_within(struct bpf_reg_state *old, 10465 struct bpf_reg_state *cur) 10466 { 10467 return old->umin_value <= cur->umin_value && 10468 old->umax_value >= cur->umax_value && 10469 old->smin_value <= cur->smin_value && 10470 old->smax_value >= cur->smax_value && 10471 old->u32_min_value <= cur->u32_min_value && 10472 old->u32_max_value >= cur->u32_max_value && 10473 old->s32_min_value <= cur->s32_min_value && 10474 old->s32_max_value >= cur->s32_max_value; 10475 } 10476 10477 /* If in the old state two registers had the same id, then they need to have 10478 * the same id in the new state as well. But that id could be different from 10479 * the old state, so we need to track the mapping from old to new ids. 10480 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 10481 * regs with old id 5 must also have new id 9 for the new state to be safe. But 10482 * regs with a different old id could still have new id 9, we don't care about 10483 * that. 10484 * So we look through our idmap to see if this old id has been seen before. If 10485 * so, we require the new id to match; otherwise, we add the id pair to the map. 10486 */ 10487 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap) 10488 { 10489 unsigned int i; 10490 10491 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 10492 if (!idmap[i].old) { 10493 /* Reached an empty slot; haven't seen this id before */ 10494 idmap[i].old = old_id; 10495 idmap[i].cur = cur_id; 10496 return true; 10497 } 10498 if (idmap[i].old == old_id) 10499 return idmap[i].cur == cur_id; 10500 } 10501 /* We ran out of idmap slots, which should be impossible */ 10502 WARN_ON_ONCE(1); 10503 return false; 10504 } 10505 10506 static void clean_func_state(struct bpf_verifier_env *env, 10507 struct bpf_func_state *st) 10508 { 10509 enum bpf_reg_liveness live; 10510 int i, j; 10511 10512 for (i = 0; i < BPF_REG_FP; i++) { 10513 live = st->regs[i].live; 10514 /* liveness must not touch this register anymore */ 10515 st->regs[i].live |= REG_LIVE_DONE; 10516 if (!(live & REG_LIVE_READ)) 10517 /* since the register is unused, clear its state 10518 * to make further comparison simpler 10519 */ 10520 __mark_reg_not_init(env, &st->regs[i]); 10521 } 10522 10523 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 10524 live = st->stack[i].spilled_ptr.live; 10525 /* liveness must not touch this stack slot anymore */ 10526 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 10527 if (!(live & REG_LIVE_READ)) { 10528 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 10529 for (j = 0; j < BPF_REG_SIZE; j++) 10530 st->stack[i].slot_type[j] = STACK_INVALID; 10531 } 10532 } 10533 } 10534 10535 static void clean_verifier_state(struct bpf_verifier_env *env, 10536 struct bpf_verifier_state *st) 10537 { 10538 int i; 10539 10540 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 10541 /* all regs in this state in all frames were already marked */ 10542 return; 10543 10544 for (i = 0; i <= st->curframe; i++) 10545 clean_func_state(env, st->frame[i]); 10546 } 10547 10548 /* the parentage chains form a tree. 10549 * the verifier states are added to state lists at given insn and 10550 * pushed into state stack for future exploration. 10551 * when the verifier reaches bpf_exit insn some of the verifer states 10552 * stored in the state lists have their final liveness state already, 10553 * but a lot of states will get revised from liveness point of view when 10554 * the verifier explores other branches. 10555 * Example: 10556 * 1: r0 = 1 10557 * 2: if r1 == 100 goto pc+1 10558 * 3: r0 = 2 10559 * 4: exit 10560 * when the verifier reaches exit insn the register r0 in the state list of 10561 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 10562 * of insn 2 and goes exploring further. At the insn 4 it will walk the 10563 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 10564 * 10565 * Since the verifier pushes the branch states as it sees them while exploring 10566 * the program the condition of walking the branch instruction for the second 10567 * time means that all states below this branch were already explored and 10568 * their final liveness marks are already propagated. 10569 * Hence when the verifier completes the search of state list in is_state_visited() 10570 * we can call this clean_live_states() function to mark all liveness states 10571 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 10572 * will not be used. 10573 * This function also clears the registers and stack for states that !READ 10574 * to simplify state merging. 10575 * 10576 * Important note here that walking the same branch instruction in the callee 10577 * doesn't meant that the states are DONE. The verifier has to compare 10578 * the callsites 10579 */ 10580 static void clean_live_states(struct bpf_verifier_env *env, int insn, 10581 struct bpf_verifier_state *cur) 10582 { 10583 struct bpf_verifier_state_list *sl; 10584 int i; 10585 10586 sl = *explored_state(env, insn); 10587 while (sl) { 10588 if (sl->state.branches) 10589 goto next; 10590 if (sl->state.insn_idx != insn || 10591 sl->state.curframe != cur->curframe) 10592 goto next; 10593 for (i = 0; i <= cur->curframe; i++) 10594 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 10595 goto next; 10596 clean_verifier_state(env, &sl->state); 10597 next: 10598 sl = sl->next; 10599 } 10600 } 10601 10602 /* Returns true if (rold safe implies rcur safe) */ 10603 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 10604 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap) 10605 { 10606 bool equal; 10607 10608 if (!(rold->live & REG_LIVE_READ)) 10609 /* explored state didn't use this */ 10610 return true; 10611 10612 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0; 10613 10614 if (rold->type == PTR_TO_STACK) 10615 /* two stack pointers are equal only if they're pointing to 10616 * the same stack frame, since fp-8 in foo != fp-8 in bar 10617 */ 10618 return equal && rold->frameno == rcur->frameno; 10619 10620 if (equal) 10621 return true; 10622 10623 if (rold->type == NOT_INIT) 10624 /* explored state can't have used this */ 10625 return true; 10626 if (rcur->type == NOT_INIT) 10627 return false; 10628 switch (base_type(rold->type)) { 10629 case SCALAR_VALUE: 10630 if (env->explore_alu_limits) 10631 return false; 10632 if (rcur->type == SCALAR_VALUE) { 10633 if (!rold->precise && !rcur->precise) 10634 return true; 10635 /* new val must satisfy old val knowledge */ 10636 return range_within(rold, rcur) && 10637 tnum_in(rold->var_off, rcur->var_off); 10638 } else { 10639 /* We're trying to use a pointer in place of a scalar. 10640 * Even if the scalar was unbounded, this could lead to 10641 * pointer leaks because scalars are allowed to leak 10642 * while pointers are not. We could make this safe in 10643 * special cases if root is calling us, but it's 10644 * probably not worth the hassle. 10645 */ 10646 return false; 10647 } 10648 case PTR_TO_MAP_KEY: 10649 case PTR_TO_MAP_VALUE: 10650 /* a PTR_TO_MAP_VALUE could be safe to use as a 10651 * PTR_TO_MAP_VALUE_OR_NULL into the same map. 10652 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- 10653 * checked, doing so could have affected others with the same 10654 * id, and we can't check for that because we lost the id when 10655 * we converted to a PTR_TO_MAP_VALUE. 10656 */ 10657 if (type_may_be_null(rold->type)) { 10658 if (!type_may_be_null(rcur->type)) 10659 return false; 10660 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) 10661 return false; 10662 /* Check our ids match any regs they're supposed to */ 10663 return check_ids(rold->id, rcur->id, idmap); 10664 } 10665 10666 /* If the new min/max/var_off satisfy the old ones and 10667 * everything else matches, we are OK. 10668 * 'id' is not compared, since it's only used for maps with 10669 * bpf_spin_lock inside map element and in such cases if 10670 * the rest of the prog is valid for one map element then 10671 * it's valid for all map elements regardless of the key 10672 * used in bpf_map_lookup() 10673 */ 10674 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 10675 range_within(rold, rcur) && 10676 tnum_in(rold->var_off, rcur->var_off); 10677 case PTR_TO_PACKET_META: 10678 case PTR_TO_PACKET: 10679 if (rcur->type != rold->type) 10680 return false; 10681 /* We must have at least as much range as the old ptr 10682 * did, so that any accesses which were safe before are 10683 * still safe. This is true even if old range < old off, 10684 * since someone could have accessed through (ptr - k), or 10685 * even done ptr -= k in a register, to get a safe access. 10686 */ 10687 if (rold->range > rcur->range) 10688 return false; 10689 /* If the offsets don't match, we can't trust our alignment; 10690 * nor can we be sure that we won't fall out of range. 10691 */ 10692 if (rold->off != rcur->off) 10693 return false; 10694 /* id relations must be preserved */ 10695 if (rold->id && !check_ids(rold->id, rcur->id, idmap)) 10696 return false; 10697 /* new val must satisfy old val knowledge */ 10698 return range_within(rold, rcur) && 10699 tnum_in(rold->var_off, rcur->var_off); 10700 case PTR_TO_CTX: 10701 case CONST_PTR_TO_MAP: 10702 case PTR_TO_PACKET_END: 10703 case PTR_TO_FLOW_KEYS: 10704 case PTR_TO_SOCKET: 10705 case PTR_TO_SOCK_COMMON: 10706 case PTR_TO_TCP_SOCK: 10707 case PTR_TO_XDP_SOCK: 10708 /* Only valid matches are exact, which memcmp() above 10709 * would have accepted 10710 */ 10711 default: 10712 /* Don't know what's going on, just say it's not safe */ 10713 return false; 10714 } 10715 10716 /* Shouldn't get here; if we do, say it's not safe */ 10717 WARN_ON_ONCE(1); 10718 return false; 10719 } 10720 10721 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 10722 struct bpf_func_state *cur, struct bpf_id_pair *idmap) 10723 { 10724 int i, spi; 10725 10726 /* walk slots of the explored stack and ignore any additional 10727 * slots in the current stack, since explored(safe) state 10728 * didn't use them 10729 */ 10730 for (i = 0; i < old->allocated_stack; i++) { 10731 spi = i / BPF_REG_SIZE; 10732 10733 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 10734 i += BPF_REG_SIZE - 1; 10735 /* explored state didn't use this */ 10736 continue; 10737 } 10738 10739 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 10740 continue; 10741 10742 /* explored stack has more populated slots than current stack 10743 * and these slots were used 10744 */ 10745 if (i >= cur->allocated_stack) 10746 return false; 10747 10748 /* if old state was safe with misc data in the stack 10749 * it will be safe with zero-initialized stack. 10750 * The opposite is not true 10751 */ 10752 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 10753 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 10754 continue; 10755 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 10756 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 10757 /* Ex: old explored (safe) state has STACK_SPILL in 10758 * this stack slot, but current has STACK_MISC -> 10759 * this verifier states are not equivalent, 10760 * return false to continue verification of this path 10761 */ 10762 return false; 10763 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 10764 continue; 10765 if (!is_spilled_reg(&old->stack[spi])) 10766 continue; 10767 if (!regsafe(env, &old->stack[spi].spilled_ptr, 10768 &cur->stack[spi].spilled_ptr, idmap)) 10769 /* when explored and current stack slot are both storing 10770 * spilled registers, check that stored pointers types 10771 * are the same as well. 10772 * Ex: explored safe path could have stored 10773 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 10774 * but current path has stored: 10775 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 10776 * such verifier states are not equivalent. 10777 * return false to continue verification of this path 10778 */ 10779 return false; 10780 } 10781 return true; 10782 } 10783 10784 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur) 10785 { 10786 if (old->acquired_refs != cur->acquired_refs) 10787 return false; 10788 return !memcmp(old->refs, cur->refs, 10789 sizeof(*old->refs) * old->acquired_refs); 10790 } 10791 10792 /* compare two verifier states 10793 * 10794 * all states stored in state_list are known to be valid, since 10795 * verifier reached 'bpf_exit' instruction through them 10796 * 10797 * this function is called when verifier exploring different branches of 10798 * execution popped from the state stack. If it sees an old state that has 10799 * more strict register state and more strict stack state then this execution 10800 * branch doesn't need to be explored further, since verifier already 10801 * concluded that more strict state leads to valid finish. 10802 * 10803 * Therefore two states are equivalent if register state is more conservative 10804 * and explored stack state is more conservative than the current one. 10805 * Example: 10806 * explored current 10807 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 10808 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 10809 * 10810 * In other words if current stack state (one being explored) has more 10811 * valid slots than old one that already passed validation, it means 10812 * the verifier can stop exploring and conclude that current state is valid too 10813 * 10814 * Similarly with registers. If explored state has register type as invalid 10815 * whereas register type in current state is meaningful, it means that 10816 * the current state will reach 'bpf_exit' instruction safely 10817 */ 10818 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 10819 struct bpf_func_state *cur) 10820 { 10821 int i; 10822 10823 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch)); 10824 for (i = 0; i < MAX_BPF_REG; i++) 10825 if (!regsafe(env, &old->regs[i], &cur->regs[i], 10826 env->idmap_scratch)) 10827 return false; 10828 10829 if (!stacksafe(env, old, cur, env->idmap_scratch)) 10830 return false; 10831 10832 if (!refsafe(old, cur)) 10833 return false; 10834 10835 return true; 10836 } 10837 10838 static bool states_equal(struct bpf_verifier_env *env, 10839 struct bpf_verifier_state *old, 10840 struct bpf_verifier_state *cur) 10841 { 10842 int i; 10843 10844 if (old->curframe != cur->curframe) 10845 return false; 10846 10847 /* Verification state from speculative execution simulation 10848 * must never prune a non-speculative execution one. 10849 */ 10850 if (old->speculative && !cur->speculative) 10851 return false; 10852 10853 if (old->active_spin_lock != cur->active_spin_lock) 10854 return false; 10855 10856 /* for states to be equal callsites have to be the same 10857 * and all frame states need to be equivalent 10858 */ 10859 for (i = 0; i <= old->curframe; i++) { 10860 if (old->frame[i]->callsite != cur->frame[i]->callsite) 10861 return false; 10862 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 10863 return false; 10864 } 10865 return true; 10866 } 10867 10868 /* Return 0 if no propagation happened. Return negative error code if error 10869 * happened. Otherwise, return the propagated bit. 10870 */ 10871 static int propagate_liveness_reg(struct bpf_verifier_env *env, 10872 struct bpf_reg_state *reg, 10873 struct bpf_reg_state *parent_reg) 10874 { 10875 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 10876 u8 flag = reg->live & REG_LIVE_READ; 10877 int err; 10878 10879 /* When comes here, read flags of PARENT_REG or REG could be any of 10880 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 10881 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 10882 */ 10883 if (parent_flag == REG_LIVE_READ64 || 10884 /* Or if there is no read flag from REG. */ 10885 !flag || 10886 /* Or if the read flag from REG is the same as PARENT_REG. */ 10887 parent_flag == flag) 10888 return 0; 10889 10890 err = mark_reg_read(env, reg, parent_reg, flag); 10891 if (err) 10892 return err; 10893 10894 return flag; 10895 } 10896 10897 /* A write screens off any subsequent reads; but write marks come from the 10898 * straight-line code between a state and its parent. When we arrive at an 10899 * equivalent state (jump target or such) we didn't arrive by the straight-line 10900 * code, so read marks in the state must propagate to the parent regardless 10901 * of the state's write marks. That's what 'parent == state->parent' comparison 10902 * in mark_reg_read() is for. 10903 */ 10904 static int propagate_liveness(struct bpf_verifier_env *env, 10905 const struct bpf_verifier_state *vstate, 10906 struct bpf_verifier_state *vparent) 10907 { 10908 struct bpf_reg_state *state_reg, *parent_reg; 10909 struct bpf_func_state *state, *parent; 10910 int i, frame, err = 0; 10911 10912 if (vparent->curframe != vstate->curframe) { 10913 WARN(1, "propagate_live: parent frame %d current frame %d\n", 10914 vparent->curframe, vstate->curframe); 10915 return -EFAULT; 10916 } 10917 /* Propagate read liveness of registers... */ 10918 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 10919 for (frame = 0; frame <= vstate->curframe; frame++) { 10920 parent = vparent->frame[frame]; 10921 state = vstate->frame[frame]; 10922 parent_reg = parent->regs; 10923 state_reg = state->regs; 10924 /* We don't need to worry about FP liveness, it's read-only */ 10925 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 10926 err = propagate_liveness_reg(env, &state_reg[i], 10927 &parent_reg[i]); 10928 if (err < 0) 10929 return err; 10930 if (err == REG_LIVE_READ64) 10931 mark_insn_zext(env, &parent_reg[i]); 10932 } 10933 10934 /* Propagate stack slots. */ 10935 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 10936 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 10937 parent_reg = &parent->stack[i].spilled_ptr; 10938 state_reg = &state->stack[i].spilled_ptr; 10939 err = propagate_liveness_reg(env, state_reg, 10940 parent_reg); 10941 if (err < 0) 10942 return err; 10943 } 10944 } 10945 return 0; 10946 } 10947 10948 /* find precise scalars in the previous equivalent state and 10949 * propagate them into the current state 10950 */ 10951 static int propagate_precision(struct bpf_verifier_env *env, 10952 const struct bpf_verifier_state *old) 10953 { 10954 struct bpf_reg_state *state_reg; 10955 struct bpf_func_state *state; 10956 int i, err = 0; 10957 10958 state = old->frame[old->curframe]; 10959 state_reg = state->regs; 10960 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 10961 if (state_reg->type != SCALAR_VALUE || 10962 !state_reg->precise) 10963 continue; 10964 if (env->log.level & BPF_LOG_LEVEL2) 10965 verbose(env, "propagating r%d\n", i); 10966 err = mark_chain_precision(env, i); 10967 if (err < 0) 10968 return err; 10969 } 10970 10971 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 10972 if (!is_spilled_reg(&state->stack[i])) 10973 continue; 10974 state_reg = &state->stack[i].spilled_ptr; 10975 if (state_reg->type != SCALAR_VALUE || 10976 !state_reg->precise) 10977 continue; 10978 if (env->log.level & BPF_LOG_LEVEL2) 10979 verbose(env, "propagating fp%d\n", 10980 (-i - 1) * BPF_REG_SIZE); 10981 err = mark_chain_precision_stack(env, i); 10982 if (err < 0) 10983 return err; 10984 } 10985 return 0; 10986 } 10987 10988 static bool states_maybe_looping(struct bpf_verifier_state *old, 10989 struct bpf_verifier_state *cur) 10990 { 10991 struct bpf_func_state *fold, *fcur; 10992 int i, fr = cur->curframe; 10993 10994 if (old->curframe != fr) 10995 return false; 10996 10997 fold = old->frame[fr]; 10998 fcur = cur->frame[fr]; 10999 for (i = 0; i < MAX_BPF_REG; i++) 11000 if (memcmp(&fold->regs[i], &fcur->regs[i], 11001 offsetof(struct bpf_reg_state, parent))) 11002 return false; 11003 return true; 11004 } 11005 11006 11007 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 11008 { 11009 struct bpf_verifier_state_list *new_sl; 11010 struct bpf_verifier_state_list *sl, **pprev; 11011 struct bpf_verifier_state *cur = env->cur_state, *new; 11012 int i, j, err, states_cnt = 0; 11013 bool add_new_state = env->test_state_freq ? true : false; 11014 11015 cur->last_insn_idx = env->prev_insn_idx; 11016 if (!env->insn_aux_data[insn_idx].prune_point) 11017 /* this 'insn_idx' instruction wasn't marked, so we will not 11018 * be doing state search here 11019 */ 11020 return 0; 11021 11022 /* bpf progs typically have pruning point every 4 instructions 11023 * http://vger.kernel.org/bpfconf2019.html#session-1 11024 * Do not add new state for future pruning if the verifier hasn't seen 11025 * at least 2 jumps and at least 8 instructions. 11026 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 11027 * In tests that amounts to up to 50% reduction into total verifier 11028 * memory consumption and 20% verifier time speedup. 11029 */ 11030 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 11031 env->insn_processed - env->prev_insn_processed >= 8) 11032 add_new_state = true; 11033 11034 pprev = explored_state(env, insn_idx); 11035 sl = *pprev; 11036 11037 clean_live_states(env, insn_idx, cur); 11038 11039 while (sl) { 11040 states_cnt++; 11041 if (sl->state.insn_idx != insn_idx) 11042 goto next; 11043 11044 if (sl->state.branches) { 11045 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 11046 11047 if (frame->in_async_callback_fn && 11048 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 11049 /* Different async_entry_cnt means that the verifier is 11050 * processing another entry into async callback. 11051 * Seeing the same state is not an indication of infinite 11052 * loop or infinite recursion. 11053 * But finding the same state doesn't mean that it's safe 11054 * to stop processing the current state. The previous state 11055 * hasn't yet reached bpf_exit, since state.branches > 0. 11056 * Checking in_async_callback_fn alone is not enough either. 11057 * Since the verifier still needs to catch infinite loops 11058 * inside async callbacks. 11059 */ 11060 } else if (states_maybe_looping(&sl->state, cur) && 11061 states_equal(env, &sl->state, cur)) { 11062 verbose_linfo(env, insn_idx, "; "); 11063 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 11064 return -EINVAL; 11065 } 11066 /* if the verifier is processing a loop, avoid adding new state 11067 * too often, since different loop iterations have distinct 11068 * states and may not help future pruning. 11069 * This threshold shouldn't be too low to make sure that 11070 * a loop with large bound will be rejected quickly. 11071 * The most abusive loop will be: 11072 * r1 += 1 11073 * if r1 < 1000000 goto pc-2 11074 * 1M insn_procssed limit / 100 == 10k peak states. 11075 * This threshold shouldn't be too high either, since states 11076 * at the end of the loop are likely to be useful in pruning. 11077 */ 11078 if (env->jmps_processed - env->prev_jmps_processed < 20 && 11079 env->insn_processed - env->prev_insn_processed < 100) 11080 add_new_state = false; 11081 goto miss; 11082 } 11083 if (states_equal(env, &sl->state, cur)) { 11084 sl->hit_cnt++; 11085 /* reached equivalent register/stack state, 11086 * prune the search. 11087 * Registers read by the continuation are read by us. 11088 * If we have any write marks in env->cur_state, they 11089 * will prevent corresponding reads in the continuation 11090 * from reaching our parent (an explored_state). Our 11091 * own state will get the read marks recorded, but 11092 * they'll be immediately forgotten as we're pruning 11093 * this state and will pop a new one. 11094 */ 11095 err = propagate_liveness(env, &sl->state, cur); 11096 11097 /* if previous state reached the exit with precision and 11098 * current state is equivalent to it (except precsion marks) 11099 * the precision needs to be propagated back in 11100 * the current state. 11101 */ 11102 err = err ? : push_jmp_history(env, cur); 11103 err = err ? : propagate_precision(env, &sl->state); 11104 if (err) 11105 return err; 11106 return 1; 11107 } 11108 miss: 11109 /* when new state is not going to be added do not increase miss count. 11110 * Otherwise several loop iterations will remove the state 11111 * recorded earlier. The goal of these heuristics is to have 11112 * states from some iterations of the loop (some in the beginning 11113 * and some at the end) to help pruning. 11114 */ 11115 if (add_new_state) 11116 sl->miss_cnt++; 11117 /* heuristic to determine whether this state is beneficial 11118 * to keep checking from state equivalence point of view. 11119 * Higher numbers increase max_states_per_insn and verification time, 11120 * but do not meaningfully decrease insn_processed. 11121 */ 11122 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 11123 /* the state is unlikely to be useful. Remove it to 11124 * speed up verification 11125 */ 11126 *pprev = sl->next; 11127 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 11128 u32 br = sl->state.branches; 11129 11130 WARN_ONCE(br, 11131 "BUG live_done but branches_to_explore %d\n", 11132 br); 11133 free_verifier_state(&sl->state, false); 11134 kfree(sl); 11135 env->peak_states--; 11136 } else { 11137 /* cannot free this state, since parentage chain may 11138 * walk it later. Add it for free_list instead to 11139 * be freed at the end of verification 11140 */ 11141 sl->next = env->free_list; 11142 env->free_list = sl; 11143 } 11144 sl = *pprev; 11145 continue; 11146 } 11147 next: 11148 pprev = &sl->next; 11149 sl = *pprev; 11150 } 11151 11152 if (env->max_states_per_insn < states_cnt) 11153 env->max_states_per_insn = states_cnt; 11154 11155 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 11156 return push_jmp_history(env, cur); 11157 11158 if (!add_new_state) 11159 return push_jmp_history(env, cur); 11160 11161 /* There were no equivalent states, remember the current one. 11162 * Technically the current state is not proven to be safe yet, 11163 * but it will either reach outer most bpf_exit (which means it's safe) 11164 * or it will be rejected. When there are no loops the verifier won't be 11165 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 11166 * again on the way to bpf_exit. 11167 * When looping the sl->state.branches will be > 0 and this state 11168 * will not be considered for equivalence until branches == 0. 11169 */ 11170 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 11171 if (!new_sl) 11172 return -ENOMEM; 11173 env->total_states++; 11174 env->peak_states++; 11175 env->prev_jmps_processed = env->jmps_processed; 11176 env->prev_insn_processed = env->insn_processed; 11177 11178 /* add new state to the head of linked list */ 11179 new = &new_sl->state; 11180 err = copy_verifier_state(new, cur); 11181 if (err) { 11182 free_verifier_state(new, false); 11183 kfree(new_sl); 11184 return err; 11185 } 11186 new->insn_idx = insn_idx; 11187 WARN_ONCE(new->branches != 1, 11188 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 11189 11190 cur->parent = new; 11191 cur->first_insn_idx = insn_idx; 11192 clear_jmp_history(cur); 11193 new_sl->next = *explored_state(env, insn_idx); 11194 *explored_state(env, insn_idx) = new_sl; 11195 /* connect new state to parentage chain. Current frame needs all 11196 * registers connected. Only r6 - r9 of the callers are alive (pushed 11197 * to the stack implicitly by JITs) so in callers' frames connect just 11198 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 11199 * the state of the call instruction (with WRITTEN set), and r0 comes 11200 * from callee with its full parentage chain, anyway. 11201 */ 11202 /* clear write marks in current state: the writes we did are not writes 11203 * our child did, so they don't screen off its reads from us. 11204 * (There are no read marks in current state, because reads always mark 11205 * their parent and current state never has children yet. Only 11206 * explored_states can get read marks.) 11207 */ 11208 for (j = 0; j <= cur->curframe; j++) { 11209 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 11210 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 11211 for (i = 0; i < BPF_REG_FP; i++) 11212 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 11213 } 11214 11215 /* all stack frames are accessible from callee, clear them all */ 11216 for (j = 0; j <= cur->curframe; j++) { 11217 struct bpf_func_state *frame = cur->frame[j]; 11218 struct bpf_func_state *newframe = new->frame[j]; 11219 11220 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 11221 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 11222 frame->stack[i].spilled_ptr.parent = 11223 &newframe->stack[i].spilled_ptr; 11224 } 11225 } 11226 return 0; 11227 } 11228 11229 /* Return true if it's OK to have the same insn return a different type. */ 11230 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 11231 { 11232 switch (base_type(type)) { 11233 case PTR_TO_CTX: 11234 case PTR_TO_SOCKET: 11235 case PTR_TO_SOCK_COMMON: 11236 case PTR_TO_TCP_SOCK: 11237 case PTR_TO_XDP_SOCK: 11238 case PTR_TO_BTF_ID: 11239 return false; 11240 default: 11241 return true; 11242 } 11243 } 11244 11245 /* If an instruction was previously used with particular pointer types, then we 11246 * need to be careful to avoid cases such as the below, where it may be ok 11247 * for one branch accessing the pointer, but not ok for the other branch: 11248 * 11249 * R1 = sock_ptr 11250 * goto X; 11251 * ... 11252 * R1 = some_other_valid_ptr; 11253 * goto X; 11254 * ... 11255 * R2 = *(u32 *)(R1 + 0); 11256 */ 11257 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 11258 { 11259 return src != prev && (!reg_type_mismatch_ok(src) || 11260 !reg_type_mismatch_ok(prev)); 11261 } 11262 11263 static int do_check(struct bpf_verifier_env *env) 11264 { 11265 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 11266 struct bpf_verifier_state *state = env->cur_state; 11267 struct bpf_insn *insns = env->prog->insnsi; 11268 struct bpf_reg_state *regs; 11269 int insn_cnt = env->prog->len; 11270 bool do_print_state = false; 11271 int prev_insn_idx = -1; 11272 11273 for (;;) { 11274 struct bpf_insn *insn; 11275 u8 class; 11276 int err; 11277 11278 env->prev_insn_idx = prev_insn_idx; 11279 if (env->insn_idx >= insn_cnt) { 11280 verbose(env, "invalid insn idx %d insn_cnt %d\n", 11281 env->insn_idx, insn_cnt); 11282 return -EFAULT; 11283 } 11284 11285 insn = &insns[env->insn_idx]; 11286 class = BPF_CLASS(insn->code); 11287 11288 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 11289 verbose(env, 11290 "BPF program is too large. Processed %d insn\n", 11291 env->insn_processed); 11292 return -E2BIG; 11293 } 11294 11295 err = is_state_visited(env, env->insn_idx); 11296 if (err < 0) 11297 return err; 11298 if (err == 1) { 11299 /* found equivalent state, can prune the search */ 11300 if (env->log.level & BPF_LOG_LEVEL) { 11301 if (do_print_state) 11302 verbose(env, "\nfrom %d to %d%s: safe\n", 11303 env->prev_insn_idx, env->insn_idx, 11304 env->cur_state->speculative ? 11305 " (speculative execution)" : ""); 11306 else 11307 verbose(env, "%d: safe\n", env->insn_idx); 11308 } 11309 goto process_bpf_exit; 11310 } 11311 11312 if (signal_pending(current)) 11313 return -EAGAIN; 11314 11315 if (need_resched()) 11316 cond_resched(); 11317 11318 if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) { 11319 verbose(env, "\nfrom %d to %d%s:", 11320 env->prev_insn_idx, env->insn_idx, 11321 env->cur_state->speculative ? 11322 " (speculative execution)" : ""); 11323 print_verifier_state(env, state->frame[state->curframe], true); 11324 do_print_state = false; 11325 } 11326 11327 if (env->log.level & BPF_LOG_LEVEL) { 11328 const struct bpf_insn_cbs cbs = { 11329 .cb_call = disasm_kfunc_name, 11330 .cb_print = verbose, 11331 .private_data = env, 11332 }; 11333 11334 if (verifier_state_scratched(env)) 11335 print_insn_state(env, state->frame[state->curframe]); 11336 11337 verbose_linfo(env, env->insn_idx, "; "); 11338 env->prev_log_len = env->log.len_used; 11339 verbose(env, "%d: ", env->insn_idx); 11340 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 11341 env->prev_insn_print_len = env->log.len_used - env->prev_log_len; 11342 env->prev_log_len = env->log.len_used; 11343 } 11344 11345 if (bpf_prog_is_dev_bound(env->prog->aux)) { 11346 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 11347 env->prev_insn_idx); 11348 if (err) 11349 return err; 11350 } 11351 11352 regs = cur_regs(env); 11353 sanitize_mark_insn_seen(env); 11354 prev_insn_idx = env->insn_idx; 11355 11356 if (class == BPF_ALU || class == BPF_ALU64) { 11357 err = check_alu_op(env, insn); 11358 if (err) 11359 return err; 11360 11361 } else if (class == BPF_LDX) { 11362 enum bpf_reg_type *prev_src_type, src_reg_type; 11363 11364 /* check for reserved fields is already done */ 11365 11366 /* check src operand */ 11367 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11368 if (err) 11369 return err; 11370 11371 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 11372 if (err) 11373 return err; 11374 11375 src_reg_type = regs[insn->src_reg].type; 11376 11377 /* check that memory (src_reg + off) is readable, 11378 * the state of dst_reg will be updated by this func 11379 */ 11380 err = check_mem_access(env, env->insn_idx, insn->src_reg, 11381 insn->off, BPF_SIZE(insn->code), 11382 BPF_READ, insn->dst_reg, false); 11383 if (err) 11384 return err; 11385 11386 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 11387 11388 if (*prev_src_type == NOT_INIT) { 11389 /* saw a valid insn 11390 * dst_reg = *(u32 *)(src_reg + off) 11391 * save type to validate intersecting paths 11392 */ 11393 *prev_src_type = src_reg_type; 11394 11395 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 11396 /* ABuser program is trying to use the same insn 11397 * dst_reg = *(u32*) (src_reg + off) 11398 * with different pointer types: 11399 * src_reg == ctx in one branch and 11400 * src_reg == stack|map in some other branch. 11401 * Reject it. 11402 */ 11403 verbose(env, "same insn cannot be used with different pointers\n"); 11404 return -EINVAL; 11405 } 11406 11407 } else if (class == BPF_STX) { 11408 enum bpf_reg_type *prev_dst_type, dst_reg_type; 11409 11410 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 11411 err = check_atomic(env, env->insn_idx, insn); 11412 if (err) 11413 return err; 11414 env->insn_idx++; 11415 continue; 11416 } 11417 11418 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 11419 verbose(env, "BPF_STX uses reserved fields\n"); 11420 return -EINVAL; 11421 } 11422 11423 /* check src1 operand */ 11424 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11425 if (err) 11426 return err; 11427 /* check src2 operand */ 11428 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11429 if (err) 11430 return err; 11431 11432 dst_reg_type = regs[insn->dst_reg].type; 11433 11434 /* check that memory (dst_reg + off) is writeable */ 11435 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 11436 insn->off, BPF_SIZE(insn->code), 11437 BPF_WRITE, insn->src_reg, false); 11438 if (err) 11439 return err; 11440 11441 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 11442 11443 if (*prev_dst_type == NOT_INIT) { 11444 *prev_dst_type = dst_reg_type; 11445 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 11446 verbose(env, "same insn cannot be used with different pointers\n"); 11447 return -EINVAL; 11448 } 11449 11450 } else if (class == BPF_ST) { 11451 if (BPF_MODE(insn->code) != BPF_MEM || 11452 insn->src_reg != BPF_REG_0) { 11453 verbose(env, "BPF_ST uses reserved fields\n"); 11454 return -EINVAL; 11455 } 11456 /* check src operand */ 11457 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11458 if (err) 11459 return err; 11460 11461 if (is_ctx_reg(env, insn->dst_reg)) { 11462 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 11463 insn->dst_reg, 11464 reg_type_str(env, reg_state(env, insn->dst_reg)->type)); 11465 return -EACCES; 11466 } 11467 11468 /* check that memory (dst_reg + off) is writeable */ 11469 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 11470 insn->off, BPF_SIZE(insn->code), 11471 BPF_WRITE, -1, false); 11472 if (err) 11473 return err; 11474 11475 } else if (class == BPF_JMP || class == BPF_JMP32) { 11476 u8 opcode = BPF_OP(insn->code); 11477 11478 env->jmps_processed++; 11479 if (opcode == BPF_CALL) { 11480 if (BPF_SRC(insn->code) != BPF_K || 11481 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 11482 && insn->off != 0) || 11483 (insn->src_reg != BPF_REG_0 && 11484 insn->src_reg != BPF_PSEUDO_CALL && 11485 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 11486 insn->dst_reg != BPF_REG_0 || 11487 class == BPF_JMP32) { 11488 verbose(env, "BPF_CALL uses reserved fields\n"); 11489 return -EINVAL; 11490 } 11491 11492 if (env->cur_state->active_spin_lock && 11493 (insn->src_reg == BPF_PSEUDO_CALL || 11494 insn->imm != BPF_FUNC_spin_unlock)) { 11495 verbose(env, "function calls are not allowed while holding a lock\n"); 11496 return -EINVAL; 11497 } 11498 if (insn->src_reg == BPF_PSEUDO_CALL) 11499 err = check_func_call(env, insn, &env->insn_idx); 11500 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 11501 err = check_kfunc_call(env, insn); 11502 else 11503 err = check_helper_call(env, insn, &env->insn_idx); 11504 if (err) 11505 return err; 11506 } else if (opcode == BPF_JA) { 11507 if (BPF_SRC(insn->code) != BPF_K || 11508 insn->imm != 0 || 11509 insn->src_reg != BPF_REG_0 || 11510 insn->dst_reg != BPF_REG_0 || 11511 class == BPF_JMP32) { 11512 verbose(env, "BPF_JA uses reserved fields\n"); 11513 return -EINVAL; 11514 } 11515 11516 env->insn_idx += insn->off + 1; 11517 continue; 11518 11519 } else if (opcode == BPF_EXIT) { 11520 if (BPF_SRC(insn->code) != BPF_K || 11521 insn->imm != 0 || 11522 insn->src_reg != BPF_REG_0 || 11523 insn->dst_reg != BPF_REG_0 || 11524 class == BPF_JMP32) { 11525 verbose(env, "BPF_EXIT uses reserved fields\n"); 11526 return -EINVAL; 11527 } 11528 11529 if (env->cur_state->active_spin_lock) { 11530 verbose(env, "bpf_spin_unlock is missing\n"); 11531 return -EINVAL; 11532 } 11533 11534 if (state->curframe) { 11535 /* exit from nested function */ 11536 err = prepare_func_exit(env, &env->insn_idx); 11537 if (err) 11538 return err; 11539 do_print_state = true; 11540 continue; 11541 } 11542 11543 err = check_reference_leak(env); 11544 if (err) 11545 return err; 11546 11547 err = check_return_code(env); 11548 if (err) 11549 return err; 11550 process_bpf_exit: 11551 mark_verifier_state_scratched(env); 11552 update_branch_counts(env, env->cur_state); 11553 err = pop_stack(env, &prev_insn_idx, 11554 &env->insn_idx, pop_log); 11555 if (err < 0) { 11556 if (err != -ENOENT) 11557 return err; 11558 break; 11559 } else { 11560 do_print_state = true; 11561 continue; 11562 } 11563 } else { 11564 err = check_cond_jmp_op(env, insn, &env->insn_idx); 11565 if (err) 11566 return err; 11567 } 11568 } else if (class == BPF_LD) { 11569 u8 mode = BPF_MODE(insn->code); 11570 11571 if (mode == BPF_ABS || mode == BPF_IND) { 11572 err = check_ld_abs(env, insn); 11573 if (err) 11574 return err; 11575 11576 } else if (mode == BPF_IMM) { 11577 err = check_ld_imm(env, insn); 11578 if (err) 11579 return err; 11580 11581 env->insn_idx++; 11582 sanitize_mark_insn_seen(env); 11583 } else { 11584 verbose(env, "invalid BPF_LD mode\n"); 11585 return -EINVAL; 11586 } 11587 } else { 11588 verbose(env, "unknown insn class %d\n", class); 11589 return -EINVAL; 11590 } 11591 11592 env->insn_idx++; 11593 } 11594 11595 return 0; 11596 } 11597 11598 static int find_btf_percpu_datasec(struct btf *btf) 11599 { 11600 const struct btf_type *t; 11601 const char *tname; 11602 int i, n; 11603 11604 /* 11605 * Both vmlinux and module each have their own ".data..percpu" 11606 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 11607 * types to look at only module's own BTF types. 11608 */ 11609 n = btf_nr_types(btf); 11610 if (btf_is_module(btf)) 11611 i = btf_nr_types(btf_vmlinux); 11612 else 11613 i = 1; 11614 11615 for(; i < n; i++) { 11616 t = btf_type_by_id(btf, i); 11617 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 11618 continue; 11619 11620 tname = btf_name_by_offset(btf, t->name_off); 11621 if (!strcmp(tname, ".data..percpu")) 11622 return i; 11623 } 11624 11625 return -ENOENT; 11626 } 11627 11628 /* replace pseudo btf_id with kernel symbol address */ 11629 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 11630 struct bpf_insn *insn, 11631 struct bpf_insn_aux_data *aux) 11632 { 11633 const struct btf_var_secinfo *vsi; 11634 const struct btf_type *datasec; 11635 struct btf_mod_pair *btf_mod; 11636 const struct btf_type *t; 11637 const char *sym_name; 11638 bool percpu = false; 11639 u32 type, id = insn->imm; 11640 struct btf *btf; 11641 s32 datasec_id; 11642 u64 addr; 11643 int i, btf_fd, err; 11644 11645 btf_fd = insn[1].imm; 11646 if (btf_fd) { 11647 btf = btf_get_by_fd(btf_fd); 11648 if (IS_ERR(btf)) { 11649 verbose(env, "invalid module BTF object FD specified.\n"); 11650 return -EINVAL; 11651 } 11652 } else { 11653 if (!btf_vmlinux) { 11654 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 11655 return -EINVAL; 11656 } 11657 btf = btf_vmlinux; 11658 btf_get(btf); 11659 } 11660 11661 t = btf_type_by_id(btf, id); 11662 if (!t) { 11663 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 11664 err = -ENOENT; 11665 goto err_put; 11666 } 11667 11668 if (!btf_type_is_var(t)) { 11669 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id); 11670 err = -EINVAL; 11671 goto err_put; 11672 } 11673 11674 sym_name = btf_name_by_offset(btf, t->name_off); 11675 addr = kallsyms_lookup_name(sym_name); 11676 if (!addr) { 11677 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 11678 sym_name); 11679 err = -ENOENT; 11680 goto err_put; 11681 } 11682 11683 datasec_id = find_btf_percpu_datasec(btf); 11684 if (datasec_id > 0) { 11685 datasec = btf_type_by_id(btf, datasec_id); 11686 for_each_vsi(i, datasec, vsi) { 11687 if (vsi->type == id) { 11688 percpu = true; 11689 break; 11690 } 11691 } 11692 } 11693 11694 insn[0].imm = (u32)addr; 11695 insn[1].imm = addr >> 32; 11696 11697 type = t->type; 11698 t = btf_type_skip_modifiers(btf, type, NULL); 11699 if (percpu) { 11700 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID; 11701 aux->btf_var.btf = btf; 11702 aux->btf_var.btf_id = type; 11703 } else if (!btf_type_is_struct(t)) { 11704 const struct btf_type *ret; 11705 const char *tname; 11706 u32 tsize; 11707 11708 /* resolve the type size of ksym. */ 11709 ret = btf_resolve_size(btf, t, &tsize); 11710 if (IS_ERR(ret)) { 11711 tname = btf_name_by_offset(btf, t->name_off); 11712 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 11713 tname, PTR_ERR(ret)); 11714 err = -EINVAL; 11715 goto err_put; 11716 } 11717 aux->btf_var.reg_type = PTR_TO_MEM | MEM_RDONLY; 11718 aux->btf_var.mem_size = tsize; 11719 } else { 11720 aux->btf_var.reg_type = PTR_TO_BTF_ID; 11721 aux->btf_var.btf = btf; 11722 aux->btf_var.btf_id = type; 11723 } 11724 11725 /* check whether we recorded this BTF (and maybe module) already */ 11726 for (i = 0; i < env->used_btf_cnt; i++) { 11727 if (env->used_btfs[i].btf == btf) { 11728 btf_put(btf); 11729 return 0; 11730 } 11731 } 11732 11733 if (env->used_btf_cnt >= MAX_USED_BTFS) { 11734 err = -E2BIG; 11735 goto err_put; 11736 } 11737 11738 btf_mod = &env->used_btfs[env->used_btf_cnt]; 11739 btf_mod->btf = btf; 11740 btf_mod->module = NULL; 11741 11742 /* if we reference variables from kernel module, bump its refcount */ 11743 if (btf_is_module(btf)) { 11744 btf_mod->module = btf_try_get_module(btf); 11745 if (!btf_mod->module) { 11746 err = -ENXIO; 11747 goto err_put; 11748 } 11749 } 11750 11751 env->used_btf_cnt++; 11752 11753 return 0; 11754 err_put: 11755 btf_put(btf); 11756 return err; 11757 } 11758 11759 static int check_map_prealloc(struct bpf_map *map) 11760 { 11761 return (map->map_type != BPF_MAP_TYPE_HASH && 11762 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 11763 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || 11764 !(map->map_flags & BPF_F_NO_PREALLOC); 11765 } 11766 11767 static bool is_tracing_prog_type(enum bpf_prog_type type) 11768 { 11769 switch (type) { 11770 case BPF_PROG_TYPE_KPROBE: 11771 case BPF_PROG_TYPE_TRACEPOINT: 11772 case BPF_PROG_TYPE_PERF_EVENT: 11773 case BPF_PROG_TYPE_RAW_TRACEPOINT: 11774 return true; 11775 default: 11776 return false; 11777 } 11778 } 11779 11780 static bool is_preallocated_map(struct bpf_map *map) 11781 { 11782 if (!check_map_prealloc(map)) 11783 return false; 11784 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) 11785 return false; 11786 return true; 11787 } 11788 11789 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 11790 struct bpf_map *map, 11791 struct bpf_prog *prog) 11792 11793 { 11794 enum bpf_prog_type prog_type = resolve_prog_type(prog); 11795 /* 11796 * Validate that trace type programs use preallocated hash maps. 11797 * 11798 * For programs attached to PERF events this is mandatory as the 11799 * perf NMI can hit any arbitrary code sequence. 11800 * 11801 * All other trace types using preallocated hash maps are unsafe as 11802 * well because tracepoint or kprobes can be inside locked regions 11803 * of the memory allocator or at a place where a recursion into the 11804 * memory allocator would see inconsistent state. 11805 * 11806 * On RT enabled kernels run-time allocation of all trace type 11807 * programs is strictly prohibited due to lock type constraints. On 11808 * !RT kernels it is allowed for backwards compatibility reasons for 11809 * now, but warnings are emitted so developers are made aware of 11810 * the unsafety and can fix their programs before this is enforced. 11811 */ 11812 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) { 11813 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) { 11814 verbose(env, "perf_event programs can only use preallocated hash map\n"); 11815 return -EINVAL; 11816 } 11817 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 11818 verbose(env, "trace type programs can only use preallocated hash map\n"); 11819 return -EINVAL; 11820 } 11821 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n"); 11822 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n"); 11823 } 11824 11825 if (map_value_has_spin_lock(map)) { 11826 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 11827 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 11828 return -EINVAL; 11829 } 11830 11831 if (is_tracing_prog_type(prog_type)) { 11832 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 11833 return -EINVAL; 11834 } 11835 11836 if (prog->aux->sleepable) { 11837 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 11838 return -EINVAL; 11839 } 11840 } 11841 11842 if (map_value_has_timer(map)) { 11843 if (is_tracing_prog_type(prog_type)) { 11844 verbose(env, "tracing progs cannot use bpf_timer yet\n"); 11845 return -EINVAL; 11846 } 11847 } 11848 11849 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) && 11850 !bpf_offload_prog_map_match(prog, map)) { 11851 verbose(env, "offload device mismatch between prog and map\n"); 11852 return -EINVAL; 11853 } 11854 11855 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 11856 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 11857 return -EINVAL; 11858 } 11859 11860 if (prog->aux->sleepable) 11861 switch (map->map_type) { 11862 case BPF_MAP_TYPE_HASH: 11863 case BPF_MAP_TYPE_LRU_HASH: 11864 case BPF_MAP_TYPE_ARRAY: 11865 case BPF_MAP_TYPE_PERCPU_HASH: 11866 case BPF_MAP_TYPE_PERCPU_ARRAY: 11867 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 11868 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 11869 case BPF_MAP_TYPE_HASH_OF_MAPS: 11870 if (!is_preallocated_map(map)) { 11871 verbose(env, 11872 "Sleepable programs can only use preallocated maps\n"); 11873 return -EINVAL; 11874 } 11875 break; 11876 case BPF_MAP_TYPE_RINGBUF: 11877 break; 11878 default: 11879 verbose(env, 11880 "Sleepable programs can only use array, hash, and ringbuf maps\n"); 11881 return -EINVAL; 11882 } 11883 11884 return 0; 11885 } 11886 11887 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 11888 { 11889 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 11890 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 11891 } 11892 11893 /* find and rewrite pseudo imm in ld_imm64 instructions: 11894 * 11895 * 1. if it accesses map FD, replace it with actual map pointer. 11896 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 11897 * 11898 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 11899 */ 11900 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 11901 { 11902 struct bpf_insn *insn = env->prog->insnsi; 11903 int insn_cnt = env->prog->len; 11904 int i, j, err; 11905 11906 err = bpf_prog_calc_tag(env->prog); 11907 if (err) 11908 return err; 11909 11910 for (i = 0; i < insn_cnt; i++, insn++) { 11911 if (BPF_CLASS(insn->code) == BPF_LDX && 11912 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 11913 verbose(env, "BPF_LDX uses reserved fields\n"); 11914 return -EINVAL; 11915 } 11916 11917 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 11918 struct bpf_insn_aux_data *aux; 11919 struct bpf_map *map; 11920 struct fd f; 11921 u64 addr; 11922 u32 fd; 11923 11924 if (i == insn_cnt - 1 || insn[1].code != 0 || 11925 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 11926 insn[1].off != 0) { 11927 verbose(env, "invalid bpf_ld_imm64 insn\n"); 11928 return -EINVAL; 11929 } 11930 11931 if (insn[0].src_reg == 0) 11932 /* valid generic load 64-bit imm */ 11933 goto next_insn; 11934 11935 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 11936 aux = &env->insn_aux_data[i]; 11937 err = check_pseudo_btf_id(env, insn, aux); 11938 if (err) 11939 return err; 11940 goto next_insn; 11941 } 11942 11943 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 11944 aux = &env->insn_aux_data[i]; 11945 aux->ptr_type = PTR_TO_FUNC; 11946 goto next_insn; 11947 } 11948 11949 /* In final convert_pseudo_ld_imm64() step, this is 11950 * converted into regular 64-bit imm load insn. 11951 */ 11952 switch (insn[0].src_reg) { 11953 case BPF_PSEUDO_MAP_VALUE: 11954 case BPF_PSEUDO_MAP_IDX_VALUE: 11955 break; 11956 case BPF_PSEUDO_MAP_FD: 11957 case BPF_PSEUDO_MAP_IDX: 11958 if (insn[1].imm == 0) 11959 break; 11960 fallthrough; 11961 default: 11962 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 11963 return -EINVAL; 11964 } 11965 11966 switch (insn[0].src_reg) { 11967 case BPF_PSEUDO_MAP_IDX_VALUE: 11968 case BPF_PSEUDO_MAP_IDX: 11969 if (bpfptr_is_null(env->fd_array)) { 11970 verbose(env, "fd_idx without fd_array is invalid\n"); 11971 return -EPROTO; 11972 } 11973 if (copy_from_bpfptr_offset(&fd, env->fd_array, 11974 insn[0].imm * sizeof(fd), 11975 sizeof(fd))) 11976 return -EFAULT; 11977 break; 11978 default: 11979 fd = insn[0].imm; 11980 break; 11981 } 11982 11983 f = fdget(fd); 11984 map = __bpf_map_get(f); 11985 if (IS_ERR(map)) { 11986 verbose(env, "fd %d is not pointing to valid bpf_map\n", 11987 insn[0].imm); 11988 return PTR_ERR(map); 11989 } 11990 11991 err = check_map_prog_compatibility(env, map, env->prog); 11992 if (err) { 11993 fdput(f); 11994 return err; 11995 } 11996 11997 aux = &env->insn_aux_data[i]; 11998 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 11999 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 12000 addr = (unsigned long)map; 12001 } else { 12002 u32 off = insn[1].imm; 12003 12004 if (off >= BPF_MAX_VAR_OFF) { 12005 verbose(env, "direct value offset of %u is not allowed\n", off); 12006 fdput(f); 12007 return -EINVAL; 12008 } 12009 12010 if (!map->ops->map_direct_value_addr) { 12011 verbose(env, "no direct value access support for this map type\n"); 12012 fdput(f); 12013 return -EINVAL; 12014 } 12015 12016 err = map->ops->map_direct_value_addr(map, &addr, off); 12017 if (err) { 12018 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 12019 map->value_size, off); 12020 fdput(f); 12021 return err; 12022 } 12023 12024 aux->map_off = off; 12025 addr += off; 12026 } 12027 12028 insn[0].imm = (u32)addr; 12029 insn[1].imm = addr >> 32; 12030 12031 /* check whether we recorded this map already */ 12032 for (j = 0; j < env->used_map_cnt; j++) { 12033 if (env->used_maps[j] == map) { 12034 aux->map_index = j; 12035 fdput(f); 12036 goto next_insn; 12037 } 12038 } 12039 12040 if (env->used_map_cnt >= MAX_USED_MAPS) { 12041 fdput(f); 12042 return -E2BIG; 12043 } 12044 12045 /* hold the map. If the program is rejected by verifier, 12046 * the map will be released by release_maps() or it 12047 * will be used by the valid program until it's unloaded 12048 * and all maps are released in free_used_maps() 12049 */ 12050 bpf_map_inc(map); 12051 12052 aux->map_index = env->used_map_cnt; 12053 env->used_maps[env->used_map_cnt++] = map; 12054 12055 if (bpf_map_is_cgroup_storage(map) && 12056 bpf_cgroup_storage_assign(env->prog->aux, map)) { 12057 verbose(env, "only one cgroup storage of each type is allowed\n"); 12058 fdput(f); 12059 return -EBUSY; 12060 } 12061 12062 fdput(f); 12063 next_insn: 12064 insn++; 12065 i++; 12066 continue; 12067 } 12068 12069 /* Basic sanity check before we invest more work here. */ 12070 if (!bpf_opcode_in_insntable(insn->code)) { 12071 verbose(env, "unknown opcode %02x\n", insn->code); 12072 return -EINVAL; 12073 } 12074 } 12075 12076 /* now all pseudo BPF_LD_IMM64 instructions load valid 12077 * 'struct bpf_map *' into a register instead of user map_fd. 12078 * These pointers will be used later by verifier to validate map access. 12079 */ 12080 return 0; 12081 } 12082 12083 /* drop refcnt of maps used by the rejected program */ 12084 static void release_maps(struct bpf_verifier_env *env) 12085 { 12086 __bpf_free_used_maps(env->prog->aux, env->used_maps, 12087 env->used_map_cnt); 12088 } 12089 12090 /* drop refcnt of maps used by the rejected program */ 12091 static void release_btfs(struct bpf_verifier_env *env) 12092 { 12093 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 12094 env->used_btf_cnt); 12095 } 12096 12097 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 12098 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 12099 { 12100 struct bpf_insn *insn = env->prog->insnsi; 12101 int insn_cnt = env->prog->len; 12102 int i; 12103 12104 for (i = 0; i < insn_cnt; i++, insn++) { 12105 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 12106 continue; 12107 if (insn->src_reg == BPF_PSEUDO_FUNC) 12108 continue; 12109 insn->src_reg = 0; 12110 } 12111 } 12112 12113 /* single env->prog->insni[off] instruction was replaced with the range 12114 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 12115 * [0, off) and [off, end) to new locations, so the patched range stays zero 12116 */ 12117 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 12118 struct bpf_insn_aux_data *new_data, 12119 struct bpf_prog *new_prog, u32 off, u32 cnt) 12120 { 12121 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 12122 struct bpf_insn *insn = new_prog->insnsi; 12123 u32 old_seen = old_data[off].seen; 12124 u32 prog_len; 12125 int i; 12126 12127 /* aux info at OFF always needs adjustment, no matter fast path 12128 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 12129 * original insn at old prog. 12130 */ 12131 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 12132 12133 if (cnt == 1) 12134 return; 12135 prog_len = new_prog->len; 12136 12137 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 12138 memcpy(new_data + off + cnt - 1, old_data + off, 12139 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 12140 for (i = off; i < off + cnt - 1; i++) { 12141 /* Expand insni[off]'s seen count to the patched range. */ 12142 new_data[i].seen = old_seen; 12143 new_data[i].zext_dst = insn_has_def32(env, insn + i); 12144 } 12145 env->insn_aux_data = new_data; 12146 vfree(old_data); 12147 } 12148 12149 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 12150 { 12151 int i; 12152 12153 if (len == 1) 12154 return; 12155 /* NOTE: fake 'exit' subprog should be updated as well. */ 12156 for (i = 0; i <= env->subprog_cnt; i++) { 12157 if (env->subprog_info[i].start <= off) 12158 continue; 12159 env->subprog_info[i].start += len - 1; 12160 } 12161 } 12162 12163 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 12164 { 12165 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 12166 int i, sz = prog->aux->size_poke_tab; 12167 struct bpf_jit_poke_descriptor *desc; 12168 12169 for (i = 0; i < sz; i++) { 12170 desc = &tab[i]; 12171 if (desc->insn_idx <= off) 12172 continue; 12173 desc->insn_idx += len - 1; 12174 } 12175 } 12176 12177 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 12178 const struct bpf_insn *patch, u32 len) 12179 { 12180 struct bpf_prog *new_prog; 12181 struct bpf_insn_aux_data *new_data = NULL; 12182 12183 if (len > 1) { 12184 new_data = vzalloc(array_size(env->prog->len + len - 1, 12185 sizeof(struct bpf_insn_aux_data))); 12186 if (!new_data) 12187 return NULL; 12188 } 12189 12190 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 12191 if (IS_ERR(new_prog)) { 12192 if (PTR_ERR(new_prog) == -ERANGE) 12193 verbose(env, 12194 "insn %d cannot be patched due to 16-bit range\n", 12195 env->insn_aux_data[off].orig_idx); 12196 vfree(new_data); 12197 return NULL; 12198 } 12199 adjust_insn_aux_data(env, new_data, new_prog, off, len); 12200 adjust_subprog_starts(env, off, len); 12201 adjust_poke_descs(new_prog, off, len); 12202 return new_prog; 12203 } 12204 12205 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 12206 u32 off, u32 cnt) 12207 { 12208 int i, j; 12209 12210 /* find first prog starting at or after off (first to remove) */ 12211 for (i = 0; i < env->subprog_cnt; i++) 12212 if (env->subprog_info[i].start >= off) 12213 break; 12214 /* find first prog starting at or after off + cnt (first to stay) */ 12215 for (j = i; j < env->subprog_cnt; j++) 12216 if (env->subprog_info[j].start >= off + cnt) 12217 break; 12218 /* if j doesn't start exactly at off + cnt, we are just removing 12219 * the front of previous prog 12220 */ 12221 if (env->subprog_info[j].start != off + cnt) 12222 j--; 12223 12224 if (j > i) { 12225 struct bpf_prog_aux *aux = env->prog->aux; 12226 int move; 12227 12228 /* move fake 'exit' subprog as well */ 12229 move = env->subprog_cnt + 1 - j; 12230 12231 memmove(env->subprog_info + i, 12232 env->subprog_info + j, 12233 sizeof(*env->subprog_info) * move); 12234 env->subprog_cnt -= j - i; 12235 12236 /* remove func_info */ 12237 if (aux->func_info) { 12238 move = aux->func_info_cnt - j; 12239 12240 memmove(aux->func_info + i, 12241 aux->func_info + j, 12242 sizeof(*aux->func_info) * move); 12243 aux->func_info_cnt -= j - i; 12244 /* func_info->insn_off is set after all code rewrites, 12245 * in adjust_btf_func() - no need to adjust 12246 */ 12247 } 12248 } else { 12249 /* convert i from "first prog to remove" to "first to adjust" */ 12250 if (env->subprog_info[i].start == off) 12251 i++; 12252 } 12253 12254 /* update fake 'exit' subprog as well */ 12255 for (; i <= env->subprog_cnt; i++) 12256 env->subprog_info[i].start -= cnt; 12257 12258 return 0; 12259 } 12260 12261 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 12262 u32 cnt) 12263 { 12264 struct bpf_prog *prog = env->prog; 12265 u32 i, l_off, l_cnt, nr_linfo; 12266 struct bpf_line_info *linfo; 12267 12268 nr_linfo = prog->aux->nr_linfo; 12269 if (!nr_linfo) 12270 return 0; 12271 12272 linfo = prog->aux->linfo; 12273 12274 /* find first line info to remove, count lines to be removed */ 12275 for (i = 0; i < nr_linfo; i++) 12276 if (linfo[i].insn_off >= off) 12277 break; 12278 12279 l_off = i; 12280 l_cnt = 0; 12281 for (; i < nr_linfo; i++) 12282 if (linfo[i].insn_off < off + cnt) 12283 l_cnt++; 12284 else 12285 break; 12286 12287 /* First live insn doesn't match first live linfo, it needs to "inherit" 12288 * last removed linfo. prog is already modified, so prog->len == off 12289 * means no live instructions after (tail of the program was removed). 12290 */ 12291 if (prog->len != off && l_cnt && 12292 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 12293 l_cnt--; 12294 linfo[--i].insn_off = off + cnt; 12295 } 12296 12297 /* remove the line info which refer to the removed instructions */ 12298 if (l_cnt) { 12299 memmove(linfo + l_off, linfo + i, 12300 sizeof(*linfo) * (nr_linfo - i)); 12301 12302 prog->aux->nr_linfo -= l_cnt; 12303 nr_linfo = prog->aux->nr_linfo; 12304 } 12305 12306 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 12307 for (i = l_off; i < nr_linfo; i++) 12308 linfo[i].insn_off -= cnt; 12309 12310 /* fix up all subprogs (incl. 'exit') which start >= off */ 12311 for (i = 0; i <= env->subprog_cnt; i++) 12312 if (env->subprog_info[i].linfo_idx > l_off) { 12313 /* program may have started in the removed region but 12314 * may not be fully removed 12315 */ 12316 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 12317 env->subprog_info[i].linfo_idx -= l_cnt; 12318 else 12319 env->subprog_info[i].linfo_idx = l_off; 12320 } 12321 12322 return 0; 12323 } 12324 12325 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 12326 { 12327 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 12328 unsigned int orig_prog_len = env->prog->len; 12329 int err; 12330 12331 if (bpf_prog_is_dev_bound(env->prog->aux)) 12332 bpf_prog_offload_remove_insns(env, off, cnt); 12333 12334 err = bpf_remove_insns(env->prog, off, cnt); 12335 if (err) 12336 return err; 12337 12338 err = adjust_subprog_starts_after_remove(env, off, cnt); 12339 if (err) 12340 return err; 12341 12342 err = bpf_adj_linfo_after_remove(env, off, cnt); 12343 if (err) 12344 return err; 12345 12346 memmove(aux_data + off, aux_data + off + cnt, 12347 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 12348 12349 return 0; 12350 } 12351 12352 /* The verifier does more data flow analysis than llvm and will not 12353 * explore branches that are dead at run time. Malicious programs can 12354 * have dead code too. Therefore replace all dead at-run-time code 12355 * with 'ja -1'. 12356 * 12357 * Just nops are not optimal, e.g. if they would sit at the end of the 12358 * program and through another bug we would manage to jump there, then 12359 * we'd execute beyond program memory otherwise. Returning exception 12360 * code also wouldn't work since we can have subprogs where the dead 12361 * code could be located. 12362 */ 12363 static void sanitize_dead_code(struct bpf_verifier_env *env) 12364 { 12365 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 12366 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 12367 struct bpf_insn *insn = env->prog->insnsi; 12368 const int insn_cnt = env->prog->len; 12369 int i; 12370 12371 for (i = 0; i < insn_cnt; i++) { 12372 if (aux_data[i].seen) 12373 continue; 12374 memcpy(insn + i, &trap, sizeof(trap)); 12375 aux_data[i].zext_dst = false; 12376 } 12377 } 12378 12379 static bool insn_is_cond_jump(u8 code) 12380 { 12381 u8 op; 12382 12383 if (BPF_CLASS(code) == BPF_JMP32) 12384 return true; 12385 12386 if (BPF_CLASS(code) != BPF_JMP) 12387 return false; 12388 12389 op = BPF_OP(code); 12390 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 12391 } 12392 12393 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 12394 { 12395 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 12396 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 12397 struct bpf_insn *insn = env->prog->insnsi; 12398 const int insn_cnt = env->prog->len; 12399 int i; 12400 12401 for (i = 0; i < insn_cnt; i++, insn++) { 12402 if (!insn_is_cond_jump(insn->code)) 12403 continue; 12404 12405 if (!aux_data[i + 1].seen) 12406 ja.off = insn->off; 12407 else if (!aux_data[i + 1 + insn->off].seen) 12408 ja.off = 0; 12409 else 12410 continue; 12411 12412 if (bpf_prog_is_dev_bound(env->prog->aux)) 12413 bpf_prog_offload_replace_insn(env, i, &ja); 12414 12415 memcpy(insn, &ja, sizeof(ja)); 12416 } 12417 } 12418 12419 static int opt_remove_dead_code(struct bpf_verifier_env *env) 12420 { 12421 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 12422 int insn_cnt = env->prog->len; 12423 int i, err; 12424 12425 for (i = 0; i < insn_cnt; i++) { 12426 int j; 12427 12428 j = 0; 12429 while (i + j < insn_cnt && !aux_data[i + j].seen) 12430 j++; 12431 if (!j) 12432 continue; 12433 12434 err = verifier_remove_insns(env, i, j); 12435 if (err) 12436 return err; 12437 insn_cnt = env->prog->len; 12438 } 12439 12440 return 0; 12441 } 12442 12443 static int opt_remove_nops(struct bpf_verifier_env *env) 12444 { 12445 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 12446 struct bpf_insn *insn = env->prog->insnsi; 12447 int insn_cnt = env->prog->len; 12448 int i, err; 12449 12450 for (i = 0; i < insn_cnt; i++) { 12451 if (memcmp(&insn[i], &ja, sizeof(ja))) 12452 continue; 12453 12454 err = verifier_remove_insns(env, i, 1); 12455 if (err) 12456 return err; 12457 insn_cnt--; 12458 i--; 12459 } 12460 12461 return 0; 12462 } 12463 12464 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 12465 const union bpf_attr *attr) 12466 { 12467 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 12468 struct bpf_insn_aux_data *aux = env->insn_aux_data; 12469 int i, patch_len, delta = 0, len = env->prog->len; 12470 struct bpf_insn *insns = env->prog->insnsi; 12471 struct bpf_prog *new_prog; 12472 bool rnd_hi32; 12473 12474 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 12475 zext_patch[1] = BPF_ZEXT_REG(0); 12476 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 12477 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 12478 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 12479 for (i = 0; i < len; i++) { 12480 int adj_idx = i + delta; 12481 struct bpf_insn insn; 12482 int load_reg; 12483 12484 insn = insns[adj_idx]; 12485 load_reg = insn_def_regno(&insn); 12486 if (!aux[adj_idx].zext_dst) { 12487 u8 code, class; 12488 u32 imm_rnd; 12489 12490 if (!rnd_hi32) 12491 continue; 12492 12493 code = insn.code; 12494 class = BPF_CLASS(code); 12495 if (load_reg == -1) 12496 continue; 12497 12498 /* NOTE: arg "reg" (the fourth one) is only used for 12499 * BPF_STX + SRC_OP, so it is safe to pass NULL 12500 * here. 12501 */ 12502 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 12503 if (class == BPF_LD && 12504 BPF_MODE(code) == BPF_IMM) 12505 i++; 12506 continue; 12507 } 12508 12509 /* ctx load could be transformed into wider load. */ 12510 if (class == BPF_LDX && 12511 aux[adj_idx].ptr_type == PTR_TO_CTX) 12512 continue; 12513 12514 imm_rnd = get_random_int(); 12515 rnd_hi32_patch[0] = insn; 12516 rnd_hi32_patch[1].imm = imm_rnd; 12517 rnd_hi32_patch[3].dst_reg = load_reg; 12518 patch = rnd_hi32_patch; 12519 patch_len = 4; 12520 goto apply_patch_buffer; 12521 } 12522 12523 /* Add in an zero-extend instruction if a) the JIT has requested 12524 * it or b) it's a CMPXCHG. 12525 * 12526 * The latter is because: BPF_CMPXCHG always loads a value into 12527 * R0, therefore always zero-extends. However some archs' 12528 * equivalent instruction only does this load when the 12529 * comparison is successful. This detail of CMPXCHG is 12530 * orthogonal to the general zero-extension behaviour of the 12531 * CPU, so it's treated independently of bpf_jit_needs_zext. 12532 */ 12533 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 12534 continue; 12535 12536 if (WARN_ON(load_reg == -1)) { 12537 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 12538 return -EFAULT; 12539 } 12540 12541 zext_patch[0] = insn; 12542 zext_patch[1].dst_reg = load_reg; 12543 zext_patch[1].src_reg = load_reg; 12544 patch = zext_patch; 12545 patch_len = 2; 12546 apply_patch_buffer: 12547 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 12548 if (!new_prog) 12549 return -ENOMEM; 12550 env->prog = new_prog; 12551 insns = new_prog->insnsi; 12552 aux = env->insn_aux_data; 12553 delta += patch_len - 1; 12554 } 12555 12556 return 0; 12557 } 12558 12559 /* convert load instructions that access fields of a context type into a 12560 * sequence of instructions that access fields of the underlying structure: 12561 * struct __sk_buff -> struct sk_buff 12562 * struct bpf_sock_ops -> struct sock 12563 */ 12564 static int convert_ctx_accesses(struct bpf_verifier_env *env) 12565 { 12566 const struct bpf_verifier_ops *ops = env->ops; 12567 int i, cnt, size, ctx_field_size, delta = 0; 12568 const int insn_cnt = env->prog->len; 12569 struct bpf_insn insn_buf[16], *insn; 12570 u32 target_size, size_default, off; 12571 struct bpf_prog *new_prog; 12572 enum bpf_access_type type; 12573 bool is_narrower_load; 12574 12575 if (ops->gen_prologue || env->seen_direct_write) { 12576 if (!ops->gen_prologue) { 12577 verbose(env, "bpf verifier is misconfigured\n"); 12578 return -EINVAL; 12579 } 12580 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 12581 env->prog); 12582 if (cnt >= ARRAY_SIZE(insn_buf)) { 12583 verbose(env, "bpf verifier is misconfigured\n"); 12584 return -EINVAL; 12585 } else if (cnt) { 12586 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 12587 if (!new_prog) 12588 return -ENOMEM; 12589 12590 env->prog = new_prog; 12591 delta += cnt - 1; 12592 } 12593 } 12594 12595 if (bpf_prog_is_dev_bound(env->prog->aux)) 12596 return 0; 12597 12598 insn = env->prog->insnsi + delta; 12599 12600 for (i = 0; i < insn_cnt; i++, insn++) { 12601 bpf_convert_ctx_access_t convert_ctx_access; 12602 bool ctx_access; 12603 12604 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 12605 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 12606 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 12607 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) { 12608 type = BPF_READ; 12609 ctx_access = true; 12610 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 12611 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 12612 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 12613 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 12614 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 12615 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 12616 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 12617 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 12618 type = BPF_WRITE; 12619 ctx_access = BPF_CLASS(insn->code) == BPF_STX; 12620 } else { 12621 continue; 12622 } 12623 12624 if (type == BPF_WRITE && 12625 env->insn_aux_data[i + delta].sanitize_stack_spill) { 12626 struct bpf_insn patch[] = { 12627 *insn, 12628 BPF_ST_NOSPEC(), 12629 }; 12630 12631 cnt = ARRAY_SIZE(patch); 12632 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 12633 if (!new_prog) 12634 return -ENOMEM; 12635 12636 delta += cnt - 1; 12637 env->prog = new_prog; 12638 insn = new_prog->insnsi + i + delta; 12639 continue; 12640 } 12641 12642 if (!ctx_access) 12643 continue; 12644 12645 switch (env->insn_aux_data[i + delta].ptr_type) { 12646 case PTR_TO_CTX: 12647 if (!ops->convert_ctx_access) 12648 continue; 12649 convert_ctx_access = ops->convert_ctx_access; 12650 break; 12651 case PTR_TO_SOCKET: 12652 case PTR_TO_SOCK_COMMON: 12653 convert_ctx_access = bpf_sock_convert_ctx_access; 12654 break; 12655 case PTR_TO_TCP_SOCK: 12656 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 12657 break; 12658 case PTR_TO_XDP_SOCK: 12659 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 12660 break; 12661 case PTR_TO_BTF_ID: 12662 if (type == BPF_READ) { 12663 insn->code = BPF_LDX | BPF_PROBE_MEM | 12664 BPF_SIZE((insn)->code); 12665 env->prog->aux->num_exentries++; 12666 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) { 12667 verbose(env, "Writes through BTF pointers are not allowed\n"); 12668 return -EINVAL; 12669 } 12670 continue; 12671 default: 12672 continue; 12673 } 12674 12675 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 12676 size = BPF_LDST_BYTES(insn); 12677 12678 /* If the read access is a narrower load of the field, 12679 * convert to a 4/8-byte load, to minimum program type specific 12680 * convert_ctx_access changes. If conversion is successful, 12681 * we will apply proper mask to the result. 12682 */ 12683 is_narrower_load = size < ctx_field_size; 12684 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 12685 off = insn->off; 12686 if (is_narrower_load) { 12687 u8 size_code; 12688 12689 if (type == BPF_WRITE) { 12690 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 12691 return -EINVAL; 12692 } 12693 12694 size_code = BPF_H; 12695 if (ctx_field_size == 4) 12696 size_code = BPF_W; 12697 else if (ctx_field_size == 8) 12698 size_code = BPF_DW; 12699 12700 insn->off = off & ~(size_default - 1); 12701 insn->code = BPF_LDX | BPF_MEM | size_code; 12702 } 12703 12704 target_size = 0; 12705 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 12706 &target_size); 12707 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 12708 (ctx_field_size && !target_size)) { 12709 verbose(env, "bpf verifier is misconfigured\n"); 12710 return -EINVAL; 12711 } 12712 12713 if (is_narrower_load && size < target_size) { 12714 u8 shift = bpf_ctx_narrow_access_offset( 12715 off, size, size_default) * 8; 12716 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 12717 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 12718 return -EINVAL; 12719 } 12720 if (ctx_field_size <= 4) { 12721 if (shift) 12722 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 12723 insn->dst_reg, 12724 shift); 12725 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 12726 (1 << size * 8) - 1); 12727 } else { 12728 if (shift) 12729 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 12730 insn->dst_reg, 12731 shift); 12732 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 12733 (1ULL << size * 8) - 1); 12734 } 12735 } 12736 12737 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12738 if (!new_prog) 12739 return -ENOMEM; 12740 12741 delta += cnt - 1; 12742 12743 /* keep walking new program and skip insns we just inserted */ 12744 env->prog = new_prog; 12745 insn = new_prog->insnsi + i + delta; 12746 } 12747 12748 return 0; 12749 } 12750 12751 static int jit_subprogs(struct bpf_verifier_env *env) 12752 { 12753 struct bpf_prog *prog = env->prog, **func, *tmp; 12754 int i, j, subprog_start, subprog_end = 0, len, subprog; 12755 struct bpf_map *map_ptr; 12756 struct bpf_insn *insn; 12757 void *old_bpf_func; 12758 int err, num_exentries; 12759 12760 if (env->subprog_cnt <= 1) 12761 return 0; 12762 12763 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 12764 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn)) 12765 continue; 12766 12767 /* Upon error here we cannot fall back to interpreter but 12768 * need a hard reject of the program. Thus -EFAULT is 12769 * propagated in any case. 12770 */ 12771 subprog = find_subprog(env, i + insn->imm + 1); 12772 if (subprog < 0) { 12773 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 12774 i + insn->imm + 1); 12775 return -EFAULT; 12776 } 12777 /* temporarily remember subprog id inside insn instead of 12778 * aux_data, since next loop will split up all insns into funcs 12779 */ 12780 insn->off = subprog; 12781 /* remember original imm in case JIT fails and fallback 12782 * to interpreter will be needed 12783 */ 12784 env->insn_aux_data[i].call_imm = insn->imm; 12785 /* point imm to __bpf_call_base+1 from JITs point of view */ 12786 insn->imm = 1; 12787 if (bpf_pseudo_func(insn)) 12788 /* jit (e.g. x86_64) may emit fewer instructions 12789 * if it learns a u32 imm is the same as a u64 imm. 12790 * Force a non zero here. 12791 */ 12792 insn[1].imm = 1; 12793 } 12794 12795 err = bpf_prog_alloc_jited_linfo(prog); 12796 if (err) 12797 goto out_undo_insn; 12798 12799 err = -ENOMEM; 12800 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 12801 if (!func) 12802 goto out_undo_insn; 12803 12804 for (i = 0; i < env->subprog_cnt; i++) { 12805 subprog_start = subprog_end; 12806 subprog_end = env->subprog_info[i + 1].start; 12807 12808 len = subprog_end - subprog_start; 12809 /* bpf_prog_run() doesn't call subprogs directly, 12810 * hence main prog stats include the runtime of subprogs. 12811 * subprogs don't have IDs and not reachable via prog_get_next_id 12812 * func[i]->stats will never be accessed and stays NULL 12813 */ 12814 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 12815 if (!func[i]) 12816 goto out_free; 12817 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 12818 len * sizeof(struct bpf_insn)); 12819 func[i]->type = prog->type; 12820 func[i]->len = len; 12821 if (bpf_prog_calc_tag(func[i])) 12822 goto out_free; 12823 func[i]->is_func = 1; 12824 func[i]->aux->func_idx = i; 12825 /* Below members will be freed only at prog->aux */ 12826 func[i]->aux->btf = prog->aux->btf; 12827 func[i]->aux->func_info = prog->aux->func_info; 12828 func[i]->aux->poke_tab = prog->aux->poke_tab; 12829 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 12830 12831 for (j = 0; j < prog->aux->size_poke_tab; j++) { 12832 struct bpf_jit_poke_descriptor *poke; 12833 12834 poke = &prog->aux->poke_tab[j]; 12835 if (poke->insn_idx < subprog_end && 12836 poke->insn_idx >= subprog_start) 12837 poke->aux = func[i]->aux; 12838 } 12839 12840 /* Use bpf_prog_F_tag to indicate functions in stack traces. 12841 * Long term would need debug info to populate names 12842 */ 12843 func[i]->aux->name[0] = 'F'; 12844 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 12845 func[i]->jit_requested = 1; 12846 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 12847 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 12848 func[i]->aux->linfo = prog->aux->linfo; 12849 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 12850 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 12851 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 12852 num_exentries = 0; 12853 insn = func[i]->insnsi; 12854 for (j = 0; j < func[i]->len; j++, insn++) { 12855 if (BPF_CLASS(insn->code) == BPF_LDX && 12856 BPF_MODE(insn->code) == BPF_PROBE_MEM) 12857 num_exentries++; 12858 } 12859 func[i]->aux->num_exentries = num_exentries; 12860 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 12861 func[i] = bpf_int_jit_compile(func[i]); 12862 if (!func[i]->jited) { 12863 err = -ENOTSUPP; 12864 goto out_free; 12865 } 12866 cond_resched(); 12867 } 12868 12869 /* at this point all bpf functions were successfully JITed 12870 * now populate all bpf_calls with correct addresses and 12871 * run last pass of JIT 12872 */ 12873 for (i = 0; i < env->subprog_cnt; i++) { 12874 insn = func[i]->insnsi; 12875 for (j = 0; j < func[i]->len; j++, insn++) { 12876 if (bpf_pseudo_func(insn)) { 12877 subprog = insn->off; 12878 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 12879 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 12880 continue; 12881 } 12882 if (!bpf_pseudo_call(insn)) 12883 continue; 12884 subprog = insn->off; 12885 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 12886 } 12887 12888 /* we use the aux data to keep a list of the start addresses 12889 * of the JITed images for each function in the program 12890 * 12891 * for some architectures, such as powerpc64, the imm field 12892 * might not be large enough to hold the offset of the start 12893 * address of the callee's JITed image from __bpf_call_base 12894 * 12895 * in such cases, we can lookup the start address of a callee 12896 * by using its subprog id, available from the off field of 12897 * the call instruction, as an index for this list 12898 */ 12899 func[i]->aux->func = func; 12900 func[i]->aux->func_cnt = env->subprog_cnt; 12901 } 12902 for (i = 0; i < env->subprog_cnt; i++) { 12903 old_bpf_func = func[i]->bpf_func; 12904 tmp = bpf_int_jit_compile(func[i]); 12905 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 12906 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 12907 err = -ENOTSUPP; 12908 goto out_free; 12909 } 12910 cond_resched(); 12911 } 12912 12913 /* finally lock prog and jit images for all functions and 12914 * populate kallsysm 12915 */ 12916 for (i = 0; i < env->subprog_cnt; i++) { 12917 bpf_prog_lock_ro(func[i]); 12918 bpf_prog_kallsyms_add(func[i]); 12919 } 12920 12921 /* Last step: make now unused interpreter insns from main 12922 * prog consistent for later dump requests, so they can 12923 * later look the same as if they were interpreted only. 12924 */ 12925 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 12926 if (bpf_pseudo_func(insn)) { 12927 insn[0].imm = env->insn_aux_data[i].call_imm; 12928 insn[1].imm = insn->off; 12929 insn->off = 0; 12930 continue; 12931 } 12932 if (!bpf_pseudo_call(insn)) 12933 continue; 12934 insn->off = env->insn_aux_data[i].call_imm; 12935 subprog = find_subprog(env, i + insn->off + 1); 12936 insn->imm = subprog; 12937 } 12938 12939 prog->jited = 1; 12940 prog->bpf_func = func[0]->bpf_func; 12941 prog->aux->func = func; 12942 prog->aux->func_cnt = env->subprog_cnt; 12943 bpf_prog_jit_attempt_done(prog); 12944 return 0; 12945 out_free: 12946 /* We failed JIT'ing, so at this point we need to unregister poke 12947 * descriptors from subprogs, so that kernel is not attempting to 12948 * patch it anymore as we're freeing the subprog JIT memory. 12949 */ 12950 for (i = 0; i < prog->aux->size_poke_tab; i++) { 12951 map_ptr = prog->aux->poke_tab[i].tail_call.map; 12952 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 12953 } 12954 /* At this point we're guaranteed that poke descriptors are not 12955 * live anymore. We can just unlink its descriptor table as it's 12956 * released with the main prog. 12957 */ 12958 for (i = 0; i < env->subprog_cnt; i++) { 12959 if (!func[i]) 12960 continue; 12961 func[i]->aux->poke_tab = NULL; 12962 bpf_jit_free(func[i]); 12963 } 12964 kfree(func); 12965 out_undo_insn: 12966 /* cleanup main prog to be interpreted */ 12967 prog->jit_requested = 0; 12968 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 12969 if (!bpf_pseudo_call(insn)) 12970 continue; 12971 insn->off = 0; 12972 insn->imm = env->insn_aux_data[i].call_imm; 12973 } 12974 bpf_prog_jit_attempt_done(prog); 12975 return err; 12976 } 12977 12978 static int fixup_call_args(struct bpf_verifier_env *env) 12979 { 12980 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 12981 struct bpf_prog *prog = env->prog; 12982 struct bpf_insn *insn = prog->insnsi; 12983 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 12984 int i, depth; 12985 #endif 12986 int err = 0; 12987 12988 if (env->prog->jit_requested && 12989 !bpf_prog_is_dev_bound(env->prog->aux)) { 12990 err = jit_subprogs(env); 12991 if (err == 0) 12992 return 0; 12993 if (err == -EFAULT) 12994 return err; 12995 } 12996 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 12997 if (has_kfunc_call) { 12998 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 12999 return -EINVAL; 13000 } 13001 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 13002 /* When JIT fails the progs with bpf2bpf calls and tail_calls 13003 * have to be rejected, since interpreter doesn't support them yet. 13004 */ 13005 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 13006 return -EINVAL; 13007 } 13008 for (i = 0; i < prog->len; i++, insn++) { 13009 if (bpf_pseudo_func(insn)) { 13010 /* When JIT fails the progs with callback calls 13011 * have to be rejected, since interpreter doesn't support them yet. 13012 */ 13013 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 13014 return -EINVAL; 13015 } 13016 13017 if (!bpf_pseudo_call(insn)) 13018 continue; 13019 depth = get_callee_stack_depth(env, insn, i); 13020 if (depth < 0) 13021 return depth; 13022 bpf_patch_call_args(insn, depth); 13023 } 13024 err = 0; 13025 #endif 13026 return err; 13027 } 13028 13029 static int fixup_kfunc_call(struct bpf_verifier_env *env, 13030 struct bpf_insn *insn) 13031 { 13032 const struct bpf_kfunc_desc *desc; 13033 13034 if (!insn->imm) { 13035 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 13036 return -EINVAL; 13037 } 13038 13039 /* insn->imm has the btf func_id. Replace it with 13040 * an address (relative to __bpf_base_call). 13041 */ 13042 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 13043 if (!desc) { 13044 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 13045 insn->imm); 13046 return -EFAULT; 13047 } 13048 13049 insn->imm = desc->imm; 13050 13051 return 0; 13052 } 13053 13054 /* Do various post-verification rewrites in a single program pass. 13055 * These rewrites simplify JIT and interpreter implementations. 13056 */ 13057 static int do_misc_fixups(struct bpf_verifier_env *env) 13058 { 13059 struct bpf_prog *prog = env->prog; 13060 enum bpf_attach_type eatype = prog->expected_attach_type; 13061 bool expect_blinding = bpf_jit_blinding_enabled(prog); 13062 enum bpf_prog_type prog_type = resolve_prog_type(prog); 13063 struct bpf_insn *insn = prog->insnsi; 13064 const struct bpf_func_proto *fn; 13065 const int insn_cnt = prog->len; 13066 const struct bpf_map_ops *ops; 13067 struct bpf_insn_aux_data *aux; 13068 struct bpf_insn insn_buf[16]; 13069 struct bpf_prog *new_prog; 13070 struct bpf_map *map_ptr; 13071 int i, ret, cnt, delta = 0; 13072 13073 for (i = 0; i < insn_cnt; i++, insn++) { 13074 /* Make divide-by-zero exceptions impossible. */ 13075 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 13076 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 13077 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 13078 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 13079 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 13080 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 13081 struct bpf_insn *patchlet; 13082 struct bpf_insn chk_and_div[] = { 13083 /* [R,W]x div 0 -> 0 */ 13084 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 13085 BPF_JNE | BPF_K, insn->src_reg, 13086 0, 2, 0), 13087 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 13088 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 13089 *insn, 13090 }; 13091 struct bpf_insn chk_and_mod[] = { 13092 /* [R,W]x mod 0 -> [R,W]x */ 13093 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 13094 BPF_JEQ | BPF_K, insn->src_reg, 13095 0, 1 + (is64 ? 0 : 1), 0), 13096 *insn, 13097 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 13098 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 13099 }; 13100 13101 patchlet = isdiv ? chk_and_div : chk_and_mod; 13102 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 13103 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 13104 13105 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 13106 if (!new_prog) 13107 return -ENOMEM; 13108 13109 delta += cnt - 1; 13110 env->prog = prog = new_prog; 13111 insn = new_prog->insnsi + i + delta; 13112 continue; 13113 } 13114 13115 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 13116 if (BPF_CLASS(insn->code) == BPF_LD && 13117 (BPF_MODE(insn->code) == BPF_ABS || 13118 BPF_MODE(insn->code) == BPF_IND)) { 13119 cnt = env->ops->gen_ld_abs(insn, insn_buf); 13120 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 13121 verbose(env, "bpf verifier is misconfigured\n"); 13122 return -EINVAL; 13123 } 13124 13125 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 13126 if (!new_prog) 13127 return -ENOMEM; 13128 13129 delta += cnt - 1; 13130 env->prog = prog = new_prog; 13131 insn = new_prog->insnsi + i + delta; 13132 continue; 13133 } 13134 13135 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 13136 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 13137 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 13138 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 13139 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 13140 struct bpf_insn *patch = &insn_buf[0]; 13141 bool issrc, isneg, isimm; 13142 u32 off_reg; 13143 13144 aux = &env->insn_aux_data[i + delta]; 13145 if (!aux->alu_state || 13146 aux->alu_state == BPF_ALU_NON_POINTER) 13147 continue; 13148 13149 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 13150 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 13151 BPF_ALU_SANITIZE_SRC; 13152 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 13153 13154 off_reg = issrc ? insn->src_reg : insn->dst_reg; 13155 if (isimm) { 13156 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 13157 } else { 13158 if (isneg) 13159 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 13160 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 13161 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 13162 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 13163 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 13164 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 13165 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 13166 } 13167 if (!issrc) 13168 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 13169 insn->src_reg = BPF_REG_AX; 13170 if (isneg) 13171 insn->code = insn->code == code_add ? 13172 code_sub : code_add; 13173 *patch++ = *insn; 13174 if (issrc && isneg && !isimm) 13175 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 13176 cnt = patch - insn_buf; 13177 13178 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 13179 if (!new_prog) 13180 return -ENOMEM; 13181 13182 delta += cnt - 1; 13183 env->prog = prog = new_prog; 13184 insn = new_prog->insnsi + i + delta; 13185 continue; 13186 } 13187 13188 if (insn->code != (BPF_JMP | BPF_CALL)) 13189 continue; 13190 if (insn->src_reg == BPF_PSEUDO_CALL) 13191 continue; 13192 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 13193 ret = fixup_kfunc_call(env, insn); 13194 if (ret) 13195 return ret; 13196 continue; 13197 } 13198 13199 if (insn->imm == BPF_FUNC_get_route_realm) 13200 prog->dst_needed = 1; 13201 if (insn->imm == BPF_FUNC_get_prandom_u32) 13202 bpf_user_rnd_init_once(); 13203 if (insn->imm == BPF_FUNC_override_return) 13204 prog->kprobe_override = 1; 13205 if (insn->imm == BPF_FUNC_tail_call) { 13206 /* If we tail call into other programs, we 13207 * cannot make any assumptions since they can 13208 * be replaced dynamically during runtime in 13209 * the program array. 13210 */ 13211 prog->cb_access = 1; 13212 if (!allow_tail_call_in_subprogs(env)) 13213 prog->aux->stack_depth = MAX_BPF_STACK; 13214 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 13215 13216 /* mark bpf_tail_call as different opcode to avoid 13217 * conditional branch in the interpreter for every normal 13218 * call and to prevent accidental JITing by JIT compiler 13219 * that doesn't support bpf_tail_call yet 13220 */ 13221 insn->imm = 0; 13222 insn->code = BPF_JMP | BPF_TAIL_CALL; 13223 13224 aux = &env->insn_aux_data[i + delta]; 13225 if (env->bpf_capable && !expect_blinding && 13226 prog->jit_requested && 13227 !bpf_map_key_poisoned(aux) && 13228 !bpf_map_ptr_poisoned(aux) && 13229 !bpf_map_ptr_unpriv(aux)) { 13230 struct bpf_jit_poke_descriptor desc = { 13231 .reason = BPF_POKE_REASON_TAIL_CALL, 13232 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 13233 .tail_call.key = bpf_map_key_immediate(aux), 13234 .insn_idx = i + delta, 13235 }; 13236 13237 ret = bpf_jit_add_poke_descriptor(prog, &desc); 13238 if (ret < 0) { 13239 verbose(env, "adding tail call poke descriptor failed\n"); 13240 return ret; 13241 } 13242 13243 insn->imm = ret + 1; 13244 continue; 13245 } 13246 13247 if (!bpf_map_ptr_unpriv(aux)) 13248 continue; 13249 13250 /* instead of changing every JIT dealing with tail_call 13251 * emit two extra insns: 13252 * if (index >= max_entries) goto out; 13253 * index &= array->index_mask; 13254 * to avoid out-of-bounds cpu speculation 13255 */ 13256 if (bpf_map_ptr_poisoned(aux)) { 13257 verbose(env, "tail_call abusing map_ptr\n"); 13258 return -EINVAL; 13259 } 13260 13261 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 13262 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 13263 map_ptr->max_entries, 2); 13264 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 13265 container_of(map_ptr, 13266 struct bpf_array, 13267 map)->index_mask); 13268 insn_buf[2] = *insn; 13269 cnt = 3; 13270 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 13271 if (!new_prog) 13272 return -ENOMEM; 13273 13274 delta += cnt - 1; 13275 env->prog = prog = new_prog; 13276 insn = new_prog->insnsi + i + delta; 13277 continue; 13278 } 13279 13280 if (insn->imm == BPF_FUNC_timer_set_callback) { 13281 /* The verifier will process callback_fn as many times as necessary 13282 * with different maps and the register states prepared by 13283 * set_timer_callback_state will be accurate. 13284 * 13285 * The following use case is valid: 13286 * map1 is shared by prog1, prog2, prog3. 13287 * prog1 calls bpf_timer_init for some map1 elements 13288 * prog2 calls bpf_timer_set_callback for some map1 elements. 13289 * Those that were not bpf_timer_init-ed will return -EINVAL. 13290 * prog3 calls bpf_timer_start for some map1 elements. 13291 * Those that were not both bpf_timer_init-ed and 13292 * bpf_timer_set_callback-ed will return -EINVAL. 13293 */ 13294 struct bpf_insn ld_addrs[2] = { 13295 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 13296 }; 13297 13298 insn_buf[0] = ld_addrs[0]; 13299 insn_buf[1] = ld_addrs[1]; 13300 insn_buf[2] = *insn; 13301 cnt = 3; 13302 13303 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 13304 if (!new_prog) 13305 return -ENOMEM; 13306 13307 delta += cnt - 1; 13308 env->prog = prog = new_prog; 13309 insn = new_prog->insnsi + i + delta; 13310 goto patch_call_imm; 13311 } 13312 13313 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 13314 * and other inlining handlers are currently limited to 64 bit 13315 * only. 13316 */ 13317 if (prog->jit_requested && BITS_PER_LONG == 64 && 13318 (insn->imm == BPF_FUNC_map_lookup_elem || 13319 insn->imm == BPF_FUNC_map_update_elem || 13320 insn->imm == BPF_FUNC_map_delete_elem || 13321 insn->imm == BPF_FUNC_map_push_elem || 13322 insn->imm == BPF_FUNC_map_pop_elem || 13323 insn->imm == BPF_FUNC_map_peek_elem || 13324 insn->imm == BPF_FUNC_redirect_map || 13325 insn->imm == BPF_FUNC_for_each_map_elem)) { 13326 aux = &env->insn_aux_data[i + delta]; 13327 if (bpf_map_ptr_poisoned(aux)) 13328 goto patch_call_imm; 13329 13330 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 13331 ops = map_ptr->ops; 13332 if (insn->imm == BPF_FUNC_map_lookup_elem && 13333 ops->map_gen_lookup) { 13334 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 13335 if (cnt == -EOPNOTSUPP) 13336 goto patch_map_ops_generic; 13337 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 13338 verbose(env, "bpf verifier is misconfigured\n"); 13339 return -EINVAL; 13340 } 13341 13342 new_prog = bpf_patch_insn_data(env, i + delta, 13343 insn_buf, cnt); 13344 if (!new_prog) 13345 return -ENOMEM; 13346 13347 delta += cnt - 1; 13348 env->prog = prog = new_prog; 13349 insn = new_prog->insnsi + i + delta; 13350 continue; 13351 } 13352 13353 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 13354 (void *(*)(struct bpf_map *map, void *key))NULL)); 13355 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 13356 (int (*)(struct bpf_map *map, void *key))NULL)); 13357 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 13358 (int (*)(struct bpf_map *map, void *key, void *value, 13359 u64 flags))NULL)); 13360 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 13361 (int (*)(struct bpf_map *map, void *value, 13362 u64 flags))NULL)); 13363 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 13364 (int (*)(struct bpf_map *map, void *value))NULL)); 13365 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 13366 (int (*)(struct bpf_map *map, void *value))NULL)); 13367 BUILD_BUG_ON(!__same_type(ops->map_redirect, 13368 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL)); 13369 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 13370 (int (*)(struct bpf_map *map, 13371 bpf_callback_t callback_fn, 13372 void *callback_ctx, 13373 u64 flags))NULL)); 13374 13375 patch_map_ops_generic: 13376 switch (insn->imm) { 13377 case BPF_FUNC_map_lookup_elem: 13378 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 13379 continue; 13380 case BPF_FUNC_map_update_elem: 13381 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 13382 continue; 13383 case BPF_FUNC_map_delete_elem: 13384 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 13385 continue; 13386 case BPF_FUNC_map_push_elem: 13387 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 13388 continue; 13389 case BPF_FUNC_map_pop_elem: 13390 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 13391 continue; 13392 case BPF_FUNC_map_peek_elem: 13393 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 13394 continue; 13395 case BPF_FUNC_redirect_map: 13396 insn->imm = BPF_CALL_IMM(ops->map_redirect); 13397 continue; 13398 case BPF_FUNC_for_each_map_elem: 13399 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 13400 continue; 13401 } 13402 13403 goto patch_call_imm; 13404 } 13405 13406 /* Implement bpf_jiffies64 inline. */ 13407 if (prog->jit_requested && BITS_PER_LONG == 64 && 13408 insn->imm == BPF_FUNC_jiffies64) { 13409 struct bpf_insn ld_jiffies_addr[2] = { 13410 BPF_LD_IMM64(BPF_REG_0, 13411 (unsigned long)&jiffies), 13412 }; 13413 13414 insn_buf[0] = ld_jiffies_addr[0]; 13415 insn_buf[1] = ld_jiffies_addr[1]; 13416 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 13417 BPF_REG_0, 0); 13418 cnt = 3; 13419 13420 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 13421 cnt); 13422 if (!new_prog) 13423 return -ENOMEM; 13424 13425 delta += cnt - 1; 13426 env->prog = prog = new_prog; 13427 insn = new_prog->insnsi + i + delta; 13428 continue; 13429 } 13430 13431 /* Implement bpf_get_func_arg inline. */ 13432 if (prog_type == BPF_PROG_TYPE_TRACING && 13433 insn->imm == BPF_FUNC_get_func_arg) { 13434 /* Load nr_args from ctx - 8 */ 13435 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 13436 insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6); 13437 insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3); 13438 insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1); 13439 insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0); 13440 insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 13441 insn_buf[6] = BPF_MOV64_IMM(BPF_REG_0, 0); 13442 insn_buf[7] = BPF_JMP_A(1); 13443 insn_buf[8] = BPF_MOV64_IMM(BPF_REG_0, -EINVAL); 13444 cnt = 9; 13445 13446 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 13447 if (!new_prog) 13448 return -ENOMEM; 13449 13450 delta += cnt - 1; 13451 env->prog = prog = new_prog; 13452 insn = new_prog->insnsi + i + delta; 13453 continue; 13454 } 13455 13456 /* Implement bpf_get_func_ret inline. */ 13457 if (prog_type == BPF_PROG_TYPE_TRACING && 13458 insn->imm == BPF_FUNC_get_func_ret) { 13459 if (eatype == BPF_TRACE_FEXIT || 13460 eatype == BPF_MODIFY_RETURN) { 13461 /* Load nr_args from ctx - 8 */ 13462 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 13463 insn_buf[1] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_0, 3); 13464 insn_buf[2] = BPF_ALU64_REG(BPF_ADD, BPF_REG_0, BPF_REG_1); 13465 insn_buf[3] = BPF_LDX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0); 13466 insn_buf[4] = BPF_STX_MEM(BPF_DW, BPF_REG_2, BPF_REG_3, 0); 13467 insn_buf[5] = BPF_MOV64_IMM(BPF_REG_0, 0); 13468 cnt = 6; 13469 } else { 13470 insn_buf[0] = BPF_MOV64_IMM(BPF_REG_0, -EOPNOTSUPP); 13471 cnt = 1; 13472 } 13473 13474 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 13475 if (!new_prog) 13476 return -ENOMEM; 13477 13478 delta += cnt - 1; 13479 env->prog = prog = new_prog; 13480 insn = new_prog->insnsi + i + delta; 13481 continue; 13482 } 13483 13484 /* Implement get_func_arg_cnt inline. */ 13485 if (prog_type == BPF_PROG_TYPE_TRACING && 13486 insn->imm == BPF_FUNC_get_func_arg_cnt) { 13487 /* Load nr_args from ctx - 8 */ 13488 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 13489 13490 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 13491 if (!new_prog) 13492 return -ENOMEM; 13493 13494 env->prog = prog = new_prog; 13495 insn = new_prog->insnsi + i + delta; 13496 continue; 13497 } 13498 13499 /* Implement bpf_get_func_ip inline. */ 13500 if (prog_type == BPF_PROG_TYPE_TRACING && 13501 insn->imm == BPF_FUNC_get_func_ip) { 13502 /* Load IP address from ctx - 16 */ 13503 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -16); 13504 13505 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 13506 if (!new_prog) 13507 return -ENOMEM; 13508 13509 env->prog = prog = new_prog; 13510 insn = new_prog->insnsi + i + delta; 13511 continue; 13512 } 13513 13514 patch_call_imm: 13515 fn = env->ops->get_func_proto(insn->imm, env->prog); 13516 /* all functions that have prototype and verifier allowed 13517 * programs to call them, must be real in-kernel functions 13518 */ 13519 if (!fn->func) { 13520 verbose(env, 13521 "kernel subsystem misconfigured func %s#%d\n", 13522 func_id_name(insn->imm), insn->imm); 13523 return -EFAULT; 13524 } 13525 insn->imm = fn->func - __bpf_call_base; 13526 } 13527 13528 /* Since poke tab is now finalized, publish aux to tracker. */ 13529 for (i = 0; i < prog->aux->size_poke_tab; i++) { 13530 map_ptr = prog->aux->poke_tab[i].tail_call.map; 13531 if (!map_ptr->ops->map_poke_track || 13532 !map_ptr->ops->map_poke_untrack || 13533 !map_ptr->ops->map_poke_run) { 13534 verbose(env, "bpf verifier is misconfigured\n"); 13535 return -EINVAL; 13536 } 13537 13538 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 13539 if (ret < 0) { 13540 verbose(env, "tracking tail call prog failed\n"); 13541 return ret; 13542 } 13543 } 13544 13545 sort_kfunc_descs_by_imm(env->prog); 13546 13547 return 0; 13548 } 13549 13550 static void free_states(struct bpf_verifier_env *env) 13551 { 13552 struct bpf_verifier_state_list *sl, *sln; 13553 int i; 13554 13555 sl = env->free_list; 13556 while (sl) { 13557 sln = sl->next; 13558 free_verifier_state(&sl->state, false); 13559 kfree(sl); 13560 sl = sln; 13561 } 13562 env->free_list = NULL; 13563 13564 if (!env->explored_states) 13565 return; 13566 13567 for (i = 0; i < state_htab_size(env); i++) { 13568 sl = env->explored_states[i]; 13569 13570 while (sl) { 13571 sln = sl->next; 13572 free_verifier_state(&sl->state, false); 13573 kfree(sl); 13574 sl = sln; 13575 } 13576 env->explored_states[i] = NULL; 13577 } 13578 } 13579 13580 static int do_check_common(struct bpf_verifier_env *env, int subprog) 13581 { 13582 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 13583 struct bpf_verifier_state *state; 13584 struct bpf_reg_state *regs; 13585 int ret, i; 13586 13587 env->prev_linfo = NULL; 13588 env->pass_cnt++; 13589 13590 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 13591 if (!state) 13592 return -ENOMEM; 13593 state->curframe = 0; 13594 state->speculative = false; 13595 state->branches = 1; 13596 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 13597 if (!state->frame[0]) { 13598 kfree(state); 13599 return -ENOMEM; 13600 } 13601 env->cur_state = state; 13602 init_func_state(env, state->frame[0], 13603 BPF_MAIN_FUNC /* callsite */, 13604 0 /* frameno */, 13605 subprog); 13606 13607 regs = state->frame[state->curframe]->regs; 13608 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 13609 ret = btf_prepare_func_args(env, subprog, regs); 13610 if (ret) 13611 goto out; 13612 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 13613 if (regs[i].type == PTR_TO_CTX) 13614 mark_reg_known_zero(env, regs, i); 13615 else if (regs[i].type == SCALAR_VALUE) 13616 mark_reg_unknown(env, regs, i); 13617 else if (base_type(regs[i].type) == PTR_TO_MEM) { 13618 const u32 mem_size = regs[i].mem_size; 13619 13620 mark_reg_known_zero(env, regs, i); 13621 regs[i].mem_size = mem_size; 13622 regs[i].id = ++env->id_gen; 13623 } 13624 } 13625 } else { 13626 /* 1st arg to a function */ 13627 regs[BPF_REG_1].type = PTR_TO_CTX; 13628 mark_reg_known_zero(env, regs, BPF_REG_1); 13629 ret = btf_check_subprog_arg_match(env, subprog, regs); 13630 if (ret == -EFAULT) 13631 /* unlikely verifier bug. abort. 13632 * ret == 0 and ret < 0 are sadly acceptable for 13633 * main() function due to backward compatibility. 13634 * Like socket filter program may be written as: 13635 * int bpf_prog(struct pt_regs *ctx) 13636 * and never dereference that ctx in the program. 13637 * 'struct pt_regs' is a type mismatch for socket 13638 * filter that should be using 'struct __sk_buff'. 13639 */ 13640 goto out; 13641 } 13642 13643 ret = do_check(env); 13644 out: 13645 /* check for NULL is necessary, since cur_state can be freed inside 13646 * do_check() under memory pressure. 13647 */ 13648 if (env->cur_state) { 13649 free_verifier_state(env->cur_state, true); 13650 env->cur_state = NULL; 13651 } 13652 while (!pop_stack(env, NULL, NULL, false)); 13653 if (!ret && pop_log) 13654 bpf_vlog_reset(&env->log, 0); 13655 free_states(env); 13656 return ret; 13657 } 13658 13659 /* Verify all global functions in a BPF program one by one based on their BTF. 13660 * All global functions must pass verification. Otherwise the whole program is rejected. 13661 * Consider: 13662 * int bar(int); 13663 * int foo(int f) 13664 * { 13665 * return bar(f); 13666 * } 13667 * int bar(int b) 13668 * { 13669 * ... 13670 * } 13671 * foo() will be verified first for R1=any_scalar_value. During verification it 13672 * will be assumed that bar() already verified successfully and call to bar() 13673 * from foo() will be checked for type match only. Later bar() will be verified 13674 * independently to check that it's safe for R1=any_scalar_value. 13675 */ 13676 static int do_check_subprogs(struct bpf_verifier_env *env) 13677 { 13678 struct bpf_prog_aux *aux = env->prog->aux; 13679 int i, ret; 13680 13681 if (!aux->func_info) 13682 return 0; 13683 13684 for (i = 1; i < env->subprog_cnt; i++) { 13685 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 13686 continue; 13687 env->insn_idx = env->subprog_info[i].start; 13688 WARN_ON_ONCE(env->insn_idx == 0); 13689 ret = do_check_common(env, i); 13690 if (ret) { 13691 return ret; 13692 } else if (env->log.level & BPF_LOG_LEVEL) { 13693 verbose(env, 13694 "Func#%d is safe for any args that match its prototype\n", 13695 i); 13696 } 13697 } 13698 return 0; 13699 } 13700 13701 static int do_check_main(struct bpf_verifier_env *env) 13702 { 13703 int ret; 13704 13705 env->insn_idx = 0; 13706 ret = do_check_common(env, 0); 13707 if (!ret) 13708 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 13709 return ret; 13710 } 13711 13712 13713 static void print_verification_stats(struct bpf_verifier_env *env) 13714 { 13715 int i; 13716 13717 if (env->log.level & BPF_LOG_STATS) { 13718 verbose(env, "verification time %lld usec\n", 13719 div_u64(env->verification_time, 1000)); 13720 verbose(env, "stack depth "); 13721 for (i = 0; i < env->subprog_cnt; i++) { 13722 u32 depth = env->subprog_info[i].stack_depth; 13723 13724 verbose(env, "%d", depth); 13725 if (i + 1 < env->subprog_cnt) 13726 verbose(env, "+"); 13727 } 13728 verbose(env, "\n"); 13729 } 13730 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 13731 "total_states %d peak_states %d mark_read %d\n", 13732 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 13733 env->max_states_per_insn, env->total_states, 13734 env->peak_states, env->longest_mark_read_walk); 13735 } 13736 13737 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 13738 { 13739 const struct btf_type *t, *func_proto; 13740 const struct bpf_struct_ops *st_ops; 13741 const struct btf_member *member; 13742 struct bpf_prog *prog = env->prog; 13743 u32 btf_id, member_idx; 13744 const char *mname; 13745 13746 if (!prog->gpl_compatible) { 13747 verbose(env, "struct ops programs must have a GPL compatible license\n"); 13748 return -EINVAL; 13749 } 13750 13751 btf_id = prog->aux->attach_btf_id; 13752 st_ops = bpf_struct_ops_find(btf_id); 13753 if (!st_ops) { 13754 verbose(env, "attach_btf_id %u is not a supported struct\n", 13755 btf_id); 13756 return -ENOTSUPP; 13757 } 13758 13759 t = st_ops->type; 13760 member_idx = prog->expected_attach_type; 13761 if (member_idx >= btf_type_vlen(t)) { 13762 verbose(env, "attach to invalid member idx %u of struct %s\n", 13763 member_idx, st_ops->name); 13764 return -EINVAL; 13765 } 13766 13767 member = &btf_type_member(t)[member_idx]; 13768 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 13769 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 13770 NULL); 13771 if (!func_proto) { 13772 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 13773 mname, member_idx, st_ops->name); 13774 return -EINVAL; 13775 } 13776 13777 if (st_ops->check_member) { 13778 int err = st_ops->check_member(t, member); 13779 13780 if (err) { 13781 verbose(env, "attach to unsupported member %s of struct %s\n", 13782 mname, st_ops->name); 13783 return err; 13784 } 13785 } 13786 13787 prog->aux->attach_func_proto = func_proto; 13788 prog->aux->attach_func_name = mname; 13789 env->ops = st_ops->verifier_ops; 13790 13791 return 0; 13792 } 13793 #define SECURITY_PREFIX "security_" 13794 13795 static int check_attach_modify_return(unsigned long addr, const char *func_name) 13796 { 13797 if (within_error_injection_list(addr) || 13798 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 13799 return 0; 13800 13801 return -EINVAL; 13802 } 13803 13804 /* list of non-sleepable functions that are otherwise on 13805 * ALLOW_ERROR_INJECTION list 13806 */ 13807 BTF_SET_START(btf_non_sleepable_error_inject) 13808 /* Three functions below can be called from sleepable and non-sleepable context. 13809 * Assume non-sleepable from bpf safety point of view. 13810 */ 13811 BTF_ID(func, __filemap_add_folio) 13812 BTF_ID(func, should_fail_alloc_page) 13813 BTF_ID(func, should_failslab) 13814 BTF_SET_END(btf_non_sleepable_error_inject) 13815 13816 static int check_non_sleepable_error_inject(u32 btf_id) 13817 { 13818 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 13819 } 13820 13821 int bpf_check_attach_target(struct bpf_verifier_log *log, 13822 const struct bpf_prog *prog, 13823 const struct bpf_prog *tgt_prog, 13824 u32 btf_id, 13825 struct bpf_attach_target_info *tgt_info) 13826 { 13827 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 13828 const char prefix[] = "btf_trace_"; 13829 int ret = 0, subprog = -1, i; 13830 const struct btf_type *t; 13831 bool conservative = true; 13832 const char *tname; 13833 struct btf *btf; 13834 long addr = 0; 13835 13836 if (!btf_id) { 13837 bpf_log(log, "Tracing programs must provide btf_id\n"); 13838 return -EINVAL; 13839 } 13840 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 13841 if (!btf) { 13842 bpf_log(log, 13843 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 13844 return -EINVAL; 13845 } 13846 t = btf_type_by_id(btf, btf_id); 13847 if (!t) { 13848 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 13849 return -EINVAL; 13850 } 13851 tname = btf_name_by_offset(btf, t->name_off); 13852 if (!tname) { 13853 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 13854 return -EINVAL; 13855 } 13856 if (tgt_prog) { 13857 struct bpf_prog_aux *aux = tgt_prog->aux; 13858 13859 for (i = 0; i < aux->func_info_cnt; i++) 13860 if (aux->func_info[i].type_id == btf_id) { 13861 subprog = i; 13862 break; 13863 } 13864 if (subprog == -1) { 13865 bpf_log(log, "Subprog %s doesn't exist\n", tname); 13866 return -EINVAL; 13867 } 13868 conservative = aux->func_info_aux[subprog].unreliable; 13869 if (prog_extension) { 13870 if (conservative) { 13871 bpf_log(log, 13872 "Cannot replace static functions\n"); 13873 return -EINVAL; 13874 } 13875 if (!prog->jit_requested) { 13876 bpf_log(log, 13877 "Extension programs should be JITed\n"); 13878 return -EINVAL; 13879 } 13880 } 13881 if (!tgt_prog->jited) { 13882 bpf_log(log, "Can attach to only JITed progs\n"); 13883 return -EINVAL; 13884 } 13885 if (tgt_prog->type == prog->type) { 13886 /* Cannot fentry/fexit another fentry/fexit program. 13887 * Cannot attach program extension to another extension. 13888 * It's ok to attach fentry/fexit to extension program. 13889 */ 13890 bpf_log(log, "Cannot recursively attach\n"); 13891 return -EINVAL; 13892 } 13893 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 13894 prog_extension && 13895 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 13896 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 13897 /* Program extensions can extend all program types 13898 * except fentry/fexit. The reason is the following. 13899 * The fentry/fexit programs are used for performance 13900 * analysis, stats and can be attached to any program 13901 * type except themselves. When extension program is 13902 * replacing XDP function it is necessary to allow 13903 * performance analysis of all functions. Both original 13904 * XDP program and its program extension. Hence 13905 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 13906 * allowed. If extending of fentry/fexit was allowed it 13907 * would be possible to create long call chain 13908 * fentry->extension->fentry->extension beyond 13909 * reasonable stack size. Hence extending fentry is not 13910 * allowed. 13911 */ 13912 bpf_log(log, "Cannot extend fentry/fexit\n"); 13913 return -EINVAL; 13914 } 13915 } else { 13916 if (prog_extension) { 13917 bpf_log(log, "Cannot replace kernel functions\n"); 13918 return -EINVAL; 13919 } 13920 } 13921 13922 switch (prog->expected_attach_type) { 13923 case BPF_TRACE_RAW_TP: 13924 if (tgt_prog) { 13925 bpf_log(log, 13926 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 13927 return -EINVAL; 13928 } 13929 if (!btf_type_is_typedef(t)) { 13930 bpf_log(log, "attach_btf_id %u is not a typedef\n", 13931 btf_id); 13932 return -EINVAL; 13933 } 13934 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 13935 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 13936 btf_id, tname); 13937 return -EINVAL; 13938 } 13939 tname += sizeof(prefix) - 1; 13940 t = btf_type_by_id(btf, t->type); 13941 if (!btf_type_is_ptr(t)) 13942 /* should never happen in valid vmlinux build */ 13943 return -EINVAL; 13944 t = btf_type_by_id(btf, t->type); 13945 if (!btf_type_is_func_proto(t)) 13946 /* should never happen in valid vmlinux build */ 13947 return -EINVAL; 13948 13949 break; 13950 case BPF_TRACE_ITER: 13951 if (!btf_type_is_func(t)) { 13952 bpf_log(log, "attach_btf_id %u is not a function\n", 13953 btf_id); 13954 return -EINVAL; 13955 } 13956 t = btf_type_by_id(btf, t->type); 13957 if (!btf_type_is_func_proto(t)) 13958 return -EINVAL; 13959 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 13960 if (ret) 13961 return ret; 13962 break; 13963 default: 13964 if (!prog_extension) 13965 return -EINVAL; 13966 fallthrough; 13967 case BPF_MODIFY_RETURN: 13968 case BPF_LSM_MAC: 13969 case BPF_TRACE_FENTRY: 13970 case BPF_TRACE_FEXIT: 13971 if (!btf_type_is_func(t)) { 13972 bpf_log(log, "attach_btf_id %u is not a function\n", 13973 btf_id); 13974 return -EINVAL; 13975 } 13976 if (prog_extension && 13977 btf_check_type_match(log, prog, btf, t)) 13978 return -EINVAL; 13979 t = btf_type_by_id(btf, t->type); 13980 if (!btf_type_is_func_proto(t)) 13981 return -EINVAL; 13982 13983 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 13984 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 13985 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 13986 return -EINVAL; 13987 13988 if (tgt_prog && conservative) 13989 t = NULL; 13990 13991 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 13992 if (ret < 0) 13993 return ret; 13994 13995 if (tgt_prog) { 13996 if (subprog == 0) 13997 addr = (long) tgt_prog->bpf_func; 13998 else 13999 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 14000 } else { 14001 addr = kallsyms_lookup_name(tname); 14002 if (!addr) { 14003 bpf_log(log, 14004 "The address of function %s cannot be found\n", 14005 tname); 14006 return -ENOENT; 14007 } 14008 } 14009 14010 if (prog->aux->sleepable) { 14011 ret = -EINVAL; 14012 switch (prog->type) { 14013 case BPF_PROG_TYPE_TRACING: 14014 /* fentry/fexit/fmod_ret progs can be sleepable only if they are 14015 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 14016 */ 14017 if (!check_non_sleepable_error_inject(btf_id) && 14018 within_error_injection_list(addr)) 14019 ret = 0; 14020 break; 14021 case BPF_PROG_TYPE_LSM: 14022 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 14023 * Only some of them are sleepable. 14024 */ 14025 if (bpf_lsm_is_sleepable_hook(btf_id)) 14026 ret = 0; 14027 break; 14028 default: 14029 break; 14030 } 14031 if (ret) { 14032 bpf_log(log, "%s is not sleepable\n", tname); 14033 return ret; 14034 } 14035 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 14036 if (tgt_prog) { 14037 bpf_log(log, "can't modify return codes of BPF programs\n"); 14038 return -EINVAL; 14039 } 14040 ret = check_attach_modify_return(addr, tname); 14041 if (ret) { 14042 bpf_log(log, "%s() is not modifiable\n", tname); 14043 return ret; 14044 } 14045 } 14046 14047 break; 14048 } 14049 tgt_info->tgt_addr = addr; 14050 tgt_info->tgt_name = tname; 14051 tgt_info->tgt_type = t; 14052 return 0; 14053 } 14054 14055 BTF_SET_START(btf_id_deny) 14056 BTF_ID_UNUSED 14057 #ifdef CONFIG_SMP 14058 BTF_ID(func, migrate_disable) 14059 BTF_ID(func, migrate_enable) 14060 #endif 14061 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 14062 BTF_ID(func, rcu_read_unlock_strict) 14063 #endif 14064 BTF_SET_END(btf_id_deny) 14065 14066 static int check_attach_btf_id(struct bpf_verifier_env *env) 14067 { 14068 struct bpf_prog *prog = env->prog; 14069 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 14070 struct bpf_attach_target_info tgt_info = {}; 14071 u32 btf_id = prog->aux->attach_btf_id; 14072 struct bpf_trampoline *tr; 14073 int ret; 14074 u64 key; 14075 14076 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 14077 if (prog->aux->sleepable) 14078 /* attach_btf_id checked to be zero already */ 14079 return 0; 14080 verbose(env, "Syscall programs can only be sleepable\n"); 14081 return -EINVAL; 14082 } 14083 14084 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING && 14085 prog->type != BPF_PROG_TYPE_LSM) { 14086 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n"); 14087 return -EINVAL; 14088 } 14089 14090 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 14091 return check_struct_ops_btf_id(env); 14092 14093 if (prog->type != BPF_PROG_TYPE_TRACING && 14094 prog->type != BPF_PROG_TYPE_LSM && 14095 prog->type != BPF_PROG_TYPE_EXT) 14096 return 0; 14097 14098 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 14099 if (ret) 14100 return ret; 14101 14102 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 14103 /* to make freplace equivalent to their targets, they need to 14104 * inherit env->ops and expected_attach_type for the rest of the 14105 * verification 14106 */ 14107 env->ops = bpf_verifier_ops[tgt_prog->type]; 14108 prog->expected_attach_type = tgt_prog->expected_attach_type; 14109 } 14110 14111 /* store info about the attachment target that will be used later */ 14112 prog->aux->attach_func_proto = tgt_info.tgt_type; 14113 prog->aux->attach_func_name = tgt_info.tgt_name; 14114 14115 if (tgt_prog) { 14116 prog->aux->saved_dst_prog_type = tgt_prog->type; 14117 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 14118 } 14119 14120 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 14121 prog->aux->attach_btf_trace = true; 14122 return 0; 14123 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 14124 if (!bpf_iter_prog_supported(prog)) 14125 return -EINVAL; 14126 return 0; 14127 } 14128 14129 if (prog->type == BPF_PROG_TYPE_LSM) { 14130 ret = bpf_lsm_verify_prog(&env->log, prog); 14131 if (ret < 0) 14132 return ret; 14133 } else if (prog->type == BPF_PROG_TYPE_TRACING && 14134 btf_id_set_contains(&btf_id_deny, btf_id)) { 14135 return -EINVAL; 14136 } 14137 14138 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 14139 tr = bpf_trampoline_get(key, &tgt_info); 14140 if (!tr) 14141 return -ENOMEM; 14142 14143 prog->aux->dst_trampoline = tr; 14144 return 0; 14145 } 14146 14147 struct btf *bpf_get_btf_vmlinux(void) 14148 { 14149 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 14150 mutex_lock(&bpf_verifier_lock); 14151 if (!btf_vmlinux) 14152 btf_vmlinux = btf_parse_vmlinux(); 14153 mutex_unlock(&bpf_verifier_lock); 14154 } 14155 return btf_vmlinux; 14156 } 14157 14158 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr) 14159 { 14160 u64 start_time = ktime_get_ns(); 14161 struct bpf_verifier_env *env; 14162 struct bpf_verifier_log *log; 14163 int i, len, ret = -EINVAL; 14164 bool is_priv; 14165 14166 /* no program is valid */ 14167 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 14168 return -EINVAL; 14169 14170 /* 'struct bpf_verifier_env' can be global, but since it's not small, 14171 * allocate/free it every time bpf_check() is called 14172 */ 14173 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 14174 if (!env) 14175 return -ENOMEM; 14176 log = &env->log; 14177 14178 len = (*prog)->len; 14179 env->insn_aux_data = 14180 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 14181 ret = -ENOMEM; 14182 if (!env->insn_aux_data) 14183 goto err_free_env; 14184 for (i = 0; i < len; i++) 14185 env->insn_aux_data[i].orig_idx = i; 14186 env->prog = *prog; 14187 env->ops = bpf_verifier_ops[env->prog->type]; 14188 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 14189 is_priv = bpf_capable(); 14190 14191 bpf_get_btf_vmlinux(); 14192 14193 /* grab the mutex to protect few globals used by verifier */ 14194 if (!is_priv) 14195 mutex_lock(&bpf_verifier_lock); 14196 14197 if (attr->log_level || attr->log_buf || attr->log_size) { 14198 /* user requested verbose verifier output 14199 * and supplied buffer to store the verification trace 14200 */ 14201 log->level = attr->log_level; 14202 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 14203 log->len_total = attr->log_size; 14204 14205 /* log attributes have to be sane */ 14206 if (!bpf_verifier_log_attr_valid(log)) { 14207 ret = -EINVAL; 14208 goto err_unlock; 14209 } 14210 } 14211 14212 mark_verifier_state_clean(env); 14213 14214 if (IS_ERR(btf_vmlinux)) { 14215 /* Either gcc or pahole or kernel are broken. */ 14216 verbose(env, "in-kernel BTF is malformed\n"); 14217 ret = PTR_ERR(btf_vmlinux); 14218 goto skip_full_check; 14219 } 14220 14221 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 14222 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 14223 env->strict_alignment = true; 14224 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 14225 env->strict_alignment = false; 14226 14227 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 14228 env->allow_uninit_stack = bpf_allow_uninit_stack(); 14229 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access(); 14230 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 14231 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 14232 env->bpf_capable = bpf_capable(); 14233 14234 if (is_priv) 14235 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 14236 14237 env->explored_states = kvcalloc(state_htab_size(env), 14238 sizeof(struct bpf_verifier_state_list *), 14239 GFP_USER); 14240 ret = -ENOMEM; 14241 if (!env->explored_states) 14242 goto skip_full_check; 14243 14244 ret = add_subprog_and_kfunc(env); 14245 if (ret < 0) 14246 goto skip_full_check; 14247 14248 ret = check_subprogs(env); 14249 if (ret < 0) 14250 goto skip_full_check; 14251 14252 ret = check_btf_info(env, attr, uattr); 14253 if (ret < 0) 14254 goto skip_full_check; 14255 14256 ret = check_attach_btf_id(env); 14257 if (ret) 14258 goto skip_full_check; 14259 14260 ret = resolve_pseudo_ldimm64(env); 14261 if (ret < 0) 14262 goto skip_full_check; 14263 14264 if (bpf_prog_is_dev_bound(env->prog->aux)) { 14265 ret = bpf_prog_offload_verifier_prep(env->prog); 14266 if (ret) 14267 goto skip_full_check; 14268 } 14269 14270 ret = check_cfg(env); 14271 if (ret < 0) 14272 goto skip_full_check; 14273 14274 ret = do_check_subprogs(env); 14275 ret = ret ?: do_check_main(env); 14276 14277 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux)) 14278 ret = bpf_prog_offload_finalize(env); 14279 14280 skip_full_check: 14281 kvfree(env->explored_states); 14282 14283 if (ret == 0) 14284 ret = check_max_stack_depth(env); 14285 14286 /* instruction rewrites happen after this point */ 14287 if (is_priv) { 14288 if (ret == 0) 14289 opt_hard_wire_dead_code_branches(env); 14290 if (ret == 0) 14291 ret = opt_remove_dead_code(env); 14292 if (ret == 0) 14293 ret = opt_remove_nops(env); 14294 } else { 14295 if (ret == 0) 14296 sanitize_dead_code(env); 14297 } 14298 14299 if (ret == 0) 14300 /* program is valid, convert *(u32*)(ctx + off) accesses */ 14301 ret = convert_ctx_accesses(env); 14302 14303 if (ret == 0) 14304 ret = do_misc_fixups(env); 14305 14306 /* do 32-bit optimization after insn patching has done so those patched 14307 * insns could be handled correctly. 14308 */ 14309 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) { 14310 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 14311 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 14312 : false; 14313 } 14314 14315 if (ret == 0) 14316 ret = fixup_call_args(env); 14317 14318 env->verification_time = ktime_get_ns() - start_time; 14319 print_verification_stats(env); 14320 env->prog->aux->verified_insns = env->insn_processed; 14321 14322 if (log->level && bpf_verifier_log_full(log)) 14323 ret = -ENOSPC; 14324 if (log->level && !log->ubuf) { 14325 ret = -EFAULT; 14326 goto err_release_maps; 14327 } 14328 14329 if (ret) 14330 goto err_release_maps; 14331 14332 if (env->used_map_cnt) { 14333 /* if program passed verifier, update used_maps in bpf_prog_info */ 14334 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 14335 sizeof(env->used_maps[0]), 14336 GFP_KERNEL); 14337 14338 if (!env->prog->aux->used_maps) { 14339 ret = -ENOMEM; 14340 goto err_release_maps; 14341 } 14342 14343 memcpy(env->prog->aux->used_maps, env->used_maps, 14344 sizeof(env->used_maps[0]) * env->used_map_cnt); 14345 env->prog->aux->used_map_cnt = env->used_map_cnt; 14346 } 14347 if (env->used_btf_cnt) { 14348 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 14349 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 14350 sizeof(env->used_btfs[0]), 14351 GFP_KERNEL); 14352 if (!env->prog->aux->used_btfs) { 14353 ret = -ENOMEM; 14354 goto err_release_maps; 14355 } 14356 14357 memcpy(env->prog->aux->used_btfs, env->used_btfs, 14358 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 14359 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 14360 } 14361 if (env->used_map_cnt || env->used_btf_cnt) { 14362 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 14363 * bpf_ld_imm64 instructions 14364 */ 14365 convert_pseudo_ld_imm64(env); 14366 } 14367 14368 adjust_btf_func(env); 14369 14370 err_release_maps: 14371 if (!env->prog->aux->used_maps) 14372 /* if we didn't copy map pointers into bpf_prog_info, release 14373 * them now. Otherwise free_used_maps() will release them. 14374 */ 14375 release_maps(env); 14376 if (!env->prog->aux->used_btfs) 14377 release_btfs(env); 14378 14379 /* extension progs temporarily inherit the attach_type of their targets 14380 for verification purposes, so set it back to zero before returning 14381 */ 14382 if (env->prog->type == BPF_PROG_TYPE_EXT) 14383 env->prog->expected_attach_type = 0; 14384 14385 *prog = env->prog; 14386 err_unlock: 14387 if (!is_priv) 14388 mutex_unlock(&bpf_verifier_lock); 14389 vfree(env->insn_aux_data); 14390 err_free_env: 14391 kfree(env); 14392 return ret; 14393 } 14394