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/kernel.h> 8 #include <linux/types.h> 9 #include <linux/slab.h> 10 #include <linux/bpf.h> 11 #include <linux/btf.h> 12 #include <linux/bpf_verifier.h> 13 #include <linux/filter.h> 14 #include <net/netlink.h> 15 #include <linux/file.h> 16 #include <linux/vmalloc.h> 17 #include <linux/stringify.h> 18 #include <linux/bsearch.h> 19 #include <linux/sort.h> 20 #include <linux/perf_event.h> 21 #include <linux/ctype.h> 22 #include <linux/error-injection.h> 23 #include <linux/bpf_lsm.h> 24 25 #include "disasm.h" 26 27 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 28 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 29 [_id] = & _name ## _verifier_ops, 30 #define BPF_MAP_TYPE(_id, _ops) 31 #define BPF_LINK_TYPE(_id, _name) 32 #include <linux/bpf_types.h> 33 #undef BPF_PROG_TYPE 34 #undef BPF_MAP_TYPE 35 #undef BPF_LINK_TYPE 36 }; 37 38 /* bpf_check() is a static code analyzer that walks eBPF program 39 * instruction by instruction and updates register/stack state. 40 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 41 * 42 * The first pass is depth-first-search to check that the program is a DAG. 43 * It rejects the following programs: 44 * - larger than BPF_MAXINSNS insns 45 * - if loop is present (detected via back-edge) 46 * - unreachable insns exist (shouldn't be a forest. program = one function) 47 * - out of bounds or malformed jumps 48 * The second pass is all possible path descent from the 1st insn. 49 * Since it's analyzing all pathes through the program, the length of the 50 * analysis is limited to 64k insn, which may be hit even if total number of 51 * insn is less then 4K, but there are too many branches that change stack/regs. 52 * Number of 'branches to be analyzed' is limited to 1k 53 * 54 * On entry to each instruction, each register has a type, and the instruction 55 * changes the types of the registers depending on instruction semantics. 56 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 57 * copied to R1. 58 * 59 * All registers are 64-bit. 60 * R0 - return register 61 * R1-R5 argument passing registers 62 * R6-R9 callee saved registers 63 * R10 - frame pointer read-only 64 * 65 * At the start of BPF program the register R1 contains a pointer to bpf_context 66 * and has type PTR_TO_CTX. 67 * 68 * Verifier tracks arithmetic operations on pointers in case: 69 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 70 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 71 * 1st insn copies R10 (which has FRAME_PTR) type into R1 72 * and 2nd arithmetic instruction is pattern matched to recognize 73 * that it wants to construct a pointer to some element within stack. 74 * So after 2nd insn, the register R1 has type PTR_TO_STACK 75 * (and -20 constant is saved for further stack bounds checking). 76 * Meaning that this reg is a pointer to stack plus known immediate constant. 77 * 78 * Most of the time the registers have SCALAR_VALUE type, which 79 * means the register has some value, but it's not a valid pointer. 80 * (like pointer plus pointer becomes SCALAR_VALUE type) 81 * 82 * When verifier sees load or store instructions the type of base register 83 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 84 * four pointer types recognized by check_mem_access() function. 85 * 86 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 87 * and the range of [ptr, ptr + map's value_size) is accessible. 88 * 89 * registers used to pass values to function calls are checked against 90 * function argument constraints. 91 * 92 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 93 * It means that the register type passed to this function must be 94 * PTR_TO_STACK and it will be used inside the function as 95 * 'pointer to map element key' 96 * 97 * For example the argument constraints for bpf_map_lookup_elem(): 98 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 99 * .arg1_type = ARG_CONST_MAP_PTR, 100 * .arg2_type = ARG_PTR_TO_MAP_KEY, 101 * 102 * ret_type says that this function returns 'pointer to map elem value or null' 103 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 104 * 2nd argument should be a pointer to stack, which will be used inside 105 * the helper function as a pointer to map element key. 106 * 107 * On the kernel side the helper function looks like: 108 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 109 * { 110 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 111 * void *key = (void *) (unsigned long) r2; 112 * void *value; 113 * 114 * here kernel can access 'key' and 'map' pointers safely, knowing that 115 * [key, key + map->key_size) bytes are valid and were initialized on 116 * the stack of eBPF program. 117 * } 118 * 119 * Corresponding eBPF program may look like: 120 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 121 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 122 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 123 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 124 * here verifier looks at prototype of map_lookup_elem() and sees: 125 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 126 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 127 * 128 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 129 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 130 * and were initialized prior to this call. 131 * If it's ok, then verifier allows this BPF_CALL insn and looks at 132 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 133 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 134 * returns ether pointer to map value or NULL. 135 * 136 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 137 * insn, the register holding that pointer in the true branch changes state to 138 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 139 * branch. See check_cond_jmp_op(). 140 * 141 * After the call R0 is set to return type of the function and registers R1-R5 142 * are set to NOT_INIT to indicate that they are no longer readable. 143 * 144 * The following reference types represent a potential reference to a kernel 145 * resource which, after first being allocated, must be checked and freed by 146 * the BPF program: 147 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 148 * 149 * When the verifier sees a helper call return a reference type, it allocates a 150 * pointer id for the reference and stores it in the current function state. 151 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 152 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 153 * passes through a NULL-check conditional. For the branch wherein the state is 154 * changed to CONST_IMM, the verifier releases the reference. 155 * 156 * For each helper function that allocates a reference, such as 157 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 158 * bpf_sk_release(). When a reference type passes into the release function, 159 * the verifier also releases the reference. If any unchecked or unreleased 160 * reference remains at the end of the program, the verifier rejects it. 161 */ 162 163 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 164 struct bpf_verifier_stack_elem { 165 /* verifer state is 'st' 166 * before processing instruction 'insn_idx' 167 * and after processing instruction 'prev_insn_idx' 168 */ 169 struct bpf_verifier_state st; 170 int insn_idx; 171 int prev_insn_idx; 172 struct bpf_verifier_stack_elem *next; 173 /* length of verifier log at the time this state was pushed on stack */ 174 u32 log_pos; 175 }; 176 177 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 178 #define BPF_COMPLEXITY_LIMIT_STATES 64 179 180 #define BPF_MAP_KEY_POISON (1ULL << 63) 181 #define BPF_MAP_KEY_SEEN (1ULL << 62) 182 183 #define BPF_MAP_PTR_UNPRIV 1UL 184 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 185 POISON_POINTER_DELTA)) 186 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 187 188 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 189 { 190 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 191 } 192 193 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 194 { 195 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 196 } 197 198 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 199 const struct bpf_map *map, bool unpriv) 200 { 201 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 202 unpriv |= bpf_map_ptr_unpriv(aux); 203 aux->map_ptr_state = (unsigned long)map | 204 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 205 } 206 207 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 208 { 209 return aux->map_key_state & BPF_MAP_KEY_POISON; 210 } 211 212 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 213 { 214 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 215 } 216 217 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 218 { 219 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 220 } 221 222 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 223 { 224 bool poisoned = bpf_map_key_poisoned(aux); 225 226 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 227 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 228 } 229 230 struct bpf_call_arg_meta { 231 struct bpf_map *map_ptr; 232 bool raw_mode; 233 bool pkt_access; 234 int regno; 235 int access_size; 236 u64 msize_max_value; 237 int ref_obj_id; 238 int func_id; 239 u32 btf_id; 240 }; 241 242 struct btf *btf_vmlinux; 243 244 static DEFINE_MUTEX(bpf_verifier_lock); 245 246 static const struct bpf_line_info * 247 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 248 { 249 const struct bpf_line_info *linfo; 250 const struct bpf_prog *prog; 251 u32 i, nr_linfo; 252 253 prog = env->prog; 254 nr_linfo = prog->aux->nr_linfo; 255 256 if (!nr_linfo || insn_off >= prog->len) 257 return NULL; 258 259 linfo = prog->aux->linfo; 260 for (i = 1; i < nr_linfo; i++) 261 if (insn_off < linfo[i].insn_off) 262 break; 263 264 return &linfo[i - 1]; 265 } 266 267 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, 268 va_list args) 269 { 270 unsigned int n; 271 272 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); 273 274 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, 275 "verifier log line truncated - local buffer too short\n"); 276 277 n = min(log->len_total - log->len_used - 1, n); 278 log->kbuf[n] = '\0'; 279 280 if (log->level == BPF_LOG_KERNEL) { 281 pr_err("BPF:%s\n", log->kbuf); 282 return; 283 } 284 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) 285 log->len_used += n; 286 else 287 log->ubuf = NULL; 288 } 289 290 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos) 291 { 292 char zero = 0; 293 294 if (!bpf_verifier_log_needed(log)) 295 return; 296 297 log->len_used = new_pos; 298 if (put_user(zero, log->ubuf + new_pos)) 299 log->ubuf = NULL; 300 } 301 302 /* log_level controls verbosity level of eBPF verifier. 303 * bpf_verifier_log_write() is used to dump the verification trace to the log, 304 * so the user can figure out what's wrong with the program 305 */ 306 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 307 const char *fmt, ...) 308 { 309 va_list args; 310 311 if (!bpf_verifier_log_needed(&env->log)) 312 return; 313 314 va_start(args, fmt); 315 bpf_verifier_vlog(&env->log, fmt, args); 316 va_end(args); 317 } 318 EXPORT_SYMBOL_GPL(bpf_verifier_log_write); 319 320 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 321 { 322 struct bpf_verifier_env *env = private_data; 323 va_list args; 324 325 if (!bpf_verifier_log_needed(&env->log)) 326 return; 327 328 va_start(args, fmt); 329 bpf_verifier_vlog(&env->log, fmt, args); 330 va_end(args); 331 } 332 333 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log, 334 const char *fmt, ...) 335 { 336 va_list args; 337 338 if (!bpf_verifier_log_needed(log)) 339 return; 340 341 va_start(args, fmt); 342 bpf_verifier_vlog(log, fmt, args); 343 va_end(args); 344 } 345 346 static const char *ltrim(const char *s) 347 { 348 while (isspace(*s)) 349 s++; 350 351 return s; 352 } 353 354 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 355 u32 insn_off, 356 const char *prefix_fmt, ...) 357 { 358 const struct bpf_line_info *linfo; 359 360 if (!bpf_verifier_log_needed(&env->log)) 361 return; 362 363 linfo = find_linfo(env, insn_off); 364 if (!linfo || linfo == env->prev_linfo) 365 return; 366 367 if (prefix_fmt) { 368 va_list args; 369 370 va_start(args, prefix_fmt); 371 bpf_verifier_vlog(&env->log, prefix_fmt, args); 372 va_end(args); 373 } 374 375 verbose(env, "%s\n", 376 ltrim(btf_name_by_offset(env->prog->aux->btf, 377 linfo->line_off))); 378 379 env->prev_linfo = linfo; 380 } 381 382 static bool type_is_pkt_pointer(enum bpf_reg_type type) 383 { 384 return type == PTR_TO_PACKET || 385 type == PTR_TO_PACKET_META; 386 } 387 388 static bool type_is_sk_pointer(enum bpf_reg_type type) 389 { 390 return type == PTR_TO_SOCKET || 391 type == PTR_TO_SOCK_COMMON || 392 type == PTR_TO_TCP_SOCK || 393 type == PTR_TO_XDP_SOCK; 394 } 395 396 static bool reg_type_not_null(enum bpf_reg_type type) 397 { 398 return type == PTR_TO_SOCKET || 399 type == PTR_TO_TCP_SOCK || 400 type == PTR_TO_MAP_VALUE || 401 type == PTR_TO_SOCK_COMMON || 402 type == PTR_TO_BTF_ID; 403 } 404 405 static bool reg_type_may_be_null(enum bpf_reg_type type) 406 { 407 return type == PTR_TO_MAP_VALUE_OR_NULL || 408 type == PTR_TO_SOCKET_OR_NULL || 409 type == PTR_TO_SOCK_COMMON_OR_NULL || 410 type == PTR_TO_TCP_SOCK_OR_NULL || 411 type == PTR_TO_BTF_ID_OR_NULL; 412 } 413 414 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 415 { 416 return reg->type == PTR_TO_MAP_VALUE && 417 map_value_has_spin_lock(reg->map_ptr); 418 } 419 420 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type) 421 { 422 return type == PTR_TO_SOCKET || 423 type == PTR_TO_SOCKET_OR_NULL || 424 type == PTR_TO_TCP_SOCK || 425 type == PTR_TO_TCP_SOCK_OR_NULL; 426 } 427 428 static bool arg_type_may_be_refcounted(enum bpf_arg_type type) 429 { 430 return type == ARG_PTR_TO_SOCK_COMMON; 431 } 432 433 /* Determine whether the function releases some resources allocated by another 434 * function call. The first reference type argument will be assumed to be 435 * released by release_reference(). 436 */ 437 static bool is_release_function(enum bpf_func_id func_id) 438 { 439 return func_id == BPF_FUNC_sk_release; 440 } 441 442 static bool may_be_acquire_function(enum bpf_func_id func_id) 443 { 444 return func_id == BPF_FUNC_sk_lookup_tcp || 445 func_id == BPF_FUNC_sk_lookup_udp || 446 func_id == BPF_FUNC_skc_lookup_tcp || 447 func_id == BPF_FUNC_map_lookup_elem; 448 } 449 450 static bool is_acquire_function(enum bpf_func_id func_id, 451 const struct bpf_map *map) 452 { 453 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 454 455 if (func_id == BPF_FUNC_sk_lookup_tcp || 456 func_id == BPF_FUNC_sk_lookup_udp || 457 func_id == BPF_FUNC_skc_lookup_tcp) 458 return true; 459 460 if (func_id == BPF_FUNC_map_lookup_elem && 461 (map_type == BPF_MAP_TYPE_SOCKMAP || 462 map_type == BPF_MAP_TYPE_SOCKHASH)) 463 return true; 464 465 return false; 466 } 467 468 static bool is_ptr_cast_function(enum bpf_func_id func_id) 469 { 470 return func_id == BPF_FUNC_tcp_sock || 471 func_id == BPF_FUNC_sk_fullsock; 472 } 473 474 /* string representation of 'enum bpf_reg_type' */ 475 static const char * const reg_type_str[] = { 476 [NOT_INIT] = "?", 477 [SCALAR_VALUE] = "inv", 478 [PTR_TO_CTX] = "ctx", 479 [CONST_PTR_TO_MAP] = "map_ptr", 480 [PTR_TO_MAP_VALUE] = "map_value", 481 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", 482 [PTR_TO_STACK] = "fp", 483 [PTR_TO_PACKET] = "pkt", 484 [PTR_TO_PACKET_META] = "pkt_meta", 485 [PTR_TO_PACKET_END] = "pkt_end", 486 [PTR_TO_FLOW_KEYS] = "flow_keys", 487 [PTR_TO_SOCKET] = "sock", 488 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null", 489 [PTR_TO_SOCK_COMMON] = "sock_common", 490 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null", 491 [PTR_TO_TCP_SOCK] = "tcp_sock", 492 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null", 493 [PTR_TO_TP_BUFFER] = "tp_buffer", 494 [PTR_TO_XDP_SOCK] = "xdp_sock", 495 [PTR_TO_BTF_ID] = "ptr_", 496 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_", 497 }; 498 499 static char slot_type_char[] = { 500 [STACK_INVALID] = '?', 501 [STACK_SPILL] = 'r', 502 [STACK_MISC] = 'm', 503 [STACK_ZERO] = '0', 504 }; 505 506 static void print_liveness(struct bpf_verifier_env *env, 507 enum bpf_reg_liveness live) 508 { 509 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 510 verbose(env, "_"); 511 if (live & REG_LIVE_READ) 512 verbose(env, "r"); 513 if (live & REG_LIVE_WRITTEN) 514 verbose(env, "w"); 515 if (live & REG_LIVE_DONE) 516 verbose(env, "D"); 517 } 518 519 static struct bpf_func_state *func(struct bpf_verifier_env *env, 520 const struct bpf_reg_state *reg) 521 { 522 struct bpf_verifier_state *cur = env->cur_state; 523 524 return cur->frame[reg->frameno]; 525 } 526 527 const char *kernel_type_name(u32 id) 528 { 529 return btf_name_by_offset(btf_vmlinux, 530 btf_type_by_id(btf_vmlinux, id)->name_off); 531 } 532 533 static void print_verifier_state(struct bpf_verifier_env *env, 534 const struct bpf_func_state *state) 535 { 536 const struct bpf_reg_state *reg; 537 enum bpf_reg_type t; 538 int i; 539 540 if (state->frameno) 541 verbose(env, " frame%d:", state->frameno); 542 for (i = 0; i < MAX_BPF_REG; i++) { 543 reg = &state->regs[i]; 544 t = reg->type; 545 if (t == NOT_INIT) 546 continue; 547 verbose(env, " R%d", i); 548 print_liveness(env, reg->live); 549 verbose(env, "=%s", reg_type_str[t]); 550 if (t == SCALAR_VALUE && reg->precise) 551 verbose(env, "P"); 552 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 553 tnum_is_const(reg->var_off)) { 554 /* reg->off should be 0 for SCALAR_VALUE */ 555 verbose(env, "%lld", reg->var_off.value + reg->off); 556 } else { 557 if (t == PTR_TO_BTF_ID || t == PTR_TO_BTF_ID_OR_NULL) 558 verbose(env, "%s", kernel_type_name(reg->btf_id)); 559 verbose(env, "(id=%d", reg->id); 560 if (reg_type_may_be_refcounted_or_null(t)) 561 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id); 562 if (t != SCALAR_VALUE) 563 verbose(env, ",off=%d", reg->off); 564 if (type_is_pkt_pointer(t)) 565 verbose(env, ",r=%d", reg->range); 566 else if (t == CONST_PTR_TO_MAP || 567 t == PTR_TO_MAP_VALUE || 568 t == PTR_TO_MAP_VALUE_OR_NULL) 569 verbose(env, ",ks=%d,vs=%d", 570 reg->map_ptr->key_size, 571 reg->map_ptr->value_size); 572 if (tnum_is_const(reg->var_off)) { 573 /* Typically an immediate SCALAR_VALUE, but 574 * could be a pointer whose offset is too big 575 * for reg->off 576 */ 577 verbose(env, ",imm=%llx", reg->var_off.value); 578 } else { 579 if (reg->smin_value != reg->umin_value && 580 reg->smin_value != S64_MIN) 581 verbose(env, ",smin_value=%lld", 582 (long long)reg->smin_value); 583 if (reg->smax_value != reg->umax_value && 584 reg->smax_value != S64_MAX) 585 verbose(env, ",smax_value=%lld", 586 (long long)reg->smax_value); 587 if (reg->umin_value != 0) 588 verbose(env, ",umin_value=%llu", 589 (unsigned long long)reg->umin_value); 590 if (reg->umax_value != U64_MAX) 591 verbose(env, ",umax_value=%llu", 592 (unsigned long long)reg->umax_value); 593 if (!tnum_is_unknown(reg->var_off)) { 594 char tn_buf[48]; 595 596 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 597 verbose(env, ",var_off=%s", tn_buf); 598 } 599 if (reg->s32_min_value != reg->smin_value && 600 reg->s32_min_value != S32_MIN) 601 verbose(env, ",s32_min_value=%d", 602 (int)(reg->s32_min_value)); 603 if (reg->s32_max_value != reg->smax_value && 604 reg->s32_max_value != S32_MAX) 605 verbose(env, ",s32_max_value=%d", 606 (int)(reg->s32_max_value)); 607 if (reg->u32_min_value != reg->umin_value && 608 reg->u32_min_value != U32_MIN) 609 verbose(env, ",u32_min_value=%d", 610 (int)(reg->u32_min_value)); 611 if (reg->u32_max_value != reg->umax_value && 612 reg->u32_max_value != U32_MAX) 613 verbose(env, ",u32_max_value=%d", 614 (int)(reg->u32_max_value)); 615 } 616 verbose(env, ")"); 617 } 618 } 619 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 620 char types_buf[BPF_REG_SIZE + 1]; 621 bool valid = false; 622 int j; 623 624 for (j = 0; j < BPF_REG_SIZE; j++) { 625 if (state->stack[i].slot_type[j] != STACK_INVALID) 626 valid = true; 627 types_buf[j] = slot_type_char[ 628 state->stack[i].slot_type[j]]; 629 } 630 types_buf[BPF_REG_SIZE] = 0; 631 if (!valid) 632 continue; 633 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 634 print_liveness(env, state->stack[i].spilled_ptr.live); 635 if (state->stack[i].slot_type[0] == STACK_SPILL) { 636 reg = &state->stack[i].spilled_ptr; 637 t = reg->type; 638 verbose(env, "=%s", reg_type_str[t]); 639 if (t == SCALAR_VALUE && reg->precise) 640 verbose(env, "P"); 641 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 642 verbose(env, "%lld", reg->var_off.value + reg->off); 643 } else { 644 verbose(env, "=%s", types_buf); 645 } 646 } 647 if (state->acquired_refs && state->refs[0].id) { 648 verbose(env, " refs=%d", state->refs[0].id); 649 for (i = 1; i < state->acquired_refs; i++) 650 if (state->refs[i].id) 651 verbose(env, ",%d", state->refs[i].id); 652 } 653 verbose(env, "\n"); 654 } 655 656 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \ 657 static int copy_##NAME##_state(struct bpf_func_state *dst, \ 658 const struct bpf_func_state *src) \ 659 { \ 660 if (!src->FIELD) \ 661 return 0; \ 662 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \ 663 /* internal bug, make state invalid to reject the program */ \ 664 memset(dst, 0, sizeof(*dst)); \ 665 return -EFAULT; \ 666 } \ 667 memcpy(dst->FIELD, src->FIELD, \ 668 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \ 669 return 0; \ 670 } 671 /* copy_reference_state() */ 672 COPY_STATE_FN(reference, acquired_refs, refs, 1) 673 /* copy_stack_state() */ 674 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE) 675 #undef COPY_STATE_FN 676 677 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \ 678 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \ 679 bool copy_old) \ 680 { \ 681 u32 old_size = state->COUNT; \ 682 struct bpf_##NAME##_state *new_##FIELD; \ 683 int slot = size / SIZE; \ 684 \ 685 if (size <= old_size || !size) { \ 686 if (copy_old) \ 687 return 0; \ 688 state->COUNT = slot * SIZE; \ 689 if (!size && old_size) { \ 690 kfree(state->FIELD); \ 691 state->FIELD = NULL; \ 692 } \ 693 return 0; \ 694 } \ 695 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \ 696 GFP_KERNEL); \ 697 if (!new_##FIELD) \ 698 return -ENOMEM; \ 699 if (copy_old) { \ 700 if (state->FIELD) \ 701 memcpy(new_##FIELD, state->FIELD, \ 702 sizeof(*new_##FIELD) * (old_size / SIZE)); \ 703 memset(new_##FIELD + old_size / SIZE, 0, \ 704 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \ 705 } \ 706 state->COUNT = slot * SIZE; \ 707 kfree(state->FIELD); \ 708 state->FIELD = new_##FIELD; \ 709 return 0; \ 710 } 711 /* realloc_reference_state() */ 712 REALLOC_STATE_FN(reference, acquired_refs, refs, 1) 713 /* realloc_stack_state() */ 714 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE) 715 #undef REALLOC_STATE_FN 716 717 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to 718 * make it consume minimal amount of memory. check_stack_write() access from 719 * the program calls into realloc_func_state() to grow the stack size. 720 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state 721 * which realloc_stack_state() copies over. It points to previous 722 * bpf_verifier_state which is never reallocated. 723 */ 724 static int realloc_func_state(struct bpf_func_state *state, int stack_size, 725 int refs_size, bool copy_old) 726 { 727 int err = realloc_reference_state(state, refs_size, copy_old); 728 if (err) 729 return err; 730 return realloc_stack_state(state, stack_size, copy_old); 731 } 732 733 /* Acquire a pointer id from the env and update the state->refs to include 734 * this new pointer reference. 735 * On success, returns a valid pointer id to associate with the register 736 * On failure, returns a negative errno. 737 */ 738 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 739 { 740 struct bpf_func_state *state = cur_func(env); 741 int new_ofs = state->acquired_refs; 742 int id, err; 743 744 err = realloc_reference_state(state, state->acquired_refs + 1, true); 745 if (err) 746 return err; 747 id = ++env->id_gen; 748 state->refs[new_ofs].id = id; 749 state->refs[new_ofs].insn_idx = insn_idx; 750 751 return id; 752 } 753 754 /* release function corresponding to acquire_reference_state(). Idempotent. */ 755 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 756 { 757 int i, last_idx; 758 759 last_idx = state->acquired_refs - 1; 760 for (i = 0; i < state->acquired_refs; i++) { 761 if (state->refs[i].id == ptr_id) { 762 if (last_idx && i != last_idx) 763 memcpy(&state->refs[i], &state->refs[last_idx], 764 sizeof(*state->refs)); 765 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 766 state->acquired_refs--; 767 return 0; 768 } 769 } 770 return -EINVAL; 771 } 772 773 static int transfer_reference_state(struct bpf_func_state *dst, 774 struct bpf_func_state *src) 775 { 776 int err = realloc_reference_state(dst, src->acquired_refs, false); 777 if (err) 778 return err; 779 err = copy_reference_state(dst, src); 780 if (err) 781 return err; 782 return 0; 783 } 784 785 static void free_func_state(struct bpf_func_state *state) 786 { 787 if (!state) 788 return; 789 kfree(state->refs); 790 kfree(state->stack); 791 kfree(state); 792 } 793 794 static void clear_jmp_history(struct bpf_verifier_state *state) 795 { 796 kfree(state->jmp_history); 797 state->jmp_history = NULL; 798 state->jmp_history_cnt = 0; 799 } 800 801 static void free_verifier_state(struct bpf_verifier_state *state, 802 bool free_self) 803 { 804 int i; 805 806 for (i = 0; i <= state->curframe; i++) { 807 free_func_state(state->frame[i]); 808 state->frame[i] = NULL; 809 } 810 clear_jmp_history(state); 811 if (free_self) 812 kfree(state); 813 } 814 815 /* copy verifier state from src to dst growing dst stack space 816 * when necessary to accommodate larger src stack 817 */ 818 static int copy_func_state(struct bpf_func_state *dst, 819 const struct bpf_func_state *src) 820 { 821 int err; 822 823 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs, 824 false); 825 if (err) 826 return err; 827 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 828 err = copy_reference_state(dst, src); 829 if (err) 830 return err; 831 return copy_stack_state(dst, src); 832 } 833 834 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 835 const struct bpf_verifier_state *src) 836 { 837 struct bpf_func_state *dst; 838 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt; 839 int i, err; 840 841 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) { 842 kfree(dst_state->jmp_history); 843 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER); 844 if (!dst_state->jmp_history) 845 return -ENOMEM; 846 } 847 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz); 848 dst_state->jmp_history_cnt = src->jmp_history_cnt; 849 850 /* if dst has more stack frames then src frame, free them */ 851 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 852 free_func_state(dst_state->frame[i]); 853 dst_state->frame[i] = NULL; 854 } 855 dst_state->speculative = src->speculative; 856 dst_state->curframe = src->curframe; 857 dst_state->active_spin_lock = src->active_spin_lock; 858 dst_state->branches = src->branches; 859 dst_state->parent = src->parent; 860 dst_state->first_insn_idx = src->first_insn_idx; 861 dst_state->last_insn_idx = src->last_insn_idx; 862 for (i = 0; i <= src->curframe; i++) { 863 dst = dst_state->frame[i]; 864 if (!dst) { 865 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 866 if (!dst) 867 return -ENOMEM; 868 dst_state->frame[i] = dst; 869 } 870 err = copy_func_state(dst, src->frame[i]); 871 if (err) 872 return err; 873 } 874 return 0; 875 } 876 877 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 878 { 879 while (st) { 880 u32 br = --st->branches; 881 882 /* WARN_ON(br > 1) technically makes sense here, 883 * but see comment in push_stack(), hence: 884 */ 885 WARN_ONCE((int)br < 0, 886 "BUG update_branch_counts:branches_to_explore=%d\n", 887 br); 888 if (br) 889 break; 890 st = st->parent; 891 } 892 } 893 894 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 895 int *insn_idx, bool pop_log) 896 { 897 struct bpf_verifier_state *cur = env->cur_state; 898 struct bpf_verifier_stack_elem *elem, *head = env->head; 899 int err; 900 901 if (env->head == NULL) 902 return -ENOENT; 903 904 if (cur) { 905 err = copy_verifier_state(cur, &head->st); 906 if (err) 907 return err; 908 } 909 if (pop_log) 910 bpf_vlog_reset(&env->log, head->log_pos); 911 if (insn_idx) 912 *insn_idx = head->insn_idx; 913 if (prev_insn_idx) 914 *prev_insn_idx = head->prev_insn_idx; 915 elem = head->next; 916 free_verifier_state(&head->st, false); 917 kfree(head); 918 env->head = elem; 919 env->stack_size--; 920 return 0; 921 } 922 923 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 924 int insn_idx, int prev_insn_idx, 925 bool speculative) 926 { 927 struct bpf_verifier_state *cur = env->cur_state; 928 struct bpf_verifier_stack_elem *elem; 929 int err; 930 931 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 932 if (!elem) 933 goto err; 934 935 elem->insn_idx = insn_idx; 936 elem->prev_insn_idx = prev_insn_idx; 937 elem->next = env->head; 938 elem->log_pos = env->log.len_used; 939 env->head = elem; 940 env->stack_size++; 941 err = copy_verifier_state(&elem->st, cur); 942 if (err) 943 goto err; 944 elem->st.speculative |= speculative; 945 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 946 verbose(env, "The sequence of %d jumps is too complex.\n", 947 env->stack_size); 948 goto err; 949 } 950 if (elem->st.parent) { 951 ++elem->st.parent->branches; 952 /* WARN_ON(branches > 2) technically makes sense here, 953 * but 954 * 1. speculative states will bump 'branches' for non-branch 955 * instructions 956 * 2. is_state_visited() heuristics may decide not to create 957 * a new state for a sequence of branches and all such current 958 * and cloned states will be pointing to a single parent state 959 * which might have large 'branches' count. 960 */ 961 } 962 return &elem->st; 963 err: 964 free_verifier_state(env->cur_state, true); 965 env->cur_state = NULL; 966 /* pop all elements and return */ 967 while (!pop_stack(env, NULL, NULL, false)); 968 return NULL; 969 } 970 971 #define CALLER_SAVED_REGS 6 972 static const int caller_saved[CALLER_SAVED_REGS] = { 973 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 974 }; 975 976 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 977 struct bpf_reg_state *reg); 978 979 /* Mark the unknown part of a register (variable offset or scalar value) as 980 * known to have the value @imm. 981 */ 982 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 983 { 984 /* Clear id, off, and union(map_ptr, range) */ 985 memset(((u8 *)reg) + sizeof(reg->type), 0, 986 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 987 reg->var_off = tnum_const(imm); 988 reg->smin_value = (s64)imm; 989 reg->smax_value = (s64)imm; 990 reg->umin_value = imm; 991 reg->umax_value = imm; 992 993 reg->s32_min_value = (s32)imm; 994 reg->s32_max_value = (s32)imm; 995 reg->u32_min_value = (u32)imm; 996 reg->u32_max_value = (u32)imm; 997 } 998 999 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1000 { 1001 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1002 reg->s32_min_value = (s32)imm; 1003 reg->s32_max_value = (s32)imm; 1004 reg->u32_min_value = (u32)imm; 1005 reg->u32_max_value = (u32)imm; 1006 } 1007 1008 /* Mark the 'variable offset' part of a register as zero. This should be 1009 * used only on registers holding a pointer type. 1010 */ 1011 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1012 { 1013 __mark_reg_known(reg, 0); 1014 } 1015 1016 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1017 { 1018 __mark_reg_known(reg, 0); 1019 reg->type = SCALAR_VALUE; 1020 } 1021 1022 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1023 struct bpf_reg_state *regs, u32 regno) 1024 { 1025 if (WARN_ON(regno >= MAX_BPF_REG)) { 1026 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1027 /* Something bad happened, let's kill all regs */ 1028 for (regno = 0; regno < MAX_BPF_REG; regno++) 1029 __mark_reg_not_init(env, regs + regno); 1030 return; 1031 } 1032 __mark_reg_known_zero(regs + regno); 1033 } 1034 1035 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1036 { 1037 return type_is_pkt_pointer(reg->type); 1038 } 1039 1040 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1041 { 1042 return reg_is_pkt_pointer(reg) || 1043 reg->type == PTR_TO_PACKET_END; 1044 } 1045 1046 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1047 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1048 enum bpf_reg_type which) 1049 { 1050 /* The register can already have a range from prior markings. 1051 * This is fine as long as it hasn't been advanced from its 1052 * origin. 1053 */ 1054 return reg->type == which && 1055 reg->id == 0 && 1056 reg->off == 0 && 1057 tnum_equals_const(reg->var_off, 0); 1058 } 1059 1060 /* Reset the min/max bounds of a register */ 1061 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1062 { 1063 reg->smin_value = S64_MIN; 1064 reg->smax_value = S64_MAX; 1065 reg->umin_value = 0; 1066 reg->umax_value = U64_MAX; 1067 1068 reg->s32_min_value = S32_MIN; 1069 reg->s32_max_value = S32_MAX; 1070 reg->u32_min_value = 0; 1071 reg->u32_max_value = U32_MAX; 1072 } 1073 1074 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1075 { 1076 reg->smin_value = S64_MIN; 1077 reg->smax_value = S64_MAX; 1078 reg->umin_value = 0; 1079 reg->umax_value = U64_MAX; 1080 } 1081 1082 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1083 { 1084 reg->s32_min_value = S32_MIN; 1085 reg->s32_max_value = S32_MAX; 1086 reg->u32_min_value = 0; 1087 reg->u32_max_value = U32_MAX; 1088 } 1089 1090 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1091 { 1092 struct tnum var32_off = tnum_subreg(reg->var_off); 1093 1094 /* min signed is max(sign bit) | min(other bits) */ 1095 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1096 var32_off.value | (var32_off.mask & S32_MIN)); 1097 /* max signed is min(sign bit) | max(other bits) */ 1098 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1099 var32_off.value | (var32_off.mask & S32_MAX)); 1100 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1101 reg->u32_max_value = min(reg->u32_max_value, 1102 (u32)(var32_off.value | var32_off.mask)); 1103 } 1104 1105 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1106 { 1107 /* min signed is max(sign bit) | min(other bits) */ 1108 reg->smin_value = max_t(s64, reg->smin_value, 1109 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1110 /* max signed is min(sign bit) | max(other bits) */ 1111 reg->smax_value = min_t(s64, reg->smax_value, 1112 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1113 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1114 reg->umax_value = min(reg->umax_value, 1115 reg->var_off.value | reg->var_off.mask); 1116 } 1117 1118 static void __update_reg_bounds(struct bpf_reg_state *reg) 1119 { 1120 __update_reg32_bounds(reg); 1121 __update_reg64_bounds(reg); 1122 } 1123 1124 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1125 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1126 { 1127 /* Learn sign from signed bounds. 1128 * If we cannot cross the sign boundary, then signed and unsigned bounds 1129 * are the same, so combine. This works even in the negative case, e.g. 1130 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1131 */ 1132 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 1133 reg->s32_min_value = reg->u32_min_value = 1134 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1135 reg->s32_max_value = reg->u32_max_value = 1136 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1137 return; 1138 } 1139 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1140 * boundary, so we must be careful. 1141 */ 1142 if ((s32)reg->u32_max_value >= 0) { 1143 /* Positive. We can't learn anything from the smin, but smax 1144 * is positive, hence safe. 1145 */ 1146 reg->s32_min_value = reg->u32_min_value; 1147 reg->s32_max_value = reg->u32_max_value = 1148 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1149 } else if ((s32)reg->u32_min_value < 0) { 1150 /* Negative. We can't learn anything from the smax, but smin 1151 * is negative, hence safe. 1152 */ 1153 reg->s32_min_value = reg->u32_min_value = 1154 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1155 reg->s32_max_value = reg->u32_max_value; 1156 } 1157 } 1158 1159 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 1160 { 1161 /* Learn sign from signed bounds. 1162 * If we cannot cross the sign boundary, then signed and unsigned bounds 1163 * are the same, so combine. This works even in the negative case, e.g. 1164 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1165 */ 1166 if (reg->smin_value >= 0 || reg->smax_value < 0) { 1167 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1168 reg->umin_value); 1169 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1170 reg->umax_value); 1171 return; 1172 } 1173 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1174 * boundary, so we must be careful. 1175 */ 1176 if ((s64)reg->umax_value >= 0) { 1177 /* Positive. We can't learn anything from the smin, but smax 1178 * is positive, hence safe. 1179 */ 1180 reg->smin_value = reg->umin_value; 1181 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1182 reg->umax_value); 1183 } else if ((s64)reg->umin_value < 0) { 1184 /* Negative. We can't learn anything from the smax, but smin 1185 * is negative, hence safe. 1186 */ 1187 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1188 reg->umin_value); 1189 reg->smax_value = reg->umax_value; 1190 } 1191 } 1192 1193 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 1194 { 1195 __reg32_deduce_bounds(reg); 1196 __reg64_deduce_bounds(reg); 1197 } 1198 1199 /* Attempts to improve var_off based on unsigned min/max information */ 1200 static void __reg_bound_offset(struct bpf_reg_state *reg) 1201 { 1202 struct tnum var64_off = tnum_intersect(reg->var_off, 1203 tnum_range(reg->umin_value, 1204 reg->umax_value)); 1205 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off), 1206 tnum_range(reg->u32_min_value, 1207 reg->u32_max_value)); 1208 1209 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 1210 } 1211 1212 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 1213 { 1214 reg->umin_value = reg->u32_min_value; 1215 reg->umax_value = reg->u32_max_value; 1216 /* Attempt to pull 32-bit signed bounds into 64-bit bounds 1217 * but must be positive otherwise set to worse case bounds 1218 * and refine later from tnum. 1219 */ 1220 if (reg->s32_min_value > 0) 1221 reg->smin_value = reg->s32_min_value; 1222 else 1223 reg->smin_value = 0; 1224 if (reg->s32_max_value > 0) 1225 reg->smax_value = reg->s32_max_value; 1226 else 1227 reg->smax_value = U32_MAX; 1228 } 1229 1230 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 1231 { 1232 /* special case when 64-bit register has upper 32-bit register 1233 * zeroed. Typically happens after zext or <<32, >>32 sequence 1234 * allowing us to use 32-bit bounds directly, 1235 */ 1236 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 1237 __reg_assign_32_into_64(reg); 1238 } else { 1239 /* Otherwise the best we can do is push lower 32bit known and 1240 * unknown bits into register (var_off set from jmp logic) 1241 * then learn as much as possible from the 64-bit tnum 1242 * known and unknown bits. The previous smin/smax bounds are 1243 * invalid here because of jmp32 compare so mark them unknown 1244 * so they do not impact tnum bounds calculation. 1245 */ 1246 __mark_reg64_unbounded(reg); 1247 __update_reg_bounds(reg); 1248 } 1249 1250 /* Intersecting with the old var_off might have improved our bounds 1251 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1252 * then new var_off is (0; 0x7f...fc) which improves our umax. 1253 */ 1254 __reg_deduce_bounds(reg); 1255 __reg_bound_offset(reg); 1256 __update_reg_bounds(reg); 1257 } 1258 1259 static bool __reg64_bound_s32(s64 a) 1260 { 1261 if (a > S32_MIN && a < S32_MAX) 1262 return true; 1263 return false; 1264 } 1265 1266 static bool __reg64_bound_u32(u64 a) 1267 { 1268 if (a > U32_MIN && a < U32_MAX) 1269 return true; 1270 return false; 1271 } 1272 1273 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 1274 { 1275 __mark_reg32_unbounded(reg); 1276 1277 if (__reg64_bound_s32(reg->smin_value)) 1278 reg->s32_min_value = (s32)reg->smin_value; 1279 if (__reg64_bound_s32(reg->smax_value)) 1280 reg->s32_max_value = (s32)reg->smax_value; 1281 if (__reg64_bound_u32(reg->umin_value)) 1282 reg->u32_min_value = (u32)reg->umin_value; 1283 if (__reg64_bound_u32(reg->umax_value)) 1284 reg->u32_max_value = (u32)reg->umax_value; 1285 1286 /* Intersecting with the old var_off might have improved our bounds 1287 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1288 * then new var_off is (0; 0x7f...fc) which improves our umax. 1289 */ 1290 __reg_deduce_bounds(reg); 1291 __reg_bound_offset(reg); 1292 __update_reg_bounds(reg); 1293 } 1294 1295 /* Mark a register as having a completely unknown (scalar) value. */ 1296 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1297 struct bpf_reg_state *reg) 1298 { 1299 /* 1300 * Clear type, id, off, and union(map_ptr, range) and 1301 * padding between 'type' and union 1302 */ 1303 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 1304 reg->type = SCALAR_VALUE; 1305 reg->var_off = tnum_unknown; 1306 reg->frameno = 0; 1307 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable; 1308 __mark_reg_unbounded(reg); 1309 } 1310 1311 static void mark_reg_unknown(struct bpf_verifier_env *env, 1312 struct bpf_reg_state *regs, u32 regno) 1313 { 1314 if (WARN_ON(regno >= MAX_BPF_REG)) { 1315 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 1316 /* Something bad happened, let's kill all regs except FP */ 1317 for (regno = 0; regno < BPF_REG_FP; regno++) 1318 __mark_reg_not_init(env, regs + regno); 1319 return; 1320 } 1321 __mark_reg_unknown(env, regs + regno); 1322 } 1323 1324 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1325 struct bpf_reg_state *reg) 1326 { 1327 __mark_reg_unknown(env, reg); 1328 reg->type = NOT_INIT; 1329 } 1330 1331 static void mark_reg_not_init(struct bpf_verifier_env *env, 1332 struct bpf_reg_state *regs, u32 regno) 1333 { 1334 if (WARN_ON(regno >= MAX_BPF_REG)) { 1335 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 1336 /* Something bad happened, let's kill all regs except FP */ 1337 for (regno = 0; regno < BPF_REG_FP; regno++) 1338 __mark_reg_not_init(env, regs + regno); 1339 return; 1340 } 1341 __mark_reg_not_init(env, regs + regno); 1342 } 1343 1344 #define DEF_NOT_SUBREG (0) 1345 static void init_reg_state(struct bpf_verifier_env *env, 1346 struct bpf_func_state *state) 1347 { 1348 struct bpf_reg_state *regs = state->regs; 1349 int i; 1350 1351 for (i = 0; i < MAX_BPF_REG; i++) { 1352 mark_reg_not_init(env, regs, i); 1353 regs[i].live = REG_LIVE_NONE; 1354 regs[i].parent = NULL; 1355 regs[i].subreg_def = DEF_NOT_SUBREG; 1356 } 1357 1358 /* frame pointer */ 1359 regs[BPF_REG_FP].type = PTR_TO_STACK; 1360 mark_reg_known_zero(env, regs, BPF_REG_FP); 1361 regs[BPF_REG_FP].frameno = state->frameno; 1362 } 1363 1364 #define BPF_MAIN_FUNC (-1) 1365 static void init_func_state(struct bpf_verifier_env *env, 1366 struct bpf_func_state *state, 1367 int callsite, int frameno, int subprogno) 1368 { 1369 state->callsite = callsite; 1370 state->frameno = frameno; 1371 state->subprogno = subprogno; 1372 init_reg_state(env, state); 1373 } 1374 1375 enum reg_arg_type { 1376 SRC_OP, /* register is used as source operand */ 1377 DST_OP, /* register is used as destination operand */ 1378 DST_OP_NO_MARK /* same as above, check only, don't mark */ 1379 }; 1380 1381 static int cmp_subprogs(const void *a, const void *b) 1382 { 1383 return ((struct bpf_subprog_info *)a)->start - 1384 ((struct bpf_subprog_info *)b)->start; 1385 } 1386 1387 static int find_subprog(struct bpf_verifier_env *env, int off) 1388 { 1389 struct bpf_subprog_info *p; 1390 1391 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 1392 sizeof(env->subprog_info[0]), cmp_subprogs); 1393 if (!p) 1394 return -ENOENT; 1395 return p - env->subprog_info; 1396 1397 } 1398 1399 static int add_subprog(struct bpf_verifier_env *env, int off) 1400 { 1401 int insn_cnt = env->prog->len; 1402 int ret; 1403 1404 if (off >= insn_cnt || off < 0) { 1405 verbose(env, "call to invalid destination\n"); 1406 return -EINVAL; 1407 } 1408 ret = find_subprog(env, off); 1409 if (ret >= 0) 1410 return 0; 1411 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 1412 verbose(env, "too many subprograms\n"); 1413 return -E2BIG; 1414 } 1415 env->subprog_info[env->subprog_cnt++].start = off; 1416 sort(env->subprog_info, env->subprog_cnt, 1417 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 1418 return 0; 1419 } 1420 1421 static int check_subprogs(struct bpf_verifier_env *env) 1422 { 1423 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0; 1424 struct bpf_subprog_info *subprog = env->subprog_info; 1425 struct bpf_insn *insn = env->prog->insnsi; 1426 int insn_cnt = env->prog->len; 1427 1428 /* Add entry function. */ 1429 ret = add_subprog(env, 0); 1430 if (ret < 0) 1431 return ret; 1432 1433 /* determine subprog starts. The end is one before the next starts */ 1434 for (i = 0; i < insn_cnt; i++) { 1435 if (insn[i].code != (BPF_JMP | BPF_CALL)) 1436 continue; 1437 if (insn[i].src_reg != BPF_PSEUDO_CALL) 1438 continue; 1439 if (!env->bpf_capable) { 1440 verbose(env, 1441 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 1442 return -EPERM; 1443 } 1444 ret = add_subprog(env, i + insn[i].imm + 1); 1445 if (ret < 0) 1446 return ret; 1447 } 1448 1449 /* Add a fake 'exit' subprog which could simplify subprog iteration 1450 * logic. 'subprog_cnt' should not be increased. 1451 */ 1452 subprog[env->subprog_cnt].start = insn_cnt; 1453 1454 if (env->log.level & BPF_LOG_LEVEL2) 1455 for (i = 0; i < env->subprog_cnt; i++) 1456 verbose(env, "func#%d @%d\n", i, subprog[i].start); 1457 1458 /* now check that all jumps are within the same subprog */ 1459 subprog_start = subprog[cur_subprog].start; 1460 subprog_end = subprog[cur_subprog + 1].start; 1461 for (i = 0; i < insn_cnt; i++) { 1462 u8 code = insn[i].code; 1463 1464 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 1465 goto next; 1466 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 1467 goto next; 1468 off = i + insn[i].off + 1; 1469 if (off < subprog_start || off >= subprog_end) { 1470 verbose(env, "jump out of range from insn %d to %d\n", i, off); 1471 return -EINVAL; 1472 } 1473 next: 1474 if (i == subprog_end - 1) { 1475 /* to avoid fall-through from one subprog into another 1476 * the last insn of the subprog should be either exit 1477 * or unconditional jump back 1478 */ 1479 if (code != (BPF_JMP | BPF_EXIT) && 1480 code != (BPF_JMP | BPF_JA)) { 1481 verbose(env, "last insn is not an exit or jmp\n"); 1482 return -EINVAL; 1483 } 1484 subprog_start = subprog_end; 1485 cur_subprog++; 1486 if (cur_subprog < env->subprog_cnt) 1487 subprog_end = subprog[cur_subprog + 1].start; 1488 } 1489 } 1490 return 0; 1491 } 1492 1493 /* Parentage chain of this register (or stack slot) should take care of all 1494 * issues like callee-saved registers, stack slot allocation time, etc. 1495 */ 1496 static int mark_reg_read(struct bpf_verifier_env *env, 1497 const struct bpf_reg_state *state, 1498 struct bpf_reg_state *parent, u8 flag) 1499 { 1500 bool writes = parent == state->parent; /* Observe write marks */ 1501 int cnt = 0; 1502 1503 while (parent) { 1504 /* if read wasn't screened by an earlier write ... */ 1505 if (writes && state->live & REG_LIVE_WRITTEN) 1506 break; 1507 if (parent->live & REG_LIVE_DONE) { 1508 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 1509 reg_type_str[parent->type], 1510 parent->var_off.value, parent->off); 1511 return -EFAULT; 1512 } 1513 /* The first condition is more likely to be true than the 1514 * second, checked it first. 1515 */ 1516 if ((parent->live & REG_LIVE_READ) == flag || 1517 parent->live & REG_LIVE_READ64) 1518 /* The parentage chain never changes and 1519 * this parent was already marked as LIVE_READ. 1520 * There is no need to keep walking the chain again and 1521 * keep re-marking all parents as LIVE_READ. 1522 * This case happens when the same register is read 1523 * multiple times without writes into it in-between. 1524 * Also, if parent has the stronger REG_LIVE_READ64 set, 1525 * then no need to set the weak REG_LIVE_READ32. 1526 */ 1527 break; 1528 /* ... then we depend on parent's value */ 1529 parent->live |= flag; 1530 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 1531 if (flag == REG_LIVE_READ64) 1532 parent->live &= ~REG_LIVE_READ32; 1533 state = parent; 1534 parent = state->parent; 1535 writes = true; 1536 cnt++; 1537 } 1538 1539 if (env->longest_mark_read_walk < cnt) 1540 env->longest_mark_read_walk = cnt; 1541 return 0; 1542 } 1543 1544 /* This function is supposed to be used by the following 32-bit optimization 1545 * code only. It returns TRUE if the source or destination register operates 1546 * on 64-bit, otherwise return FALSE. 1547 */ 1548 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 1549 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 1550 { 1551 u8 code, class, op; 1552 1553 code = insn->code; 1554 class = BPF_CLASS(code); 1555 op = BPF_OP(code); 1556 if (class == BPF_JMP) { 1557 /* BPF_EXIT for "main" will reach here. Return TRUE 1558 * conservatively. 1559 */ 1560 if (op == BPF_EXIT) 1561 return true; 1562 if (op == BPF_CALL) { 1563 /* BPF to BPF call will reach here because of marking 1564 * caller saved clobber with DST_OP_NO_MARK for which we 1565 * don't care the register def because they are anyway 1566 * marked as NOT_INIT already. 1567 */ 1568 if (insn->src_reg == BPF_PSEUDO_CALL) 1569 return false; 1570 /* Helper call will reach here because of arg type 1571 * check, conservatively return TRUE. 1572 */ 1573 if (t == SRC_OP) 1574 return true; 1575 1576 return false; 1577 } 1578 } 1579 1580 if (class == BPF_ALU64 || class == BPF_JMP || 1581 /* BPF_END always use BPF_ALU class. */ 1582 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 1583 return true; 1584 1585 if (class == BPF_ALU || class == BPF_JMP32) 1586 return false; 1587 1588 if (class == BPF_LDX) { 1589 if (t != SRC_OP) 1590 return BPF_SIZE(code) == BPF_DW; 1591 /* LDX source must be ptr. */ 1592 return true; 1593 } 1594 1595 if (class == BPF_STX) { 1596 if (reg->type != SCALAR_VALUE) 1597 return true; 1598 return BPF_SIZE(code) == BPF_DW; 1599 } 1600 1601 if (class == BPF_LD) { 1602 u8 mode = BPF_MODE(code); 1603 1604 /* LD_IMM64 */ 1605 if (mode == BPF_IMM) 1606 return true; 1607 1608 /* Both LD_IND and LD_ABS return 32-bit data. */ 1609 if (t != SRC_OP) 1610 return false; 1611 1612 /* Implicit ctx ptr. */ 1613 if (regno == BPF_REG_6) 1614 return true; 1615 1616 /* Explicit source could be any width. */ 1617 return true; 1618 } 1619 1620 if (class == BPF_ST) 1621 /* The only source register for BPF_ST is a ptr. */ 1622 return true; 1623 1624 /* Conservatively return true at default. */ 1625 return true; 1626 } 1627 1628 /* Return TRUE if INSN doesn't have explicit value define. */ 1629 static bool insn_no_def(struct bpf_insn *insn) 1630 { 1631 u8 class = BPF_CLASS(insn->code); 1632 1633 return (class == BPF_JMP || class == BPF_JMP32 || 1634 class == BPF_STX || class == BPF_ST); 1635 } 1636 1637 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 1638 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 1639 { 1640 if (insn_no_def(insn)) 1641 return false; 1642 1643 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP); 1644 } 1645 1646 static void mark_insn_zext(struct bpf_verifier_env *env, 1647 struct bpf_reg_state *reg) 1648 { 1649 s32 def_idx = reg->subreg_def; 1650 1651 if (def_idx == DEF_NOT_SUBREG) 1652 return; 1653 1654 env->insn_aux_data[def_idx - 1].zext_dst = true; 1655 /* The dst will be zero extended, so won't be sub-register anymore. */ 1656 reg->subreg_def = DEF_NOT_SUBREG; 1657 } 1658 1659 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 1660 enum reg_arg_type t) 1661 { 1662 struct bpf_verifier_state *vstate = env->cur_state; 1663 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 1664 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 1665 struct bpf_reg_state *reg, *regs = state->regs; 1666 bool rw64; 1667 1668 if (regno >= MAX_BPF_REG) { 1669 verbose(env, "R%d is invalid\n", regno); 1670 return -EINVAL; 1671 } 1672 1673 reg = ®s[regno]; 1674 rw64 = is_reg64(env, insn, regno, reg, t); 1675 if (t == SRC_OP) { 1676 /* check whether register used as source operand can be read */ 1677 if (reg->type == NOT_INIT) { 1678 verbose(env, "R%d !read_ok\n", regno); 1679 return -EACCES; 1680 } 1681 /* We don't need to worry about FP liveness because it's read-only */ 1682 if (regno == BPF_REG_FP) 1683 return 0; 1684 1685 if (rw64) 1686 mark_insn_zext(env, reg); 1687 1688 return mark_reg_read(env, reg, reg->parent, 1689 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 1690 } else { 1691 /* check whether register used as dest operand can be written to */ 1692 if (regno == BPF_REG_FP) { 1693 verbose(env, "frame pointer is read only\n"); 1694 return -EACCES; 1695 } 1696 reg->live |= REG_LIVE_WRITTEN; 1697 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 1698 if (t == DST_OP) 1699 mark_reg_unknown(env, regs, regno); 1700 } 1701 return 0; 1702 } 1703 1704 /* for any branch, call, exit record the history of jmps in the given state */ 1705 static int push_jmp_history(struct bpf_verifier_env *env, 1706 struct bpf_verifier_state *cur) 1707 { 1708 u32 cnt = cur->jmp_history_cnt; 1709 struct bpf_idx_pair *p; 1710 1711 cnt++; 1712 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER); 1713 if (!p) 1714 return -ENOMEM; 1715 p[cnt - 1].idx = env->insn_idx; 1716 p[cnt - 1].prev_idx = env->prev_insn_idx; 1717 cur->jmp_history = p; 1718 cur->jmp_history_cnt = cnt; 1719 return 0; 1720 } 1721 1722 /* Backtrack one insn at a time. If idx is not at the top of recorded 1723 * history then previous instruction came from straight line execution. 1724 */ 1725 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 1726 u32 *history) 1727 { 1728 u32 cnt = *history; 1729 1730 if (cnt && st->jmp_history[cnt - 1].idx == i) { 1731 i = st->jmp_history[cnt - 1].prev_idx; 1732 (*history)--; 1733 } else { 1734 i--; 1735 } 1736 return i; 1737 } 1738 1739 /* For given verifier state backtrack_insn() is called from the last insn to 1740 * the first insn. Its purpose is to compute a bitmask of registers and 1741 * stack slots that needs precision in the parent verifier state. 1742 */ 1743 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 1744 u32 *reg_mask, u64 *stack_mask) 1745 { 1746 const struct bpf_insn_cbs cbs = { 1747 .cb_print = verbose, 1748 .private_data = env, 1749 }; 1750 struct bpf_insn *insn = env->prog->insnsi + idx; 1751 u8 class = BPF_CLASS(insn->code); 1752 u8 opcode = BPF_OP(insn->code); 1753 u8 mode = BPF_MODE(insn->code); 1754 u32 dreg = 1u << insn->dst_reg; 1755 u32 sreg = 1u << insn->src_reg; 1756 u32 spi; 1757 1758 if (insn->code == 0) 1759 return 0; 1760 if (env->log.level & BPF_LOG_LEVEL) { 1761 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask); 1762 verbose(env, "%d: ", idx); 1763 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 1764 } 1765 1766 if (class == BPF_ALU || class == BPF_ALU64) { 1767 if (!(*reg_mask & dreg)) 1768 return 0; 1769 if (opcode == BPF_MOV) { 1770 if (BPF_SRC(insn->code) == BPF_X) { 1771 /* dreg = sreg 1772 * dreg needs precision after this insn 1773 * sreg needs precision before this insn 1774 */ 1775 *reg_mask &= ~dreg; 1776 *reg_mask |= sreg; 1777 } else { 1778 /* dreg = K 1779 * dreg needs precision after this insn. 1780 * Corresponding register is already marked 1781 * as precise=true in this verifier state. 1782 * No further markings in parent are necessary 1783 */ 1784 *reg_mask &= ~dreg; 1785 } 1786 } else { 1787 if (BPF_SRC(insn->code) == BPF_X) { 1788 /* dreg += sreg 1789 * both dreg and sreg need precision 1790 * before this insn 1791 */ 1792 *reg_mask |= sreg; 1793 } /* else dreg += K 1794 * dreg still needs precision before this insn 1795 */ 1796 } 1797 } else if (class == BPF_LDX) { 1798 if (!(*reg_mask & dreg)) 1799 return 0; 1800 *reg_mask &= ~dreg; 1801 1802 /* scalars can only be spilled into stack w/o losing precision. 1803 * Load from any other memory can be zero extended. 1804 * The desire to keep that precision is already indicated 1805 * by 'precise' mark in corresponding register of this state. 1806 * No further tracking necessary. 1807 */ 1808 if (insn->src_reg != BPF_REG_FP) 1809 return 0; 1810 if (BPF_SIZE(insn->code) != BPF_DW) 1811 return 0; 1812 1813 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 1814 * that [fp - off] slot contains scalar that needs to be 1815 * tracked with precision 1816 */ 1817 spi = (-insn->off - 1) / BPF_REG_SIZE; 1818 if (spi >= 64) { 1819 verbose(env, "BUG spi %d\n", spi); 1820 WARN_ONCE(1, "verifier backtracking bug"); 1821 return -EFAULT; 1822 } 1823 *stack_mask |= 1ull << spi; 1824 } else if (class == BPF_STX || class == BPF_ST) { 1825 if (*reg_mask & dreg) 1826 /* stx & st shouldn't be using _scalar_ dst_reg 1827 * to access memory. It means backtracking 1828 * encountered a case of pointer subtraction. 1829 */ 1830 return -ENOTSUPP; 1831 /* scalars can only be spilled into stack */ 1832 if (insn->dst_reg != BPF_REG_FP) 1833 return 0; 1834 if (BPF_SIZE(insn->code) != BPF_DW) 1835 return 0; 1836 spi = (-insn->off - 1) / BPF_REG_SIZE; 1837 if (spi >= 64) { 1838 verbose(env, "BUG spi %d\n", spi); 1839 WARN_ONCE(1, "verifier backtracking bug"); 1840 return -EFAULT; 1841 } 1842 if (!(*stack_mask & (1ull << spi))) 1843 return 0; 1844 *stack_mask &= ~(1ull << spi); 1845 if (class == BPF_STX) 1846 *reg_mask |= sreg; 1847 } else if (class == BPF_JMP || class == BPF_JMP32) { 1848 if (opcode == BPF_CALL) { 1849 if (insn->src_reg == BPF_PSEUDO_CALL) 1850 return -ENOTSUPP; 1851 /* regular helper call sets R0 */ 1852 *reg_mask &= ~1; 1853 if (*reg_mask & 0x3f) { 1854 /* if backtracing was looking for registers R1-R5 1855 * they should have been found already. 1856 */ 1857 verbose(env, "BUG regs %x\n", *reg_mask); 1858 WARN_ONCE(1, "verifier backtracking bug"); 1859 return -EFAULT; 1860 } 1861 } else if (opcode == BPF_EXIT) { 1862 return -ENOTSUPP; 1863 } 1864 } else if (class == BPF_LD) { 1865 if (!(*reg_mask & dreg)) 1866 return 0; 1867 *reg_mask &= ~dreg; 1868 /* It's ld_imm64 or ld_abs or ld_ind. 1869 * For ld_imm64 no further tracking of precision 1870 * into parent is necessary 1871 */ 1872 if (mode == BPF_IND || mode == BPF_ABS) 1873 /* to be analyzed */ 1874 return -ENOTSUPP; 1875 } 1876 return 0; 1877 } 1878 1879 /* the scalar precision tracking algorithm: 1880 * . at the start all registers have precise=false. 1881 * . scalar ranges are tracked as normal through alu and jmp insns. 1882 * . once precise value of the scalar register is used in: 1883 * . ptr + scalar alu 1884 * . if (scalar cond K|scalar) 1885 * . helper_call(.., scalar, ...) where ARG_CONST is expected 1886 * backtrack through the verifier states and mark all registers and 1887 * stack slots with spilled constants that these scalar regisers 1888 * should be precise. 1889 * . during state pruning two registers (or spilled stack slots) 1890 * are equivalent if both are not precise. 1891 * 1892 * Note the verifier cannot simply walk register parentage chain, 1893 * since many different registers and stack slots could have been 1894 * used to compute single precise scalar. 1895 * 1896 * The approach of starting with precise=true for all registers and then 1897 * backtrack to mark a register as not precise when the verifier detects 1898 * that program doesn't care about specific value (e.g., when helper 1899 * takes register as ARG_ANYTHING parameter) is not safe. 1900 * 1901 * It's ok to walk single parentage chain of the verifier states. 1902 * It's possible that this backtracking will go all the way till 1st insn. 1903 * All other branches will be explored for needing precision later. 1904 * 1905 * The backtracking needs to deal with cases like: 1906 * 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) 1907 * r9 -= r8 1908 * r5 = r9 1909 * if r5 > 0x79f goto pc+7 1910 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 1911 * r5 += 1 1912 * ... 1913 * call bpf_perf_event_output#25 1914 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 1915 * 1916 * and this case: 1917 * r6 = 1 1918 * call foo // uses callee's r6 inside to compute r0 1919 * r0 += r6 1920 * if r0 == 0 goto 1921 * 1922 * to track above reg_mask/stack_mask needs to be independent for each frame. 1923 * 1924 * Also if parent's curframe > frame where backtracking started, 1925 * the verifier need to mark registers in both frames, otherwise callees 1926 * may incorrectly prune callers. This is similar to 1927 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 1928 * 1929 * For now backtracking falls back into conservative marking. 1930 */ 1931 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 1932 struct bpf_verifier_state *st) 1933 { 1934 struct bpf_func_state *func; 1935 struct bpf_reg_state *reg; 1936 int i, j; 1937 1938 /* big hammer: mark all scalars precise in this path. 1939 * pop_stack may still get !precise scalars. 1940 */ 1941 for (; st; st = st->parent) 1942 for (i = 0; i <= st->curframe; i++) { 1943 func = st->frame[i]; 1944 for (j = 0; j < BPF_REG_FP; j++) { 1945 reg = &func->regs[j]; 1946 if (reg->type != SCALAR_VALUE) 1947 continue; 1948 reg->precise = true; 1949 } 1950 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 1951 if (func->stack[j].slot_type[0] != STACK_SPILL) 1952 continue; 1953 reg = &func->stack[j].spilled_ptr; 1954 if (reg->type != SCALAR_VALUE) 1955 continue; 1956 reg->precise = true; 1957 } 1958 } 1959 } 1960 1961 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno, 1962 int spi) 1963 { 1964 struct bpf_verifier_state *st = env->cur_state; 1965 int first_idx = st->first_insn_idx; 1966 int last_idx = env->insn_idx; 1967 struct bpf_func_state *func; 1968 struct bpf_reg_state *reg; 1969 u32 reg_mask = regno >= 0 ? 1u << regno : 0; 1970 u64 stack_mask = spi >= 0 ? 1ull << spi : 0; 1971 bool skip_first = true; 1972 bool new_marks = false; 1973 int i, err; 1974 1975 if (!env->bpf_capable) 1976 return 0; 1977 1978 func = st->frame[st->curframe]; 1979 if (regno >= 0) { 1980 reg = &func->regs[regno]; 1981 if (reg->type != SCALAR_VALUE) { 1982 WARN_ONCE(1, "backtracing misuse"); 1983 return -EFAULT; 1984 } 1985 if (!reg->precise) 1986 new_marks = true; 1987 else 1988 reg_mask = 0; 1989 reg->precise = true; 1990 } 1991 1992 while (spi >= 0) { 1993 if (func->stack[spi].slot_type[0] != STACK_SPILL) { 1994 stack_mask = 0; 1995 break; 1996 } 1997 reg = &func->stack[spi].spilled_ptr; 1998 if (reg->type != SCALAR_VALUE) { 1999 stack_mask = 0; 2000 break; 2001 } 2002 if (!reg->precise) 2003 new_marks = true; 2004 else 2005 stack_mask = 0; 2006 reg->precise = true; 2007 break; 2008 } 2009 2010 if (!new_marks) 2011 return 0; 2012 if (!reg_mask && !stack_mask) 2013 return 0; 2014 for (;;) { 2015 DECLARE_BITMAP(mask, 64); 2016 u32 history = st->jmp_history_cnt; 2017 2018 if (env->log.level & BPF_LOG_LEVEL) 2019 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx); 2020 for (i = last_idx;;) { 2021 if (skip_first) { 2022 err = 0; 2023 skip_first = false; 2024 } else { 2025 err = backtrack_insn(env, i, ®_mask, &stack_mask); 2026 } 2027 if (err == -ENOTSUPP) { 2028 mark_all_scalars_precise(env, st); 2029 return 0; 2030 } else if (err) { 2031 return err; 2032 } 2033 if (!reg_mask && !stack_mask) 2034 /* Found assignment(s) into tracked register in this state. 2035 * Since this state is already marked, just return. 2036 * Nothing to be tracked further in the parent state. 2037 */ 2038 return 0; 2039 if (i == first_idx) 2040 break; 2041 i = get_prev_insn_idx(st, i, &history); 2042 if (i >= env->prog->len) { 2043 /* This can happen if backtracking reached insn 0 2044 * and there are still reg_mask or stack_mask 2045 * to backtrack. 2046 * It means the backtracking missed the spot where 2047 * particular register was initialized with a constant. 2048 */ 2049 verbose(env, "BUG backtracking idx %d\n", i); 2050 WARN_ONCE(1, "verifier backtracking bug"); 2051 return -EFAULT; 2052 } 2053 } 2054 st = st->parent; 2055 if (!st) 2056 break; 2057 2058 new_marks = false; 2059 func = st->frame[st->curframe]; 2060 bitmap_from_u64(mask, reg_mask); 2061 for_each_set_bit(i, mask, 32) { 2062 reg = &func->regs[i]; 2063 if (reg->type != SCALAR_VALUE) { 2064 reg_mask &= ~(1u << i); 2065 continue; 2066 } 2067 if (!reg->precise) 2068 new_marks = true; 2069 reg->precise = true; 2070 } 2071 2072 bitmap_from_u64(mask, stack_mask); 2073 for_each_set_bit(i, mask, 64) { 2074 if (i >= func->allocated_stack / BPF_REG_SIZE) { 2075 /* the sequence of instructions: 2076 * 2: (bf) r3 = r10 2077 * 3: (7b) *(u64 *)(r3 -8) = r0 2078 * 4: (79) r4 = *(u64 *)(r10 -8) 2079 * doesn't contain jmps. It's backtracked 2080 * as a single block. 2081 * During backtracking insn 3 is not recognized as 2082 * stack access, so at the end of backtracking 2083 * stack slot fp-8 is still marked in stack_mask. 2084 * However the parent state may not have accessed 2085 * fp-8 and it's "unallocated" stack space. 2086 * In such case fallback to conservative. 2087 */ 2088 mark_all_scalars_precise(env, st); 2089 return 0; 2090 } 2091 2092 if (func->stack[i].slot_type[0] != STACK_SPILL) { 2093 stack_mask &= ~(1ull << i); 2094 continue; 2095 } 2096 reg = &func->stack[i].spilled_ptr; 2097 if (reg->type != SCALAR_VALUE) { 2098 stack_mask &= ~(1ull << i); 2099 continue; 2100 } 2101 if (!reg->precise) 2102 new_marks = true; 2103 reg->precise = true; 2104 } 2105 if (env->log.level & BPF_LOG_LEVEL) { 2106 print_verifier_state(env, func); 2107 verbose(env, "parent %s regs=%x stack=%llx marks\n", 2108 new_marks ? "didn't have" : "already had", 2109 reg_mask, stack_mask); 2110 } 2111 2112 if (!reg_mask && !stack_mask) 2113 break; 2114 if (!new_marks) 2115 break; 2116 2117 last_idx = st->last_insn_idx; 2118 first_idx = st->first_insn_idx; 2119 } 2120 return 0; 2121 } 2122 2123 static int mark_chain_precision(struct bpf_verifier_env *env, int regno) 2124 { 2125 return __mark_chain_precision(env, regno, -1); 2126 } 2127 2128 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi) 2129 { 2130 return __mark_chain_precision(env, -1, spi); 2131 } 2132 2133 static bool is_spillable_regtype(enum bpf_reg_type type) 2134 { 2135 switch (type) { 2136 case PTR_TO_MAP_VALUE: 2137 case PTR_TO_MAP_VALUE_OR_NULL: 2138 case PTR_TO_STACK: 2139 case PTR_TO_CTX: 2140 case PTR_TO_PACKET: 2141 case PTR_TO_PACKET_META: 2142 case PTR_TO_PACKET_END: 2143 case PTR_TO_FLOW_KEYS: 2144 case CONST_PTR_TO_MAP: 2145 case PTR_TO_SOCKET: 2146 case PTR_TO_SOCKET_OR_NULL: 2147 case PTR_TO_SOCK_COMMON: 2148 case PTR_TO_SOCK_COMMON_OR_NULL: 2149 case PTR_TO_TCP_SOCK: 2150 case PTR_TO_TCP_SOCK_OR_NULL: 2151 case PTR_TO_XDP_SOCK: 2152 case PTR_TO_BTF_ID: 2153 case PTR_TO_BTF_ID_OR_NULL: 2154 return true; 2155 default: 2156 return false; 2157 } 2158 } 2159 2160 /* Does this register contain a constant zero? */ 2161 static bool register_is_null(struct bpf_reg_state *reg) 2162 { 2163 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 2164 } 2165 2166 static bool register_is_const(struct bpf_reg_state *reg) 2167 { 2168 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 2169 } 2170 2171 static bool __is_pointer_value(bool allow_ptr_leaks, 2172 const struct bpf_reg_state *reg) 2173 { 2174 if (allow_ptr_leaks) 2175 return false; 2176 2177 return reg->type != SCALAR_VALUE; 2178 } 2179 2180 static void save_register_state(struct bpf_func_state *state, 2181 int spi, struct bpf_reg_state *reg) 2182 { 2183 int i; 2184 2185 state->stack[spi].spilled_ptr = *reg; 2186 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2187 2188 for (i = 0; i < BPF_REG_SIZE; i++) 2189 state->stack[spi].slot_type[i] = STACK_SPILL; 2190 } 2191 2192 /* check_stack_read/write functions track spill/fill of registers, 2193 * stack boundary and alignment are checked in check_mem_access() 2194 */ 2195 static int check_stack_write(struct bpf_verifier_env *env, 2196 struct bpf_func_state *state, /* func where register points to */ 2197 int off, int size, int value_regno, int insn_idx) 2198 { 2199 struct bpf_func_state *cur; /* state of the current function */ 2200 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 2201 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg; 2202 struct bpf_reg_state *reg = NULL; 2203 2204 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE), 2205 state->acquired_refs, true); 2206 if (err) 2207 return err; 2208 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 2209 * so it's aligned access and [off, off + size) are within stack limits 2210 */ 2211 if (!env->allow_ptr_leaks && 2212 state->stack[spi].slot_type[0] == STACK_SPILL && 2213 size != BPF_REG_SIZE) { 2214 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 2215 return -EACCES; 2216 } 2217 2218 cur = env->cur_state->frame[env->cur_state->curframe]; 2219 if (value_regno >= 0) 2220 reg = &cur->regs[value_regno]; 2221 2222 if (reg && size == BPF_REG_SIZE && register_is_const(reg) && 2223 !register_is_null(reg) && env->bpf_capable) { 2224 if (dst_reg != BPF_REG_FP) { 2225 /* The backtracking logic can only recognize explicit 2226 * stack slot address like [fp - 8]. Other spill of 2227 * scalar via different register has to be conervative. 2228 * Backtrack from here and mark all registers as precise 2229 * that contributed into 'reg' being a constant. 2230 */ 2231 err = mark_chain_precision(env, value_regno); 2232 if (err) 2233 return err; 2234 } 2235 save_register_state(state, spi, reg); 2236 } else if (reg && is_spillable_regtype(reg->type)) { 2237 /* register containing pointer is being spilled into stack */ 2238 if (size != BPF_REG_SIZE) { 2239 verbose_linfo(env, insn_idx, "; "); 2240 verbose(env, "invalid size of register spill\n"); 2241 return -EACCES; 2242 } 2243 2244 if (state != cur && reg->type == PTR_TO_STACK) { 2245 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 2246 return -EINVAL; 2247 } 2248 2249 if (!env->bypass_spec_v4) { 2250 bool sanitize = false; 2251 2252 if (state->stack[spi].slot_type[0] == STACK_SPILL && 2253 register_is_const(&state->stack[spi].spilled_ptr)) 2254 sanitize = true; 2255 for (i = 0; i < BPF_REG_SIZE; i++) 2256 if (state->stack[spi].slot_type[i] == STACK_MISC) { 2257 sanitize = true; 2258 break; 2259 } 2260 if (sanitize) { 2261 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off; 2262 int soff = (-spi - 1) * BPF_REG_SIZE; 2263 2264 /* detected reuse of integer stack slot with a pointer 2265 * which means either llvm is reusing stack slot or 2266 * an attacker is trying to exploit CVE-2018-3639 2267 * (speculative store bypass) 2268 * Have to sanitize that slot with preemptive 2269 * store of zero. 2270 */ 2271 if (*poff && *poff != soff) { 2272 /* disallow programs where single insn stores 2273 * into two different stack slots, since verifier 2274 * cannot sanitize them 2275 */ 2276 verbose(env, 2277 "insn %d cannot access two stack slots fp%d and fp%d", 2278 insn_idx, *poff, soff); 2279 return -EINVAL; 2280 } 2281 *poff = soff; 2282 } 2283 } 2284 save_register_state(state, spi, reg); 2285 } else { 2286 u8 type = STACK_MISC; 2287 2288 /* regular write of data into stack destroys any spilled ptr */ 2289 state->stack[spi].spilled_ptr.type = NOT_INIT; 2290 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */ 2291 if (state->stack[spi].slot_type[0] == STACK_SPILL) 2292 for (i = 0; i < BPF_REG_SIZE; i++) 2293 state->stack[spi].slot_type[i] = STACK_MISC; 2294 2295 /* only mark the slot as written if all 8 bytes were written 2296 * otherwise read propagation may incorrectly stop too soon 2297 * when stack slots are partially written. 2298 * This heuristic means that read propagation will be 2299 * conservative, since it will add reg_live_read marks 2300 * to stack slots all the way to first state when programs 2301 * writes+reads less than 8 bytes 2302 */ 2303 if (size == BPF_REG_SIZE) 2304 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2305 2306 /* when we zero initialize stack slots mark them as such */ 2307 if (reg && register_is_null(reg)) { 2308 /* backtracking doesn't work for STACK_ZERO yet. */ 2309 err = mark_chain_precision(env, value_regno); 2310 if (err) 2311 return err; 2312 type = STACK_ZERO; 2313 } 2314 2315 /* Mark slots affected by this stack write. */ 2316 for (i = 0; i < size; i++) 2317 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 2318 type; 2319 } 2320 return 0; 2321 } 2322 2323 static int check_stack_read(struct bpf_verifier_env *env, 2324 struct bpf_func_state *reg_state /* func where register points to */, 2325 int off, int size, int value_regno) 2326 { 2327 struct bpf_verifier_state *vstate = env->cur_state; 2328 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2329 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 2330 struct bpf_reg_state *reg; 2331 u8 *stype; 2332 2333 if (reg_state->allocated_stack <= slot) { 2334 verbose(env, "invalid read from stack off %d+0 size %d\n", 2335 off, size); 2336 return -EACCES; 2337 } 2338 stype = reg_state->stack[spi].slot_type; 2339 reg = ®_state->stack[spi].spilled_ptr; 2340 2341 if (stype[0] == STACK_SPILL) { 2342 if (size != BPF_REG_SIZE) { 2343 if (reg->type != SCALAR_VALUE) { 2344 verbose_linfo(env, env->insn_idx, "; "); 2345 verbose(env, "invalid size of register fill\n"); 2346 return -EACCES; 2347 } 2348 if (value_regno >= 0) { 2349 mark_reg_unknown(env, state->regs, value_regno); 2350 state->regs[value_regno].live |= REG_LIVE_WRITTEN; 2351 } 2352 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2353 return 0; 2354 } 2355 for (i = 1; i < BPF_REG_SIZE; i++) { 2356 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { 2357 verbose(env, "corrupted spill memory\n"); 2358 return -EACCES; 2359 } 2360 } 2361 2362 if (value_regno >= 0) { 2363 /* restore register state from stack */ 2364 state->regs[value_regno] = *reg; 2365 /* mark reg as written since spilled pointer state likely 2366 * has its liveness marks cleared by is_state_visited() 2367 * which resets stack/reg liveness for state transitions 2368 */ 2369 state->regs[value_regno].live |= REG_LIVE_WRITTEN; 2370 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 2371 /* If value_regno==-1, the caller is asking us whether 2372 * it is acceptable to use this value as a SCALAR_VALUE 2373 * (e.g. for XADD). 2374 * We must not allow unprivileged callers to do that 2375 * with spilled pointers. 2376 */ 2377 verbose(env, "leaking pointer from stack off %d\n", 2378 off); 2379 return -EACCES; 2380 } 2381 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2382 } else { 2383 int zeros = 0; 2384 2385 for (i = 0; i < size; i++) { 2386 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC) 2387 continue; 2388 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) { 2389 zeros++; 2390 continue; 2391 } 2392 verbose(env, "invalid read from stack off %d+%d size %d\n", 2393 off, i, size); 2394 return -EACCES; 2395 } 2396 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2397 if (value_regno >= 0) { 2398 if (zeros == size) { 2399 /* any size read into register is zero extended, 2400 * so the whole register == const_zero 2401 */ 2402 __mark_reg_const_zero(&state->regs[value_regno]); 2403 /* backtracking doesn't support STACK_ZERO yet, 2404 * so mark it precise here, so that later 2405 * backtracking can stop here. 2406 * Backtracking may not need this if this register 2407 * doesn't participate in pointer adjustment. 2408 * Forward propagation of precise flag is not 2409 * necessary either. This mark is only to stop 2410 * backtracking. Any register that contributed 2411 * to const 0 was marked precise before spill. 2412 */ 2413 state->regs[value_regno].precise = true; 2414 } else { 2415 /* have read misc data from the stack */ 2416 mark_reg_unknown(env, state->regs, value_regno); 2417 } 2418 state->regs[value_regno].live |= REG_LIVE_WRITTEN; 2419 } 2420 } 2421 return 0; 2422 } 2423 2424 static int check_stack_access(struct bpf_verifier_env *env, 2425 const struct bpf_reg_state *reg, 2426 int off, int size) 2427 { 2428 /* Stack accesses must be at a fixed offset, so that we 2429 * can determine what type of data were returned. See 2430 * check_stack_read(). 2431 */ 2432 if (!tnum_is_const(reg->var_off)) { 2433 char tn_buf[48]; 2434 2435 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2436 verbose(env, "variable stack access var_off=%s off=%d size=%d\n", 2437 tn_buf, off, size); 2438 return -EACCES; 2439 } 2440 2441 if (off >= 0 || off < -MAX_BPF_STACK) { 2442 verbose(env, "invalid stack off=%d size=%d\n", off, size); 2443 return -EACCES; 2444 } 2445 2446 return 0; 2447 } 2448 2449 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 2450 int off, int size, enum bpf_access_type type) 2451 { 2452 struct bpf_reg_state *regs = cur_regs(env); 2453 struct bpf_map *map = regs[regno].map_ptr; 2454 u32 cap = bpf_map_flags_to_cap(map); 2455 2456 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 2457 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 2458 map->value_size, off, size); 2459 return -EACCES; 2460 } 2461 2462 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 2463 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 2464 map->value_size, off, size); 2465 return -EACCES; 2466 } 2467 2468 return 0; 2469 } 2470 2471 /* check read/write into map element returned by bpf_map_lookup_elem() */ 2472 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off, 2473 int size, bool zero_size_allowed) 2474 { 2475 struct bpf_reg_state *regs = cur_regs(env); 2476 struct bpf_map *map = regs[regno].map_ptr; 2477 2478 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || 2479 off + size > map->value_size) { 2480 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 2481 map->value_size, off, size); 2482 return -EACCES; 2483 } 2484 return 0; 2485 } 2486 2487 /* check read/write into a map element with possible variable offset */ 2488 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 2489 int off, int size, bool zero_size_allowed) 2490 { 2491 struct bpf_verifier_state *vstate = env->cur_state; 2492 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2493 struct bpf_reg_state *reg = &state->regs[regno]; 2494 int err; 2495 2496 /* We may have adjusted the register to this map value, so we 2497 * need to try adding each of min_value and max_value to off 2498 * to make sure our theoretical access will be safe. 2499 */ 2500 if (env->log.level & BPF_LOG_LEVEL) 2501 print_verifier_state(env, state); 2502 2503 /* The minimum value is only important with signed 2504 * comparisons where we can't assume the floor of a 2505 * value is 0. If we are using signed variables for our 2506 * index'es we need to make sure that whatever we use 2507 * will have a set floor within our range. 2508 */ 2509 if (reg->smin_value < 0 && 2510 (reg->smin_value == S64_MIN || 2511 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 2512 reg->smin_value + off < 0)) { 2513 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 2514 regno); 2515 return -EACCES; 2516 } 2517 err = __check_map_access(env, regno, reg->smin_value + off, size, 2518 zero_size_allowed); 2519 if (err) { 2520 verbose(env, "R%d min value is outside of the array range\n", 2521 regno); 2522 return err; 2523 } 2524 2525 /* If we haven't set a max value then we need to bail since we can't be 2526 * sure we won't do bad things. 2527 * If reg->umax_value + off could overflow, treat that as unbounded too. 2528 */ 2529 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 2530 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n", 2531 regno); 2532 return -EACCES; 2533 } 2534 err = __check_map_access(env, regno, reg->umax_value + off, size, 2535 zero_size_allowed); 2536 if (err) 2537 verbose(env, "R%d max value is outside of the array range\n", 2538 regno); 2539 2540 if (map_value_has_spin_lock(reg->map_ptr)) { 2541 u32 lock = reg->map_ptr->spin_lock_off; 2542 2543 /* if any part of struct bpf_spin_lock can be touched by 2544 * load/store reject this program. 2545 * To check that [x1, x2) overlaps with [y1, y2) 2546 * it is sufficient to check x1 < y2 && y1 < x2. 2547 */ 2548 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) && 2549 lock < reg->umax_value + off + size) { 2550 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n"); 2551 return -EACCES; 2552 } 2553 } 2554 return err; 2555 } 2556 2557 #define MAX_PACKET_OFF 0xffff 2558 2559 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 2560 const struct bpf_call_arg_meta *meta, 2561 enum bpf_access_type t) 2562 { 2563 switch (env->prog->type) { 2564 /* Program types only with direct read access go here! */ 2565 case BPF_PROG_TYPE_LWT_IN: 2566 case BPF_PROG_TYPE_LWT_OUT: 2567 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 2568 case BPF_PROG_TYPE_SK_REUSEPORT: 2569 case BPF_PROG_TYPE_FLOW_DISSECTOR: 2570 case BPF_PROG_TYPE_CGROUP_SKB: 2571 if (t == BPF_WRITE) 2572 return false; 2573 /* fallthrough */ 2574 2575 /* Program types with direct read + write access go here! */ 2576 case BPF_PROG_TYPE_SCHED_CLS: 2577 case BPF_PROG_TYPE_SCHED_ACT: 2578 case BPF_PROG_TYPE_XDP: 2579 case BPF_PROG_TYPE_LWT_XMIT: 2580 case BPF_PROG_TYPE_SK_SKB: 2581 case BPF_PROG_TYPE_SK_MSG: 2582 if (meta) 2583 return meta->pkt_access; 2584 2585 env->seen_direct_write = true; 2586 return true; 2587 2588 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 2589 if (t == BPF_WRITE) 2590 env->seen_direct_write = true; 2591 2592 return true; 2593 2594 default: 2595 return false; 2596 } 2597 } 2598 2599 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno, 2600 int off, int size, bool zero_size_allowed) 2601 { 2602 struct bpf_reg_state *regs = cur_regs(env); 2603 struct bpf_reg_state *reg = ®s[regno]; 2604 2605 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || 2606 (u64)off + size > reg->range) { 2607 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 2608 off, size, regno, reg->id, reg->off, reg->range); 2609 return -EACCES; 2610 } 2611 return 0; 2612 } 2613 2614 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 2615 int size, bool zero_size_allowed) 2616 { 2617 struct bpf_reg_state *regs = cur_regs(env); 2618 struct bpf_reg_state *reg = ®s[regno]; 2619 int err; 2620 2621 /* We may have added a variable offset to the packet pointer; but any 2622 * reg->range we have comes after that. We are only checking the fixed 2623 * offset. 2624 */ 2625 2626 /* We don't allow negative numbers, because we aren't tracking enough 2627 * detail to prove they're safe. 2628 */ 2629 if (reg->smin_value < 0) { 2630 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 2631 regno); 2632 return -EACCES; 2633 } 2634 err = __check_packet_access(env, regno, off, size, zero_size_allowed); 2635 if (err) { 2636 verbose(env, "R%d offset is outside of the packet\n", regno); 2637 return err; 2638 } 2639 2640 /* __check_packet_access has made sure "off + size - 1" is within u16. 2641 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 2642 * otherwise find_good_pkt_pointers would have refused to set range info 2643 * that __check_packet_access would have rejected this pkt access. 2644 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 2645 */ 2646 env->prog->aux->max_pkt_offset = 2647 max_t(u32, env->prog->aux->max_pkt_offset, 2648 off + reg->umax_value + size - 1); 2649 2650 return err; 2651 } 2652 2653 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 2654 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 2655 enum bpf_access_type t, enum bpf_reg_type *reg_type, 2656 u32 *btf_id) 2657 { 2658 struct bpf_insn_access_aux info = { 2659 .reg_type = *reg_type, 2660 .log = &env->log, 2661 }; 2662 2663 if (env->ops->is_valid_access && 2664 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 2665 /* A non zero info.ctx_field_size indicates that this field is a 2666 * candidate for later verifier transformation to load the whole 2667 * field and then apply a mask when accessed with a narrower 2668 * access than actual ctx access size. A zero info.ctx_field_size 2669 * will only allow for whole field access and rejects any other 2670 * type of narrower access. 2671 */ 2672 *reg_type = info.reg_type; 2673 2674 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) 2675 *btf_id = info.btf_id; 2676 else 2677 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 2678 /* remember the offset of last byte accessed in ctx */ 2679 if (env->prog->aux->max_ctx_offset < off + size) 2680 env->prog->aux->max_ctx_offset = off + size; 2681 return 0; 2682 } 2683 2684 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 2685 return -EACCES; 2686 } 2687 2688 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 2689 int size) 2690 { 2691 if (size < 0 || off < 0 || 2692 (u64)off + size > sizeof(struct bpf_flow_keys)) { 2693 verbose(env, "invalid access to flow keys off=%d size=%d\n", 2694 off, size); 2695 return -EACCES; 2696 } 2697 return 0; 2698 } 2699 2700 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 2701 u32 regno, int off, int size, 2702 enum bpf_access_type t) 2703 { 2704 struct bpf_reg_state *regs = cur_regs(env); 2705 struct bpf_reg_state *reg = ®s[regno]; 2706 struct bpf_insn_access_aux info = {}; 2707 bool valid; 2708 2709 if (reg->smin_value < 0) { 2710 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 2711 regno); 2712 return -EACCES; 2713 } 2714 2715 switch (reg->type) { 2716 case PTR_TO_SOCK_COMMON: 2717 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 2718 break; 2719 case PTR_TO_SOCKET: 2720 valid = bpf_sock_is_valid_access(off, size, t, &info); 2721 break; 2722 case PTR_TO_TCP_SOCK: 2723 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 2724 break; 2725 case PTR_TO_XDP_SOCK: 2726 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 2727 break; 2728 default: 2729 valid = false; 2730 } 2731 2732 2733 if (valid) { 2734 env->insn_aux_data[insn_idx].ctx_field_size = 2735 info.ctx_field_size; 2736 return 0; 2737 } 2738 2739 verbose(env, "R%d invalid %s access off=%d size=%d\n", 2740 regno, reg_type_str[reg->type], off, size); 2741 2742 return -EACCES; 2743 } 2744 2745 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 2746 { 2747 return cur_regs(env) + regno; 2748 } 2749 2750 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 2751 { 2752 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 2753 } 2754 2755 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 2756 { 2757 const struct bpf_reg_state *reg = reg_state(env, regno); 2758 2759 return reg->type == PTR_TO_CTX; 2760 } 2761 2762 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 2763 { 2764 const struct bpf_reg_state *reg = reg_state(env, regno); 2765 2766 return type_is_sk_pointer(reg->type); 2767 } 2768 2769 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 2770 { 2771 const struct bpf_reg_state *reg = reg_state(env, regno); 2772 2773 return type_is_pkt_pointer(reg->type); 2774 } 2775 2776 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 2777 { 2778 const struct bpf_reg_state *reg = reg_state(env, regno); 2779 2780 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 2781 return reg->type == PTR_TO_FLOW_KEYS; 2782 } 2783 2784 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 2785 const struct bpf_reg_state *reg, 2786 int off, int size, bool strict) 2787 { 2788 struct tnum reg_off; 2789 int ip_align; 2790 2791 /* Byte size accesses are always allowed. */ 2792 if (!strict || size == 1) 2793 return 0; 2794 2795 /* For platforms that do not have a Kconfig enabling 2796 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 2797 * NET_IP_ALIGN is universally set to '2'. And on platforms 2798 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 2799 * to this code only in strict mode where we want to emulate 2800 * the NET_IP_ALIGN==2 checking. Therefore use an 2801 * unconditional IP align value of '2'. 2802 */ 2803 ip_align = 2; 2804 2805 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 2806 if (!tnum_is_aligned(reg_off, size)) { 2807 char tn_buf[48]; 2808 2809 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2810 verbose(env, 2811 "misaligned packet access off %d+%s+%d+%d size %d\n", 2812 ip_align, tn_buf, reg->off, off, size); 2813 return -EACCES; 2814 } 2815 2816 return 0; 2817 } 2818 2819 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 2820 const struct bpf_reg_state *reg, 2821 const char *pointer_desc, 2822 int off, int size, bool strict) 2823 { 2824 struct tnum reg_off; 2825 2826 /* Byte size accesses are always allowed. */ 2827 if (!strict || size == 1) 2828 return 0; 2829 2830 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 2831 if (!tnum_is_aligned(reg_off, size)) { 2832 char tn_buf[48]; 2833 2834 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2835 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 2836 pointer_desc, tn_buf, reg->off, off, size); 2837 return -EACCES; 2838 } 2839 2840 return 0; 2841 } 2842 2843 static int check_ptr_alignment(struct bpf_verifier_env *env, 2844 const struct bpf_reg_state *reg, int off, 2845 int size, bool strict_alignment_once) 2846 { 2847 bool strict = env->strict_alignment || strict_alignment_once; 2848 const char *pointer_desc = ""; 2849 2850 switch (reg->type) { 2851 case PTR_TO_PACKET: 2852 case PTR_TO_PACKET_META: 2853 /* Special case, because of NET_IP_ALIGN. Given metadata sits 2854 * right in front, treat it the very same way. 2855 */ 2856 return check_pkt_ptr_alignment(env, reg, off, size, strict); 2857 case PTR_TO_FLOW_KEYS: 2858 pointer_desc = "flow keys "; 2859 break; 2860 case PTR_TO_MAP_VALUE: 2861 pointer_desc = "value "; 2862 break; 2863 case PTR_TO_CTX: 2864 pointer_desc = "context "; 2865 break; 2866 case PTR_TO_STACK: 2867 pointer_desc = "stack "; 2868 /* The stack spill tracking logic in check_stack_write() 2869 * and check_stack_read() relies on stack accesses being 2870 * aligned. 2871 */ 2872 strict = true; 2873 break; 2874 case PTR_TO_SOCKET: 2875 pointer_desc = "sock "; 2876 break; 2877 case PTR_TO_SOCK_COMMON: 2878 pointer_desc = "sock_common "; 2879 break; 2880 case PTR_TO_TCP_SOCK: 2881 pointer_desc = "tcp_sock "; 2882 break; 2883 case PTR_TO_XDP_SOCK: 2884 pointer_desc = "xdp_sock "; 2885 break; 2886 default: 2887 break; 2888 } 2889 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 2890 strict); 2891 } 2892 2893 static int update_stack_depth(struct bpf_verifier_env *env, 2894 const struct bpf_func_state *func, 2895 int off) 2896 { 2897 u16 stack = env->subprog_info[func->subprogno].stack_depth; 2898 2899 if (stack >= -off) 2900 return 0; 2901 2902 /* update known max for given subprogram */ 2903 env->subprog_info[func->subprogno].stack_depth = -off; 2904 return 0; 2905 } 2906 2907 /* starting from main bpf function walk all instructions of the function 2908 * and recursively walk all callees that given function can call. 2909 * Ignore jump and exit insns. 2910 * Since recursion is prevented by check_cfg() this algorithm 2911 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 2912 */ 2913 static int check_max_stack_depth(struct bpf_verifier_env *env) 2914 { 2915 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 2916 struct bpf_subprog_info *subprog = env->subprog_info; 2917 struct bpf_insn *insn = env->prog->insnsi; 2918 int ret_insn[MAX_CALL_FRAMES]; 2919 int ret_prog[MAX_CALL_FRAMES]; 2920 2921 process_func: 2922 /* round up to 32-bytes, since this is granularity 2923 * of interpreter stack size 2924 */ 2925 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 2926 if (depth > MAX_BPF_STACK) { 2927 verbose(env, "combined stack size of %d calls is %d. Too large\n", 2928 frame + 1, depth); 2929 return -EACCES; 2930 } 2931 continue_func: 2932 subprog_end = subprog[idx + 1].start; 2933 for (; i < subprog_end; i++) { 2934 if (insn[i].code != (BPF_JMP | BPF_CALL)) 2935 continue; 2936 if (insn[i].src_reg != BPF_PSEUDO_CALL) 2937 continue; 2938 /* remember insn and function to return to */ 2939 ret_insn[frame] = i + 1; 2940 ret_prog[frame] = idx; 2941 2942 /* find the callee */ 2943 i = i + insn[i].imm + 1; 2944 idx = find_subprog(env, i); 2945 if (idx < 0) { 2946 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 2947 i); 2948 return -EFAULT; 2949 } 2950 frame++; 2951 if (frame >= MAX_CALL_FRAMES) { 2952 verbose(env, "the call stack of %d frames is too deep !\n", 2953 frame); 2954 return -E2BIG; 2955 } 2956 goto process_func; 2957 } 2958 /* end of for() loop means the last insn of the 'subprog' 2959 * was reached. Doesn't matter whether it was JA or EXIT 2960 */ 2961 if (frame == 0) 2962 return 0; 2963 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 2964 frame--; 2965 i = ret_insn[frame]; 2966 idx = ret_prog[frame]; 2967 goto continue_func; 2968 } 2969 2970 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 2971 static int get_callee_stack_depth(struct bpf_verifier_env *env, 2972 const struct bpf_insn *insn, int idx) 2973 { 2974 int start = idx + insn->imm + 1, subprog; 2975 2976 subprog = find_subprog(env, start); 2977 if (subprog < 0) { 2978 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 2979 start); 2980 return -EFAULT; 2981 } 2982 return env->subprog_info[subprog].stack_depth; 2983 } 2984 #endif 2985 2986 int check_ctx_reg(struct bpf_verifier_env *env, 2987 const struct bpf_reg_state *reg, int regno) 2988 { 2989 /* Access to ctx or passing it to a helper is only allowed in 2990 * its original, unmodified form. 2991 */ 2992 2993 if (reg->off) { 2994 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n", 2995 regno, reg->off); 2996 return -EACCES; 2997 } 2998 2999 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3000 char tn_buf[48]; 3001 3002 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3003 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf); 3004 return -EACCES; 3005 } 3006 3007 return 0; 3008 } 3009 3010 static int check_tp_buffer_access(struct bpf_verifier_env *env, 3011 const struct bpf_reg_state *reg, 3012 int regno, int off, int size) 3013 { 3014 if (off < 0) { 3015 verbose(env, 3016 "R%d invalid tracepoint buffer access: off=%d, size=%d", 3017 regno, off, size); 3018 return -EACCES; 3019 } 3020 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3021 char tn_buf[48]; 3022 3023 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3024 verbose(env, 3025 "R%d invalid variable buffer offset: off=%d, var_off=%s", 3026 regno, off, tn_buf); 3027 return -EACCES; 3028 } 3029 if (off + size > env->prog->aux->max_tp_access) 3030 env->prog->aux->max_tp_access = off + size; 3031 3032 return 0; 3033 } 3034 3035 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 3036 static void zext_32_to_64(struct bpf_reg_state *reg) 3037 { 3038 reg->var_off = tnum_subreg(reg->var_off); 3039 __reg_assign_32_into_64(reg); 3040 } 3041 3042 /* truncate register to smaller size (in bytes) 3043 * must be called with size < BPF_REG_SIZE 3044 */ 3045 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 3046 { 3047 u64 mask; 3048 3049 /* clear high bits in bit representation */ 3050 reg->var_off = tnum_cast(reg->var_off, size); 3051 3052 /* fix arithmetic bounds */ 3053 mask = ((u64)1 << (size * 8)) - 1; 3054 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 3055 reg->umin_value &= mask; 3056 reg->umax_value &= mask; 3057 } else { 3058 reg->umin_value = 0; 3059 reg->umax_value = mask; 3060 } 3061 reg->smin_value = reg->umin_value; 3062 reg->smax_value = reg->umax_value; 3063 3064 /* If size is smaller than 32bit register the 32bit register 3065 * values are also truncated so we push 64-bit bounds into 3066 * 32-bit bounds. Above were truncated < 32-bits already. 3067 */ 3068 if (size >= 4) 3069 return; 3070 __reg_combine_64_into_32(reg); 3071 } 3072 3073 static bool bpf_map_is_rdonly(const struct bpf_map *map) 3074 { 3075 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen; 3076 } 3077 3078 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 3079 { 3080 void *ptr; 3081 u64 addr; 3082 int err; 3083 3084 err = map->ops->map_direct_value_addr(map, &addr, off); 3085 if (err) 3086 return err; 3087 ptr = (void *)(long)addr + off; 3088 3089 switch (size) { 3090 case sizeof(u8): 3091 *val = (u64)*(u8 *)ptr; 3092 break; 3093 case sizeof(u16): 3094 *val = (u64)*(u16 *)ptr; 3095 break; 3096 case sizeof(u32): 3097 *val = (u64)*(u32 *)ptr; 3098 break; 3099 case sizeof(u64): 3100 *val = *(u64 *)ptr; 3101 break; 3102 default: 3103 return -EINVAL; 3104 } 3105 return 0; 3106 } 3107 3108 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 3109 struct bpf_reg_state *regs, 3110 int regno, int off, int size, 3111 enum bpf_access_type atype, 3112 int value_regno) 3113 { 3114 struct bpf_reg_state *reg = regs + regno; 3115 const struct btf_type *t = btf_type_by_id(btf_vmlinux, reg->btf_id); 3116 const char *tname = btf_name_by_offset(btf_vmlinux, t->name_off); 3117 u32 btf_id; 3118 int ret; 3119 3120 if (off < 0) { 3121 verbose(env, 3122 "R%d is ptr_%s invalid negative access: off=%d\n", 3123 regno, tname, off); 3124 return -EACCES; 3125 } 3126 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3127 char tn_buf[48]; 3128 3129 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3130 verbose(env, 3131 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 3132 regno, tname, off, tn_buf); 3133 return -EACCES; 3134 } 3135 3136 if (env->ops->btf_struct_access) { 3137 ret = env->ops->btf_struct_access(&env->log, t, off, size, 3138 atype, &btf_id); 3139 } else { 3140 if (atype != BPF_READ) { 3141 verbose(env, "only read is supported\n"); 3142 return -EACCES; 3143 } 3144 3145 ret = btf_struct_access(&env->log, t, off, size, atype, 3146 &btf_id); 3147 } 3148 3149 if (ret < 0) 3150 return ret; 3151 3152 if (atype == BPF_READ && value_regno >= 0) { 3153 if (ret == SCALAR_VALUE) { 3154 mark_reg_unknown(env, regs, value_regno); 3155 return 0; 3156 } 3157 mark_reg_known_zero(env, regs, value_regno); 3158 regs[value_regno].type = PTR_TO_BTF_ID; 3159 regs[value_regno].btf_id = btf_id; 3160 } 3161 3162 return 0; 3163 } 3164 3165 /* check whether memory at (regno + off) is accessible for t = (read | write) 3166 * if t==write, value_regno is a register which value is stored into memory 3167 * if t==read, value_regno is a register which will receive the value from memory 3168 * if t==write && value_regno==-1, some unknown value is stored into memory 3169 * if t==read && value_regno==-1, don't care what we read from memory 3170 */ 3171 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 3172 int off, int bpf_size, enum bpf_access_type t, 3173 int value_regno, bool strict_alignment_once) 3174 { 3175 struct bpf_reg_state *regs = cur_regs(env); 3176 struct bpf_reg_state *reg = regs + regno; 3177 struct bpf_func_state *state; 3178 int size, err = 0; 3179 3180 size = bpf_size_to_bytes(bpf_size); 3181 if (size < 0) 3182 return size; 3183 3184 /* alignment checks will add in reg->off themselves */ 3185 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 3186 if (err) 3187 return err; 3188 3189 /* for access checks, reg->off is just part of off */ 3190 off += reg->off; 3191 3192 if (reg->type == PTR_TO_MAP_VALUE) { 3193 if (t == BPF_WRITE && value_regno >= 0 && 3194 is_pointer_value(env, value_regno)) { 3195 verbose(env, "R%d leaks addr into map\n", value_regno); 3196 return -EACCES; 3197 } 3198 err = check_map_access_type(env, regno, off, size, t); 3199 if (err) 3200 return err; 3201 err = check_map_access(env, regno, off, size, false); 3202 if (!err && t == BPF_READ && value_regno >= 0) { 3203 struct bpf_map *map = reg->map_ptr; 3204 3205 /* if map is read-only, track its contents as scalars */ 3206 if (tnum_is_const(reg->var_off) && 3207 bpf_map_is_rdonly(map) && 3208 map->ops->map_direct_value_addr) { 3209 int map_off = off + reg->var_off.value; 3210 u64 val = 0; 3211 3212 err = bpf_map_direct_read(map, map_off, size, 3213 &val); 3214 if (err) 3215 return err; 3216 3217 regs[value_regno].type = SCALAR_VALUE; 3218 __mark_reg_known(®s[value_regno], val); 3219 } else { 3220 mark_reg_unknown(env, regs, value_regno); 3221 } 3222 } 3223 } else if (reg->type == PTR_TO_CTX) { 3224 enum bpf_reg_type reg_type = SCALAR_VALUE; 3225 u32 btf_id = 0; 3226 3227 if (t == BPF_WRITE && value_regno >= 0 && 3228 is_pointer_value(env, value_regno)) { 3229 verbose(env, "R%d leaks addr into ctx\n", value_regno); 3230 return -EACCES; 3231 } 3232 3233 err = check_ctx_reg(env, reg, regno); 3234 if (err < 0) 3235 return err; 3236 3237 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf_id); 3238 if (err) 3239 verbose_linfo(env, insn_idx, "; "); 3240 if (!err && t == BPF_READ && value_regno >= 0) { 3241 /* ctx access returns either a scalar, or a 3242 * PTR_TO_PACKET[_META,_END]. In the latter 3243 * case, we know the offset is zero. 3244 */ 3245 if (reg_type == SCALAR_VALUE) { 3246 mark_reg_unknown(env, regs, value_regno); 3247 } else { 3248 mark_reg_known_zero(env, regs, 3249 value_regno); 3250 if (reg_type_may_be_null(reg_type)) 3251 regs[value_regno].id = ++env->id_gen; 3252 /* A load of ctx field could have different 3253 * actual load size with the one encoded in the 3254 * insn. When the dst is PTR, it is for sure not 3255 * a sub-register. 3256 */ 3257 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 3258 if (reg_type == PTR_TO_BTF_ID || 3259 reg_type == PTR_TO_BTF_ID_OR_NULL) 3260 regs[value_regno].btf_id = btf_id; 3261 } 3262 regs[value_regno].type = reg_type; 3263 } 3264 3265 } else if (reg->type == PTR_TO_STACK) { 3266 off += reg->var_off.value; 3267 err = check_stack_access(env, reg, off, size); 3268 if (err) 3269 return err; 3270 3271 state = func(env, reg); 3272 err = update_stack_depth(env, state, off); 3273 if (err) 3274 return err; 3275 3276 if (t == BPF_WRITE) 3277 err = check_stack_write(env, state, off, size, 3278 value_regno, insn_idx); 3279 else 3280 err = check_stack_read(env, state, off, size, 3281 value_regno); 3282 } else if (reg_is_pkt_pointer(reg)) { 3283 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 3284 verbose(env, "cannot write into packet\n"); 3285 return -EACCES; 3286 } 3287 if (t == BPF_WRITE && value_regno >= 0 && 3288 is_pointer_value(env, value_regno)) { 3289 verbose(env, "R%d leaks addr into packet\n", 3290 value_regno); 3291 return -EACCES; 3292 } 3293 err = check_packet_access(env, regno, off, size, false); 3294 if (!err && t == BPF_READ && value_regno >= 0) 3295 mark_reg_unknown(env, regs, value_regno); 3296 } else if (reg->type == PTR_TO_FLOW_KEYS) { 3297 if (t == BPF_WRITE && value_regno >= 0 && 3298 is_pointer_value(env, value_regno)) { 3299 verbose(env, "R%d leaks addr into flow keys\n", 3300 value_regno); 3301 return -EACCES; 3302 } 3303 3304 err = check_flow_keys_access(env, off, size); 3305 if (!err && t == BPF_READ && value_regno >= 0) 3306 mark_reg_unknown(env, regs, value_regno); 3307 } else if (type_is_sk_pointer(reg->type)) { 3308 if (t == BPF_WRITE) { 3309 verbose(env, "R%d cannot write into %s\n", 3310 regno, reg_type_str[reg->type]); 3311 return -EACCES; 3312 } 3313 err = check_sock_access(env, insn_idx, regno, off, size, t); 3314 if (!err && value_regno >= 0) 3315 mark_reg_unknown(env, regs, value_regno); 3316 } else if (reg->type == PTR_TO_TP_BUFFER) { 3317 err = check_tp_buffer_access(env, reg, regno, off, size); 3318 if (!err && t == BPF_READ && value_regno >= 0) 3319 mark_reg_unknown(env, regs, value_regno); 3320 } else if (reg->type == PTR_TO_BTF_ID) { 3321 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 3322 value_regno); 3323 } else { 3324 verbose(env, "R%d invalid mem access '%s'\n", regno, 3325 reg_type_str[reg->type]); 3326 return -EACCES; 3327 } 3328 3329 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 3330 regs[value_regno].type == SCALAR_VALUE) { 3331 /* b/h/w load zero-extends, mark upper bits as known 0 */ 3332 coerce_reg_to_size(®s[value_regno], size); 3333 } 3334 return err; 3335 } 3336 3337 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 3338 { 3339 int err; 3340 3341 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) || 3342 insn->imm != 0) { 3343 verbose(env, "BPF_XADD uses reserved fields\n"); 3344 return -EINVAL; 3345 } 3346 3347 /* check src1 operand */ 3348 err = check_reg_arg(env, insn->src_reg, SRC_OP); 3349 if (err) 3350 return err; 3351 3352 /* check src2 operand */ 3353 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 3354 if (err) 3355 return err; 3356 3357 if (is_pointer_value(env, insn->src_reg)) { 3358 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 3359 return -EACCES; 3360 } 3361 3362 if (is_ctx_reg(env, insn->dst_reg) || 3363 is_pkt_reg(env, insn->dst_reg) || 3364 is_flow_key_reg(env, insn->dst_reg) || 3365 is_sk_reg(env, insn->dst_reg)) { 3366 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n", 3367 insn->dst_reg, 3368 reg_type_str[reg_state(env, insn->dst_reg)->type]); 3369 return -EACCES; 3370 } 3371 3372 /* check whether atomic_add can read the memory */ 3373 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 3374 BPF_SIZE(insn->code), BPF_READ, -1, true); 3375 if (err) 3376 return err; 3377 3378 /* check whether atomic_add can write into the same memory */ 3379 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 3380 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 3381 } 3382 3383 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno, 3384 int off, int access_size, 3385 bool zero_size_allowed) 3386 { 3387 struct bpf_reg_state *reg = reg_state(env, regno); 3388 3389 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || 3390 access_size < 0 || (access_size == 0 && !zero_size_allowed)) { 3391 if (tnum_is_const(reg->var_off)) { 3392 verbose(env, "invalid stack type R%d off=%d access_size=%d\n", 3393 regno, off, access_size); 3394 } else { 3395 char tn_buf[48]; 3396 3397 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3398 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n", 3399 regno, tn_buf, access_size); 3400 } 3401 return -EACCES; 3402 } 3403 return 0; 3404 } 3405 3406 /* when register 'regno' is passed into function that will read 'access_size' 3407 * bytes from that pointer, make sure that it's within stack boundary 3408 * and all elements of stack are initialized. 3409 * Unlike most pointer bounds-checking functions, this one doesn't take an 3410 * 'off' argument, so it has to add in reg->off itself. 3411 */ 3412 static int check_stack_boundary(struct bpf_verifier_env *env, int regno, 3413 int access_size, bool zero_size_allowed, 3414 struct bpf_call_arg_meta *meta) 3415 { 3416 struct bpf_reg_state *reg = reg_state(env, regno); 3417 struct bpf_func_state *state = func(env, reg); 3418 int err, min_off, max_off, i, j, slot, spi; 3419 3420 if (reg->type != PTR_TO_STACK) { 3421 /* Allow zero-byte read from NULL, regardless of pointer type */ 3422 if (zero_size_allowed && access_size == 0 && 3423 register_is_null(reg)) 3424 return 0; 3425 3426 verbose(env, "R%d type=%s expected=%s\n", regno, 3427 reg_type_str[reg->type], 3428 reg_type_str[PTR_TO_STACK]); 3429 return -EACCES; 3430 } 3431 3432 if (tnum_is_const(reg->var_off)) { 3433 min_off = max_off = reg->var_off.value + reg->off; 3434 err = __check_stack_boundary(env, regno, min_off, access_size, 3435 zero_size_allowed); 3436 if (err) 3437 return err; 3438 } else { 3439 /* Variable offset is prohibited for unprivileged mode for 3440 * simplicity since it requires corresponding support in 3441 * Spectre masking for stack ALU. 3442 * See also retrieve_ptr_limit(). 3443 */ 3444 if (!env->bypass_spec_v1) { 3445 char tn_buf[48]; 3446 3447 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3448 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n", 3449 regno, tn_buf); 3450 return -EACCES; 3451 } 3452 /* Only initialized buffer on stack is allowed to be accessed 3453 * with variable offset. With uninitialized buffer it's hard to 3454 * guarantee that whole memory is marked as initialized on 3455 * helper return since specific bounds are unknown what may 3456 * cause uninitialized stack leaking. 3457 */ 3458 if (meta && meta->raw_mode) 3459 meta = NULL; 3460 3461 if (reg->smax_value >= BPF_MAX_VAR_OFF || 3462 reg->smax_value <= -BPF_MAX_VAR_OFF) { 3463 verbose(env, "R%d unbounded indirect variable offset stack access\n", 3464 regno); 3465 return -EACCES; 3466 } 3467 min_off = reg->smin_value + reg->off; 3468 max_off = reg->smax_value + reg->off; 3469 err = __check_stack_boundary(env, regno, min_off, access_size, 3470 zero_size_allowed); 3471 if (err) { 3472 verbose(env, "R%d min value is outside of stack bound\n", 3473 regno); 3474 return err; 3475 } 3476 err = __check_stack_boundary(env, regno, max_off, access_size, 3477 zero_size_allowed); 3478 if (err) { 3479 verbose(env, "R%d max value is outside of stack bound\n", 3480 regno); 3481 return err; 3482 } 3483 } 3484 3485 if (meta && meta->raw_mode) { 3486 meta->access_size = access_size; 3487 meta->regno = regno; 3488 return 0; 3489 } 3490 3491 for (i = min_off; i < max_off + access_size; i++) { 3492 u8 *stype; 3493 3494 slot = -i - 1; 3495 spi = slot / BPF_REG_SIZE; 3496 if (state->allocated_stack <= slot) 3497 goto err; 3498 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 3499 if (*stype == STACK_MISC) 3500 goto mark; 3501 if (*stype == STACK_ZERO) { 3502 /* helper can write anything into the stack */ 3503 *stype = STACK_MISC; 3504 goto mark; 3505 } 3506 3507 if (state->stack[spi].slot_type[0] == STACK_SPILL && 3508 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID) 3509 goto mark; 3510 3511 if (state->stack[spi].slot_type[0] == STACK_SPILL && 3512 state->stack[spi].spilled_ptr.type == SCALAR_VALUE) { 3513 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 3514 for (j = 0; j < BPF_REG_SIZE; j++) 3515 state->stack[spi].slot_type[j] = STACK_MISC; 3516 goto mark; 3517 } 3518 3519 err: 3520 if (tnum_is_const(reg->var_off)) { 3521 verbose(env, "invalid indirect read from stack off %d+%d size %d\n", 3522 min_off, i - min_off, access_size); 3523 } else { 3524 char tn_buf[48]; 3525 3526 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3527 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n", 3528 tn_buf, i - min_off, access_size); 3529 } 3530 return -EACCES; 3531 mark: 3532 /* reading any byte out of 8-byte 'spill_slot' will cause 3533 * the whole slot to be marked as 'read' 3534 */ 3535 mark_reg_read(env, &state->stack[spi].spilled_ptr, 3536 state->stack[spi].spilled_ptr.parent, 3537 REG_LIVE_READ64); 3538 } 3539 return update_stack_depth(env, state, min_off); 3540 } 3541 3542 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 3543 int access_size, bool zero_size_allowed, 3544 struct bpf_call_arg_meta *meta) 3545 { 3546 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 3547 3548 switch (reg->type) { 3549 case PTR_TO_PACKET: 3550 case PTR_TO_PACKET_META: 3551 return check_packet_access(env, regno, reg->off, access_size, 3552 zero_size_allowed); 3553 case PTR_TO_MAP_VALUE: 3554 if (check_map_access_type(env, regno, reg->off, access_size, 3555 meta && meta->raw_mode ? BPF_WRITE : 3556 BPF_READ)) 3557 return -EACCES; 3558 return check_map_access(env, regno, reg->off, access_size, 3559 zero_size_allowed); 3560 default: /* scalar_value|ptr_to_stack or invalid ptr */ 3561 return check_stack_boundary(env, regno, access_size, 3562 zero_size_allowed, meta); 3563 } 3564 } 3565 3566 /* Implementation details: 3567 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL 3568 * Two bpf_map_lookups (even with the same key) will have different reg->id. 3569 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after 3570 * value_or_null->value transition, since the verifier only cares about 3571 * the range of access to valid map value pointer and doesn't care about actual 3572 * address of the map element. 3573 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 3574 * reg->id > 0 after value_or_null->value transition. By doing so 3575 * two bpf_map_lookups will be considered two different pointers that 3576 * point to different bpf_spin_locks. 3577 * The verifier allows taking only one bpf_spin_lock at a time to avoid 3578 * dead-locks. 3579 * Since only one bpf_spin_lock is allowed the checks are simpler than 3580 * reg_is_refcounted() logic. The verifier needs to remember only 3581 * one spin_lock instead of array of acquired_refs. 3582 * cur_state->active_spin_lock remembers which map value element got locked 3583 * and clears it after bpf_spin_unlock. 3584 */ 3585 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 3586 bool is_lock) 3587 { 3588 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 3589 struct bpf_verifier_state *cur = env->cur_state; 3590 bool is_const = tnum_is_const(reg->var_off); 3591 struct bpf_map *map = reg->map_ptr; 3592 u64 val = reg->var_off.value; 3593 3594 if (reg->type != PTR_TO_MAP_VALUE) { 3595 verbose(env, "R%d is not a pointer to map_value\n", regno); 3596 return -EINVAL; 3597 } 3598 if (!is_const) { 3599 verbose(env, 3600 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 3601 regno); 3602 return -EINVAL; 3603 } 3604 if (!map->btf) { 3605 verbose(env, 3606 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 3607 map->name); 3608 return -EINVAL; 3609 } 3610 if (!map_value_has_spin_lock(map)) { 3611 if (map->spin_lock_off == -E2BIG) 3612 verbose(env, 3613 "map '%s' has more than one 'struct bpf_spin_lock'\n", 3614 map->name); 3615 else if (map->spin_lock_off == -ENOENT) 3616 verbose(env, 3617 "map '%s' doesn't have 'struct bpf_spin_lock'\n", 3618 map->name); 3619 else 3620 verbose(env, 3621 "map '%s' is not a struct type or bpf_spin_lock is mangled\n", 3622 map->name); 3623 return -EINVAL; 3624 } 3625 if (map->spin_lock_off != val + reg->off) { 3626 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n", 3627 val + reg->off); 3628 return -EINVAL; 3629 } 3630 if (is_lock) { 3631 if (cur->active_spin_lock) { 3632 verbose(env, 3633 "Locking two bpf_spin_locks are not allowed\n"); 3634 return -EINVAL; 3635 } 3636 cur->active_spin_lock = reg->id; 3637 } else { 3638 if (!cur->active_spin_lock) { 3639 verbose(env, "bpf_spin_unlock without taking a lock\n"); 3640 return -EINVAL; 3641 } 3642 if (cur->active_spin_lock != reg->id) { 3643 verbose(env, "bpf_spin_unlock of different lock\n"); 3644 return -EINVAL; 3645 } 3646 cur->active_spin_lock = 0; 3647 } 3648 return 0; 3649 } 3650 3651 static bool arg_type_is_mem_ptr(enum bpf_arg_type type) 3652 { 3653 return type == ARG_PTR_TO_MEM || 3654 type == ARG_PTR_TO_MEM_OR_NULL || 3655 type == ARG_PTR_TO_UNINIT_MEM; 3656 } 3657 3658 static bool arg_type_is_mem_size(enum bpf_arg_type type) 3659 { 3660 return type == ARG_CONST_SIZE || 3661 type == ARG_CONST_SIZE_OR_ZERO; 3662 } 3663 3664 static bool arg_type_is_int_ptr(enum bpf_arg_type type) 3665 { 3666 return type == ARG_PTR_TO_INT || 3667 type == ARG_PTR_TO_LONG; 3668 } 3669 3670 static int int_ptr_type_to_size(enum bpf_arg_type type) 3671 { 3672 if (type == ARG_PTR_TO_INT) 3673 return sizeof(u32); 3674 else if (type == ARG_PTR_TO_LONG) 3675 return sizeof(u64); 3676 3677 return -EINVAL; 3678 } 3679 3680 static int check_func_arg(struct bpf_verifier_env *env, u32 regno, 3681 enum bpf_arg_type arg_type, 3682 struct bpf_call_arg_meta *meta) 3683 { 3684 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 3685 enum bpf_reg_type expected_type, type = reg->type; 3686 int err = 0; 3687 3688 if (arg_type == ARG_DONTCARE) 3689 return 0; 3690 3691 err = check_reg_arg(env, regno, SRC_OP); 3692 if (err) 3693 return err; 3694 3695 if (arg_type == ARG_ANYTHING) { 3696 if (is_pointer_value(env, regno)) { 3697 verbose(env, "R%d leaks addr into helper function\n", 3698 regno); 3699 return -EACCES; 3700 } 3701 return 0; 3702 } 3703 3704 if (type_is_pkt_pointer(type) && 3705 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 3706 verbose(env, "helper access to the packet is not allowed\n"); 3707 return -EACCES; 3708 } 3709 3710 if (arg_type == ARG_PTR_TO_MAP_KEY || 3711 arg_type == ARG_PTR_TO_MAP_VALUE || 3712 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE || 3713 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) { 3714 expected_type = PTR_TO_STACK; 3715 if (register_is_null(reg) && 3716 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) 3717 /* final test in check_stack_boundary() */; 3718 else if (!type_is_pkt_pointer(type) && 3719 type != PTR_TO_MAP_VALUE && 3720 type != expected_type) 3721 goto err_type; 3722 } else if (arg_type == ARG_CONST_SIZE || 3723 arg_type == ARG_CONST_SIZE_OR_ZERO) { 3724 expected_type = SCALAR_VALUE; 3725 if (type != expected_type) 3726 goto err_type; 3727 } else if (arg_type == ARG_CONST_MAP_PTR) { 3728 expected_type = CONST_PTR_TO_MAP; 3729 if (type != expected_type) 3730 goto err_type; 3731 } else if (arg_type == ARG_PTR_TO_CTX || 3732 arg_type == ARG_PTR_TO_CTX_OR_NULL) { 3733 expected_type = PTR_TO_CTX; 3734 if (!(register_is_null(reg) && 3735 arg_type == ARG_PTR_TO_CTX_OR_NULL)) { 3736 if (type != expected_type) 3737 goto err_type; 3738 err = check_ctx_reg(env, reg, regno); 3739 if (err < 0) 3740 return err; 3741 } 3742 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) { 3743 expected_type = PTR_TO_SOCK_COMMON; 3744 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */ 3745 if (!type_is_sk_pointer(type)) 3746 goto err_type; 3747 if (reg->ref_obj_id) { 3748 if (meta->ref_obj_id) { 3749 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 3750 regno, reg->ref_obj_id, 3751 meta->ref_obj_id); 3752 return -EFAULT; 3753 } 3754 meta->ref_obj_id = reg->ref_obj_id; 3755 } 3756 } else if (arg_type == ARG_PTR_TO_SOCKET) { 3757 expected_type = PTR_TO_SOCKET; 3758 if (type != expected_type) 3759 goto err_type; 3760 } else if (arg_type == ARG_PTR_TO_BTF_ID) { 3761 expected_type = PTR_TO_BTF_ID; 3762 if (type != expected_type) 3763 goto err_type; 3764 if (reg->btf_id != meta->btf_id) { 3765 verbose(env, "Helper has type %s got %s in R%d\n", 3766 kernel_type_name(meta->btf_id), 3767 kernel_type_name(reg->btf_id), regno); 3768 3769 return -EACCES; 3770 } 3771 if (!tnum_is_const(reg->var_off) || reg->var_off.value || reg->off) { 3772 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n", 3773 regno); 3774 return -EACCES; 3775 } 3776 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) { 3777 if (meta->func_id == BPF_FUNC_spin_lock) { 3778 if (process_spin_lock(env, regno, true)) 3779 return -EACCES; 3780 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 3781 if (process_spin_lock(env, regno, false)) 3782 return -EACCES; 3783 } else { 3784 verbose(env, "verifier internal error\n"); 3785 return -EFAULT; 3786 } 3787 } else if (arg_type_is_mem_ptr(arg_type)) { 3788 expected_type = PTR_TO_STACK; 3789 /* One exception here. In case function allows for NULL to be 3790 * passed in as argument, it's a SCALAR_VALUE type. Final test 3791 * happens during stack boundary checking. 3792 */ 3793 if (register_is_null(reg) && 3794 arg_type == ARG_PTR_TO_MEM_OR_NULL) 3795 /* final test in check_stack_boundary() */; 3796 else if (!type_is_pkt_pointer(type) && 3797 type != PTR_TO_MAP_VALUE && 3798 type != expected_type) 3799 goto err_type; 3800 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM; 3801 } else if (arg_type_is_int_ptr(arg_type)) { 3802 expected_type = PTR_TO_STACK; 3803 if (!type_is_pkt_pointer(type) && 3804 type != PTR_TO_MAP_VALUE && 3805 type != expected_type) 3806 goto err_type; 3807 } else { 3808 verbose(env, "unsupported arg_type %d\n", arg_type); 3809 return -EFAULT; 3810 } 3811 3812 if (arg_type == ARG_CONST_MAP_PTR) { 3813 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 3814 meta->map_ptr = reg->map_ptr; 3815 } else if (arg_type == ARG_PTR_TO_MAP_KEY) { 3816 /* bpf_map_xxx(..., map_ptr, ..., key) call: 3817 * check that [key, key + map->key_size) are within 3818 * stack limits and initialized 3819 */ 3820 if (!meta->map_ptr) { 3821 /* in function declaration map_ptr must come before 3822 * map_key, so that it's verified and known before 3823 * we have to check map_key here. Otherwise it means 3824 * that kernel subsystem misconfigured verifier 3825 */ 3826 verbose(env, "invalid map_ptr to access map->key\n"); 3827 return -EACCES; 3828 } 3829 err = check_helper_mem_access(env, regno, 3830 meta->map_ptr->key_size, false, 3831 NULL); 3832 } else if (arg_type == ARG_PTR_TO_MAP_VALUE || 3833 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL && 3834 !register_is_null(reg)) || 3835 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) { 3836 /* bpf_map_xxx(..., map_ptr, ..., value) call: 3837 * check [value, value + map->value_size) validity 3838 */ 3839 if (!meta->map_ptr) { 3840 /* kernel subsystem misconfigured verifier */ 3841 verbose(env, "invalid map_ptr to access map->value\n"); 3842 return -EACCES; 3843 } 3844 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE); 3845 err = check_helper_mem_access(env, regno, 3846 meta->map_ptr->value_size, false, 3847 meta); 3848 } else if (arg_type_is_mem_size(arg_type)) { 3849 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); 3850 3851 /* This is used to refine r0 return value bounds for helpers 3852 * that enforce this value as an upper bound on return values. 3853 * See do_refine_retval_range() for helpers that can refine 3854 * the return value. C type of helper is u32 so we pull register 3855 * bound from umax_value however, if negative verifier errors 3856 * out. Only upper bounds can be learned because retval is an 3857 * int type and negative retvals are allowed. 3858 */ 3859 meta->msize_max_value = reg->umax_value; 3860 3861 /* The register is SCALAR_VALUE; the access check 3862 * happens using its boundaries. 3863 */ 3864 if (!tnum_is_const(reg->var_off)) 3865 /* For unprivileged variable accesses, disable raw 3866 * mode so that the program is required to 3867 * initialize all the memory that the helper could 3868 * just partially fill up. 3869 */ 3870 meta = NULL; 3871 3872 if (reg->smin_value < 0) { 3873 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 3874 regno); 3875 return -EACCES; 3876 } 3877 3878 if (reg->umin_value == 0) { 3879 err = check_helper_mem_access(env, regno - 1, 0, 3880 zero_size_allowed, 3881 meta); 3882 if (err) 3883 return err; 3884 } 3885 3886 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 3887 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 3888 regno); 3889 return -EACCES; 3890 } 3891 err = check_helper_mem_access(env, regno - 1, 3892 reg->umax_value, 3893 zero_size_allowed, meta); 3894 if (!err) 3895 err = mark_chain_precision(env, regno); 3896 } else if (arg_type_is_int_ptr(arg_type)) { 3897 int size = int_ptr_type_to_size(arg_type); 3898 3899 err = check_helper_mem_access(env, regno, size, false, meta); 3900 if (err) 3901 return err; 3902 err = check_ptr_alignment(env, reg, 0, size, true); 3903 } 3904 3905 return err; 3906 err_type: 3907 verbose(env, "R%d type=%s expected=%s\n", regno, 3908 reg_type_str[type], reg_type_str[expected_type]); 3909 return -EACCES; 3910 } 3911 3912 static int check_map_func_compatibility(struct bpf_verifier_env *env, 3913 struct bpf_map *map, int func_id) 3914 { 3915 if (!map) 3916 return 0; 3917 3918 /* We need a two way check, first is from map perspective ... */ 3919 switch (map->map_type) { 3920 case BPF_MAP_TYPE_PROG_ARRAY: 3921 if (func_id != BPF_FUNC_tail_call) 3922 goto error; 3923 break; 3924 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 3925 if (func_id != BPF_FUNC_perf_event_read && 3926 func_id != BPF_FUNC_perf_event_output && 3927 func_id != BPF_FUNC_skb_output && 3928 func_id != BPF_FUNC_perf_event_read_value && 3929 func_id != BPF_FUNC_xdp_output) 3930 goto error; 3931 break; 3932 case BPF_MAP_TYPE_STACK_TRACE: 3933 if (func_id != BPF_FUNC_get_stackid) 3934 goto error; 3935 break; 3936 case BPF_MAP_TYPE_CGROUP_ARRAY: 3937 if (func_id != BPF_FUNC_skb_under_cgroup && 3938 func_id != BPF_FUNC_current_task_under_cgroup) 3939 goto error; 3940 break; 3941 case BPF_MAP_TYPE_CGROUP_STORAGE: 3942 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 3943 if (func_id != BPF_FUNC_get_local_storage) 3944 goto error; 3945 break; 3946 case BPF_MAP_TYPE_DEVMAP: 3947 case BPF_MAP_TYPE_DEVMAP_HASH: 3948 if (func_id != BPF_FUNC_redirect_map && 3949 func_id != BPF_FUNC_map_lookup_elem) 3950 goto error; 3951 break; 3952 /* Restrict bpf side of cpumap and xskmap, open when use-cases 3953 * appear. 3954 */ 3955 case BPF_MAP_TYPE_CPUMAP: 3956 if (func_id != BPF_FUNC_redirect_map) 3957 goto error; 3958 break; 3959 case BPF_MAP_TYPE_XSKMAP: 3960 if (func_id != BPF_FUNC_redirect_map && 3961 func_id != BPF_FUNC_map_lookup_elem) 3962 goto error; 3963 break; 3964 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 3965 case BPF_MAP_TYPE_HASH_OF_MAPS: 3966 if (func_id != BPF_FUNC_map_lookup_elem) 3967 goto error; 3968 break; 3969 case BPF_MAP_TYPE_SOCKMAP: 3970 if (func_id != BPF_FUNC_sk_redirect_map && 3971 func_id != BPF_FUNC_sock_map_update && 3972 func_id != BPF_FUNC_map_delete_elem && 3973 func_id != BPF_FUNC_msg_redirect_map && 3974 func_id != BPF_FUNC_sk_select_reuseport && 3975 func_id != BPF_FUNC_map_lookup_elem) 3976 goto error; 3977 break; 3978 case BPF_MAP_TYPE_SOCKHASH: 3979 if (func_id != BPF_FUNC_sk_redirect_hash && 3980 func_id != BPF_FUNC_sock_hash_update && 3981 func_id != BPF_FUNC_map_delete_elem && 3982 func_id != BPF_FUNC_msg_redirect_hash && 3983 func_id != BPF_FUNC_sk_select_reuseport && 3984 func_id != BPF_FUNC_map_lookup_elem) 3985 goto error; 3986 break; 3987 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 3988 if (func_id != BPF_FUNC_sk_select_reuseport) 3989 goto error; 3990 break; 3991 case BPF_MAP_TYPE_QUEUE: 3992 case BPF_MAP_TYPE_STACK: 3993 if (func_id != BPF_FUNC_map_peek_elem && 3994 func_id != BPF_FUNC_map_pop_elem && 3995 func_id != BPF_FUNC_map_push_elem) 3996 goto error; 3997 break; 3998 case BPF_MAP_TYPE_SK_STORAGE: 3999 if (func_id != BPF_FUNC_sk_storage_get && 4000 func_id != BPF_FUNC_sk_storage_delete) 4001 goto error; 4002 break; 4003 default: 4004 break; 4005 } 4006 4007 /* ... and second from the function itself. */ 4008 switch (func_id) { 4009 case BPF_FUNC_tail_call: 4010 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 4011 goto error; 4012 if (env->subprog_cnt > 1) { 4013 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n"); 4014 return -EINVAL; 4015 } 4016 break; 4017 case BPF_FUNC_perf_event_read: 4018 case BPF_FUNC_perf_event_output: 4019 case BPF_FUNC_perf_event_read_value: 4020 case BPF_FUNC_skb_output: 4021 case BPF_FUNC_xdp_output: 4022 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 4023 goto error; 4024 break; 4025 case BPF_FUNC_get_stackid: 4026 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 4027 goto error; 4028 break; 4029 case BPF_FUNC_current_task_under_cgroup: 4030 case BPF_FUNC_skb_under_cgroup: 4031 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 4032 goto error; 4033 break; 4034 case BPF_FUNC_redirect_map: 4035 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 4036 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 4037 map->map_type != BPF_MAP_TYPE_CPUMAP && 4038 map->map_type != BPF_MAP_TYPE_XSKMAP) 4039 goto error; 4040 break; 4041 case BPF_FUNC_sk_redirect_map: 4042 case BPF_FUNC_msg_redirect_map: 4043 case BPF_FUNC_sock_map_update: 4044 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 4045 goto error; 4046 break; 4047 case BPF_FUNC_sk_redirect_hash: 4048 case BPF_FUNC_msg_redirect_hash: 4049 case BPF_FUNC_sock_hash_update: 4050 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 4051 goto error; 4052 break; 4053 case BPF_FUNC_get_local_storage: 4054 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 4055 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 4056 goto error; 4057 break; 4058 case BPF_FUNC_sk_select_reuseport: 4059 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 4060 map->map_type != BPF_MAP_TYPE_SOCKMAP && 4061 map->map_type != BPF_MAP_TYPE_SOCKHASH) 4062 goto error; 4063 break; 4064 case BPF_FUNC_map_peek_elem: 4065 case BPF_FUNC_map_pop_elem: 4066 case BPF_FUNC_map_push_elem: 4067 if (map->map_type != BPF_MAP_TYPE_QUEUE && 4068 map->map_type != BPF_MAP_TYPE_STACK) 4069 goto error; 4070 break; 4071 case BPF_FUNC_sk_storage_get: 4072 case BPF_FUNC_sk_storage_delete: 4073 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 4074 goto error; 4075 break; 4076 default: 4077 break; 4078 } 4079 4080 return 0; 4081 error: 4082 verbose(env, "cannot pass map_type %d into func %s#%d\n", 4083 map->map_type, func_id_name(func_id), func_id); 4084 return -EINVAL; 4085 } 4086 4087 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 4088 { 4089 int count = 0; 4090 4091 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 4092 count++; 4093 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 4094 count++; 4095 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 4096 count++; 4097 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 4098 count++; 4099 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 4100 count++; 4101 4102 /* We only support one arg being in raw mode at the moment, 4103 * which is sufficient for the helper functions we have 4104 * right now. 4105 */ 4106 return count <= 1; 4107 } 4108 4109 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr, 4110 enum bpf_arg_type arg_next) 4111 { 4112 return (arg_type_is_mem_ptr(arg_curr) && 4113 !arg_type_is_mem_size(arg_next)) || 4114 (!arg_type_is_mem_ptr(arg_curr) && 4115 arg_type_is_mem_size(arg_next)); 4116 } 4117 4118 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 4119 { 4120 /* bpf_xxx(..., buf, len) call will access 'len' 4121 * bytes from memory 'buf'. Both arg types need 4122 * to be paired, so make sure there's no buggy 4123 * helper function specification. 4124 */ 4125 if (arg_type_is_mem_size(fn->arg1_type) || 4126 arg_type_is_mem_ptr(fn->arg5_type) || 4127 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) || 4128 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) || 4129 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) || 4130 check_args_pair_invalid(fn->arg4_type, fn->arg5_type)) 4131 return false; 4132 4133 return true; 4134 } 4135 4136 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id) 4137 { 4138 int count = 0; 4139 4140 if (arg_type_may_be_refcounted(fn->arg1_type)) 4141 count++; 4142 if (arg_type_may_be_refcounted(fn->arg2_type)) 4143 count++; 4144 if (arg_type_may_be_refcounted(fn->arg3_type)) 4145 count++; 4146 if (arg_type_may_be_refcounted(fn->arg4_type)) 4147 count++; 4148 if (arg_type_may_be_refcounted(fn->arg5_type)) 4149 count++; 4150 4151 /* A reference acquiring function cannot acquire 4152 * another refcounted ptr. 4153 */ 4154 if (may_be_acquire_function(func_id) && count) 4155 return false; 4156 4157 /* We only support one arg being unreferenced at the moment, 4158 * which is sufficient for the helper functions we have right now. 4159 */ 4160 return count <= 1; 4161 } 4162 4163 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 4164 { 4165 return check_raw_mode_ok(fn) && 4166 check_arg_pair_ok(fn) && 4167 check_refcount_ok(fn, func_id) ? 0 : -EINVAL; 4168 } 4169 4170 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 4171 * are now invalid, so turn them into unknown SCALAR_VALUE. 4172 */ 4173 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env, 4174 struct bpf_func_state *state) 4175 { 4176 struct bpf_reg_state *regs = state->regs, *reg; 4177 int i; 4178 4179 for (i = 0; i < MAX_BPF_REG; i++) 4180 if (reg_is_pkt_pointer_any(®s[i])) 4181 mark_reg_unknown(env, regs, i); 4182 4183 bpf_for_each_spilled_reg(i, state, reg) { 4184 if (!reg) 4185 continue; 4186 if (reg_is_pkt_pointer_any(reg)) 4187 __mark_reg_unknown(env, reg); 4188 } 4189 } 4190 4191 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 4192 { 4193 struct bpf_verifier_state *vstate = env->cur_state; 4194 int i; 4195 4196 for (i = 0; i <= vstate->curframe; i++) 4197 __clear_all_pkt_pointers(env, vstate->frame[i]); 4198 } 4199 4200 static void release_reg_references(struct bpf_verifier_env *env, 4201 struct bpf_func_state *state, 4202 int ref_obj_id) 4203 { 4204 struct bpf_reg_state *regs = state->regs, *reg; 4205 int i; 4206 4207 for (i = 0; i < MAX_BPF_REG; i++) 4208 if (regs[i].ref_obj_id == ref_obj_id) 4209 mark_reg_unknown(env, regs, i); 4210 4211 bpf_for_each_spilled_reg(i, state, reg) { 4212 if (!reg) 4213 continue; 4214 if (reg->ref_obj_id == ref_obj_id) 4215 __mark_reg_unknown(env, reg); 4216 } 4217 } 4218 4219 /* The pointer with the specified id has released its reference to kernel 4220 * resources. Identify all copies of the same pointer and clear the reference. 4221 */ 4222 static int release_reference(struct bpf_verifier_env *env, 4223 int ref_obj_id) 4224 { 4225 struct bpf_verifier_state *vstate = env->cur_state; 4226 int err; 4227 int i; 4228 4229 err = release_reference_state(cur_func(env), ref_obj_id); 4230 if (err) 4231 return err; 4232 4233 for (i = 0; i <= vstate->curframe; i++) 4234 release_reg_references(env, vstate->frame[i], ref_obj_id); 4235 4236 return 0; 4237 } 4238 4239 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 4240 struct bpf_reg_state *regs) 4241 { 4242 int i; 4243 4244 /* after the call registers r0 - r5 were scratched */ 4245 for (i = 0; i < CALLER_SAVED_REGS; i++) { 4246 mark_reg_not_init(env, regs, caller_saved[i]); 4247 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 4248 } 4249 } 4250 4251 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 4252 int *insn_idx) 4253 { 4254 struct bpf_verifier_state *state = env->cur_state; 4255 struct bpf_func_info_aux *func_info_aux; 4256 struct bpf_func_state *caller, *callee; 4257 int i, err, subprog, target_insn; 4258 bool is_global = false; 4259 4260 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 4261 verbose(env, "the call stack of %d frames is too deep\n", 4262 state->curframe + 2); 4263 return -E2BIG; 4264 } 4265 4266 target_insn = *insn_idx + insn->imm; 4267 subprog = find_subprog(env, target_insn + 1); 4268 if (subprog < 0) { 4269 verbose(env, "verifier bug. No program starts at insn %d\n", 4270 target_insn + 1); 4271 return -EFAULT; 4272 } 4273 4274 caller = state->frame[state->curframe]; 4275 if (state->frame[state->curframe + 1]) { 4276 verbose(env, "verifier bug. Frame %d already allocated\n", 4277 state->curframe + 1); 4278 return -EFAULT; 4279 } 4280 4281 func_info_aux = env->prog->aux->func_info_aux; 4282 if (func_info_aux) 4283 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 4284 err = btf_check_func_arg_match(env, subprog, caller->regs); 4285 if (err == -EFAULT) 4286 return err; 4287 if (is_global) { 4288 if (err) { 4289 verbose(env, "Caller passes invalid args into func#%d\n", 4290 subprog); 4291 return err; 4292 } else { 4293 if (env->log.level & BPF_LOG_LEVEL) 4294 verbose(env, 4295 "Func#%d is global and valid. Skipping.\n", 4296 subprog); 4297 clear_caller_saved_regs(env, caller->regs); 4298 4299 /* All global functions return SCALAR_VALUE */ 4300 mark_reg_unknown(env, caller->regs, BPF_REG_0); 4301 4302 /* continue with next insn after call */ 4303 return 0; 4304 } 4305 } 4306 4307 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 4308 if (!callee) 4309 return -ENOMEM; 4310 state->frame[state->curframe + 1] = callee; 4311 4312 /* callee cannot access r0, r6 - r9 for reading and has to write 4313 * into its own stack before reading from it. 4314 * callee can read/write into caller's stack 4315 */ 4316 init_func_state(env, callee, 4317 /* remember the callsite, it will be used by bpf_exit */ 4318 *insn_idx /* callsite */, 4319 state->curframe + 1 /* frameno within this callchain */, 4320 subprog /* subprog number within this prog */); 4321 4322 /* Transfer references to the callee */ 4323 err = transfer_reference_state(callee, caller); 4324 if (err) 4325 return err; 4326 4327 /* copy r1 - r5 args that callee can access. The copy includes parent 4328 * pointers, which connects us up to the liveness chain 4329 */ 4330 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 4331 callee->regs[i] = caller->regs[i]; 4332 4333 clear_caller_saved_regs(env, caller->regs); 4334 4335 /* only increment it after check_reg_arg() finished */ 4336 state->curframe++; 4337 4338 /* and go analyze first insn of the callee */ 4339 *insn_idx = target_insn; 4340 4341 if (env->log.level & BPF_LOG_LEVEL) { 4342 verbose(env, "caller:\n"); 4343 print_verifier_state(env, caller); 4344 verbose(env, "callee:\n"); 4345 print_verifier_state(env, callee); 4346 } 4347 return 0; 4348 } 4349 4350 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 4351 { 4352 struct bpf_verifier_state *state = env->cur_state; 4353 struct bpf_func_state *caller, *callee; 4354 struct bpf_reg_state *r0; 4355 int err; 4356 4357 callee = state->frame[state->curframe]; 4358 r0 = &callee->regs[BPF_REG_0]; 4359 if (r0->type == PTR_TO_STACK) { 4360 /* technically it's ok to return caller's stack pointer 4361 * (or caller's caller's pointer) back to the caller, 4362 * since these pointers are valid. Only current stack 4363 * pointer will be invalid as soon as function exits, 4364 * but let's be conservative 4365 */ 4366 verbose(env, "cannot return stack pointer to the caller\n"); 4367 return -EINVAL; 4368 } 4369 4370 state->curframe--; 4371 caller = state->frame[state->curframe]; 4372 /* return to the caller whatever r0 had in the callee */ 4373 caller->regs[BPF_REG_0] = *r0; 4374 4375 /* Transfer references to the caller */ 4376 err = transfer_reference_state(caller, callee); 4377 if (err) 4378 return err; 4379 4380 *insn_idx = callee->callsite + 1; 4381 if (env->log.level & BPF_LOG_LEVEL) { 4382 verbose(env, "returning from callee:\n"); 4383 print_verifier_state(env, callee); 4384 verbose(env, "to caller at %d:\n", *insn_idx); 4385 print_verifier_state(env, caller); 4386 } 4387 /* clear everything in the callee */ 4388 free_func_state(callee); 4389 state->frame[state->curframe + 1] = NULL; 4390 return 0; 4391 } 4392 4393 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 4394 int func_id, 4395 struct bpf_call_arg_meta *meta) 4396 { 4397 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 4398 4399 if (ret_type != RET_INTEGER || 4400 (func_id != BPF_FUNC_get_stack && 4401 func_id != BPF_FUNC_probe_read_str && 4402 func_id != BPF_FUNC_probe_read_kernel_str && 4403 func_id != BPF_FUNC_probe_read_user_str)) 4404 return; 4405 4406 ret_reg->smax_value = meta->msize_max_value; 4407 ret_reg->s32_max_value = meta->msize_max_value; 4408 __reg_deduce_bounds(ret_reg); 4409 __reg_bound_offset(ret_reg); 4410 __update_reg_bounds(ret_reg); 4411 } 4412 4413 static int 4414 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 4415 int func_id, int insn_idx) 4416 { 4417 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 4418 struct bpf_map *map = meta->map_ptr; 4419 4420 if (func_id != BPF_FUNC_tail_call && 4421 func_id != BPF_FUNC_map_lookup_elem && 4422 func_id != BPF_FUNC_map_update_elem && 4423 func_id != BPF_FUNC_map_delete_elem && 4424 func_id != BPF_FUNC_map_push_elem && 4425 func_id != BPF_FUNC_map_pop_elem && 4426 func_id != BPF_FUNC_map_peek_elem) 4427 return 0; 4428 4429 if (map == NULL) { 4430 verbose(env, "kernel subsystem misconfigured verifier\n"); 4431 return -EINVAL; 4432 } 4433 4434 /* In case of read-only, some additional restrictions 4435 * need to be applied in order to prevent altering the 4436 * state of the map from program side. 4437 */ 4438 if ((map->map_flags & BPF_F_RDONLY_PROG) && 4439 (func_id == BPF_FUNC_map_delete_elem || 4440 func_id == BPF_FUNC_map_update_elem || 4441 func_id == BPF_FUNC_map_push_elem || 4442 func_id == BPF_FUNC_map_pop_elem)) { 4443 verbose(env, "write into map forbidden\n"); 4444 return -EACCES; 4445 } 4446 4447 if (!BPF_MAP_PTR(aux->map_ptr_state)) 4448 bpf_map_ptr_store(aux, meta->map_ptr, 4449 !meta->map_ptr->bypass_spec_v1); 4450 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 4451 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 4452 !meta->map_ptr->bypass_spec_v1); 4453 return 0; 4454 } 4455 4456 static int 4457 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 4458 int func_id, int insn_idx) 4459 { 4460 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 4461 struct bpf_reg_state *regs = cur_regs(env), *reg; 4462 struct bpf_map *map = meta->map_ptr; 4463 struct tnum range; 4464 u64 val; 4465 int err; 4466 4467 if (func_id != BPF_FUNC_tail_call) 4468 return 0; 4469 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 4470 verbose(env, "kernel subsystem misconfigured verifier\n"); 4471 return -EINVAL; 4472 } 4473 4474 range = tnum_range(0, map->max_entries - 1); 4475 reg = ®s[BPF_REG_3]; 4476 4477 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) { 4478 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 4479 return 0; 4480 } 4481 4482 err = mark_chain_precision(env, BPF_REG_3); 4483 if (err) 4484 return err; 4485 4486 val = reg->var_off.value; 4487 if (bpf_map_key_unseen(aux)) 4488 bpf_map_key_store(aux, val); 4489 else if (!bpf_map_key_poisoned(aux) && 4490 bpf_map_key_immediate(aux) != val) 4491 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 4492 return 0; 4493 } 4494 4495 static int check_reference_leak(struct bpf_verifier_env *env) 4496 { 4497 struct bpf_func_state *state = cur_func(env); 4498 int i; 4499 4500 for (i = 0; i < state->acquired_refs; i++) { 4501 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 4502 state->refs[i].id, state->refs[i].insn_idx); 4503 } 4504 return state->acquired_refs ? -EINVAL : 0; 4505 } 4506 4507 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx) 4508 { 4509 const struct bpf_func_proto *fn = NULL; 4510 struct bpf_reg_state *regs; 4511 struct bpf_call_arg_meta meta; 4512 bool changes_data; 4513 int i, err; 4514 4515 /* find function prototype */ 4516 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 4517 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 4518 func_id); 4519 return -EINVAL; 4520 } 4521 4522 if (env->ops->get_func_proto) 4523 fn = env->ops->get_func_proto(func_id, env->prog); 4524 if (!fn) { 4525 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 4526 func_id); 4527 return -EINVAL; 4528 } 4529 4530 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 4531 if (!env->prog->gpl_compatible && fn->gpl_only) { 4532 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 4533 return -EINVAL; 4534 } 4535 4536 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 4537 changes_data = bpf_helper_changes_pkt_data(fn->func); 4538 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 4539 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 4540 func_id_name(func_id), func_id); 4541 return -EINVAL; 4542 } 4543 4544 memset(&meta, 0, sizeof(meta)); 4545 meta.pkt_access = fn->pkt_access; 4546 4547 err = check_func_proto(fn, func_id); 4548 if (err) { 4549 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 4550 func_id_name(func_id), func_id); 4551 return err; 4552 } 4553 4554 meta.func_id = func_id; 4555 /* check args */ 4556 for (i = 0; i < 5; i++) { 4557 err = btf_resolve_helper_id(&env->log, fn, i); 4558 if (err > 0) 4559 meta.btf_id = err; 4560 err = check_func_arg(env, BPF_REG_1 + i, fn->arg_type[i], &meta); 4561 if (err) 4562 return err; 4563 } 4564 4565 err = record_func_map(env, &meta, func_id, insn_idx); 4566 if (err) 4567 return err; 4568 4569 err = record_func_key(env, &meta, func_id, insn_idx); 4570 if (err) 4571 return err; 4572 4573 /* Mark slots with STACK_MISC in case of raw mode, stack offset 4574 * is inferred from register state. 4575 */ 4576 for (i = 0; i < meta.access_size; i++) { 4577 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 4578 BPF_WRITE, -1, false); 4579 if (err) 4580 return err; 4581 } 4582 4583 if (func_id == BPF_FUNC_tail_call) { 4584 err = check_reference_leak(env); 4585 if (err) { 4586 verbose(env, "tail_call would lead to reference leak\n"); 4587 return err; 4588 } 4589 } else if (is_release_function(func_id)) { 4590 err = release_reference(env, meta.ref_obj_id); 4591 if (err) { 4592 verbose(env, "func %s#%d reference has not been acquired before\n", 4593 func_id_name(func_id), func_id); 4594 return err; 4595 } 4596 } 4597 4598 regs = cur_regs(env); 4599 4600 /* check that flags argument in get_local_storage(map, flags) is 0, 4601 * this is required because get_local_storage() can't return an error. 4602 */ 4603 if (func_id == BPF_FUNC_get_local_storage && 4604 !register_is_null(®s[BPF_REG_2])) { 4605 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 4606 return -EINVAL; 4607 } 4608 4609 /* reset caller saved regs */ 4610 for (i = 0; i < CALLER_SAVED_REGS; i++) { 4611 mark_reg_not_init(env, regs, caller_saved[i]); 4612 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 4613 } 4614 4615 /* helper call returns 64-bit value. */ 4616 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 4617 4618 /* update return register (already marked as written above) */ 4619 if (fn->ret_type == RET_INTEGER) { 4620 /* sets type to SCALAR_VALUE */ 4621 mark_reg_unknown(env, regs, BPF_REG_0); 4622 } else if (fn->ret_type == RET_VOID) { 4623 regs[BPF_REG_0].type = NOT_INIT; 4624 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL || 4625 fn->ret_type == RET_PTR_TO_MAP_VALUE) { 4626 /* There is no offset yet applied, variable or fixed */ 4627 mark_reg_known_zero(env, regs, BPF_REG_0); 4628 /* remember map_ptr, so that check_map_access() 4629 * can check 'value_size' boundary of memory access 4630 * to map element returned from bpf_map_lookup_elem() 4631 */ 4632 if (meta.map_ptr == NULL) { 4633 verbose(env, 4634 "kernel subsystem misconfigured verifier\n"); 4635 return -EINVAL; 4636 } 4637 regs[BPF_REG_0].map_ptr = meta.map_ptr; 4638 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) { 4639 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE; 4640 if (map_value_has_spin_lock(meta.map_ptr)) 4641 regs[BPF_REG_0].id = ++env->id_gen; 4642 } else { 4643 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; 4644 regs[BPF_REG_0].id = ++env->id_gen; 4645 } 4646 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) { 4647 mark_reg_known_zero(env, regs, BPF_REG_0); 4648 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL; 4649 regs[BPF_REG_0].id = ++env->id_gen; 4650 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) { 4651 mark_reg_known_zero(env, regs, BPF_REG_0); 4652 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL; 4653 regs[BPF_REG_0].id = ++env->id_gen; 4654 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) { 4655 mark_reg_known_zero(env, regs, BPF_REG_0); 4656 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL; 4657 regs[BPF_REG_0].id = ++env->id_gen; 4658 } else { 4659 verbose(env, "unknown return type %d of func %s#%d\n", 4660 fn->ret_type, func_id_name(func_id), func_id); 4661 return -EINVAL; 4662 } 4663 4664 if (is_ptr_cast_function(func_id)) { 4665 /* For release_reference() */ 4666 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 4667 } else if (is_acquire_function(func_id, meta.map_ptr)) { 4668 int id = acquire_reference_state(env, insn_idx); 4669 4670 if (id < 0) 4671 return id; 4672 /* For mark_ptr_or_null_reg() */ 4673 regs[BPF_REG_0].id = id; 4674 /* For release_reference() */ 4675 regs[BPF_REG_0].ref_obj_id = id; 4676 } 4677 4678 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 4679 4680 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 4681 if (err) 4682 return err; 4683 4684 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) { 4685 const char *err_str; 4686 4687 #ifdef CONFIG_PERF_EVENTS 4688 err = get_callchain_buffers(sysctl_perf_event_max_stack); 4689 err_str = "cannot get callchain buffer for func %s#%d\n"; 4690 #else 4691 err = -ENOTSUPP; 4692 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 4693 #endif 4694 if (err) { 4695 verbose(env, err_str, func_id_name(func_id), func_id); 4696 return err; 4697 } 4698 4699 env->prog->has_callchain_buf = true; 4700 } 4701 4702 if (changes_data) 4703 clear_all_pkt_pointers(env); 4704 return 0; 4705 } 4706 4707 static bool signed_add_overflows(s64 a, s64 b) 4708 { 4709 /* Do the add in u64, where overflow is well-defined */ 4710 s64 res = (s64)((u64)a + (u64)b); 4711 4712 if (b < 0) 4713 return res > a; 4714 return res < a; 4715 } 4716 4717 static bool signed_add32_overflows(s64 a, s64 b) 4718 { 4719 /* Do the add in u32, where overflow is well-defined */ 4720 s32 res = (s32)((u32)a + (u32)b); 4721 4722 if (b < 0) 4723 return res > a; 4724 return res < a; 4725 } 4726 4727 static bool signed_sub_overflows(s32 a, s32 b) 4728 { 4729 /* Do the sub in u64, where overflow is well-defined */ 4730 s64 res = (s64)((u64)a - (u64)b); 4731 4732 if (b < 0) 4733 return res < a; 4734 return res > a; 4735 } 4736 4737 static bool signed_sub32_overflows(s32 a, s32 b) 4738 { 4739 /* Do the sub in u64, where overflow is well-defined */ 4740 s32 res = (s32)((u32)a - (u32)b); 4741 4742 if (b < 0) 4743 return res < a; 4744 return res > a; 4745 } 4746 4747 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 4748 const struct bpf_reg_state *reg, 4749 enum bpf_reg_type type) 4750 { 4751 bool known = tnum_is_const(reg->var_off); 4752 s64 val = reg->var_off.value; 4753 s64 smin = reg->smin_value; 4754 4755 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 4756 verbose(env, "math between %s pointer and %lld is not allowed\n", 4757 reg_type_str[type], val); 4758 return false; 4759 } 4760 4761 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 4762 verbose(env, "%s pointer offset %d is not allowed\n", 4763 reg_type_str[type], reg->off); 4764 return false; 4765 } 4766 4767 if (smin == S64_MIN) { 4768 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 4769 reg_type_str[type]); 4770 return false; 4771 } 4772 4773 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 4774 verbose(env, "value %lld makes %s pointer be out of bounds\n", 4775 smin, reg_type_str[type]); 4776 return false; 4777 } 4778 4779 return true; 4780 } 4781 4782 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 4783 { 4784 return &env->insn_aux_data[env->insn_idx]; 4785 } 4786 4787 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 4788 u32 *ptr_limit, u8 opcode, bool off_is_neg) 4789 { 4790 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) || 4791 (opcode == BPF_SUB && !off_is_neg); 4792 u32 off; 4793 4794 switch (ptr_reg->type) { 4795 case PTR_TO_STACK: 4796 /* Indirect variable offset stack access is prohibited in 4797 * unprivileged mode so it's not handled here. 4798 */ 4799 off = ptr_reg->off + ptr_reg->var_off.value; 4800 if (mask_to_left) 4801 *ptr_limit = MAX_BPF_STACK + off; 4802 else 4803 *ptr_limit = -off; 4804 return 0; 4805 case PTR_TO_MAP_VALUE: 4806 if (mask_to_left) { 4807 *ptr_limit = ptr_reg->umax_value + ptr_reg->off; 4808 } else { 4809 off = ptr_reg->smin_value + ptr_reg->off; 4810 *ptr_limit = ptr_reg->map_ptr->value_size - off; 4811 } 4812 return 0; 4813 default: 4814 return -EINVAL; 4815 } 4816 } 4817 4818 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 4819 const struct bpf_insn *insn) 4820 { 4821 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 4822 } 4823 4824 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 4825 u32 alu_state, u32 alu_limit) 4826 { 4827 /* If we arrived here from different branches with different 4828 * state or limits to sanitize, then this won't work. 4829 */ 4830 if (aux->alu_state && 4831 (aux->alu_state != alu_state || 4832 aux->alu_limit != alu_limit)) 4833 return -EACCES; 4834 4835 /* Corresponding fixup done in fixup_bpf_calls(). */ 4836 aux->alu_state = alu_state; 4837 aux->alu_limit = alu_limit; 4838 return 0; 4839 } 4840 4841 static int sanitize_val_alu(struct bpf_verifier_env *env, 4842 struct bpf_insn *insn) 4843 { 4844 struct bpf_insn_aux_data *aux = cur_aux(env); 4845 4846 if (can_skip_alu_sanitation(env, insn)) 4847 return 0; 4848 4849 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 4850 } 4851 4852 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 4853 struct bpf_insn *insn, 4854 const struct bpf_reg_state *ptr_reg, 4855 struct bpf_reg_state *dst_reg, 4856 bool off_is_neg) 4857 { 4858 struct bpf_verifier_state *vstate = env->cur_state; 4859 struct bpf_insn_aux_data *aux = cur_aux(env); 4860 bool ptr_is_dst_reg = ptr_reg == dst_reg; 4861 u8 opcode = BPF_OP(insn->code); 4862 u32 alu_state, alu_limit; 4863 struct bpf_reg_state tmp; 4864 bool ret; 4865 4866 if (can_skip_alu_sanitation(env, insn)) 4867 return 0; 4868 4869 /* We already marked aux for masking from non-speculative 4870 * paths, thus we got here in the first place. We only care 4871 * to explore bad access from here. 4872 */ 4873 if (vstate->speculative) 4874 goto do_sim; 4875 4876 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 4877 alu_state |= ptr_is_dst_reg ? 4878 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 4879 4880 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg)) 4881 return 0; 4882 if (update_alu_sanitation_state(aux, alu_state, alu_limit)) 4883 return -EACCES; 4884 do_sim: 4885 /* Simulate and find potential out-of-bounds access under 4886 * speculative execution from truncation as a result of 4887 * masking when off was not within expected range. If off 4888 * sits in dst, then we temporarily need to move ptr there 4889 * to simulate dst (== 0) +/-= ptr. Needed, for example, 4890 * for cases where we use K-based arithmetic in one direction 4891 * and truncated reg-based in the other in order to explore 4892 * bad access. 4893 */ 4894 if (!ptr_is_dst_reg) { 4895 tmp = *dst_reg; 4896 *dst_reg = *ptr_reg; 4897 } 4898 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true); 4899 if (!ptr_is_dst_reg && ret) 4900 *dst_reg = tmp; 4901 return !ret ? -EFAULT : 0; 4902 } 4903 4904 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 4905 * Caller should also handle BPF_MOV case separately. 4906 * If we return -EACCES, caller may want to try again treating pointer as a 4907 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 4908 */ 4909 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 4910 struct bpf_insn *insn, 4911 const struct bpf_reg_state *ptr_reg, 4912 const struct bpf_reg_state *off_reg) 4913 { 4914 struct bpf_verifier_state *vstate = env->cur_state; 4915 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4916 struct bpf_reg_state *regs = state->regs, *dst_reg; 4917 bool known = tnum_is_const(off_reg->var_off); 4918 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 4919 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 4920 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 4921 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 4922 u32 dst = insn->dst_reg, src = insn->src_reg; 4923 u8 opcode = BPF_OP(insn->code); 4924 int ret; 4925 4926 dst_reg = ®s[dst]; 4927 4928 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 4929 smin_val > smax_val || umin_val > umax_val) { 4930 /* Taint dst register if offset had invalid bounds derived from 4931 * e.g. dead branches. 4932 */ 4933 __mark_reg_unknown(env, dst_reg); 4934 return 0; 4935 } 4936 4937 if (BPF_CLASS(insn->code) != BPF_ALU64) { 4938 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 4939 verbose(env, 4940 "R%d 32-bit pointer arithmetic prohibited\n", 4941 dst); 4942 return -EACCES; 4943 } 4944 4945 switch (ptr_reg->type) { 4946 case PTR_TO_MAP_VALUE_OR_NULL: 4947 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 4948 dst, reg_type_str[ptr_reg->type]); 4949 return -EACCES; 4950 case CONST_PTR_TO_MAP: 4951 case PTR_TO_PACKET_END: 4952 case PTR_TO_SOCKET: 4953 case PTR_TO_SOCKET_OR_NULL: 4954 case PTR_TO_SOCK_COMMON: 4955 case PTR_TO_SOCK_COMMON_OR_NULL: 4956 case PTR_TO_TCP_SOCK: 4957 case PTR_TO_TCP_SOCK_OR_NULL: 4958 case PTR_TO_XDP_SOCK: 4959 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 4960 dst, reg_type_str[ptr_reg->type]); 4961 return -EACCES; 4962 case PTR_TO_MAP_VALUE: 4963 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) { 4964 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n", 4965 off_reg == dst_reg ? dst : src); 4966 return -EACCES; 4967 } 4968 /* fall-through */ 4969 default: 4970 break; 4971 } 4972 4973 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 4974 * The id may be overwritten later if we create a new variable offset. 4975 */ 4976 dst_reg->type = ptr_reg->type; 4977 dst_reg->id = ptr_reg->id; 4978 4979 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 4980 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 4981 return -EINVAL; 4982 4983 /* pointer types do not carry 32-bit bounds at the moment. */ 4984 __mark_reg32_unbounded(dst_reg); 4985 4986 switch (opcode) { 4987 case BPF_ADD: 4988 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0); 4989 if (ret < 0) { 4990 verbose(env, "R%d tried to add from different maps or paths\n", dst); 4991 return ret; 4992 } 4993 /* We can take a fixed offset as long as it doesn't overflow 4994 * the s32 'off' field 4995 */ 4996 if (known && (ptr_reg->off + smin_val == 4997 (s64)(s32)(ptr_reg->off + smin_val))) { 4998 /* pointer += K. Accumulate it into fixed offset */ 4999 dst_reg->smin_value = smin_ptr; 5000 dst_reg->smax_value = smax_ptr; 5001 dst_reg->umin_value = umin_ptr; 5002 dst_reg->umax_value = umax_ptr; 5003 dst_reg->var_off = ptr_reg->var_off; 5004 dst_reg->off = ptr_reg->off + smin_val; 5005 dst_reg->raw = ptr_reg->raw; 5006 break; 5007 } 5008 /* A new variable offset is created. Note that off_reg->off 5009 * == 0, since it's a scalar. 5010 * dst_reg gets the pointer type and since some positive 5011 * integer value was added to the pointer, give it a new 'id' 5012 * if it's a PTR_TO_PACKET. 5013 * this creates a new 'base' pointer, off_reg (variable) gets 5014 * added into the variable offset, and we copy the fixed offset 5015 * from ptr_reg. 5016 */ 5017 if (signed_add_overflows(smin_ptr, smin_val) || 5018 signed_add_overflows(smax_ptr, smax_val)) { 5019 dst_reg->smin_value = S64_MIN; 5020 dst_reg->smax_value = S64_MAX; 5021 } else { 5022 dst_reg->smin_value = smin_ptr + smin_val; 5023 dst_reg->smax_value = smax_ptr + smax_val; 5024 } 5025 if (umin_ptr + umin_val < umin_ptr || 5026 umax_ptr + umax_val < umax_ptr) { 5027 dst_reg->umin_value = 0; 5028 dst_reg->umax_value = U64_MAX; 5029 } else { 5030 dst_reg->umin_value = umin_ptr + umin_val; 5031 dst_reg->umax_value = umax_ptr + umax_val; 5032 } 5033 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 5034 dst_reg->off = ptr_reg->off; 5035 dst_reg->raw = ptr_reg->raw; 5036 if (reg_is_pkt_pointer(ptr_reg)) { 5037 dst_reg->id = ++env->id_gen; 5038 /* something was added to pkt_ptr, set range to zero */ 5039 dst_reg->raw = 0; 5040 } 5041 break; 5042 case BPF_SUB: 5043 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0); 5044 if (ret < 0) { 5045 verbose(env, "R%d tried to sub from different maps or paths\n", dst); 5046 return ret; 5047 } 5048 if (dst_reg == off_reg) { 5049 /* scalar -= pointer. Creates an unknown scalar */ 5050 verbose(env, "R%d tried to subtract pointer from scalar\n", 5051 dst); 5052 return -EACCES; 5053 } 5054 /* We don't allow subtraction from FP, because (according to 5055 * test_verifier.c test "invalid fp arithmetic", JITs might not 5056 * be able to deal with it. 5057 */ 5058 if (ptr_reg->type == PTR_TO_STACK) { 5059 verbose(env, "R%d subtraction from stack pointer prohibited\n", 5060 dst); 5061 return -EACCES; 5062 } 5063 if (known && (ptr_reg->off - smin_val == 5064 (s64)(s32)(ptr_reg->off - smin_val))) { 5065 /* pointer -= K. Subtract it from fixed offset */ 5066 dst_reg->smin_value = smin_ptr; 5067 dst_reg->smax_value = smax_ptr; 5068 dst_reg->umin_value = umin_ptr; 5069 dst_reg->umax_value = umax_ptr; 5070 dst_reg->var_off = ptr_reg->var_off; 5071 dst_reg->id = ptr_reg->id; 5072 dst_reg->off = ptr_reg->off - smin_val; 5073 dst_reg->raw = ptr_reg->raw; 5074 break; 5075 } 5076 /* A new variable offset is created. If the subtrahend is known 5077 * nonnegative, then any reg->range we had before is still good. 5078 */ 5079 if (signed_sub_overflows(smin_ptr, smax_val) || 5080 signed_sub_overflows(smax_ptr, smin_val)) { 5081 /* Overflow possible, we know nothing */ 5082 dst_reg->smin_value = S64_MIN; 5083 dst_reg->smax_value = S64_MAX; 5084 } else { 5085 dst_reg->smin_value = smin_ptr - smax_val; 5086 dst_reg->smax_value = smax_ptr - smin_val; 5087 } 5088 if (umin_ptr < umax_val) { 5089 /* Overflow possible, we know nothing */ 5090 dst_reg->umin_value = 0; 5091 dst_reg->umax_value = U64_MAX; 5092 } else { 5093 /* Cannot overflow (as long as bounds are consistent) */ 5094 dst_reg->umin_value = umin_ptr - umax_val; 5095 dst_reg->umax_value = umax_ptr - umin_val; 5096 } 5097 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 5098 dst_reg->off = ptr_reg->off; 5099 dst_reg->raw = ptr_reg->raw; 5100 if (reg_is_pkt_pointer(ptr_reg)) { 5101 dst_reg->id = ++env->id_gen; 5102 /* something was added to pkt_ptr, set range to zero */ 5103 if (smin_val < 0) 5104 dst_reg->raw = 0; 5105 } 5106 break; 5107 case BPF_AND: 5108 case BPF_OR: 5109 case BPF_XOR: 5110 /* bitwise ops on pointers are troublesome, prohibit. */ 5111 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 5112 dst, bpf_alu_string[opcode >> 4]); 5113 return -EACCES; 5114 default: 5115 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 5116 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 5117 dst, bpf_alu_string[opcode >> 4]); 5118 return -EACCES; 5119 } 5120 5121 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 5122 return -EINVAL; 5123 5124 __update_reg_bounds(dst_reg); 5125 __reg_deduce_bounds(dst_reg); 5126 __reg_bound_offset(dst_reg); 5127 5128 /* For unprivileged we require that resulting offset must be in bounds 5129 * in order to be able to sanitize access later on. 5130 */ 5131 if (!env->bypass_spec_v1) { 5132 if (dst_reg->type == PTR_TO_MAP_VALUE && 5133 check_map_access(env, dst, dst_reg->off, 1, false)) { 5134 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 5135 "prohibited for !root\n", dst); 5136 return -EACCES; 5137 } else if (dst_reg->type == PTR_TO_STACK && 5138 check_stack_access(env, dst_reg, dst_reg->off + 5139 dst_reg->var_off.value, 1)) { 5140 verbose(env, "R%d stack pointer arithmetic goes out of range, " 5141 "prohibited for !root\n", dst); 5142 return -EACCES; 5143 } 5144 } 5145 5146 return 0; 5147 } 5148 5149 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 5150 struct bpf_reg_state *src_reg) 5151 { 5152 s32 smin_val = src_reg->s32_min_value; 5153 s32 smax_val = src_reg->s32_max_value; 5154 u32 umin_val = src_reg->u32_min_value; 5155 u32 umax_val = src_reg->u32_max_value; 5156 5157 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 5158 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 5159 dst_reg->s32_min_value = S32_MIN; 5160 dst_reg->s32_max_value = S32_MAX; 5161 } else { 5162 dst_reg->s32_min_value += smin_val; 5163 dst_reg->s32_max_value += smax_val; 5164 } 5165 if (dst_reg->u32_min_value + umin_val < umin_val || 5166 dst_reg->u32_max_value + umax_val < umax_val) { 5167 dst_reg->u32_min_value = 0; 5168 dst_reg->u32_max_value = U32_MAX; 5169 } else { 5170 dst_reg->u32_min_value += umin_val; 5171 dst_reg->u32_max_value += umax_val; 5172 } 5173 } 5174 5175 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 5176 struct bpf_reg_state *src_reg) 5177 { 5178 s64 smin_val = src_reg->smin_value; 5179 s64 smax_val = src_reg->smax_value; 5180 u64 umin_val = src_reg->umin_value; 5181 u64 umax_val = src_reg->umax_value; 5182 5183 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 5184 signed_add_overflows(dst_reg->smax_value, smax_val)) { 5185 dst_reg->smin_value = S64_MIN; 5186 dst_reg->smax_value = S64_MAX; 5187 } else { 5188 dst_reg->smin_value += smin_val; 5189 dst_reg->smax_value += smax_val; 5190 } 5191 if (dst_reg->umin_value + umin_val < umin_val || 5192 dst_reg->umax_value + umax_val < umax_val) { 5193 dst_reg->umin_value = 0; 5194 dst_reg->umax_value = U64_MAX; 5195 } else { 5196 dst_reg->umin_value += umin_val; 5197 dst_reg->umax_value += umax_val; 5198 } 5199 } 5200 5201 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 5202 struct bpf_reg_state *src_reg) 5203 { 5204 s32 smin_val = src_reg->s32_min_value; 5205 s32 smax_val = src_reg->s32_max_value; 5206 u32 umin_val = src_reg->u32_min_value; 5207 u32 umax_val = src_reg->u32_max_value; 5208 5209 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 5210 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 5211 /* Overflow possible, we know nothing */ 5212 dst_reg->s32_min_value = S32_MIN; 5213 dst_reg->s32_max_value = S32_MAX; 5214 } else { 5215 dst_reg->s32_min_value -= smax_val; 5216 dst_reg->s32_max_value -= smin_val; 5217 } 5218 if (dst_reg->u32_min_value < umax_val) { 5219 /* Overflow possible, we know nothing */ 5220 dst_reg->u32_min_value = 0; 5221 dst_reg->u32_max_value = U32_MAX; 5222 } else { 5223 /* Cannot overflow (as long as bounds are consistent) */ 5224 dst_reg->u32_min_value -= umax_val; 5225 dst_reg->u32_max_value -= umin_val; 5226 } 5227 } 5228 5229 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 5230 struct bpf_reg_state *src_reg) 5231 { 5232 s64 smin_val = src_reg->smin_value; 5233 s64 smax_val = src_reg->smax_value; 5234 u64 umin_val = src_reg->umin_value; 5235 u64 umax_val = src_reg->umax_value; 5236 5237 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 5238 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 5239 /* Overflow possible, we know nothing */ 5240 dst_reg->smin_value = S64_MIN; 5241 dst_reg->smax_value = S64_MAX; 5242 } else { 5243 dst_reg->smin_value -= smax_val; 5244 dst_reg->smax_value -= smin_val; 5245 } 5246 if (dst_reg->umin_value < umax_val) { 5247 /* Overflow possible, we know nothing */ 5248 dst_reg->umin_value = 0; 5249 dst_reg->umax_value = U64_MAX; 5250 } else { 5251 /* Cannot overflow (as long as bounds are consistent) */ 5252 dst_reg->umin_value -= umax_val; 5253 dst_reg->umax_value -= umin_val; 5254 } 5255 } 5256 5257 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 5258 struct bpf_reg_state *src_reg) 5259 { 5260 s32 smin_val = src_reg->s32_min_value; 5261 u32 umin_val = src_reg->u32_min_value; 5262 u32 umax_val = src_reg->u32_max_value; 5263 5264 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 5265 /* Ain't nobody got time to multiply that sign */ 5266 __mark_reg32_unbounded(dst_reg); 5267 return; 5268 } 5269 /* Both values are positive, so we can work with unsigned and 5270 * copy the result to signed (unless it exceeds S32_MAX). 5271 */ 5272 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 5273 /* Potential overflow, we know nothing */ 5274 __mark_reg32_unbounded(dst_reg); 5275 return; 5276 } 5277 dst_reg->u32_min_value *= umin_val; 5278 dst_reg->u32_max_value *= umax_val; 5279 if (dst_reg->u32_max_value > S32_MAX) { 5280 /* Overflow possible, we know nothing */ 5281 dst_reg->s32_min_value = S32_MIN; 5282 dst_reg->s32_max_value = S32_MAX; 5283 } else { 5284 dst_reg->s32_min_value = dst_reg->u32_min_value; 5285 dst_reg->s32_max_value = dst_reg->u32_max_value; 5286 } 5287 } 5288 5289 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 5290 struct bpf_reg_state *src_reg) 5291 { 5292 s64 smin_val = src_reg->smin_value; 5293 u64 umin_val = src_reg->umin_value; 5294 u64 umax_val = src_reg->umax_value; 5295 5296 if (smin_val < 0 || dst_reg->smin_value < 0) { 5297 /* Ain't nobody got time to multiply that sign */ 5298 __mark_reg64_unbounded(dst_reg); 5299 return; 5300 } 5301 /* Both values are positive, so we can work with unsigned and 5302 * copy the result to signed (unless it exceeds S64_MAX). 5303 */ 5304 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 5305 /* Potential overflow, we know nothing */ 5306 __mark_reg64_unbounded(dst_reg); 5307 return; 5308 } 5309 dst_reg->umin_value *= umin_val; 5310 dst_reg->umax_value *= umax_val; 5311 if (dst_reg->umax_value > S64_MAX) { 5312 /* Overflow possible, we know nothing */ 5313 dst_reg->smin_value = S64_MIN; 5314 dst_reg->smax_value = S64_MAX; 5315 } else { 5316 dst_reg->smin_value = dst_reg->umin_value; 5317 dst_reg->smax_value = dst_reg->umax_value; 5318 } 5319 } 5320 5321 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 5322 struct bpf_reg_state *src_reg) 5323 { 5324 bool src_known = tnum_subreg_is_const(src_reg->var_off); 5325 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 5326 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 5327 s32 smin_val = src_reg->s32_min_value; 5328 u32 umax_val = src_reg->u32_max_value; 5329 5330 /* Assuming scalar64_min_max_and will be called so its safe 5331 * to skip updating register for known 32-bit case. 5332 */ 5333 if (src_known && dst_known) 5334 return; 5335 5336 /* We get our minimum from the var_off, since that's inherently 5337 * bitwise. Our maximum is the minimum of the operands' maxima. 5338 */ 5339 dst_reg->u32_min_value = var32_off.value; 5340 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 5341 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 5342 /* Lose signed bounds when ANDing negative numbers, 5343 * ain't nobody got time for that. 5344 */ 5345 dst_reg->s32_min_value = S32_MIN; 5346 dst_reg->s32_max_value = S32_MAX; 5347 } else { 5348 /* ANDing two positives gives a positive, so safe to 5349 * cast result into s64. 5350 */ 5351 dst_reg->s32_min_value = dst_reg->u32_min_value; 5352 dst_reg->s32_max_value = dst_reg->u32_max_value; 5353 } 5354 5355 } 5356 5357 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 5358 struct bpf_reg_state *src_reg) 5359 { 5360 bool src_known = tnum_is_const(src_reg->var_off); 5361 bool dst_known = tnum_is_const(dst_reg->var_off); 5362 s64 smin_val = src_reg->smin_value; 5363 u64 umax_val = src_reg->umax_value; 5364 5365 if (src_known && dst_known) { 5366 __mark_reg_known(dst_reg, dst_reg->var_off.value & 5367 src_reg->var_off.value); 5368 return; 5369 } 5370 5371 /* We get our minimum from the var_off, since that's inherently 5372 * bitwise. Our maximum is the minimum of the operands' maxima. 5373 */ 5374 dst_reg->umin_value = dst_reg->var_off.value; 5375 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 5376 if (dst_reg->smin_value < 0 || smin_val < 0) { 5377 /* Lose signed bounds when ANDing negative numbers, 5378 * ain't nobody got time for that. 5379 */ 5380 dst_reg->smin_value = S64_MIN; 5381 dst_reg->smax_value = S64_MAX; 5382 } else { 5383 /* ANDing two positives gives a positive, so safe to 5384 * cast result into s64. 5385 */ 5386 dst_reg->smin_value = dst_reg->umin_value; 5387 dst_reg->smax_value = dst_reg->umax_value; 5388 } 5389 /* We may learn something more from the var_off */ 5390 __update_reg_bounds(dst_reg); 5391 } 5392 5393 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 5394 struct bpf_reg_state *src_reg) 5395 { 5396 bool src_known = tnum_subreg_is_const(src_reg->var_off); 5397 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 5398 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 5399 s32 smin_val = src_reg->smin_value; 5400 u32 umin_val = src_reg->umin_value; 5401 5402 /* Assuming scalar64_min_max_or will be called so it is safe 5403 * to skip updating register for known case. 5404 */ 5405 if (src_known && dst_known) 5406 return; 5407 5408 /* We get our maximum from the var_off, and our minimum is the 5409 * maximum of the operands' minima 5410 */ 5411 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 5412 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 5413 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 5414 /* Lose signed bounds when ORing negative numbers, 5415 * ain't nobody got time for that. 5416 */ 5417 dst_reg->s32_min_value = S32_MIN; 5418 dst_reg->s32_max_value = S32_MAX; 5419 } else { 5420 /* ORing two positives gives a positive, so safe to 5421 * cast result into s64. 5422 */ 5423 dst_reg->s32_min_value = dst_reg->umin_value; 5424 dst_reg->s32_max_value = dst_reg->umax_value; 5425 } 5426 } 5427 5428 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 5429 struct bpf_reg_state *src_reg) 5430 { 5431 bool src_known = tnum_is_const(src_reg->var_off); 5432 bool dst_known = tnum_is_const(dst_reg->var_off); 5433 s64 smin_val = src_reg->smin_value; 5434 u64 umin_val = src_reg->umin_value; 5435 5436 if (src_known && dst_known) { 5437 __mark_reg_known(dst_reg, dst_reg->var_off.value | 5438 src_reg->var_off.value); 5439 return; 5440 } 5441 5442 /* We get our maximum from the var_off, and our minimum is the 5443 * maximum of the operands' minima 5444 */ 5445 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 5446 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 5447 if (dst_reg->smin_value < 0 || smin_val < 0) { 5448 /* Lose signed bounds when ORing negative numbers, 5449 * ain't nobody got time for that. 5450 */ 5451 dst_reg->smin_value = S64_MIN; 5452 dst_reg->smax_value = S64_MAX; 5453 } else { 5454 /* ORing two positives gives a positive, so safe to 5455 * cast result into s64. 5456 */ 5457 dst_reg->smin_value = dst_reg->umin_value; 5458 dst_reg->smax_value = dst_reg->umax_value; 5459 } 5460 /* We may learn something more from the var_off */ 5461 __update_reg_bounds(dst_reg); 5462 } 5463 5464 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 5465 u64 umin_val, u64 umax_val) 5466 { 5467 /* We lose all sign bit information (except what we can pick 5468 * up from var_off) 5469 */ 5470 dst_reg->s32_min_value = S32_MIN; 5471 dst_reg->s32_max_value = S32_MAX; 5472 /* If we might shift our top bit out, then we know nothing */ 5473 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 5474 dst_reg->u32_min_value = 0; 5475 dst_reg->u32_max_value = U32_MAX; 5476 } else { 5477 dst_reg->u32_min_value <<= umin_val; 5478 dst_reg->u32_max_value <<= umax_val; 5479 } 5480 } 5481 5482 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 5483 struct bpf_reg_state *src_reg) 5484 { 5485 u32 umax_val = src_reg->u32_max_value; 5486 u32 umin_val = src_reg->u32_min_value; 5487 /* u32 alu operation will zext upper bits */ 5488 struct tnum subreg = tnum_subreg(dst_reg->var_off); 5489 5490 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 5491 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 5492 /* Not required but being careful mark reg64 bounds as unknown so 5493 * that we are forced to pick them up from tnum and zext later and 5494 * if some path skips this step we are still safe. 5495 */ 5496 __mark_reg64_unbounded(dst_reg); 5497 __update_reg32_bounds(dst_reg); 5498 } 5499 5500 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 5501 u64 umin_val, u64 umax_val) 5502 { 5503 /* Special case <<32 because it is a common compiler pattern to sign 5504 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 5505 * positive we know this shift will also be positive so we can track 5506 * bounds correctly. Otherwise we lose all sign bit information except 5507 * what we can pick up from var_off. Perhaps we can generalize this 5508 * later to shifts of any length. 5509 */ 5510 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 5511 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 5512 else 5513 dst_reg->smax_value = S64_MAX; 5514 5515 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 5516 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 5517 else 5518 dst_reg->smin_value = S64_MIN; 5519 5520 /* If we might shift our top bit out, then we know nothing */ 5521 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 5522 dst_reg->umin_value = 0; 5523 dst_reg->umax_value = U64_MAX; 5524 } else { 5525 dst_reg->umin_value <<= umin_val; 5526 dst_reg->umax_value <<= umax_val; 5527 } 5528 } 5529 5530 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 5531 struct bpf_reg_state *src_reg) 5532 { 5533 u64 umax_val = src_reg->umax_value; 5534 u64 umin_val = src_reg->umin_value; 5535 5536 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 5537 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 5538 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 5539 5540 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 5541 /* We may learn something more from the var_off */ 5542 __update_reg_bounds(dst_reg); 5543 } 5544 5545 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 5546 struct bpf_reg_state *src_reg) 5547 { 5548 struct tnum subreg = tnum_subreg(dst_reg->var_off); 5549 u32 umax_val = src_reg->u32_max_value; 5550 u32 umin_val = src_reg->u32_min_value; 5551 5552 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 5553 * be negative, then either: 5554 * 1) src_reg might be zero, so the sign bit of the result is 5555 * unknown, so we lose our signed bounds 5556 * 2) it's known negative, thus the unsigned bounds capture the 5557 * signed bounds 5558 * 3) the signed bounds cross zero, so they tell us nothing 5559 * about the result 5560 * If the value in dst_reg is known nonnegative, then again the 5561 * unsigned bounts capture the signed bounds. 5562 * Thus, in all cases it suffices to blow away our signed bounds 5563 * and rely on inferring new ones from the unsigned bounds and 5564 * var_off of the result. 5565 */ 5566 dst_reg->s32_min_value = S32_MIN; 5567 dst_reg->s32_max_value = S32_MAX; 5568 5569 dst_reg->var_off = tnum_rshift(subreg, umin_val); 5570 dst_reg->u32_min_value >>= umax_val; 5571 dst_reg->u32_max_value >>= umin_val; 5572 5573 __mark_reg64_unbounded(dst_reg); 5574 __update_reg32_bounds(dst_reg); 5575 } 5576 5577 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 5578 struct bpf_reg_state *src_reg) 5579 { 5580 u64 umax_val = src_reg->umax_value; 5581 u64 umin_val = src_reg->umin_value; 5582 5583 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 5584 * be negative, then either: 5585 * 1) src_reg might be zero, so the sign bit of the result is 5586 * unknown, so we lose our signed bounds 5587 * 2) it's known negative, thus the unsigned bounds capture the 5588 * signed bounds 5589 * 3) the signed bounds cross zero, so they tell us nothing 5590 * about the result 5591 * If the value in dst_reg is known nonnegative, then again the 5592 * unsigned bounts capture the signed bounds. 5593 * Thus, in all cases it suffices to blow away our signed bounds 5594 * and rely on inferring new ones from the unsigned bounds and 5595 * var_off of the result. 5596 */ 5597 dst_reg->smin_value = S64_MIN; 5598 dst_reg->smax_value = S64_MAX; 5599 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 5600 dst_reg->umin_value >>= umax_val; 5601 dst_reg->umax_value >>= umin_val; 5602 5603 /* Its not easy to operate on alu32 bounds here because it depends 5604 * on bits being shifted in. Take easy way out and mark unbounded 5605 * so we can recalculate later from tnum. 5606 */ 5607 __mark_reg32_unbounded(dst_reg); 5608 __update_reg_bounds(dst_reg); 5609 } 5610 5611 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 5612 struct bpf_reg_state *src_reg) 5613 { 5614 u64 umin_val = src_reg->u32_min_value; 5615 5616 /* Upon reaching here, src_known is true and 5617 * umax_val is equal to umin_val. 5618 */ 5619 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 5620 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 5621 5622 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 5623 5624 /* blow away the dst_reg umin_value/umax_value and rely on 5625 * dst_reg var_off to refine the result. 5626 */ 5627 dst_reg->u32_min_value = 0; 5628 dst_reg->u32_max_value = U32_MAX; 5629 5630 __mark_reg64_unbounded(dst_reg); 5631 __update_reg32_bounds(dst_reg); 5632 } 5633 5634 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 5635 struct bpf_reg_state *src_reg) 5636 { 5637 u64 umin_val = src_reg->umin_value; 5638 5639 /* Upon reaching here, src_known is true and umax_val is equal 5640 * to umin_val. 5641 */ 5642 dst_reg->smin_value >>= umin_val; 5643 dst_reg->smax_value >>= umin_val; 5644 5645 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 5646 5647 /* blow away the dst_reg umin_value/umax_value and rely on 5648 * dst_reg var_off to refine the result. 5649 */ 5650 dst_reg->umin_value = 0; 5651 dst_reg->umax_value = U64_MAX; 5652 5653 /* Its not easy to operate on alu32 bounds here because it depends 5654 * on bits being shifted in from upper 32-bits. Take easy way out 5655 * and mark unbounded so we can recalculate later from tnum. 5656 */ 5657 __mark_reg32_unbounded(dst_reg); 5658 __update_reg_bounds(dst_reg); 5659 } 5660 5661 /* WARNING: This function does calculations on 64-bit values, but the actual 5662 * execution may occur on 32-bit values. Therefore, things like bitshifts 5663 * need extra checks in the 32-bit case. 5664 */ 5665 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 5666 struct bpf_insn *insn, 5667 struct bpf_reg_state *dst_reg, 5668 struct bpf_reg_state src_reg) 5669 { 5670 struct bpf_reg_state *regs = cur_regs(env); 5671 u8 opcode = BPF_OP(insn->code); 5672 bool src_known; 5673 s64 smin_val, smax_val; 5674 u64 umin_val, umax_val; 5675 s32 s32_min_val, s32_max_val; 5676 u32 u32_min_val, u32_max_val; 5677 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 5678 u32 dst = insn->dst_reg; 5679 int ret; 5680 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 5681 5682 smin_val = src_reg.smin_value; 5683 smax_val = src_reg.smax_value; 5684 umin_val = src_reg.umin_value; 5685 umax_val = src_reg.umax_value; 5686 5687 s32_min_val = src_reg.s32_min_value; 5688 s32_max_val = src_reg.s32_max_value; 5689 u32_min_val = src_reg.u32_min_value; 5690 u32_max_val = src_reg.u32_max_value; 5691 5692 if (alu32) { 5693 src_known = tnum_subreg_is_const(src_reg.var_off); 5694 if ((src_known && 5695 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 5696 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 5697 /* Taint dst register if offset had invalid bounds 5698 * derived from e.g. dead branches. 5699 */ 5700 __mark_reg_unknown(env, dst_reg); 5701 return 0; 5702 } 5703 } else { 5704 src_known = tnum_is_const(src_reg.var_off); 5705 if ((src_known && 5706 (smin_val != smax_val || umin_val != umax_val)) || 5707 smin_val > smax_val || umin_val > umax_val) { 5708 /* Taint dst register if offset had invalid bounds 5709 * derived from e.g. dead branches. 5710 */ 5711 __mark_reg_unknown(env, dst_reg); 5712 return 0; 5713 } 5714 } 5715 5716 if (!src_known && 5717 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 5718 __mark_reg_unknown(env, dst_reg); 5719 return 0; 5720 } 5721 5722 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 5723 * There are two classes of instructions: The first class we track both 5724 * alu32 and alu64 sign/unsigned bounds independently this provides the 5725 * greatest amount of precision when alu operations are mixed with jmp32 5726 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 5727 * and BPF_OR. This is possible because these ops have fairly easy to 5728 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 5729 * See alu32 verifier tests for examples. The second class of 5730 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 5731 * with regards to tracking sign/unsigned bounds because the bits may 5732 * cross subreg boundaries in the alu64 case. When this happens we mark 5733 * the reg unbounded in the subreg bound space and use the resulting 5734 * tnum to calculate an approximation of the sign/unsigned bounds. 5735 */ 5736 switch (opcode) { 5737 case BPF_ADD: 5738 ret = sanitize_val_alu(env, insn); 5739 if (ret < 0) { 5740 verbose(env, "R%d tried to add from different pointers or scalars\n", dst); 5741 return ret; 5742 } 5743 scalar32_min_max_add(dst_reg, &src_reg); 5744 scalar_min_max_add(dst_reg, &src_reg); 5745 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 5746 break; 5747 case BPF_SUB: 5748 ret = sanitize_val_alu(env, insn); 5749 if (ret < 0) { 5750 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst); 5751 return ret; 5752 } 5753 scalar32_min_max_sub(dst_reg, &src_reg); 5754 scalar_min_max_sub(dst_reg, &src_reg); 5755 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 5756 break; 5757 case BPF_MUL: 5758 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 5759 scalar32_min_max_mul(dst_reg, &src_reg); 5760 scalar_min_max_mul(dst_reg, &src_reg); 5761 break; 5762 case BPF_AND: 5763 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 5764 scalar32_min_max_and(dst_reg, &src_reg); 5765 scalar_min_max_and(dst_reg, &src_reg); 5766 break; 5767 case BPF_OR: 5768 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 5769 scalar32_min_max_or(dst_reg, &src_reg); 5770 scalar_min_max_or(dst_reg, &src_reg); 5771 break; 5772 case BPF_LSH: 5773 if (umax_val >= insn_bitness) { 5774 /* Shifts greater than 31 or 63 are undefined. 5775 * This includes shifts by a negative number. 5776 */ 5777 mark_reg_unknown(env, regs, insn->dst_reg); 5778 break; 5779 } 5780 if (alu32) 5781 scalar32_min_max_lsh(dst_reg, &src_reg); 5782 else 5783 scalar_min_max_lsh(dst_reg, &src_reg); 5784 break; 5785 case BPF_RSH: 5786 if (umax_val >= insn_bitness) { 5787 /* Shifts greater than 31 or 63 are undefined. 5788 * This includes shifts by a negative number. 5789 */ 5790 mark_reg_unknown(env, regs, insn->dst_reg); 5791 break; 5792 } 5793 if (alu32) 5794 scalar32_min_max_rsh(dst_reg, &src_reg); 5795 else 5796 scalar_min_max_rsh(dst_reg, &src_reg); 5797 break; 5798 case BPF_ARSH: 5799 if (umax_val >= insn_bitness) { 5800 /* Shifts greater than 31 or 63 are undefined. 5801 * This includes shifts by a negative number. 5802 */ 5803 mark_reg_unknown(env, regs, insn->dst_reg); 5804 break; 5805 } 5806 if (alu32) 5807 scalar32_min_max_arsh(dst_reg, &src_reg); 5808 else 5809 scalar_min_max_arsh(dst_reg, &src_reg); 5810 break; 5811 default: 5812 mark_reg_unknown(env, regs, insn->dst_reg); 5813 break; 5814 } 5815 5816 /* ALU32 ops are zero extended into 64bit register */ 5817 if (alu32) 5818 zext_32_to_64(dst_reg); 5819 5820 __update_reg_bounds(dst_reg); 5821 __reg_deduce_bounds(dst_reg); 5822 __reg_bound_offset(dst_reg); 5823 return 0; 5824 } 5825 5826 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 5827 * and var_off. 5828 */ 5829 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 5830 struct bpf_insn *insn) 5831 { 5832 struct bpf_verifier_state *vstate = env->cur_state; 5833 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5834 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 5835 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 5836 u8 opcode = BPF_OP(insn->code); 5837 int err; 5838 5839 dst_reg = ®s[insn->dst_reg]; 5840 src_reg = NULL; 5841 if (dst_reg->type != SCALAR_VALUE) 5842 ptr_reg = dst_reg; 5843 if (BPF_SRC(insn->code) == BPF_X) { 5844 src_reg = ®s[insn->src_reg]; 5845 if (src_reg->type != SCALAR_VALUE) { 5846 if (dst_reg->type != SCALAR_VALUE) { 5847 /* Combining two pointers by any ALU op yields 5848 * an arbitrary scalar. Disallow all math except 5849 * pointer subtraction 5850 */ 5851 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 5852 mark_reg_unknown(env, regs, insn->dst_reg); 5853 return 0; 5854 } 5855 verbose(env, "R%d pointer %s pointer prohibited\n", 5856 insn->dst_reg, 5857 bpf_alu_string[opcode >> 4]); 5858 return -EACCES; 5859 } else { 5860 /* scalar += pointer 5861 * This is legal, but we have to reverse our 5862 * src/dest handling in computing the range 5863 */ 5864 err = mark_chain_precision(env, insn->dst_reg); 5865 if (err) 5866 return err; 5867 return adjust_ptr_min_max_vals(env, insn, 5868 src_reg, dst_reg); 5869 } 5870 } else if (ptr_reg) { 5871 /* pointer += scalar */ 5872 err = mark_chain_precision(env, insn->src_reg); 5873 if (err) 5874 return err; 5875 return adjust_ptr_min_max_vals(env, insn, 5876 dst_reg, src_reg); 5877 } 5878 } else { 5879 /* Pretend the src is a reg with a known value, since we only 5880 * need to be able to read from this state. 5881 */ 5882 off_reg.type = SCALAR_VALUE; 5883 __mark_reg_known(&off_reg, insn->imm); 5884 src_reg = &off_reg; 5885 if (ptr_reg) /* pointer += K */ 5886 return adjust_ptr_min_max_vals(env, insn, 5887 ptr_reg, src_reg); 5888 } 5889 5890 /* Got here implies adding two SCALAR_VALUEs */ 5891 if (WARN_ON_ONCE(ptr_reg)) { 5892 print_verifier_state(env, state); 5893 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 5894 return -EINVAL; 5895 } 5896 if (WARN_ON(!src_reg)) { 5897 print_verifier_state(env, state); 5898 verbose(env, "verifier internal error: no src_reg\n"); 5899 return -EINVAL; 5900 } 5901 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 5902 } 5903 5904 /* check validity of 32-bit and 64-bit arithmetic operations */ 5905 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 5906 { 5907 struct bpf_reg_state *regs = cur_regs(env); 5908 u8 opcode = BPF_OP(insn->code); 5909 int err; 5910 5911 if (opcode == BPF_END || opcode == BPF_NEG) { 5912 if (opcode == BPF_NEG) { 5913 if (BPF_SRC(insn->code) != 0 || 5914 insn->src_reg != BPF_REG_0 || 5915 insn->off != 0 || insn->imm != 0) { 5916 verbose(env, "BPF_NEG uses reserved fields\n"); 5917 return -EINVAL; 5918 } 5919 } else { 5920 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 5921 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 5922 BPF_CLASS(insn->code) == BPF_ALU64) { 5923 verbose(env, "BPF_END uses reserved fields\n"); 5924 return -EINVAL; 5925 } 5926 } 5927 5928 /* check src operand */ 5929 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 5930 if (err) 5931 return err; 5932 5933 if (is_pointer_value(env, insn->dst_reg)) { 5934 verbose(env, "R%d pointer arithmetic prohibited\n", 5935 insn->dst_reg); 5936 return -EACCES; 5937 } 5938 5939 /* check dest operand */ 5940 err = check_reg_arg(env, insn->dst_reg, DST_OP); 5941 if (err) 5942 return err; 5943 5944 } else if (opcode == BPF_MOV) { 5945 5946 if (BPF_SRC(insn->code) == BPF_X) { 5947 if (insn->imm != 0 || insn->off != 0) { 5948 verbose(env, "BPF_MOV uses reserved fields\n"); 5949 return -EINVAL; 5950 } 5951 5952 /* check src operand */ 5953 err = check_reg_arg(env, insn->src_reg, SRC_OP); 5954 if (err) 5955 return err; 5956 } else { 5957 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 5958 verbose(env, "BPF_MOV uses reserved fields\n"); 5959 return -EINVAL; 5960 } 5961 } 5962 5963 /* check dest operand, mark as required later */ 5964 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 5965 if (err) 5966 return err; 5967 5968 if (BPF_SRC(insn->code) == BPF_X) { 5969 struct bpf_reg_state *src_reg = regs + insn->src_reg; 5970 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 5971 5972 if (BPF_CLASS(insn->code) == BPF_ALU64) { 5973 /* case: R1 = R2 5974 * copy register state to dest reg 5975 */ 5976 *dst_reg = *src_reg; 5977 dst_reg->live |= REG_LIVE_WRITTEN; 5978 dst_reg->subreg_def = DEF_NOT_SUBREG; 5979 } else { 5980 /* R1 = (u32) R2 */ 5981 if (is_pointer_value(env, insn->src_reg)) { 5982 verbose(env, 5983 "R%d partial copy of pointer\n", 5984 insn->src_reg); 5985 return -EACCES; 5986 } else if (src_reg->type == SCALAR_VALUE) { 5987 *dst_reg = *src_reg; 5988 dst_reg->live |= REG_LIVE_WRITTEN; 5989 dst_reg->subreg_def = env->insn_idx + 1; 5990 } else { 5991 mark_reg_unknown(env, regs, 5992 insn->dst_reg); 5993 } 5994 zext_32_to_64(dst_reg); 5995 } 5996 } else { 5997 /* case: R = imm 5998 * remember the value we stored into this reg 5999 */ 6000 /* clear any state __mark_reg_known doesn't set */ 6001 mark_reg_unknown(env, regs, insn->dst_reg); 6002 regs[insn->dst_reg].type = SCALAR_VALUE; 6003 if (BPF_CLASS(insn->code) == BPF_ALU64) { 6004 __mark_reg_known(regs + insn->dst_reg, 6005 insn->imm); 6006 } else { 6007 __mark_reg_known(regs + insn->dst_reg, 6008 (u32)insn->imm); 6009 } 6010 } 6011 6012 } else if (opcode > BPF_END) { 6013 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 6014 return -EINVAL; 6015 6016 } else { /* all other ALU ops: and, sub, xor, add, ... */ 6017 6018 if (BPF_SRC(insn->code) == BPF_X) { 6019 if (insn->imm != 0 || insn->off != 0) { 6020 verbose(env, "BPF_ALU uses reserved fields\n"); 6021 return -EINVAL; 6022 } 6023 /* check src1 operand */ 6024 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6025 if (err) 6026 return err; 6027 } else { 6028 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 6029 verbose(env, "BPF_ALU uses reserved fields\n"); 6030 return -EINVAL; 6031 } 6032 } 6033 6034 /* check src2 operand */ 6035 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6036 if (err) 6037 return err; 6038 6039 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 6040 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 6041 verbose(env, "div by zero\n"); 6042 return -EINVAL; 6043 } 6044 6045 if ((opcode == BPF_LSH || opcode == BPF_RSH || 6046 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 6047 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 6048 6049 if (insn->imm < 0 || insn->imm >= size) { 6050 verbose(env, "invalid shift %d\n", insn->imm); 6051 return -EINVAL; 6052 } 6053 } 6054 6055 /* check dest operand */ 6056 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6057 if (err) 6058 return err; 6059 6060 return adjust_reg_min_max_vals(env, insn); 6061 } 6062 6063 return 0; 6064 } 6065 6066 static void __find_good_pkt_pointers(struct bpf_func_state *state, 6067 struct bpf_reg_state *dst_reg, 6068 enum bpf_reg_type type, u16 new_range) 6069 { 6070 struct bpf_reg_state *reg; 6071 int i; 6072 6073 for (i = 0; i < MAX_BPF_REG; i++) { 6074 reg = &state->regs[i]; 6075 if (reg->type == type && reg->id == dst_reg->id) 6076 /* keep the maximum range already checked */ 6077 reg->range = max(reg->range, new_range); 6078 } 6079 6080 bpf_for_each_spilled_reg(i, state, reg) { 6081 if (!reg) 6082 continue; 6083 if (reg->type == type && reg->id == dst_reg->id) 6084 reg->range = max(reg->range, new_range); 6085 } 6086 } 6087 6088 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 6089 struct bpf_reg_state *dst_reg, 6090 enum bpf_reg_type type, 6091 bool range_right_open) 6092 { 6093 u16 new_range; 6094 int i; 6095 6096 if (dst_reg->off < 0 || 6097 (dst_reg->off == 0 && range_right_open)) 6098 /* This doesn't give us any range */ 6099 return; 6100 6101 if (dst_reg->umax_value > MAX_PACKET_OFF || 6102 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 6103 /* Risk of overflow. For instance, ptr + (1<<63) may be less 6104 * than pkt_end, but that's because it's also less than pkt. 6105 */ 6106 return; 6107 6108 new_range = dst_reg->off; 6109 if (range_right_open) 6110 new_range--; 6111 6112 /* Examples for register markings: 6113 * 6114 * pkt_data in dst register: 6115 * 6116 * r2 = r3; 6117 * r2 += 8; 6118 * if (r2 > pkt_end) goto <handle exception> 6119 * <access okay> 6120 * 6121 * r2 = r3; 6122 * r2 += 8; 6123 * if (r2 < pkt_end) goto <access okay> 6124 * <handle exception> 6125 * 6126 * Where: 6127 * r2 == dst_reg, pkt_end == src_reg 6128 * r2=pkt(id=n,off=8,r=0) 6129 * r3=pkt(id=n,off=0,r=0) 6130 * 6131 * pkt_data in src register: 6132 * 6133 * r2 = r3; 6134 * r2 += 8; 6135 * if (pkt_end >= r2) goto <access okay> 6136 * <handle exception> 6137 * 6138 * r2 = r3; 6139 * r2 += 8; 6140 * if (pkt_end <= r2) goto <handle exception> 6141 * <access okay> 6142 * 6143 * Where: 6144 * pkt_end == dst_reg, r2 == src_reg 6145 * r2=pkt(id=n,off=8,r=0) 6146 * r3=pkt(id=n,off=0,r=0) 6147 * 6148 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 6149 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 6150 * and [r3, r3 + 8-1) respectively is safe to access depending on 6151 * the check. 6152 */ 6153 6154 /* If our ids match, then we must have the same max_value. And we 6155 * don't care about the other reg's fixed offset, since if it's too big 6156 * the range won't allow anything. 6157 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 6158 */ 6159 for (i = 0; i <= vstate->curframe; i++) 6160 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type, 6161 new_range); 6162 } 6163 6164 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 6165 { 6166 struct tnum subreg = tnum_subreg(reg->var_off); 6167 s32 sval = (s32)val; 6168 6169 switch (opcode) { 6170 case BPF_JEQ: 6171 if (tnum_is_const(subreg)) 6172 return !!tnum_equals_const(subreg, val); 6173 break; 6174 case BPF_JNE: 6175 if (tnum_is_const(subreg)) 6176 return !tnum_equals_const(subreg, val); 6177 break; 6178 case BPF_JSET: 6179 if ((~subreg.mask & subreg.value) & val) 6180 return 1; 6181 if (!((subreg.mask | subreg.value) & val)) 6182 return 0; 6183 break; 6184 case BPF_JGT: 6185 if (reg->u32_min_value > val) 6186 return 1; 6187 else if (reg->u32_max_value <= val) 6188 return 0; 6189 break; 6190 case BPF_JSGT: 6191 if (reg->s32_min_value > sval) 6192 return 1; 6193 else if (reg->s32_max_value < sval) 6194 return 0; 6195 break; 6196 case BPF_JLT: 6197 if (reg->u32_max_value < val) 6198 return 1; 6199 else if (reg->u32_min_value >= val) 6200 return 0; 6201 break; 6202 case BPF_JSLT: 6203 if (reg->s32_max_value < sval) 6204 return 1; 6205 else if (reg->s32_min_value >= sval) 6206 return 0; 6207 break; 6208 case BPF_JGE: 6209 if (reg->u32_min_value >= val) 6210 return 1; 6211 else if (reg->u32_max_value < val) 6212 return 0; 6213 break; 6214 case BPF_JSGE: 6215 if (reg->s32_min_value >= sval) 6216 return 1; 6217 else if (reg->s32_max_value < sval) 6218 return 0; 6219 break; 6220 case BPF_JLE: 6221 if (reg->u32_max_value <= val) 6222 return 1; 6223 else if (reg->u32_min_value > val) 6224 return 0; 6225 break; 6226 case BPF_JSLE: 6227 if (reg->s32_max_value <= sval) 6228 return 1; 6229 else if (reg->s32_min_value > sval) 6230 return 0; 6231 break; 6232 } 6233 6234 return -1; 6235 } 6236 6237 6238 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 6239 { 6240 s64 sval = (s64)val; 6241 6242 switch (opcode) { 6243 case BPF_JEQ: 6244 if (tnum_is_const(reg->var_off)) 6245 return !!tnum_equals_const(reg->var_off, val); 6246 break; 6247 case BPF_JNE: 6248 if (tnum_is_const(reg->var_off)) 6249 return !tnum_equals_const(reg->var_off, val); 6250 break; 6251 case BPF_JSET: 6252 if ((~reg->var_off.mask & reg->var_off.value) & val) 6253 return 1; 6254 if (!((reg->var_off.mask | reg->var_off.value) & val)) 6255 return 0; 6256 break; 6257 case BPF_JGT: 6258 if (reg->umin_value > val) 6259 return 1; 6260 else if (reg->umax_value <= val) 6261 return 0; 6262 break; 6263 case BPF_JSGT: 6264 if (reg->smin_value > sval) 6265 return 1; 6266 else if (reg->smax_value < sval) 6267 return 0; 6268 break; 6269 case BPF_JLT: 6270 if (reg->umax_value < val) 6271 return 1; 6272 else if (reg->umin_value >= val) 6273 return 0; 6274 break; 6275 case BPF_JSLT: 6276 if (reg->smax_value < sval) 6277 return 1; 6278 else if (reg->smin_value >= sval) 6279 return 0; 6280 break; 6281 case BPF_JGE: 6282 if (reg->umin_value >= val) 6283 return 1; 6284 else if (reg->umax_value < val) 6285 return 0; 6286 break; 6287 case BPF_JSGE: 6288 if (reg->smin_value >= sval) 6289 return 1; 6290 else if (reg->smax_value < sval) 6291 return 0; 6292 break; 6293 case BPF_JLE: 6294 if (reg->umax_value <= val) 6295 return 1; 6296 else if (reg->umin_value > val) 6297 return 0; 6298 break; 6299 case BPF_JSLE: 6300 if (reg->smax_value <= sval) 6301 return 1; 6302 else if (reg->smin_value > sval) 6303 return 0; 6304 break; 6305 } 6306 6307 return -1; 6308 } 6309 6310 /* compute branch direction of the expression "if (reg opcode val) goto target;" 6311 * and return: 6312 * 1 - branch will be taken and "goto target" will be executed 6313 * 0 - branch will not be taken and fall-through to next insn 6314 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 6315 * range [0,10] 6316 */ 6317 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 6318 bool is_jmp32) 6319 { 6320 if (__is_pointer_value(false, reg)) { 6321 if (!reg_type_not_null(reg->type)) 6322 return -1; 6323 6324 /* If pointer is valid tests against zero will fail so we can 6325 * use this to direct branch taken. 6326 */ 6327 if (val != 0) 6328 return -1; 6329 6330 switch (opcode) { 6331 case BPF_JEQ: 6332 return 0; 6333 case BPF_JNE: 6334 return 1; 6335 default: 6336 return -1; 6337 } 6338 } 6339 6340 if (is_jmp32) 6341 return is_branch32_taken(reg, val, opcode); 6342 return is_branch64_taken(reg, val, opcode); 6343 } 6344 6345 /* Adjusts the register min/max values in the case that the dst_reg is the 6346 * variable register that we are working on, and src_reg is a constant or we're 6347 * simply doing a BPF_K check. 6348 * In JEQ/JNE cases we also adjust the var_off values. 6349 */ 6350 static void reg_set_min_max(struct bpf_reg_state *true_reg, 6351 struct bpf_reg_state *false_reg, 6352 u64 val, u32 val32, 6353 u8 opcode, bool is_jmp32) 6354 { 6355 struct tnum false_32off = tnum_subreg(false_reg->var_off); 6356 struct tnum false_64off = false_reg->var_off; 6357 struct tnum true_32off = tnum_subreg(true_reg->var_off); 6358 struct tnum true_64off = true_reg->var_off; 6359 s64 sval = (s64)val; 6360 s32 sval32 = (s32)val32; 6361 6362 /* If the dst_reg is a pointer, we can't learn anything about its 6363 * variable offset from the compare (unless src_reg were a pointer into 6364 * the same object, but we don't bother with that. 6365 * Since false_reg and true_reg have the same type by construction, we 6366 * only need to check one of them for pointerness. 6367 */ 6368 if (__is_pointer_value(false, false_reg)) 6369 return; 6370 6371 switch (opcode) { 6372 case BPF_JEQ: 6373 case BPF_JNE: 6374 { 6375 struct bpf_reg_state *reg = 6376 opcode == BPF_JEQ ? true_reg : false_reg; 6377 6378 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but 6379 * if it is true we know the value for sure. Likewise for 6380 * BPF_JNE. 6381 */ 6382 if (is_jmp32) 6383 __mark_reg32_known(reg, val32); 6384 else 6385 __mark_reg_known(reg, val); 6386 break; 6387 } 6388 case BPF_JSET: 6389 if (is_jmp32) { 6390 false_32off = tnum_and(false_32off, tnum_const(~val32)); 6391 if (is_power_of_2(val32)) 6392 true_32off = tnum_or(true_32off, 6393 tnum_const(val32)); 6394 } else { 6395 false_64off = tnum_and(false_64off, tnum_const(~val)); 6396 if (is_power_of_2(val)) 6397 true_64off = tnum_or(true_64off, 6398 tnum_const(val)); 6399 } 6400 break; 6401 case BPF_JGE: 6402 case BPF_JGT: 6403 { 6404 if (is_jmp32) { 6405 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 6406 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 6407 6408 false_reg->u32_max_value = min(false_reg->u32_max_value, 6409 false_umax); 6410 true_reg->u32_min_value = max(true_reg->u32_min_value, 6411 true_umin); 6412 } else { 6413 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 6414 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 6415 6416 false_reg->umax_value = min(false_reg->umax_value, false_umax); 6417 true_reg->umin_value = max(true_reg->umin_value, true_umin); 6418 } 6419 break; 6420 } 6421 case BPF_JSGE: 6422 case BPF_JSGT: 6423 { 6424 if (is_jmp32) { 6425 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 6426 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 6427 6428 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 6429 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 6430 } else { 6431 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 6432 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 6433 6434 false_reg->smax_value = min(false_reg->smax_value, false_smax); 6435 true_reg->smin_value = max(true_reg->smin_value, true_smin); 6436 } 6437 break; 6438 } 6439 case BPF_JLE: 6440 case BPF_JLT: 6441 { 6442 if (is_jmp32) { 6443 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 6444 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 6445 6446 false_reg->u32_min_value = max(false_reg->u32_min_value, 6447 false_umin); 6448 true_reg->u32_max_value = min(true_reg->u32_max_value, 6449 true_umax); 6450 } else { 6451 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 6452 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 6453 6454 false_reg->umin_value = max(false_reg->umin_value, false_umin); 6455 true_reg->umax_value = min(true_reg->umax_value, true_umax); 6456 } 6457 break; 6458 } 6459 case BPF_JSLE: 6460 case BPF_JSLT: 6461 { 6462 if (is_jmp32) { 6463 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 6464 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 6465 6466 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 6467 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 6468 } else { 6469 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 6470 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 6471 6472 false_reg->smin_value = max(false_reg->smin_value, false_smin); 6473 true_reg->smax_value = min(true_reg->smax_value, true_smax); 6474 } 6475 break; 6476 } 6477 default: 6478 return; 6479 } 6480 6481 if (is_jmp32) { 6482 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 6483 tnum_subreg(false_32off)); 6484 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 6485 tnum_subreg(true_32off)); 6486 __reg_combine_32_into_64(false_reg); 6487 __reg_combine_32_into_64(true_reg); 6488 } else { 6489 false_reg->var_off = false_64off; 6490 true_reg->var_off = true_64off; 6491 __reg_combine_64_into_32(false_reg); 6492 __reg_combine_64_into_32(true_reg); 6493 } 6494 } 6495 6496 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 6497 * the variable reg. 6498 */ 6499 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 6500 struct bpf_reg_state *false_reg, 6501 u64 val, u32 val32, 6502 u8 opcode, bool is_jmp32) 6503 { 6504 /* How can we transform "a <op> b" into "b <op> a"? */ 6505 static const u8 opcode_flip[16] = { 6506 /* these stay the same */ 6507 [BPF_JEQ >> 4] = BPF_JEQ, 6508 [BPF_JNE >> 4] = BPF_JNE, 6509 [BPF_JSET >> 4] = BPF_JSET, 6510 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 6511 [BPF_JGE >> 4] = BPF_JLE, 6512 [BPF_JGT >> 4] = BPF_JLT, 6513 [BPF_JLE >> 4] = BPF_JGE, 6514 [BPF_JLT >> 4] = BPF_JGT, 6515 [BPF_JSGE >> 4] = BPF_JSLE, 6516 [BPF_JSGT >> 4] = BPF_JSLT, 6517 [BPF_JSLE >> 4] = BPF_JSGE, 6518 [BPF_JSLT >> 4] = BPF_JSGT 6519 }; 6520 opcode = opcode_flip[opcode >> 4]; 6521 /* This uses zero as "not present in table"; luckily the zero opcode, 6522 * BPF_JA, can't get here. 6523 */ 6524 if (opcode) 6525 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 6526 } 6527 6528 /* Regs are known to be equal, so intersect their min/max/var_off */ 6529 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 6530 struct bpf_reg_state *dst_reg) 6531 { 6532 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 6533 dst_reg->umin_value); 6534 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 6535 dst_reg->umax_value); 6536 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 6537 dst_reg->smin_value); 6538 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 6539 dst_reg->smax_value); 6540 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 6541 dst_reg->var_off); 6542 /* We might have learned new bounds from the var_off. */ 6543 __update_reg_bounds(src_reg); 6544 __update_reg_bounds(dst_reg); 6545 /* We might have learned something about the sign bit. */ 6546 __reg_deduce_bounds(src_reg); 6547 __reg_deduce_bounds(dst_reg); 6548 /* We might have learned some bits from the bounds. */ 6549 __reg_bound_offset(src_reg); 6550 __reg_bound_offset(dst_reg); 6551 /* Intersecting with the old var_off might have improved our bounds 6552 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 6553 * then new var_off is (0; 0x7f...fc) which improves our umax. 6554 */ 6555 __update_reg_bounds(src_reg); 6556 __update_reg_bounds(dst_reg); 6557 } 6558 6559 static void reg_combine_min_max(struct bpf_reg_state *true_src, 6560 struct bpf_reg_state *true_dst, 6561 struct bpf_reg_state *false_src, 6562 struct bpf_reg_state *false_dst, 6563 u8 opcode) 6564 { 6565 switch (opcode) { 6566 case BPF_JEQ: 6567 __reg_combine_min_max(true_src, true_dst); 6568 break; 6569 case BPF_JNE: 6570 __reg_combine_min_max(false_src, false_dst); 6571 break; 6572 } 6573 } 6574 6575 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 6576 struct bpf_reg_state *reg, u32 id, 6577 bool is_null) 6578 { 6579 if (reg_type_may_be_null(reg->type) && reg->id == id) { 6580 /* Old offset (both fixed and variable parts) should 6581 * have been known-zero, because we don't allow pointer 6582 * arithmetic on pointers that might be NULL. 6583 */ 6584 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || 6585 !tnum_equals_const(reg->var_off, 0) || 6586 reg->off)) { 6587 __mark_reg_known_zero(reg); 6588 reg->off = 0; 6589 } 6590 if (is_null) { 6591 reg->type = SCALAR_VALUE; 6592 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) { 6593 const struct bpf_map *map = reg->map_ptr; 6594 6595 if (map->inner_map_meta) { 6596 reg->type = CONST_PTR_TO_MAP; 6597 reg->map_ptr = map->inner_map_meta; 6598 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 6599 reg->type = PTR_TO_XDP_SOCK; 6600 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 6601 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 6602 reg->type = PTR_TO_SOCKET; 6603 } else { 6604 reg->type = PTR_TO_MAP_VALUE; 6605 } 6606 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) { 6607 reg->type = PTR_TO_SOCKET; 6608 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) { 6609 reg->type = PTR_TO_SOCK_COMMON; 6610 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) { 6611 reg->type = PTR_TO_TCP_SOCK; 6612 } else if (reg->type == PTR_TO_BTF_ID_OR_NULL) { 6613 reg->type = PTR_TO_BTF_ID; 6614 } 6615 if (is_null) { 6616 /* We don't need id and ref_obj_id from this point 6617 * onwards anymore, thus we should better reset it, 6618 * so that state pruning has chances to take effect. 6619 */ 6620 reg->id = 0; 6621 reg->ref_obj_id = 0; 6622 } else if (!reg_may_point_to_spin_lock(reg)) { 6623 /* For not-NULL ptr, reg->ref_obj_id will be reset 6624 * in release_reg_references(). 6625 * 6626 * reg->id is still used by spin_lock ptr. Other 6627 * than spin_lock ptr type, reg->id can be reset. 6628 */ 6629 reg->id = 0; 6630 } 6631 } 6632 } 6633 6634 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id, 6635 bool is_null) 6636 { 6637 struct bpf_reg_state *reg; 6638 int i; 6639 6640 for (i = 0; i < MAX_BPF_REG; i++) 6641 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null); 6642 6643 bpf_for_each_spilled_reg(i, state, reg) { 6644 if (!reg) 6645 continue; 6646 mark_ptr_or_null_reg(state, reg, id, is_null); 6647 } 6648 } 6649 6650 /* The logic is similar to find_good_pkt_pointers(), both could eventually 6651 * be folded together at some point. 6652 */ 6653 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 6654 bool is_null) 6655 { 6656 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6657 struct bpf_reg_state *regs = state->regs; 6658 u32 ref_obj_id = regs[regno].ref_obj_id; 6659 u32 id = regs[regno].id; 6660 int i; 6661 6662 if (ref_obj_id && ref_obj_id == id && is_null) 6663 /* regs[regno] is in the " == NULL" branch. 6664 * No one could have freed the reference state before 6665 * doing the NULL check. 6666 */ 6667 WARN_ON_ONCE(release_reference_state(state, id)); 6668 6669 for (i = 0; i <= vstate->curframe; i++) 6670 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null); 6671 } 6672 6673 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 6674 struct bpf_reg_state *dst_reg, 6675 struct bpf_reg_state *src_reg, 6676 struct bpf_verifier_state *this_branch, 6677 struct bpf_verifier_state *other_branch) 6678 { 6679 if (BPF_SRC(insn->code) != BPF_X) 6680 return false; 6681 6682 /* Pointers are always 64-bit. */ 6683 if (BPF_CLASS(insn->code) == BPF_JMP32) 6684 return false; 6685 6686 switch (BPF_OP(insn->code)) { 6687 case BPF_JGT: 6688 if ((dst_reg->type == PTR_TO_PACKET && 6689 src_reg->type == PTR_TO_PACKET_END) || 6690 (dst_reg->type == PTR_TO_PACKET_META && 6691 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 6692 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 6693 find_good_pkt_pointers(this_branch, dst_reg, 6694 dst_reg->type, false); 6695 } else if ((dst_reg->type == PTR_TO_PACKET_END && 6696 src_reg->type == PTR_TO_PACKET) || 6697 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 6698 src_reg->type == PTR_TO_PACKET_META)) { 6699 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 6700 find_good_pkt_pointers(other_branch, src_reg, 6701 src_reg->type, true); 6702 } else { 6703 return false; 6704 } 6705 break; 6706 case BPF_JLT: 6707 if ((dst_reg->type == PTR_TO_PACKET && 6708 src_reg->type == PTR_TO_PACKET_END) || 6709 (dst_reg->type == PTR_TO_PACKET_META && 6710 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 6711 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 6712 find_good_pkt_pointers(other_branch, dst_reg, 6713 dst_reg->type, true); 6714 } else if ((dst_reg->type == PTR_TO_PACKET_END && 6715 src_reg->type == PTR_TO_PACKET) || 6716 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 6717 src_reg->type == PTR_TO_PACKET_META)) { 6718 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 6719 find_good_pkt_pointers(this_branch, src_reg, 6720 src_reg->type, false); 6721 } else { 6722 return false; 6723 } 6724 break; 6725 case BPF_JGE: 6726 if ((dst_reg->type == PTR_TO_PACKET && 6727 src_reg->type == PTR_TO_PACKET_END) || 6728 (dst_reg->type == PTR_TO_PACKET_META && 6729 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 6730 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 6731 find_good_pkt_pointers(this_branch, dst_reg, 6732 dst_reg->type, true); 6733 } else if ((dst_reg->type == PTR_TO_PACKET_END && 6734 src_reg->type == PTR_TO_PACKET) || 6735 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 6736 src_reg->type == PTR_TO_PACKET_META)) { 6737 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 6738 find_good_pkt_pointers(other_branch, src_reg, 6739 src_reg->type, false); 6740 } else { 6741 return false; 6742 } 6743 break; 6744 case BPF_JLE: 6745 if ((dst_reg->type == PTR_TO_PACKET && 6746 src_reg->type == PTR_TO_PACKET_END) || 6747 (dst_reg->type == PTR_TO_PACKET_META && 6748 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 6749 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 6750 find_good_pkt_pointers(other_branch, dst_reg, 6751 dst_reg->type, false); 6752 } else if ((dst_reg->type == PTR_TO_PACKET_END && 6753 src_reg->type == PTR_TO_PACKET) || 6754 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 6755 src_reg->type == PTR_TO_PACKET_META)) { 6756 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 6757 find_good_pkt_pointers(this_branch, src_reg, 6758 src_reg->type, true); 6759 } else { 6760 return false; 6761 } 6762 break; 6763 default: 6764 return false; 6765 } 6766 6767 return true; 6768 } 6769 6770 static int check_cond_jmp_op(struct bpf_verifier_env *env, 6771 struct bpf_insn *insn, int *insn_idx) 6772 { 6773 struct bpf_verifier_state *this_branch = env->cur_state; 6774 struct bpf_verifier_state *other_branch; 6775 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 6776 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 6777 u8 opcode = BPF_OP(insn->code); 6778 bool is_jmp32; 6779 int pred = -1; 6780 int err; 6781 6782 /* Only conditional jumps are expected to reach here. */ 6783 if (opcode == BPF_JA || opcode > BPF_JSLE) { 6784 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 6785 return -EINVAL; 6786 } 6787 6788 if (BPF_SRC(insn->code) == BPF_X) { 6789 if (insn->imm != 0) { 6790 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 6791 return -EINVAL; 6792 } 6793 6794 /* check src1 operand */ 6795 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6796 if (err) 6797 return err; 6798 6799 if (is_pointer_value(env, insn->src_reg)) { 6800 verbose(env, "R%d pointer comparison prohibited\n", 6801 insn->src_reg); 6802 return -EACCES; 6803 } 6804 src_reg = ®s[insn->src_reg]; 6805 } else { 6806 if (insn->src_reg != BPF_REG_0) { 6807 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 6808 return -EINVAL; 6809 } 6810 } 6811 6812 /* check src2 operand */ 6813 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6814 if (err) 6815 return err; 6816 6817 dst_reg = ®s[insn->dst_reg]; 6818 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 6819 6820 if (BPF_SRC(insn->code) == BPF_K) { 6821 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 6822 } else if (src_reg->type == SCALAR_VALUE && 6823 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 6824 pred = is_branch_taken(dst_reg, 6825 tnum_subreg(src_reg->var_off).value, 6826 opcode, 6827 is_jmp32); 6828 } else if (src_reg->type == SCALAR_VALUE && 6829 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 6830 pred = is_branch_taken(dst_reg, 6831 src_reg->var_off.value, 6832 opcode, 6833 is_jmp32); 6834 } 6835 6836 if (pred >= 0) { 6837 /* If we get here with a dst_reg pointer type it is because 6838 * above is_branch_taken() special cased the 0 comparison. 6839 */ 6840 if (!__is_pointer_value(false, dst_reg)) 6841 err = mark_chain_precision(env, insn->dst_reg); 6842 if (BPF_SRC(insn->code) == BPF_X && !err) 6843 err = mark_chain_precision(env, insn->src_reg); 6844 if (err) 6845 return err; 6846 } 6847 if (pred == 1) { 6848 /* only follow the goto, ignore fall-through */ 6849 *insn_idx += insn->off; 6850 return 0; 6851 } else if (pred == 0) { 6852 /* only follow fall-through branch, since 6853 * that's where the program will go 6854 */ 6855 return 0; 6856 } 6857 6858 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 6859 false); 6860 if (!other_branch) 6861 return -EFAULT; 6862 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 6863 6864 /* detect if we are comparing against a constant value so we can adjust 6865 * our min/max values for our dst register. 6866 * this is only legit if both are scalars (or pointers to the same 6867 * object, I suppose, but we don't support that right now), because 6868 * otherwise the different base pointers mean the offsets aren't 6869 * comparable. 6870 */ 6871 if (BPF_SRC(insn->code) == BPF_X) { 6872 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 6873 6874 if (dst_reg->type == SCALAR_VALUE && 6875 src_reg->type == SCALAR_VALUE) { 6876 if (tnum_is_const(src_reg->var_off) || 6877 (is_jmp32 && 6878 tnum_is_const(tnum_subreg(src_reg->var_off)))) 6879 reg_set_min_max(&other_branch_regs[insn->dst_reg], 6880 dst_reg, 6881 src_reg->var_off.value, 6882 tnum_subreg(src_reg->var_off).value, 6883 opcode, is_jmp32); 6884 else if (tnum_is_const(dst_reg->var_off) || 6885 (is_jmp32 && 6886 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 6887 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 6888 src_reg, 6889 dst_reg->var_off.value, 6890 tnum_subreg(dst_reg->var_off).value, 6891 opcode, is_jmp32); 6892 else if (!is_jmp32 && 6893 (opcode == BPF_JEQ || opcode == BPF_JNE)) 6894 /* Comparing for equality, we can combine knowledge */ 6895 reg_combine_min_max(&other_branch_regs[insn->src_reg], 6896 &other_branch_regs[insn->dst_reg], 6897 src_reg, dst_reg, opcode); 6898 } 6899 } else if (dst_reg->type == SCALAR_VALUE) { 6900 reg_set_min_max(&other_branch_regs[insn->dst_reg], 6901 dst_reg, insn->imm, (u32)insn->imm, 6902 opcode, is_jmp32); 6903 } 6904 6905 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 6906 * NOTE: these optimizations below are related with pointer comparison 6907 * which will never be JMP32. 6908 */ 6909 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 6910 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 6911 reg_type_may_be_null(dst_reg->type)) { 6912 /* Mark all identical registers in each branch as either 6913 * safe or unknown depending R == 0 or R != 0 conditional. 6914 */ 6915 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 6916 opcode == BPF_JNE); 6917 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 6918 opcode == BPF_JEQ); 6919 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 6920 this_branch, other_branch) && 6921 is_pointer_value(env, insn->dst_reg)) { 6922 verbose(env, "R%d pointer comparison prohibited\n", 6923 insn->dst_reg); 6924 return -EACCES; 6925 } 6926 if (env->log.level & BPF_LOG_LEVEL) 6927 print_verifier_state(env, this_branch->frame[this_branch->curframe]); 6928 return 0; 6929 } 6930 6931 /* verify BPF_LD_IMM64 instruction */ 6932 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 6933 { 6934 struct bpf_insn_aux_data *aux = cur_aux(env); 6935 struct bpf_reg_state *regs = cur_regs(env); 6936 struct bpf_map *map; 6937 int err; 6938 6939 if (BPF_SIZE(insn->code) != BPF_DW) { 6940 verbose(env, "invalid BPF_LD_IMM insn\n"); 6941 return -EINVAL; 6942 } 6943 if (insn->off != 0) { 6944 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 6945 return -EINVAL; 6946 } 6947 6948 err = check_reg_arg(env, insn->dst_reg, DST_OP); 6949 if (err) 6950 return err; 6951 6952 if (insn->src_reg == 0) { 6953 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 6954 6955 regs[insn->dst_reg].type = SCALAR_VALUE; 6956 __mark_reg_known(®s[insn->dst_reg], imm); 6957 return 0; 6958 } 6959 6960 map = env->used_maps[aux->map_index]; 6961 mark_reg_known_zero(env, regs, insn->dst_reg); 6962 regs[insn->dst_reg].map_ptr = map; 6963 6964 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) { 6965 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE; 6966 regs[insn->dst_reg].off = aux->map_off; 6967 if (map_value_has_spin_lock(map)) 6968 regs[insn->dst_reg].id = ++env->id_gen; 6969 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) { 6970 regs[insn->dst_reg].type = CONST_PTR_TO_MAP; 6971 } else { 6972 verbose(env, "bpf verifier is misconfigured\n"); 6973 return -EINVAL; 6974 } 6975 6976 return 0; 6977 } 6978 6979 static bool may_access_skb(enum bpf_prog_type type) 6980 { 6981 switch (type) { 6982 case BPF_PROG_TYPE_SOCKET_FILTER: 6983 case BPF_PROG_TYPE_SCHED_CLS: 6984 case BPF_PROG_TYPE_SCHED_ACT: 6985 return true; 6986 default: 6987 return false; 6988 } 6989 } 6990 6991 /* verify safety of LD_ABS|LD_IND instructions: 6992 * - they can only appear in the programs where ctx == skb 6993 * - since they are wrappers of function calls, they scratch R1-R5 registers, 6994 * preserve R6-R9, and store return value into R0 6995 * 6996 * Implicit input: 6997 * ctx == skb == R6 == CTX 6998 * 6999 * Explicit input: 7000 * SRC == any register 7001 * IMM == 32-bit immediate 7002 * 7003 * Output: 7004 * R0 - 8/16/32-bit skb data converted to cpu endianness 7005 */ 7006 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 7007 { 7008 struct bpf_reg_state *regs = cur_regs(env); 7009 static const int ctx_reg = BPF_REG_6; 7010 u8 mode = BPF_MODE(insn->code); 7011 int i, err; 7012 7013 if (!may_access_skb(env->prog->type)) { 7014 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 7015 return -EINVAL; 7016 } 7017 7018 if (!env->ops->gen_ld_abs) { 7019 verbose(env, "bpf verifier is misconfigured\n"); 7020 return -EINVAL; 7021 } 7022 7023 if (env->subprog_cnt > 1) { 7024 /* when program has LD_ABS insn JITs and interpreter assume 7025 * that r1 == ctx == skb which is not the case for callees 7026 * that can have arbitrary arguments. It's problematic 7027 * for main prog as well since JITs would need to analyze 7028 * all functions in order to make proper register save/restore 7029 * decisions in the main prog. Hence disallow LD_ABS with calls 7030 */ 7031 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n"); 7032 return -EINVAL; 7033 } 7034 7035 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 7036 BPF_SIZE(insn->code) == BPF_DW || 7037 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 7038 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 7039 return -EINVAL; 7040 } 7041 7042 /* check whether implicit source operand (register R6) is readable */ 7043 err = check_reg_arg(env, ctx_reg, SRC_OP); 7044 if (err) 7045 return err; 7046 7047 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 7048 * gen_ld_abs() may terminate the program at runtime, leading to 7049 * reference leak. 7050 */ 7051 err = check_reference_leak(env); 7052 if (err) { 7053 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 7054 return err; 7055 } 7056 7057 if (env->cur_state->active_spin_lock) { 7058 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 7059 return -EINVAL; 7060 } 7061 7062 if (regs[ctx_reg].type != PTR_TO_CTX) { 7063 verbose(env, 7064 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 7065 return -EINVAL; 7066 } 7067 7068 if (mode == BPF_IND) { 7069 /* check explicit source operand */ 7070 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7071 if (err) 7072 return err; 7073 } 7074 7075 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg); 7076 if (err < 0) 7077 return err; 7078 7079 /* reset caller saved regs to unreadable */ 7080 for (i = 0; i < CALLER_SAVED_REGS; i++) { 7081 mark_reg_not_init(env, regs, caller_saved[i]); 7082 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 7083 } 7084 7085 /* mark destination R0 register as readable, since it contains 7086 * the value fetched from the packet. 7087 * Already marked as written above. 7088 */ 7089 mark_reg_unknown(env, regs, BPF_REG_0); 7090 /* ld_abs load up to 32-bit skb data. */ 7091 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 7092 return 0; 7093 } 7094 7095 static int check_return_code(struct bpf_verifier_env *env) 7096 { 7097 struct tnum enforce_attach_type_range = tnum_unknown; 7098 const struct bpf_prog *prog = env->prog; 7099 struct bpf_reg_state *reg; 7100 struct tnum range = tnum_range(0, 1); 7101 int err; 7102 7103 /* LSM and struct_ops func-ptr's return type could be "void" */ 7104 if ((env->prog->type == BPF_PROG_TYPE_STRUCT_OPS || 7105 env->prog->type == BPF_PROG_TYPE_LSM) && 7106 !prog->aux->attach_func_proto->type) 7107 return 0; 7108 7109 /* eBPF calling convetion is such that R0 is used 7110 * to return the value from eBPF program. 7111 * Make sure that it's readable at this time 7112 * of bpf_exit, which means that program wrote 7113 * something into it earlier 7114 */ 7115 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 7116 if (err) 7117 return err; 7118 7119 if (is_pointer_value(env, BPF_REG_0)) { 7120 verbose(env, "R0 leaks addr as return value\n"); 7121 return -EACCES; 7122 } 7123 7124 switch (env->prog->type) { 7125 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 7126 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 7127 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 7128 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 7129 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 7130 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 7131 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 7132 range = tnum_range(1, 1); 7133 break; 7134 case BPF_PROG_TYPE_CGROUP_SKB: 7135 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 7136 range = tnum_range(0, 3); 7137 enforce_attach_type_range = tnum_range(2, 3); 7138 } 7139 break; 7140 case BPF_PROG_TYPE_CGROUP_SOCK: 7141 case BPF_PROG_TYPE_SOCK_OPS: 7142 case BPF_PROG_TYPE_CGROUP_DEVICE: 7143 case BPF_PROG_TYPE_CGROUP_SYSCTL: 7144 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 7145 break; 7146 case BPF_PROG_TYPE_RAW_TRACEPOINT: 7147 if (!env->prog->aux->attach_btf_id) 7148 return 0; 7149 range = tnum_const(0); 7150 break; 7151 case BPF_PROG_TYPE_TRACING: 7152 switch (env->prog->expected_attach_type) { 7153 case BPF_TRACE_FENTRY: 7154 case BPF_TRACE_FEXIT: 7155 range = tnum_const(0); 7156 break; 7157 case BPF_TRACE_RAW_TP: 7158 case BPF_MODIFY_RETURN: 7159 return 0; 7160 case BPF_TRACE_ITER: 7161 break; 7162 default: 7163 return -ENOTSUPP; 7164 } 7165 break; 7166 case BPF_PROG_TYPE_EXT: 7167 /* freplace program can return anything as its return value 7168 * depends on the to-be-replaced kernel func or bpf program. 7169 */ 7170 default: 7171 return 0; 7172 } 7173 7174 reg = cur_regs(env) + BPF_REG_0; 7175 if (reg->type != SCALAR_VALUE) { 7176 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 7177 reg_type_str[reg->type]); 7178 return -EINVAL; 7179 } 7180 7181 if (!tnum_in(range, reg->var_off)) { 7182 char tn_buf[48]; 7183 7184 verbose(env, "At program exit the register R0 "); 7185 if (!tnum_is_unknown(reg->var_off)) { 7186 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7187 verbose(env, "has value %s", tn_buf); 7188 } else { 7189 verbose(env, "has unknown scalar value"); 7190 } 7191 tnum_strn(tn_buf, sizeof(tn_buf), range); 7192 verbose(env, " should have been in %s\n", tn_buf); 7193 return -EINVAL; 7194 } 7195 7196 if (!tnum_is_unknown(enforce_attach_type_range) && 7197 tnum_in(enforce_attach_type_range, reg->var_off)) 7198 env->prog->enforce_expected_attach_type = 1; 7199 return 0; 7200 } 7201 7202 /* non-recursive DFS pseudo code 7203 * 1 procedure DFS-iterative(G,v): 7204 * 2 label v as discovered 7205 * 3 let S be a stack 7206 * 4 S.push(v) 7207 * 5 while S is not empty 7208 * 6 t <- S.pop() 7209 * 7 if t is what we're looking for: 7210 * 8 return t 7211 * 9 for all edges e in G.adjacentEdges(t) do 7212 * 10 if edge e is already labelled 7213 * 11 continue with the next edge 7214 * 12 w <- G.adjacentVertex(t,e) 7215 * 13 if vertex w is not discovered and not explored 7216 * 14 label e as tree-edge 7217 * 15 label w as discovered 7218 * 16 S.push(w) 7219 * 17 continue at 5 7220 * 18 else if vertex w is discovered 7221 * 19 label e as back-edge 7222 * 20 else 7223 * 21 // vertex w is explored 7224 * 22 label e as forward- or cross-edge 7225 * 23 label t as explored 7226 * 24 S.pop() 7227 * 7228 * convention: 7229 * 0x10 - discovered 7230 * 0x11 - discovered and fall-through edge labelled 7231 * 0x12 - discovered and fall-through and branch edges labelled 7232 * 0x20 - explored 7233 */ 7234 7235 enum { 7236 DISCOVERED = 0x10, 7237 EXPLORED = 0x20, 7238 FALLTHROUGH = 1, 7239 BRANCH = 2, 7240 }; 7241 7242 static u32 state_htab_size(struct bpf_verifier_env *env) 7243 { 7244 return env->prog->len; 7245 } 7246 7247 static struct bpf_verifier_state_list **explored_state( 7248 struct bpf_verifier_env *env, 7249 int idx) 7250 { 7251 struct bpf_verifier_state *cur = env->cur_state; 7252 struct bpf_func_state *state = cur->frame[cur->curframe]; 7253 7254 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 7255 } 7256 7257 static void init_explored_state(struct bpf_verifier_env *env, int idx) 7258 { 7259 env->insn_aux_data[idx].prune_point = true; 7260 } 7261 7262 /* t, w, e - match pseudo-code above: 7263 * t - index of current instruction 7264 * w - next instruction 7265 * e - edge 7266 */ 7267 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 7268 bool loop_ok) 7269 { 7270 int *insn_stack = env->cfg.insn_stack; 7271 int *insn_state = env->cfg.insn_state; 7272 7273 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 7274 return 0; 7275 7276 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 7277 return 0; 7278 7279 if (w < 0 || w >= env->prog->len) { 7280 verbose_linfo(env, t, "%d: ", t); 7281 verbose(env, "jump out of range from insn %d to %d\n", t, w); 7282 return -EINVAL; 7283 } 7284 7285 if (e == BRANCH) 7286 /* mark branch target for state pruning */ 7287 init_explored_state(env, w); 7288 7289 if (insn_state[w] == 0) { 7290 /* tree-edge */ 7291 insn_state[t] = DISCOVERED | e; 7292 insn_state[w] = DISCOVERED; 7293 if (env->cfg.cur_stack >= env->prog->len) 7294 return -E2BIG; 7295 insn_stack[env->cfg.cur_stack++] = w; 7296 return 1; 7297 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 7298 if (loop_ok && env->bpf_capable) 7299 return 0; 7300 verbose_linfo(env, t, "%d: ", t); 7301 verbose_linfo(env, w, "%d: ", w); 7302 verbose(env, "back-edge from insn %d to %d\n", t, w); 7303 return -EINVAL; 7304 } else if (insn_state[w] == EXPLORED) { 7305 /* forward- or cross-edge */ 7306 insn_state[t] = DISCOVERED | e; 7307 } else { 7308 verbose(env, "insn state internal bug\n"); 7309 return -EFAULT; 7310 } 7311 return 0; 7312 } 7313 7314 /* non-recursive depth-first-search to detect loops in BPF program 7315 * loop == back-edge in directed graph 7316 */ 7317 static int check_cfg(struct bpf_verifier_env *env) 7318 { 7319 struct bpf_insn *insns = env->prog->insnsi; 7320 int insn_cnt = env->prog->len; 7321 int *insn_stack, *insn_state; 7322 int ret = 0; 7323 int i, t; 7324 7325 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 7326 if (!insn_state) 7327 return -ENOMEM; 7328 7329 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 7330 if (!insn_stack) { 7331 kvfree(insn_state); 7332 return -ENOMEM; 7333 } 7334 7335 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 7336 insn_stack[0] = 0; /* 0 is the first instruction */ 7337 env->cfg.cur_stack = 1; 7338 7339 peek_stack: 7340 if (env->cfg.cur_stack == 0) 7341 goto check_state; 7342 t = insn_stack[env->cfg.cur_stack - 1]; 7343 7344 if (BPF_CLASS(insns[t].code) == BPF_JMP || 7345 BPF_CLASS(insns[t].code) == BPF_JMP32) { 7346 u8 opcode = BPF_OP(insns[t].code); 7347 7348 if (opcode == BPF_EXIT) { 7349 goto mark_explored; 7350 } else if (opcode == BPF_CALL) { 7351 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 7352 if (ret == 1) 7353 goto peek_stack; 7354 else if (ret < 0) 7355 goto err_free; 7356 if (t + 1 < insn_cnt) 7357 init_explored_state(env, t + 1); 7358 if (insns[t].src_reg == BPF_PSEUDO_CALL) { 7359 init_explored_state(env, t); 7360 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, 7361 env, false); 7362 if (ret == 1) 7363 goto peek_stack; 7364 else if (ret < 0) 7365 goto err_free; 7366 } 7367 } else if (opcode == BPF_JA) { 7368 if (BPF_SRC(insns[t].code) != BPF_K) { 7369 ret = -EINVAL; 7370 goto err_free; 7371 } 7372 /* unconditional jump with single edge */ 7373 ret = push_insn(t, t + insns[t].off + 1, 7374 FALLTHROUGH, env, true); 7375 if (ret == 1) 7376 goto peek_stack; 7377 else if (ret < 0) 7378 goto err_free; 7379 /* unconditional jmp is not a good pruning point, 7380 * but it's marked, since backtracking needs 7381 * to record jmp history in is_state_visited(). 7382 */ 7383 init_explored_state(env, t + insns[t].off + 1); 7384 /* tell verifier to check for equivalent states 7385 * after every call and jump 7386 */ 7387 if (t + 1 < insn_cnt) 7388 init_explored_state(env, t + 1); 7389 } else { 7390 /* conditional jump with two edges */ 7391 init_explored_state(env, t); 7392 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 7393 if (ret == 1) 7394 goto peek_stack; 7395 else if (ret < 0) 7396 goto err_free; 7397 7398 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env, true); 7399 if (ret == 1) 7400 goto peek_stack; 7401 else if (ret < 0) 7402 goto err_free; 7403 } 7404 } else { 7405 /* all other non-branch instructions with single 7406 * fall-through edge 7407 */ 7408 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 7409 if (ret == 1) 7410 goto peek_stack; 7411 else if (ret < 0) 7412 goto err_free; 7413 } 7414 7415 mark_explored: 7416 insn_state[t] = EXPLORED; 7417 if (env->cfg.cur_stack-- <= 0) { 7418 verbose(env, "pop stack internal bug\n"); 7419 ret = -EFAULT; 7420 goto err_free; 7421 } 7422 goto peek_stack; 7423 7424 check_state: 7425 for (i = 0; i < insn_cnt; i++) { 7426 if (insn_state[i] != EXPLORED) { 7427 verbose(env, "unreachable insn %d\n", i); 7428 ret = -EINVAL; 7429 goto err_free; 7430 } 7431 } 7432 ret = 0; /* cfg looks good */ 7433 7434 err_free: 7435 kvfree(insn_state); 7436 kvfree(insn_stack); 7437 env->cfg.insn_state = env->cfg.insn_stack = NULL; 7438 return ret; 7439 } 7440 7441 /* The minimum supported BTF func info size */ 7442 #define MIN_BPF_FUNCINFO_SIZE 8 7443 #define MAX_FUNCINFO_REC_SIZE 252 7444 7445 static int check_btf_func(struct bpf_verifier_env *env, 7446 const union bpf_attr *attr, 7447 union bpf_attr __user *uattr) 7448 { 7449 u32 i, nfuncs, urec_size, min_size; 7450 u32 krec_size = sizeof(struct bpf_func_info); 7451 struct bpf_func_info *krecord; 7452 struct bpf_func_info_aux *info_aux = NULL; 7453 const struct btf_type *type; 7454 struct bpf_prog *prog; 7455 const struct btf *btf; 7456 void __user *urecord; 7457 u32 prev_offset = 0; 7458 int ret = 0; 7459 7460 nfuncs = attr->func_info_cnt; 7461 if (!nfuncs) 7462 return 0; 7463 7464 if (nfuncs != env->subprog_cnt) { 7465 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 7466 return -EINVAL; 7467 } 7468 7469 urec_size = attr->func_info_rec_size; 7470 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 7471 urec_size > MAX_FUNCINFO_REC_SIZE || 7472 urec_size % sizeof(u32)) { 7473 verbose(env, "invalid func info rec size %u\n", urec_size); 7474 return -EINVAL; 7475 } 7476 7477 prog = env->prog; 7478 btf = prog->aux->btf; 7479 7480 urecord = u64_to_user_ptr(attr->func_info); 7481 min_size = min_t(u32, krec_size, urec_size); 7482 7483 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 7484 if (!krecord) 7485 return -ENOMEM; 7486 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 7487 if (!info_aux) 7488 goto err_free; 7489 7490 for (i = 0; i < nfuncs; i++) { 7491 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 7492 if (ret) { 7493 if (ret == -E2BIG) { 7494 verbose(env, "nonzero tailing record in func info"); 7495 /* set the size kernel expects so loader can zero 7496 * out the rest of the record. 7497 */ 7498 if (put_user(min_size, &uattr->func_info_rec_size)) 7499 ret = -EFAULT; 7500 } 7501 goto err_free; 7502 } 7503 7504 if (copy_from_user(&krecord[i], urecord, min_size)) { 7505 ret = -EFAULT; 7506 goto err_free; 7507 } 7508 7509 /* check insn_off */ 7510 if (i == 0) { 7511 if (krecord[i].insn_off) { 7512 verbose(env, 7513 "nonzero insn_off %u for the first func info record", 7514 krecord[i].insn_off); 7515 ret = -EINVAL; 7516 goto err_free; 7517 } 7518 } else if (krecord[i].insn_off <= prev_offset) { 7519 verbose(env, 7520 "same or smaller insn offset (%u) than previous func info record (%u)", 7521 krecord[i].insn_off, prev_offset); 7522 ret = -EINVAL; 7523 goto err_free; 7524 } 7525 7526 if (env->subprog_info[i].start != krecord[i].insn_off) { 7527 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 7528 ret = -EINVAL; 7529 goto err_free; 7530 } 7531 7532 /* check type_id */ 7533 type = btf_type_by_id(btf, krecord[i].type_id); 7534 if (!type || !btf_type_is_func(type)) { 7535 verbose(env, "invalid type id %d in func info", 7536 krecord[i].type_id); 7537 ret = -EINVAL; 7538 goto err_free; 7539 } 7540 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 7541 prev_offset = krecord[i].insn_off; 7542 urecord += urec_size; 7543 } 7544 7545 prog->aux->func_info = krecord; 7546 prog->aux->func_info_cnt = nfuncs; 7547 prog->aux->func_info_aux = info_aux; 7548 return 0; 7549 7550 err_free: 7551 kvfree(krecord); 7552 kfree(info_aux); 7553 return ret; 7554 } 7555 7556 static void adjust_btf_func(struct bpf_verifier_env *env) 7557 { 7558 struct bpf_prog_aux *aux = env->prog->aux; 7559 int i; 7560 7561 if (!aux->func_info) 7562 return; 7563 7564 for (i = 0; i < env->subprog_cnt; i++) 7565 aux->func_info[i].insn_off = env->subprog_info[i].start; 7566 } 7567 7568 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \ 7569 sizeof(((struct bpf_line_info *)(0))->line_col)) 7570 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 7571 7572 static int check_btf_line(struct bpf_verifier_env *env, 7573 const union bpf_attr *attr, 7574 union bpf_attr __user *uattr) 7575 { 7576 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 7577 struct bpf_subprog_info *sub; 7578 struct bpf_line_info *linfo; 7579 struct bpf_prog *prog; 7580 const struct btf *btf; 7581 void __user *ulinfo; 7582 int err; 7583 7584 nr_linfo = attr->line_info_cnt; 7585 if (!nr_linfo) 7586 return 0; 7587 7588 rec_size = attr->line_info_rec_size; 7589 if (rec_size < MIN_BPF_LINEINFO_SIZE || 7590 rec_size > MAX_LINEINFO_REC_SIZE || 7591 rec_size & (sizeof(u32) - 1)) 7592 return -EINVAL; 7593 7594 /* Need to zero it in case the userspace may 7595 * pass in a smaller bpf_line_info object. 7596 */ 7597 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 7598 GFP_KERNEL | __GFP_NOWARN); 7599 if (!linfo) 7600 return -ENOMEM; 7601 7602 prog = env->prog; 7603 btf = prog->aux->btf; 7604 7605 s = 0; 7606 sub = env->subprog_info; 7607 ulinfo = u64_to_user_ptr(attr->line_info); 7608 expected_size = sizeof(struct bpf_line_info); 7609 ncopy = min_t(u32, expected_size, rec_size); 7610 for (i = 0; i < nr_linfo; i++) { 7611 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 7612 if (err) { 7613 if (err == -E2BIG) { 7614 verbose(env, "nonzero tailing record in line_info"); 7615 if (put_user(expected_size, 7616 &uattr->line_info_rec_size)) 7617 err = -EFAULT; 7618 } 7619 goto err_free; 7620 } 7621 7622 if (copy_from_user(&linfo[i], ulinfo, ncopy)) { 7623 err = -EFAULT; 7624 goto err_free; 7625 } 7626 7627 /* 7628 * Check insn_off to ensure 7629 * 1) strictly increasing AND 7630 * 2) bounded by prog->len 7631 * 7632 * The linfo[0].insn_off == 0 check logically falls into 7633 * the later "missing bpf_line_info for func..." case 7634 * because the first linfo[0].insn_off must be the 7635 * first sub also and the first sub must have 7636 * subprog_info[0].start == 0. 7637 */ 7638 if ((i && linfo[i].insn_off <= prev_offset) || 7639 linfo[i].insn_off >= prog->len) { 7640 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 7641 i, linfo[i].insn_off, prev_offset, 7642 prog->len); 7643 err = -EINVAL; 7644 goto err_free; 7645 } 7646 7647 if (!prog->insnsi[linfo[i].insn_off].code) { 7648 verbose(env, 7649 "Invalid insn code at line_info[%u].insn_off\n", 7650 i); 7651 err = -EINVAL; 7652 goto err_free; 7653 } 7654 7655 if (!btf_name_by_offset(btf, linfo[i].line_off) || 7656 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 7657 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 7658 err = -EINVAL; 7659 goto err_free; 7660 } 7661 7662 if (s != env->subprog_cnt) { 7663 if (linfo[i].insn_off == sub[s].start) { 7664 sub[s].linfo_idx = i; 7665 s++; 7666 } else if (sub[s].start < linfo[i].insn_off) { 7667 verbose(env, "missing bpf_line_info for func#%u\n", s); 7668 err = -EINVAL; 7669 goto err_free; 7670 } 7671 } 7672 7673 prev_offset = linfo[i].insn_off; 7674 ulinfo += rec_size; 7675 } 7676 7677 if (s != env->subprog_cnt) { 7678 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 7679 env->subprog_cnt - s, s); 7680 err = -EINVAL; 7681 goto err_free; 7682 } 7683 7684 prog->aux->linfo = linfo; 7685 prog->aux->nr_linfo = nr_linfo; 7686 7687 return 0; 7688 7689 err_free: 7690 kvfree(linfo); 7691 return err; 7692 } 7693 7694 static int check_btf_info(struct bpf_verifier_env *env, 7695 const union bpf_attr *attr, 7696 union bpf_attr __user *uattr) 7697 { 7698 struct btf *btf; 7699 int err; 7700 7701 if (!attr->func_info_cnt && !attr->line_info_cnt) 7702 return 0; 7703 7704 btf = btf_get_by_fd(attr->prog_btf_fd); 7705 if (IS_ERR(btf)) 7706 return PTR_ERR(btf); 7707 env->prog->aux->btf = btf; 7708 7709 err = check_btf_func(env, attr, uattr); 7710 if (err) 7711 return err; 7712 7713 err = check_btf_line(env, attr, uattr); 7714 if (err) 7715 return err; 7716 7717 return 0; 7718 } 7719 7720 /* check %cur's range satisfies %old's */ 7721 static bool range_within(struct bpf_reg_state *old, 7722 struct bpf_reg_state *cur) 7723 { 7724 return old->umin_value <= cur->umin_value && 7725 old->umax_value >= cur->umax_value && 7726 old->smin_value <= cur->smin_value && 7727 old->smax_value >= cur->smax_value; 7728 } 7729 7730 /* Maximum number of register states that can exist at once */ 7731 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) 7732 struct idpair { 7733 u32 old; 7734 u32 cur; 7735 }; 7736 7737 /* If in the old state two registers had the same id, then they need to have 7738 * the same id in the new state as well. But that id could be different from 7739 * the old state, so we need to track the mapping from old to new ids. 7740 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 7741 * regs with old id 5 must also have new id 9 for the new state to be safe. But 7742 * regs with a different old id could still have new id 9, we don't care about 7743 * that. 7744 * So we look through our idmap to see if this old id has been seen before. If 7745 * so, we require the new id to match; otherwise, we add the id pair to the map. 7746 */ 7747 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) 7748 { 7749 unsigned int i; 7750 7751 for (i = 0; i < ID_MAP_SIZE; i++) { 7752 if (!idmap[i].old) { 7753 /* Reached an empty slot; haven't seen this id before */ 7754 idmap[i].old = old_id; 7755 idmap[i].cur = cur_id; 7756 return true; 7757 } 7758 if (idmap[i].old == old_id) 7759 return idmap[i].cur == cur_id; 7760 } 7761 /* We ran out of idmap slots, which should be impossible */ 7762 WARN_ON_ONCE(1); 7763 return false; 7764 } 7765 7766 static void clean_func_state(struct bpf_verifier_env *env, 7767 struct bpf_func_state *st) 7768 { 7769 enum bpf_reg_liveness live; 7770 int i, j; 7771 7772 for (i = 0; i < BPF_REG_FP; i++) { 7773 live = st->regs[i].live; 7774 /* liveness must not touch this register anymore */ 7775 st->regs[i].live |= REG_LIVE_DONE; 7776 if (!(live & REG_LIVE_READ)) 7777 /* since the register is unused, clear its state 7778 * to make further comparison simpler 7779 */ 7780 __mark_reg_not_init(env, &st->regs[i]); 7781 } 7782 7783 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 7784 live = st->stack[i].spilled_ptr.live; 7785 /* liveness must not touch this stack slot anymore */ 7786 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 7787 if (!(live & REG_LIVE_READ)) { 7788 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 7789 for (j = 0; j < BPF_REG_SIZE; j++) 7790 st->stack[i].slot_type[j] = STACK_INVALID; 7791 } 7792 } 7793 } 7794 7795 static void clean_verifier_state(struct bpf_verifier_env *env, 7796 struct bpf_verifier_state *st) 7797 { 7798 int i; 7799 7800 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 7801 /* all regs in this state in all frames were already marked */ 7802 return; 7803 7804 for (i = 0; i <= st->curframe; i++) 7805 clean_func_state(env, st->frame[i]); 7806 } 7807 7808 /* the parentage chains form a tree. 7809 * the verifier states are added to state lists at given insn and 7810 * pushed into state stack for future exploration. 7811 * when the verifier reaches bpf_exit insn some of the verifer states 7812 * stored in the state lists have their final liveness state already, 7813 * but a lot of states will get revised from liveness point of view when 7814 * the verifier explores other branches. 7815 * Example: 7816 * 1: r0 = 1 7817 * 2: if r1 == 100 goto pc+1 7818 * 3: r0 = 2 7819 * 4: exit 7820 * when the verifier reaches exit insn the register r0 in the state list of 7821 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 7822 * of insn 2 and goes exploring further. At the insn 4 it will walk the 7823 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 7824 * 7825 * Since the verifier pushes the branch states as it sees them while exploring 7826 * the program the condition of walking the branch instruction for the second 7827 * time means that all states below this branch were already explored and 7828 * their final liveness markes are already propagated. 7829 * Hence when the verifier completes the search of state list in is_state_visited() 7830 * we can call this clean_live_states() function to mark all liveness states 7831 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 7832 * will not be used. 7833 * This function also clears the registers and stack for states that !READ 7834 * to simplify state merging. 7835 * 7836 * Important note here that walking the same branch instruction in the callee 7837 * doesn't meant that the states are DONE. The verifier has to compare 7838 * the callsites 7839 */ 7840 static void clean_live_states(struct bpf_verifier_env *env, int insn, 7841 struct bpf_verifier_state *cur) 7842 { 7843 struct bpf_verifier_state_list *sl; 7844 int i; 7845 7846 sl = *explored_state(env, insn); 7847 while (sl) { 7848 if (sl->state.branches) 7849 goto next; 7850 if (sl->state.insn_idx != insn || 7851 sl->state.curframe != cur->curframe) 7852 goto next; 7853 for (i = 0; i <= cur->curframe; i++) 7854 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 7855 goto next; 7856 clean_verifier_state(env, &sl->state); 7857 next: 7858 sl = sl->next; 7859 } 7860 } 7861 7862 /* Returns true if (rold safe implies rcur safe) */ 7863 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 7864 struct idpair *idmap) 7865 { 7866 bool equal; 7867 7868 if (!(rold->live & REG_LIVE_READ)) 7869 /* explored state didn't use this */ 7870 return true; 7871 7872 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0; 7873 7874 if (rold->type == PTR_TO_STACK) 7875 /* two stack pointers are equal only if they're pointing to 7876 * the same stack frame, since fp-8 in foo != fp-8 in bar 7877 */ 7878 return equal && rold->frameno == rcur->frameno; 7879 7880 if (equal) 7881 return true; 7882 7883 if (rold->type == NOT_INIT) 7884 /* explored state can't have used this */ 7885 return true; 7886 if (rcur->type == NOT_INIT) 7887 return false; 7888 switch (rold->type) { 7889 case SCALAR_VALUE: 7890 if (rcur->type == SCALAR_VALUE) { 7891 if (!rold->precise && !rcur->precise) 7892 return true; 7893 /* new val must satisfy old val knowledge */ 7894 return range_within(rold, rcur) && 7895 tnum_in(rold->var_off, rcur->var_off); 7896 } else { 7897 /* We're trying to use a pointer in place of a scalar. 7898 * Even if the scalar was unbounded, this could lead to 7899 * pointer leaks because scalars are allowed to leak 7900 * while pointers are not. We could make this safe in 7901 * special cases if root is calling us, but it's 7902 * probably not worth the hassle. 7903 */ 7904 return false; 7905 } 7906 case PTR_TO_MAP_VALUE: 7907 /* If the new min/max/var_off satisfy the old ones and 7908 * everything else matches, we are OK. 7909 * 'id' is not compared, since it's only used for maps with 7910 * bpf_spin_lock inside map element and in such cases if 7911 * the rest of the prog is valid for one map element then 7912 * it's valid for all map elements regardless of the key 7913 * used in bpf_map_lookup() 7914 */ 7915 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 7916 range_within(rold, rcur) && 7917 tnum_in(rold->var_off, rcur->var_off); 7918 case PTR_TO_MAP_VALUE_OR_NULL: 7919 /* a PTR_TO_MAP_VALUE could be safe to use as a 7920 * PTR_TO_MAP_VALUE_OR_NULL into the same map. 7921 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- 7922 * checked, doing so could have affected others with the same 7923 * id, and we can't check for that because we lost the id when 7924 * we converted to a PTR_TO_MAP_VALUE. 7925 */ 7926 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) 7927 return false; 7928 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) 7929 return false; 7930 /* Check our ids match any regs they're supposed to */ 7931 return check_ids(rold->id, rcur->id, idmap); 7932 case PTR_TO_PACKET_META: 7933 case PTR_TO_PACKET: 7934 if (rcur->type != rold->type) 7935 return false; 7936 /* We must have at least as much range as the old ptr 7937 * did, so that any accesses which were safe before are 7938 * still safe. This is true even if old range < old off, 7939 * since someone could have accessed through (ptr - k), or 7940 * even done ptr -= k in a register, to get a safe access. 7941 */ 7942 if (rold->range > rcur->range) 7943 return false; 7944 /* If the offsets don't match, we can't trust our alignment; 7945 * nor can we be sure that we won't fall out of range. 7946 */ 7947 if (rold->off != rcur->off) 7948 return false; 7949 /* id relations must be preserved */ 7950 if (rold->id && !check_ids(rold->id, rcur->id, idmap)) 7951 return false; 7952 /* new val must satisfy old val knowledge */ 7953 return range_within(rold, rcur) && 7954 tnum_in(rold->var_off, rcur->var_off); 7955 case PTR_TO_CTX: 7956 case CONST_PTR_TO_MAP: 7957 case PTR_TO_PACKET_END: 7958 case PTR_TO_FLOW_KEYS: 7959 case PTR_TO_SOCKET: 7960 case PTR_TO_SOCKET_OR_NULL: 7961 case PTR_TO_SOCK_COMMON: 7962 case PTR_TO_SOCK_COMMON_OR_NULL: 7963 case PTR_TO_TCP_SOCK: 7964 case PTR_TO_TCP_SOCK_OR_NULL: 7965 case PTR_TO_XDP_SOCK: 7966 /* Only valid matches are exact, which memcmp() above 7967 * would have accepted 7968 */ 7969 default: 7970 /* Don't know what's going on, just say it's not safe */ 7971 return false; 7972 } 7973 7974 /* Shouldn't get here; if we do, say it's not safe */ 7975 WARN_ON_ONCE(1); 7976 return false; 7977 } 7978 7979 static bool stacksafe(struct bpf_func_state *old, 7980 struct bpf_func_state *cur, 7981 struct idpair *idmap) 7982 { 7983 int i, spi; 7984 7985 /* walk slots of the explored stack and ignore any additional 7986 * slots in the current stack, since explored(safe) state 7987 * didn't use them 7988 */ 7989 for (i = 0; i < old->allocated_stack; i++) { 7990 spi = i / BPF_REG_SIZE; 7991 7992 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 7993 i += BPF_REG_SIZE - 1; 7994 /* explored state didn't use this */ 7995 continue; 7996 } 7997 7998 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 7999 continue; 8000 8001 /* explored stack has more populated slots than current stack 8002 * and these slots were used 8003 */ 8004 if (i >= cur->allocated_stack) 8005 return false; 8006 8007 /* if old state was safe with misc data in the stack 8008 * it will be safe with zero-initialized stack. 8009 * The opposite is not true 8010 */ 8011 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 8012 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 8013 continue; 8014 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 8015 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 8016 /* Ex: old explored (safe) state has STACK_SPILL in 8017 * this stack slot, but current has has STACK_MISC -> 8018 * this verifier states are not equivalent, 8019 * return false to continue verification of this path 8020 */ 8021 return false; 8022 if (i % BPF_REG_SIZE) 8023 continue; 8024 if (old->stack[spi].slot_type[0] != STACK_SPILL) 8025 continue; 8026 if (!regsafe(&old->stack[spi].spilled_ptr, 8027 &cur->stack[spi].spilled_ptr, 8028 idmap)) 8029 /* when explored and current stack slot are both storing 8030 * spilled registers, check that stored pointers types 8031 * are the same as well. 8032 * Ex: explored safe path could have stored 8033 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 8034 * but current path has stored: 8035 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 8036 * such verifier states are not equivalent. 8037 * return false to continue verification of this path 8038 */ 8039 return false; 8040 } 8041 return true; 8042 } 8043 8044 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur) 8045 { 8046 if (old->acquired_refs != cur->acquired_refs) 8047 return false; 8048 return !memcmp(old->refs, cur->refs, 8049 sizeof(*old->refs) * old->acquired_refs); 8050 } 8051 8052 /* compare two verifier states 8053 * 8054 * all states stored in state_list are known to be valid, since 8055 * verifier reached 'bpf_exit' instruction through them 8056 * 8057 * this function is called when verifier exploring different branches of 8058 * execution popped from the state stack. If it sees an old state that has 8059 * more strict register state and more strict stack state then this execution 8060 * branch doesn't need to be explored further, since verifier already 8061 * concluded that more strict state leads to valid finish. 8062 * 8063 * Therefore two states are equivalent if register state is more conservative 8064 * and explored stack state is more conservative than the current one. 8065 * Example: 8066 * explored current 8067 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 8068 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 8069 * 8070 * In other words if current stack state (one being explored) has more 8071 * valid slots than old one that already passed validation, it means 8072 * the verifier can stop exploring and conclude that current state is valid too 8073 * 8074 * Similarly with registers. If explored state has register type as invalid 8075 * whereas register type in current state is meaningful, it means that 8076 * the current state will reach 'bpf_exit' instruction safely 8077 */ 8078 static bool func_states_equal(struct bpf_func_state *old, 8079 struct bpf_func_state *cur) 8080 { 8081 struct idpair *idmap; 8082 bool ret = false; 8083 int i; 8084 8085 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); 8086 /* If we failed to allocate the idmap, just say it's not safe */ 8087 if (!idmap) 8088 return false; 8089 8090 for (i = 0; i < MAX_BPF_REG; i++) { 8091 if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) 8092 goto out_free; 8093 } 8094 8095 if (!stacksafe(old, cur, idmap)) 8096 goto out_free; 8097 8098 if (!refsafe(old, cur)) 8099 goto out_free; 8100 ret = true; 8101 out_free: 8102 kfree(idmap); 8103 return ret; 8104 } 8105 8106 static bool states_equal(struct bpf_verifier_env *env, 8107 struct bpf_verifier_state *old, 8108 struct bpf_verifier_state *cur) 8109 { 8110 int i; 8111 8112 if (old->curframe != cur->curframe) 8113 return false; 8114 8115 /* Verification state from speculative execution simulation 8116 * must never prune a non-speculative execution one. 8117 */ 8118 if (old->speculative && !cur->speculative) 8119 return false; 8120 8121 if (old->active_spin_lock != cur->active_spin_lock) 8122 return false; 8123 8124 /* for states to be equal callsites have to be the same 8125 * and all frame states need to be equivalent 8126 */ 8127 for (i = 0; i <= old->curframe; i++) { 8128 if (old->frame[i]->callsite != cur->frame[i]->callsite) 8129 return false; 8130 if (!func_states_equal(old->frame[i], cur->frame[i])) 8131 return false; 8132 } 8133 return true; 8134 } 8135 8136 /* Return 0 if no propagation happened. Return negative error code if error 8137 * happened. Otherwise, return the propagated bit. 8138 */ 8139 static int propagate_liveness_reg(struct bpf_verifier_env *env, 8140 struct bpf_reg_state *reg, 8141 struct bpf_reg_state *parent_reg) 8142 { 8143 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 8144 u8 flag = reg->live & REG_LIVE_READ; 8145 int err; 8146 8147 /* When comes here, read flags of PARENT_REG or REG could be any of 8148 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 8149 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 8150 */ 8151 if (parent_flag == REG_LIVE_READ64 || 8152 /* Or if there is no read flag from REG. */ 8153 !flag || 8154 /* Or if the read flag from REG is the same as PARENT_REG. */ 8155 parent_flag == flag) 8156 return 0; 8157 8158 err = mark_reg_read(env, reg, parent_reg, flag); 8159 if (err) 8160 return err; 8161 8162 return flag; 8163 } 8164 8165 /* A write screens off any subsequent reads; but write marks come from the 8166 * straight-line code between a state and its parent. When we arrive at an 8167 * equivalent state (jump target or such) we didn't arrive by the straight-line 8168 * code, so read marks in the state must propagate to the parent regardless 8169 * of the state's write marks. That's what 'parent == state->parent' comparison 8170 * in mark_reg_read() is for. 8171 */ 8172 static int propagate_liveness(struct bpf_verifier_env *env, 8173 const struct bpf_verifier_state *vstate, 8174 struct bpf_verifier_state *vparent) 8175 { 8176 struct bpf_reg_state *state_reg, *parent_reg; 8177 struct bpf_func_state *state, *parent; 8178 int i, frame, err = 0; 8179 8180 if (vparent->curframe != vstate->curframe) { 8181 WARN(1, "propagate_live: parent frame %d current frame %d\n", 8182 vparent->curframe, vstate->curframe); 8183 return -EFAULT; 8184 } 8185 /* Propagate read liveness of registers... */ 8186 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 8187 for (frame = 0; frame <= vstate->curframe; frame++) { 8188 parent = vparent->frame[frame]; 8189 state = vstate->frame[frame]; 8190 parent_reg = parent->regs; 8191 state_reg = state->regs; 8192 /* We don't need to worry about FP liveness, it's read-only */ 8193 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 8194 err = propagate_liveness_reg(env, &state_reg[i], 8195 &parent_reg[i]); 8196 if (err < 0) 8197 return err; 8198 if (err == REG_LIVE_READ64) 8199 mark_insn_zext(env, &parent_reg[i]); 8200 } 8201 8202 /* Propagate stack slots. */ 8203 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 8204 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 8205 parent_reg = &parent->stack[i].spilled_ptr; 8206 state_reg = &state->stack[i].spilled_ptr; 8207 err = propagate_liveness_reg(env, state_reg, 8208 parent_reg); 8209 if (err < 0) 8210 return err; 8211 } 8212 } 8213 return 0; 8214 } 8215 8216 /* find precise scalars in the previous equivalent state and 8217 * propagate them into the current state 8218 */ 8219 static int propagate_precision(struct bpf_verifier_env *env, 8220 const struct bpf_verifier_state *old) 8221 { 8222 struct bpf_reg_state *state_reg; 8223 struct bpf_func_state *state; 8224 int i, err = 0; 8225 8226 state = old->frame[old->curframe]; 8227 state_reg = state->regs; 8228 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 8229 if (state_reg->type != SCALAR_VALUE || 8230 !state_reg->precise) 8231 continue; 8232 if (env->log.level & BPF_LOG_LEVEL2) 8233 verbose(env, "propagating r%d\n", i); 8234 err = mark_chain_precision(env, i); 8235 if (err < 0) 8236 return err; 8237 } 8238 8239 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 8240 if (state->stack[i].slot_type[0] != STACK_SPILL) 8241 continue; 8242 state_reg = &state->stack[i].spilled_ptr; 8243 if (state_reg->type != SCALAR_VALUE || 8244 !state_reg->precise) 8245 continue; 8246 if (env->log.level & BPF_LOG_LEVEL2) 8247 verbose(env, "propagating fp%d\n", 8248 (-i - 1) * BPF_REG_SIZE); 8249 err = mark_chain_precision_stack(env, i); 8250 if (err < 0) 8251 return err; 8252 } 8253 return 0; 8254 } 8255 8256 static bool states_maybe_looping(struct bpf_verifier_state *old, 8257 struct bpf_verifier_state *cur) 8258 { 8259 struct bpf_func_state *fold, *fcur; 8260 int i, fr = cur->curframe; 8261 8262 if (old->curframe != fr) 8263 return false; 8264 8265 fold = old->frame[fr]; 8266 fcur = cur->frame[fr]; 8267 for (i = 0; i < MAX_BPF_REG; i++) 8268 if (memcmp(&fold->regs[i], &fcur->regs[i], 8269 offsetof(struct bpf_reg_state, parent))) 8270 return false; 8271 return true; 8272 } 8273 8274 8275 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 8276 { 8277 struct bpf_verifier_state_list *new_sl; 8278 struct bpf_verifier_state_list *sl, **pprev; 8279 struct bpf_verifier_state *cur = env->cur_state, *new; 8280 int i, j, err, states_cnt = 0; 8281 bool add_new_state = env->test_state_freq ? true : false; 8282 8283 cur->last_insn_idx = env->prev_insn_idx; 8284 if (!env->insn_aux_data[insn_idx].prune_point) 8285 /* this 'insn_idx' instruction wasn't marked, so we will not 8286 * be doing state search here 8287 */ 8288 return 0; 8289 8290 /* bpf progs typically have pruning point every 4 instructions 8291 * http://vger.kernel.org/bpfconf2019.html#session-1 8292 * Do not add new state for future pruning if the verifier hasn't seen 8293 * at least 2 jumps and at least 8 instructions. 8294 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 8295 * In tests that amounts to up to 50% reduction into total verifier 8296 * memory consumption and 20% verifier time speedup. 8297 */ 8298 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 8299 env->insn_processed - env->prev_insn_processed >= 8) 8300 add_new_state = true; 8301 8302 pprev = explored_state(env, insn_idx); 8303 sl = *pprev; 8304 8305 clean_live_states(env, insn_idx, cur); 8306 8307 while (sl) { 8308 states_cnt++; 8309 if (sl->state.insn_idx != insn_idx) 8310 goto next; 8311 if (sl->state.branches) { 8312 if (states_maybe_looping(&sl->state, cur) && 8313 states_equal(env, &sl->state, cur)) { 8314 verbose_linfo(env, insn_idx, "; "); 8315 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 8316 return -EINVAL; 8317 } 8318 /* if the verifier is processing a loop, avoid adding new state 8319 * too often, since different loop iterations have distinct 8320 * states and may not help future pruning. 8321 * This threshold shouldn't be too low to make sure that 8322 * a loop with large bound will be rejected quickly. 8323 * The most abusive loop will be: 8324 * r1 += 1 8325 * if r1 < 1000000 goto pc-2 8326 * 1M insn_procssed limit / 100 == 10k peak states. 8327 * This threshold shouldn't be too high either, since states 8328 * at the end of the loop are likely to be useful in pruning. 8329 */ 8330 if (env->jmps_processed - env->prev_jmps_processed < 20 && 8331 env->insn_processed - env->prev_insn_processed < 100) 8332 add_new_state = false; 8333 goto miss; 8334 } 8335 if (states_equal(env, &sl->state, cur)) { 8336 sl->hit_cnt++; 8337 /* reached equivalent register/stack state, 8338 * prune the search. 8339 * Registers read by the continuation are read by us. 8340 * If we have any write marks in env->cur_state, they 8341 * will prevent corresponding reads in the continuation 8342 * from reaching our parent (an explored_state). Our 8343 * own state will get the read marks recorded, but 8344 * they'll be immediately forgotten as we're pruning 8345 * this state and will pop a new one. 8346 */ 8347 err = propagate_liveness(env, &sl->state, cur); 8348 8349 /* if previous state reached the exit with precision and 8350 * current state is equivalent to it (except precsion marks) 8351 * the precision needs to be propagated back in 8352 * the current state. 8353 */ 8354 err = err ? : push_jmp_history(env, cur); 8355 err = err ? : propagate_precision(env, &sl->state); 8356 if (err) 8357 return err; 8358 return 1; 8359 } 8360 miss: 8361 /* when new state is not going to be added do not increase miss count. 8362 * Otherwise several loop iterations will remove the state 8363 * recorded earlier. The goal of these heuristics is to have 8364 * states from some iterations of the loop (some in the beginning 8365 * and some at the end) to help pruning. 8366 */ 8367 if (add_new_state) 8368 sl->miss_cnt++; 8369 /* heuristic to determine whether this state is beneficial 8370 * to keep checking from state equivalence point of view. 8371 * Higher numbers increase max_states_per_insn and verification time, 8372 * but do not meaningfully decrease insn_processed. 8373 */ 8374 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 8375 /* the state is unlikely to be useful. Remove it to 8376 * speed up verification 8377 */ 8378 *pprev = sl->next; 8379 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 8380 u32 br = sl->state.branches; 8381 8382 WARN_ONCE(br, 8383 "BUG live_done but branches_to_explore %d\n", 8384 br); 8385 free_verifier_state(&sl->state, false); 8386 kfree(sl); 8387 env->peak_states--; 8388 } else { 8389 /* cannot free this state, since parentage chain may 8390 * walk it later. Add it for free_list instead to 8391 * be freed at the end of verification 8392 */ 8393 sl->next = env->free_list; 8394 env->free_list = sl; 8395 } 8396 sl = *pprev; 8397 continue; 8398 } 8399 next: 8400 pprev = &sl->next; 8401 sl = *pprev; 8402 } 8403 8404 if (env->max_states_per_insn < states_cnt) 8405 env->max_states_per_insn = states_cnt; 8406 8407 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 8408 return push_jmp_history(env, cur); 8409 8410 if (!add_new_state) 8411 return push_jmp_history(env, cur); 8412 8413 /* There were no equivalent states, remember the current one. 8414 * Technically the current state is not proven to be safe yet, 8415 * but it will either reach outer most bpf_exit (which means it's safe) 8416 * or it will be rejected. When there are no loops the verifier won't be 8417 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 8418 * again on the way to bpf_exit. 8419 * When looping the sl->state.branches will be > 0 and this state 8420 * will not be considered for equivalence until branches == 0. 8421 */ 8422 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 8423 if (!new_sl) 8424 return -ENOMEM; 8425 env->total_states++; 8426 env->peak_states++; 8427 env->prev_jmps_processed = env->jmps_processed; 8428 env->prev_insn_processed = env->insn_processed; 8429 8430 /* add new state to the head of linked list */ 8431 new = &new_sl->state; 8432 err = copy_verifier_state(new, cur); 8433 if (err) { 8434 free_verifier_state(new, false); 8435 kfree(new_sl); 8436 return err; 8437 } 8438 new->insn_idx = insn_idx; 8439 WARN_ONCE(new->branches != 1, 8440 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 8441 8442 cur->parent = new; 8443 cur->first_insn_idx = insn_idx; 8444 clear_jmp_history(cur); 8445 new_sl->next = *explored_state(env, insn_idx); 8446 *explored_state(env, insn_idx) = new_sl; 8447 /* connect new state to parentage chain. Current frame needs all 8448 * registers connected. Only r6 - r9 of the callers are alive (pushed 8449 * to the stack implicitly by JITs) so in callers' frames connect just 8450 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 8451 * the state of the call instruction (with WRITTEN set), and r0 comes 8452 * from callee with its full parentage chain, anyway. 8453 */ 8454 /* clear write marks in current state: the writes we did are not writes 8455 * our child did, so they don't screen off its reads from us. 8456 * (There are no read marks in current state, because reads always mark 8457 * their parent and current state never has children yet. Only 8458 * explored_states can get read marks.) 8459 */ 8460 for (j = 0; j <= cur->curframe; j++) { 8461 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 8462 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 8463 for (i = 0; i < BPF_REG_FP; i++) 8464 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 8465 } 8466 8467 /* all stack frames are accessible from callee, clear them all */ 8468 for (j = 0; j <= cur->curframe; j++) { 8469 struct bpf_func_state *frame = cur->frame[j]; 8470 struct bpf_func_state *newframe = new->frame[j]; 8471 8472 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 8473 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 8474 frame->stack[i].spilled_ptr.parent = 8475 &newframe->stack[i].spilled_ptr; 8476 } 8477 } 8478 return 0; 8479 } 8480 8481 /* Return true if it's OK to have the same insn return a different type. */ 8482 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 8483 { 8484 switch (type) { 8485 case PTR_TO_CTX: 8486 case PTR_TO_SOCKET: 8487 case PTR_TO_SOCKET_OR_NULL: 8488 case PTR_TO_SOCK_COMMON: 8489 case PTR_TO_SOCK_COMMON_OR_NULL: 8490 case PTR_TO_TCP_SOCK: 8491 case PTR_TO_TCP_SOCK_OR_NULL: 8492 case PTR_TO_XDP_SOCK: 8493 case PTR_TO_BTF_ID: 8494 case PTR_TO_BTF_ID_OR_NULL: 8495 return false; 8496 default: 8497 return true; 8498 } 8499 } 8500 8501 /* If an instruction was previously used with particular pointer types, then we 8502 * need to be careful to avoid cases such as the below, where it may be ok 8503 * for one branch accessing the pointer, but not ok for the other branch: 8504 * 8505 * R1 = sock_ptr 8506 * goto X; 8507 * ... 8508 * R1 = some_other_valid_ptr; 8509 * goto X; 8510 * ... 8511 * R2 = *(u32 *)(R1 + 0); 8512 */ 8513 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 8514 { 8515 return src != prev && (!reg_type_mismatch_ok(src) || 8516 !reg_type_mismatch_ok(prev)); 8517 } 8518 8519 static int do_check(struct bpf_verifier_env *env) 8520 { 8521 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 8522 struct bpf_verifier_state *state = env->cur_state; 8523 struct bpf_insn *insns = env->prog->insnsi; 8524 struct bpf_reg_state *regs; 8525 int insn_cnt = env->prog->len; 8526 bool do_print_state = false; 8527 int prev_insn_idx = -1; 8528 8529 for (;;) { 8530 struct bpf_insn *insn; 8531 u8 class; 8532 int err; 8533 8534 env->prev_insn_idx = prev_insn_idx; 8535 if (env->insn_idx >= insn_cnt) { 8536 verbose(env, "invalid insn idx %d insn_cnt %d\n", 8537 env->insn_idx, insn_cnt); 8538 return -EFAULT; 8539 } 8540 8541 insn = &insns[env->insn_idx]; 8542 class = BPF_CLASS(insn->code); 8543 8544 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 8545 verbose(env, 8546 "BPF program is too large. Processed %d insn\n", 8547 env->insn_processed); 8548 return -E2BIG; 8549 } 8550 8551 err = is_state_visited(env, env->insn_idx); 8552 if (err < 0) 8553 return err; 8554 if (err == 1) { 8555 /* found equivalent state, can prune the search */ 8556 if (env->log.level & BPF_LOG_LEVEL) { 8557 if (do_print_state) 8558 verbose(env, "\nfrom %d to %d%s: safe\n", 8559 env->prev_insn_idx, env->insn_idx, 8560 env->cur_state->speculative ? 8561 " (speculative execution)" : ""); 8562 else 8563 verbose(env, "%d: safe\n", env->insn_idx); 8564 } 8565 goto process_bpf_exit; 8566 } 8567 8568 if (signal_pending(current)) 8569 return -EAGAIN; 8570 8571 if (need_resched()) 8572 cond_resched(); 8573 8574 if (env->log.level & BPF_LOG_LEVEL2 || 8575 (env->log.level & BPF_LOG_LEVEL && do_print_state)) { 8576 if (env->log.level & BPF_LOG_LEVEL2) 8577 verbose(env, "%d:", env->insn_idx); 8578 else 8579 verbose(env, "\nfrom %d to %d%s:", 8580 env->prev_insn_idx, env->insn_idx, 8581 env->cur_state->speculative ? 8582 " (speculative execution)" : ""); 8583 print_verifier_state(env, state->frame[state->curframe]); 8584 do_print_state = false; 8585 } 8586 8587 if (env->log.level & BPF_LOG_LEVEL) { 8588 const struct bpf_insn_cbs cbs = { 8589 .cb_print = verbose, 8590 .private_data = env, 8591 }; 8592 8593 verbose_linfo(env, env->insn_idx, "; "); 8594 verbose(env, "%d: ", env->insn_idx); 8595 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 8596 } 8597 8598 if (bpf_prog_is_dev_bound(env->prog->aux)) { 8599 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 8600 env->prev_insn_idx); 8601 if (err) 8602 return err; 8603 } 8604 8605 regs = cur_regs(env); 8606 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 8607 prev_insn_idx = env->insn_idx; 8608 8609 if (class == BPF_ALU || class == BPF_ALU64) { 8610 err = check_alu_op(env, insn); 8611 if (err) 8612 return err; 8613 8614 } else if (class == BPF_LDX) { 8615 enum bpf_reg_type *prev_src_type, src_reg_type; 8616 8617 /* check for reserved fields is already done */ 8618 8619 /* check src operand */ 8620 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8621 if (err) 8622 return err; 8623 8624 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 8625 if (err) 8626 return err; 8627 8628 src_reg_type = regs[insn->src_reg].type; 8629 8630 /* check that memory (src_reg + off) is readable, 8631 * the state of dst_reg will be updated by this func 8632 */ 8633 err = check_mem_access(env, env->insn_idx, insn->src_reg, 8634 insn->off, BPF_SIZE(insn->code), 8635 BPF_READ, insn->dst_reg, false); 8636 if (err) 8637 return err; 8638 8639 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 8640 8641 if (*prev_src_type == NOT_INIT) { 8642 /* saw a valid insn 8643 * dst_reg = *(u32 *)(src_reg + off) 8644 * save type to validate intersecting paths 8645 */ 8646 *prev_src_type = src_reg_type; 8647 8648 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 8649 /* ABuser program is trying to use the same insn 8650 * dst_reg = *(u32*) (src_reg + off) 8651 * with different pointer types: 8652 * src_reg == ctx in one branch and 8653 * src_reg == stack|map in some other branch. 8654 * Reject it. 8655 */ 8656 verbose(env, "same insn cannot be used with different pointers\n"); 8657 return -EINVAL; 8658 } 8659 8660 } else if (class == BPF_STX) { 8661 enum bpf_reg_type *prev_dst_type, dst_reg_type; 8662 8663 if (BPF_MODE(insn->code) == BPF_XADD) { 8664 err = check_xadd(env, env->insn_idx, insn); 8665 if (err) 8666 return err; 8667 env->insn_idx++; 8668 continue; 8669 } 8670 8671 /* check src1 operand */ 8672 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8673 if (err) 8674 return err; 8675 /* check src2 operand */ 8676 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8677 if (err) 8678 return err; 8679 8680 dst_reg_type = regs[insn->dst_reg].type; 8681 8682 /* check that memory (dst_reg + off) is writeable */ 8683 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 8684 insn->off, BPF_SIZE(insn->code), 8685 BPF_WRITE, insn->src_reg, false); 8686 if (err) 8687 return err; 8688 8689 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 8690 8691 if (*prev_dst_type == NOT_INIT) { 8692 *prev_dst_type = dst_reg_type; 8693 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 8694 verbose(env, "same insn cannot be used with different pointers\n"); 8695 return -EINVAL; 8696 } 8697 8698 } else if (class == BPF_ST) { 8699 if (BPF_MODE(insn->code) != BPF_MEM || 8700 insn->src_reg != BPF_REG_0) { 8701 verbose(env, "BPF_ST uses reserved fields\n"); 8702 return -EINVAL; 8703 } 8704 /* check src operand */ 8705 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8706 if (err) 8707 return err; 8708 8709 if (is_ctx_reg(env, insn->dst_reg)) { 8710 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 8711 insn->dst_reg, 8712 reg_type_str[reg_state(env, insn->dst_reg)->type]); 8713 return -EACCES; 8714 } 8715 8716 /* check that memory (dst_reg + off) is writeable */ 8717 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 8718 insn->off, BPF_SIZE(insn->code), 8719 BPF_WRITE, -1, false); 8720 if (err) 8721 return err; 8722 8723 } else if (class == BPF_JMP || class == BPF_JMP32) { 8724 u8 opcode = BPF_OP(insn->code); 8725 8726 env->jmps_processed++; 8727 if (opcode == BPF_CALL) { 8728 if (BPF_SRC(insn->code) != BPF_K || 8729 insn->off != 0 || 8730 (insn->src_reg != BPF_REG_0 && 8731 insn->src_reg != BPF_PSEUDO_CALL) || 8732 insn->dst_reg != BPF_REG_0 || 8733 class == BPF_JMP32) { 8734 verbose(env, "BPF_CALL uses reserved fields\n"); 8735 return -EINVAL; 8736 } 8737 8738 if (env->cur_state->active_spin_lock && 8739 (insn->src_reg == BPF_PSEUDO_CALL || 8740 insn->imm != BPF_FUNC_spin_unlock)) { 8741 verbose(env, "function calls are not allowed while holding a lock\n"); 8742 return -EINVAL; 8743 } 8744 if (insn->src_reg == BPF_PSEUDO_CALL) 8745 err = check_func_call(env, insn, &env->insn_idx); 8746 else 8747 err = check_helper_call(env, insn->imm, env->insn_idx); 8748 if (err) 8749 return err; 8750 8751 } else if (opcode == BPF_JA) { 8752 if (BPF_SRC(insn->code) != BPF_K || 8753 insn->imm != 0 || 8754 insn->src_reg != BPF_REG_0 || 8755 insn->dst_reg != BPF_REG_0 || 8756 class == BPF_JMP32) { 8757 verbose(env, "BPF_JA uses reserved fields\n"); 8758 return -EINVAL; 8759 } 8760 8761 env->insn_idx += insn->off + 1; 8762 continue; 8763 8764 } else if (opcode == BPF_EXIT) { 8765 if (BPF_SRC(insn->code) != BPF_K || 8766 insn->imm != 0 || 8767 insn->src_reg != BPF_REG_0 || 8768 insn->dst_reg != BPF_REG_0 || 8769 class == BPF_JMP32) { 8770 verbose(env, "BPF_EXIT uses reserved fields\n"); 8771 return -EINVAL; 8772 } 8773 8774 if (env->cur_state->active_spin_lock) { 8775 verbose(env, "bpf_spin_unlock is missing\n"); 8776 return -EINVAL; 8777 } 8778 8779 if (state->curframe) { 8780 /* exit from nested function */ 8781 err = prepare_func_exit(env, &env->insn_idx); 8782 if (err) 8783 return err; 8784 do_print_state = true; 8785 continue; 8786 } 8787 8788 err = check_reference_leak(env); 8789 if (err) 8790 return err; 8791 8792 err = check_return_code(env); 8793 if (err) 8794 return err; 8795 process_bpf_exit: 8796 update_branch_counts(env, env->cur_state); 8797 err = pop_stack(env, &prev_insn_idx, 8798 &env->insn_idx, pop_log); 8799 if (err < 0) { 8800 if (err != -ENOENT) 8801 return err; 8802 break; 8803 } else { 8804 do_print_state = true; 8805 continue; 8806 } 8807 } else { 8808 err = check_cond_jmp_op(env, insn, &env->insn_idx); 8809 if (err) 8810 return err; 8811 } 8812 } else if (class == BPF_LD) { 8813 u8 mode = BPF_MODE(insn->code); 8814 8815 if (mode == BPF_ABS || mode == BPF_IND) { 8816 err = check_ld_abs(env, insn); 8817 if (err) 8818 return err; 8819 8820 } else if (mode == BPF_IMM) { 8821 err = check_ld_imm(env, insn); 8822 if (err) 8823 return err; 8824 8825 env->insn_idx++; 8826 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 8827 } else { 8828 verbose(env, "invalid BPF_LD mode\n"); 8829 return -EINVAL; 8830 } 8831 } else { 8832 verbose(env, "unknown insn class %d\n", class); 8833 return -EINVAL; 8834 } 8835 8836 env->insn_idx++; 8837 } 8838 8839 return 0; 8840 } 8841 8842 static int check_map_prealloc(struct bpf_map *map) 8843 { 8844 return (map->map_type != BPF_MAP_TYPE_HASH && 8845 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 8846 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || 8847 !(map->map_flags & BPF_F_NO_PREALLOC); 8848 } 8849 8850 static bool is_tracing_prog_type(enum bpf_prog_type type) 8851 { 8852 switch (type) { 8853 case BPF_PROG_TYPE_KPROBE: 8854 case BPF_PROG_TYPE_TRACEPOINT: 8855 case BPF_PROG_TYPE_PERF_EVENT: 8856 case BPF_PROG_TYPE_RAW_TRACEPOINT: 8857 return true; 8858 default: 8859 return false; 8860 } 8861 } 8862 8863 static bool is_preallocated_map(struct bpf_map *map) 8864 { 8865 if (!check_map_prealloc(map)) 8866 return false; 8867 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) 8868 return false; 8869 return true; 8870 } 8871 8872 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 8873 struct bpf_map *map, 8874 struct bpf_prog *prog) 8875 8876 { 8877 /* 8878 * Validate that trace type programs use preallocated hash maps. 8879 * 8880 * For programs attached to PERF events this is mandatory as the 8881 * perf NMI can hit any arbitrary code sequence. 8882 * 8883 * All other trace types using preallocated hash maps are unsafe as 8884 * well because tracepoint or kprobes can be inside locked regions 8885 * of the memory allocator or at a place where a recursion into the 8886 * memory allocator would see inconsistent state. 8887 * 8888 * On RT enabled kernels run-time allocation of all trace type 8889 * programs is strictly prohibited due to lock type constraints. On 8890 * !RT kernels it is allowed for backwards compatibility reasons for 8891 * now, but warnings are emitted so developers are made aware of 8892 * the unsafety and can fix their programs before this is enforced. 8893 */ 8894 if (is_tracing_prog_type(prog->type) && !is_preallocated_map(map)) { 8895 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) { 8896 verbose(env, "perf_event programs can only use preallocated hash map\n"); 8897 return -EINVAL; 8898 } 8899 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 8900 verbose(env, "trace type programs can only use preallocated hash map\n"); 8901 return -EINVAL; 8902 } 8903 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n"); 8904 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n"); 8905 } 8906 8907 if ((is_tracing_prog_type(prog->type) || 8908 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) && 8909 map_value_has_spin_lock(map)) { 8910 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 8911 return -EINVAL; 8912 } 8913 8914 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) && 8915 !bpf_offload_prog_map_match(prog, map)) { 8916 verbose(env, "offload device mismatch between prog and map\n"); 8917 return -EINVAL; 8918 } 8919 8920 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 8921 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 8922 return -EINVAL; 8923 } 8924 8925 return 0; 8926 } 8927 8928 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 8929 { 8930 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 8931 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 8932 } 8933 8934 /* look for pseudo eBPF instructions that access map FDs and 8935 * replace them with actual map pointers 8936 */ 8937 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) 8938 { 8939 struct bpf_insn *insn = env->prog->insnsi; 8940 int insn_cnt = env->prog->len; 8941 int i, j, err; 8942 8943 err = bpf_prog_calc_tag(env->prog); 8944 if (err) 8945 return err; 8946 8947 for (i = 0; i < insn_cnt; i++, insn++) { 8948 if (BPF_CLASS(insn->code) == BPF_LDX && 8949 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 8950 verbose(env, "BPF_LDX uses reserved fields\n"); 8951 return -EINVAL; 8952 } 8953 8954 if (BPF_CLASS(insn->code) == BPF_STX && 8955 ((BPF_MODE(insn->code) != BPF_MEM && 8956 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { 8957 verbose(env, "BPF_STX uses reserved fields\n"); 8958 return -EINVAL; 8959 } 8960 8961 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 8962 struct bpf_insn_aux_data *aux; 8963 struct bpf_map *map; 8964 struct fd f; 8965 u64 addr; 8966 8967 if (i == insn_cnt - 1 || insn[1].code != 0 || 8968 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 8969 insn[1].off != 0) { 8970 verbose(env, "invalid bpf_ld_imm64 insn\n"); 8971 return -EINVAL; 8972 } 8973 8974 if (insn[0].src_reg == 0) 8975 /* valid generic load 64-bit imm */ 8976 goto next_insn; 8977 8978 /* In final convert_pseudo_ld_imm64() step, this is 8979 * converted into regular 64-bit imm load insn. 8980 */ 8981 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD && 8982 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) || 8983 (insn[0].src_reg == BPF_PSEUDO_MAP_FD && 8984 insn[1].imm != 0)) { 8985 verbose(env, 8986 "unrecognized bpf_ld_imm64 insn\n"); 8987 return -EINVAL; 8988 } 8989 8990 f = fdget(insn[0].imm); 8991 map = __bpf_map_get(f); 8992 if (IS_ERR(map)) { 8993 verbose(env, "fd %d is not pointing to valid bpf_map\n", 8994 insn[0].imm); 8995 return PTR_ERR(map); 8996 } 8997 8998 err = check_map_prog_compatibility(env, map, env->prog); 8999 if (err) { 9000 fdput(f); 9001 return err; 9002 } 9003 9004 aux = &env->insn_aux_data[i]; 9005 if (insn->src_reg == BPF_PSEUDO_MAP_FD) { 9006 addr = (unsigned long)map; 9007 } else { 9008 u32 off = insn[1].imm; 9009 9010 if (off >= BPF_MAX_VAR_OFF) { 9011 verbose(env, "direct value offset of %u is not allowed\n", off); 9012 fdput(f); 9013 return -EINVAL; 9014 } 9015 9016 if (!map->ops->map_direct_value_addr) { 9017 verbose(env, "no direct value access support for this map type\n"); 9018 fdput(f); 9019 return -EINVAL; 9020 } 9021 9022 err = map->ops->map_direct_value_addr(map, &addr, off); 9023 if (err) { 9024 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 9025 map->value_size, off); 9026 fdput(f); 9027 return err; 9028 } 9029 9030 aux->map_off = off; 9031 addr += off; 9032 } 9033 9034 insn[0].imm = (u32)addr; 9035 insn[1].imm = addr >> 32; 9036 9037 /* check whether we recorded this map already */ 9038 for (j = 0; j < env->used_map_cnt; j++) { 9039 if (env->used_maps[j] == map) { 9040 aux->map_index = j; 9041 fdput(f); 9042 goto next_insn; 9043 } 9044 } 9045 9046 if (env->used_map_cnt >= MAX_USED_MAPS) { 9047 fdput(f); 9048 return -E2BIG; 9049 } 9050 9051 /* hold the map. If the program is rejected by verifier, 9052 * the map will be released by release_maps() or it 9053 * will be used by the valid program until it's unloaded 9054 * and all maps are released in free_used_maps() 9055 */ 9056 bpf_map_inc(map); 9057 9058 aux->map_index = env->used_map_cnt; 9059 env->used_maps[env->used_map_cnt++] = map; 9060 9061 if (bpf_map_is_cgroup_storage(map) && 9062 bpf_cgroup_storage_assign(env->prog->aux, map)) { 9063 verbose(env, "only one cgroup storage of each type is allowed\n"); 9064 fdput(f); 9065 return -EBUSY; 9066 } 9067 9068 fdput(f); 9069 next_insn: 9070 insn++; 9071 i++; 9072 continue; 9073 } 9074 9075 /* Basic sanity check before we invest more work here. */ 9076 if (!bpf_opcode_in_insntable(insn->code)) { 9077 verbose(env, "unknown opcode %02x\n", insn->code); 9078 return -EINVAL; 9079 } 9080 } 9081 9082 /* now all pseudo BPF_LD_IMM64 instructions load valid 9083 * 'struct bpf_map *' into a register instead of user map_fd. 9084 * These pointers will be used later by verifier to validate map access. 9085 */ 9086 return 0; 9087 } 9088 9089 /* drop refcnt of maps used by the rejected program */ 9090 static void release_maps(struct bpf_verifier_env *env) 9091 { 9092 __bpf_free_used_maps(env->prog->aux, env->used_maps, 9093 env->used_map_cnt); 9094 } 9095 9096 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 9097 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 9098 { 9099 struct bpf_insn *insn = env->prog->insnsi; 9100 int insn_cnt = env->prog->len; 9101 int i; 9102 9103 for (i = 0; i < insn_cnt; i++, insn++) 9104 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW)) 9105 insn->src_reg = 0; 9106 } 9107 9108 /* single env->prog->insni[off] instruction was replaced with the range 9109 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 9110 * [0, off) and [off, end) to new locations, so the patched range stays zero 9111 */ 9112 static int adjust_insn_aux_data(struct bpf_verifier_env *env, 9113 struct bpf_prog *new_prog, u32 off, u32 cnt) 9114 { 9115 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; 9116 struct bpf_insn *insn = new_prog->insnsi; 9117 u32 prog_len; 9118 int i; 9119 9120 /* aux info at OFF always needs adjustment, no matter fast path 9121 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 9122 * original insn at old prog. 9123 */ 9124 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 9125 9126 if (cnt == 1) 9127 return 0; 9128 prog_len = new_prog->len; 9129 new_data = vzalloc(array_size(prog_len, 9130 sizeof(struct bpf_insn_aux_data))); 9131 if (!new_data) 9132 return -ENOMEM; 9133 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 9134 memcpy(new_data + off + cnt - 1, old_data + off, 9135 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 9136 for (i = off; i < off + cnt - 1; i++) { 9137 new_data[i].seen = env->pass_cnt; 9138 new_data[i].zext_dst = insn_has_def32(env, insn + i); 9139 } 9140 env->insn_aux_data = new_data; 9141 vfree(old_data); 9142 return 0; 9143 } 9144 9145 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 9146 { 9147 int i; 9148 9149 if (len == 1) 9150 return; 9151 /* NOTE: fake 'exit' subprog should be updated as well. */ 9152 for (i = 0; i <= env->subprog_cnt; i++) { 9153 if (env->subprog_info[i].start <= off) 9154 continue; 9155 env->subprog_info[i].start += len - 1; 9156 } 9157 } 9158 9159 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 9160 const struct bpf_insn *patch, u32 len) 9161 { 9162 struct bpf_prog *new_prog; 9163 9164 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 9165 if (IS_ERR(new_prog)) { 9166 if (PTR_ERR(new_prog) == -ERANGE) 9167 verbose(env, 9168 "insn %d cannot be patched due to 16-bit range\n", 9169 env->insn_aux_data[off].orig_idx); 9170 return NULL; 9171 } 9172 if (adjust_insn_aux_data(env, new_prog, off, len)) 9173 return NULL; 9174 adjust_subprog_starts(env, off, len); 9175 return new_prog; 9176 } 9177 9178 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 9179 u32 off, u32 cnt) 9180 { 9181 int i, j; 9182 9183 /* find first prog starting at or after off (first to remove) */ 9184 for (i = 0; i < env->subprog_cnt; i++) 9185 if (env->subprog_info[i].start >= off) 9186 break; 9187 /* find first prog starting at or after off + cnt (first to stay) */ 9188 for (j = i; j < env->subprog_cnt; j++) 9189 if (env->subprog_info[j].start >= off + cnt) 9190 break; 9191 /* if j doesn't start exactly at off + cnt, we are just removing 9192 * the front of previous prog 9193 */ 9194 if (env->subprog_info[j].start != off + cnt) 9195 j--; 9196 9197 if (j > i) { 9198 struct bpf_prog_aux *aux = env->prog->aux; 9199 int move; 9200 9201 /* move fake 'exit' subprog as well */ 9202 move = env->subprog_cnt + 1 - j; 9203 9204 memmove(env->subprog_info + i, 9205 env->subprog_info + j, 9206 sizeof(*env->subprog_info) * move); 9207 env->subprog_cnt -= j - i; 9208 9209 /* remove func_info */ 9210 if (aux->func_info) { 9211 move = aux->func_info_cnt - j; 9212 9213 memmove(aux->func_info + i, 9214 aux->func_info + j, 9215 sizeof(*aux->func_info) * move); 9216 aux->func_info_cnt -= j - i; 9217 /* func_info->insn_off is set after all code rewrites, 9218 * in adjust_btf_func() - no need to adjust 9219 */ 9220 } 9221 } else { 9222 /* convert i from "first prog to remove" to "first to adjust" */ 9223 if (env->subprog_info[i].start == off) 9224 i++; 9225 } 9226 9227 /* update fake 'exit' subprog as well */ 9228 for (; i <= env->subprog_cnt; i++) 9229 env->subprog_info[i].start -= cnt; 9230 9231 return 0; 9232 } 9233 9234 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 9235 u32 cnt) 9236 { 9237 struct bpf_prog *prog = env->prog; 9238 u32 i, l_off, l_cnt, nr_linfo; 9239 struct bpf_line_info *linfo; 9240 9241 nr_linfo = prog->aux->nr_linfo; 9242 if (!nr_linfo) 9243 return 0; 9244 9245 linfo = prog->aux->linfo; 9246 9247 /* find first line info to remove, count lines to be removed */ 9248 for (i = 0; i < nr_linfo; i++) 9249 if (linfo[i].insn_off >= off) 9250 break; 9251 9252 l_off = i; 9253 l_cnt = 0; 9254 for (; i < nr_linfo; i++) 9255 if (linfo[i].insn_off < off + cnt) 9256 l_cnt++; 9257 else 9258 break; 9259 9260 /* First live insn doesn't match first live linfo, it needs to "inherit" 9261 * last removed linfo. prog is already modified, so prog->len == off 9262 * means no live instructions after (tail of the program was removed). 9263 */ 9264 if (prog->len != off && l_cnt && 9265 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 9266 l_cnt--; 9267 linfo[--i].insn_off = off + cnt; 9268 } 9269 9270 /* remove the line info which refer to the removed instructions */ 9271 if (l_cnt) { 9272 memmove(linfo + l_off, linfo + i, 9273 sizeof(*linfo) * (nr_linfo - i)); 9274 9275 prog->aux->nr_linfo -= l_cnt; 9276 nr_linfo = prog->aux->nr_linfo; 9277 } 9278 9279 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 9280 for (i = l_off; i < nr_linfo; i++) 9281 linfo[i].insn_off -= cnt; 9282 9283 /* fix up all subprogs (incl. 'exit') which start >= off */ 9284 for (i = 0; i <= env->subprog_cnt; i++) 9285 if (env->subprog_info[i].linfo_idx > l_off) { 9286 /* program may have started in the removed region but 9287 * may not be fully removed 9288 */ 9289 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 9290 env->subprog_info[i].linfo_idx -= l_cnt; 9291 else 9292 env->subprog_info[i].linfo_idx = l_off; 9293 } 9294 9295 return 0; 9296 } 9297 9298 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 9299 { 9300 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 9301 unsigned int orig_prog_len = env->prog->len; 9302 int err; 9303 9304 if (bpf_prog_is_dev_bound(env->prog->aux)) 9305 bpf_prog_offload_remove_insns(env, off, cnt); 9306 9307 err = bpf_remove_insns(env->prog, off, cnt); 9308 if (err) 9309 return err; 9310 9311 err = adjust_subprog_starts_after_remove(env, off, cnt); 9312 if (err) 9313 return err; 9314 9315 err = bpf_adj_linfo_after_remove(env, off, cnt); 9316 if (err) 9317 return err; 9318 9319 memmove(aux_data + off, aux_data + off + cnt, 9320 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 9321 9322 return 0; 9323 } 9324 9325 /* The verifier does more data flow analysis than llvm and will not 9326 * explore branches that are dead at run time. Malicious programs can 9327 * have dead code too. Therefore replace all dead at-run-time code 9328 * with 'ja -1'. 9329 * 9330 * Just nops are not optimal, e.g. if they would sit at the end of the 9331 * program and through another bug we would manage to jump there, then 9332 * we'd execute beyond program memory otherwise. Returning exception 9333 * code also wouldn't work since we can have subprogs where the dead 9334 * code could be located. 9335 */ 9336 static void sanitize_dead_code(struct bpf_verifier_env *env) 9337 { 9338 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 9339 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 9340 struct bpf_insn *insn = env->prog->insnsi; 9341 const int insn_cnt = env->prog->len; 9342 int i; 9343 9344 for (i = 0; i < insn_cnt; i++) { 9345 if (aux_data[i].seen) 9346 continue; 9347 memcpy(insn + i, &trap, sizeof(trap)); 9348 } 9349 } 9350 9351 static bool insn_is_cond_jump(u8 code) 9352 { 9353 u8 op; 9354 9355 if (BPF_CLASS(code) == BPF_JMP32) 9356 return true; 9357 9358 if (BPF_CLASS(code) != BPF_JMP) 9359 return false; 9360 9361 op = BPF_OP(code); 9362 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 9363 } 9364 9365 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 9366 { 9367 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 9368 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 9369 struct bpf_insn *insn = env->prog->insnsi; 9370 const int insn_cnt = env->prog->len; 9371 int i; 9372 9373 for (i = 0; i < insn_cnt; i++, insn++) { 9374 if (!insn_is_cond_jump(insn->code)) 9375 continue; 9376 9377 if (!aux_data[i + 1].seen) 9378 ja.off = insn->off; 9379 else if (!aux_data[i + 1 + insn->off].seen) 9380 ja.off = 0; 9381 else 9382 continue; 9383 9384 if (bpf_prog_is_dev_bound(env->prog->aux)) 9385 bpf_prog_offload_replace_insn(env, i, &ja); 9386 9387 memcpy(insn, &ja, sizeof(ja)); 9388 } 9389 } 9390 9391 static int opt_remove_dead_code(struct bpf_verifier_env *env) 9392 { 9393 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 9394 int insn_cnt = env->prog->len; 9395 int i, err; 9396 9397 for (i = 0; i < insn_cnt; i++) { 9398 int j; 9399 9400 j = 0; 9401 while (i + j < insn_cnt && !aux_data[i + j].seen) 9402 j++; 9403 if (!j) 9404 continue; 9405 9406 err = verifier_remove_insns(env, i, j); 9407 if (err) 9408 return err; 9409 insn_cnt = env->prog->len; 9410 } 9411 9412 return 0; 9413 } 9414 9415 static int opt_remove_nops(struct bpf_verifier_env *env) 9416 { 9417 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 9418 struct bpf_insn *insn = env->prog->insnsi; 9419 int insn_cnt = env->prog->len; 9420 int i, err; 9421 9422 for (i = 0; i < insn_cnt; i++) { 9423 if (memcmp(&insn[i], &ja, sizeof(ja))) 9424 continue; 9425 9426 err = verifier_remove_insns(env, i, 1); 9427 if (err) 9428 return err; 9429 insn_cnt--; 9430 i--; 9431 } 9432 9433 return 0; 9434 } 9435 9436 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 9437 const union bpf_attr *attr) 9438 { 9439 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 9440 struct bpf_insn_aux_data *aux = env->insn_aux_data; 9441 int i, patch_len, delta = 0, len = env->prog->len; 9442 struct bpf_insn *insns = env->prog->insnsi; 9443 struct bpf_prog *new_prog; 9444 bool rnd_hi32; 9445 9446 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 9447 zext_patch[1] = BPF_ZEXT_REG(0); 9448 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 9449 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 9450 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 9451 for (i = 0; i < len; i++) { 9452 int adj_idx = i + delta; 9453 struct bpf_insn insn; 9454 9455 insn = insns[adj_idx]; 9456 if (!aux[adj_idx].zext_dst) { 9457 u8 code, class; 9458 u32 imm_rnd; 9459 9460 if (!rnd_hi32) 9461 continue; 9462 9463 code = insn.code; 9464 class = BPF_CLASS(code); 9465 if (insn_no_def(&insn)) 9466 continue; 9467 9468 /* NOTE: arg "reg" (the fourth one) is only used for 9469 * BPF_STX which has been ruled out in above 9470 * check, it is safe to pass NULL here. 9471 */ 9472 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) { 9473 if (class == BPF_LD && 9474 BPF_MODE(code) == BPF_IMM) 9475 i++; 9476 continue; 9477 } 9478 9479 /* ctx load could be transformed into wider load. */ 9480 if (class == BPF_LDX && 9481 aux[adj_idx].ptr_type == PTR_TO_CTX) 9482 continue; 9483 9484 imm_rnd = get_random_int(); 9485 rnd_hi32_patch[0] = insn; 9486 rnd_hi32_patch[1].imm = imm_rnd; 9487 rnd_hi32_patch[3].dst_reg = insn.dst_reg; 9488 patch = rnd_hi32_patch; 9489 patch_len = 4; 9490 goto apply_patch_buffer; 9491 } 9492 9493 if (!bpf_jit_needs_zext()) 9494 continue; 9495 9496 zext_patch[0] = insn; 9497 zext_patch[1].dst_reg = insn.dst_reg; 9498 zext_patch[1].src_reg = insn.dst_reg; 9499 patch = zext_patch; 9500 patch_len = 2; 9501 apply_patch_buffer: 9502 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 9503 if (!new_prog) 9504 return -ENOMEM; 9505 env->prog = new_prog; 9506 insns = new_prog->insnsi; 9507 aux = env->insn_aux_data; 9508 delta += patch_len - 1; 9509 } 9510 9511 return 0; 9512 } 9513 9514 /* convert load instructions that access fields of a context type into a 9515 * sequence of instructions that access fields of the underlying structure: 9516 * struct __sk_buff -> struct sk_buff 9517 * struct bpf_sock_ops -> struct sock 9518 */ 9519 static int convert_ctx_accesses(struct bpf_verifier_env *env) 9520 { 9521 const struct bpf_verifier_ops *ops = env->ops; 9522 int i, cnt, size, ctx_field_size, delta = 0; 9523 const int insn_cnt = env->prog->len; 9524 struct bpf_insn insn_buf[16], *insn; 9525 u32 target_size, size_default, off; 9526 struct bpf_prog *new_prog; 9527 enum bpf_access_type type; 9528 bool is_narrower_load; 9529 9530 if (ops->gen_prologue || env->seen_direct_write) { 9531 if (!ops->gen_prologue) { 9532 verbose(env, "bpf verifier is misconfigured\n"); 9533 return -EINVAL; 9534 } 9535 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 9536 env->prog); 9537 if (cnt >= ARRAY_SIZE(insn_buf)) { 9538 verbose(env, "bpf verifier is misconfigured\n"); 9539 return -EINVAL; 9540 } else if (cnt) { 9541 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 9542 if (!new_prog) 9543 return -ENOMEM; 9544 9545 env->prog = new_prog; 9546 delta += cnt - 1; 9547 } 9548 } 9549 9550 if (bpf_prog_is_dev_bound(env->prog->aux)) 9551 return 0; 9552 9553 insn = env->prog->insnsi + delta; 9554 9555 for (i = 0; i < insn_cnt; i++, insn++) { 9556 bpf_convert_ctx_access_t convert_ctx_access; 9557 9558 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 9559 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 9560 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 9561 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) 9562 type = BPF_READ; 9563 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 9564 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 9565 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 9566 insn->code == (BPF_STX | BPF_MEM | BPF_DW)) 9567 type = BPF_WRITE; 9568 else 9569 continue; 9570 9571 if (type == BPF_WRITE && 9572 env->insn_aux_data[i + delta].sanitize_stack_off) { 9573 struct bpf_insn patch[] = { 9574 /* Sanitize suspicious stack slot with zero. 9575 * There are no memory dependencies for this store, 9576 * since it's only using frame pointer and immediate 9577 * constant of zero 9578 */ 9579 BPF_ST_MEM(BPF_DW, BPF_REG_FP, 9580 env->insn_aux_data[i + delta].sanitize_stack_off, 9581 0), 9582 /* the original STX instruction will immediately 9583 * overwrite the same stack slot with appropriate value 9584 */ 9585 *insn, 9586 }; 9587 9588 cnt = ARRAY_SIZE(patch); 9589 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 9590 if (!new_prog) 9591 return -ENOMEM; 9592 9593 delta += cnt - 1; 9594 env->prog = new_prog; 9595 insn = new_prog->insnsi + i + delta; 9596 continue; 9597 } 9598 9599 switch (env->insn_aux_data[i + delta].ptr_type) { 9600 case PTR_TO_CTX: 9601 if (!ops->convert_ctx_access) 9602 continue; 9603 convert_ctx_access = ops->convert_ctx_access; 9604 break; 9605 case PTR_TO_SOCKET: 9606 case PTR_TO_SOCK_COMMON: 9607 convert_ctx_access = bpf_sock_convert_ctx_access; 9608 break; 9609 case PTR_TO_TCP_SOCK: 9610 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 9611 break; 9612 case PTR_TO_XDP_SOCK: 9613 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 9614 break; 9615 case PTR_TO_BTF_ID: 9616 if (type == BPF_READ) { 9617 insn->code = BPF_LDX | BPF_PROBE_MEM | 9618 BPF_SIZE((insn)->code); 9619 env->prog->aux->num_exentries++; 9620 } else if (env->prog->type != BPF_PROG_TYPE_STRUCT_OPS) { 9621 verbose(env, "Writes through BTF pointers are not allowed\n"); 9622 return -EINVAL; 9623 } 9624 continue; 9625 default: 9626 continue; 9627 } 9628 9629 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 9630 size = BPF_LDST_BYTES(insn); 9631 9632 /* If the read access is a narrower load of the field, 9633 * convert to a 4/8-byte load, to minimum program type specific 9634 * convert_ctx_access changes. If conversion is successful, 9635 * we will apply proper mask to the result. 9636 */ 9637 is_narrower_load = size < ctx_field_size; 9638 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 9639 off = insn->off; 9640 if (is_narrower_load) { 9641 u8 size_code; 9642 9643 if (type == BPF_WRITE) { 9644 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 9645 return -EINVAL; 9646 } 9647 9648 size_code = BPF_H; 9649 if (ctx_field_size == 4) 9650 size_code = BPF_W; 9651 else if (ctx_field_size == 8) 9652 size_code = BPF_DW; 9653 9654 insn->off = off & ~(size_default - 1); 9655 insn->code = BPF_LDX | BPF_MEM | size_code; 9656 } 9657 9658 target_size = 0; 9659 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 9660 &target_size); 9661 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 9662 (ctx_field_size && !target_size)) { 9663 verbose(env, "bpf verifier is misconfigured\n"); 9664 return -EINVAL; 9665 } 9666 9667 if (is_narrower_load && size < target_size) { 9668 u8 shift = bpf_ctx_narrow_access_offset( 9669 off, size, size_default) * 8; 9670 if (ctx_field_size <= 4) { 9671 if (shift) 9672 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 9673 insn->dst_reg, 9674 shift); 9675 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 9676 (1 << size * 8) - 1); 9677 } else { 9678 if (shift) 9679 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 9680 insn->dst_reg, 9681 shift); 9682 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 9683 (1ULL << size * 8) - 1); 9684 } 9685 } 9686 9687 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 9688 if (!new_prog) 9689 return -ENOMEM; 9690 9691 delta += cnt - 1; 9692 9693 /* keep walking new program and skip insns we just inserted */ 9694 env->prog = new_prog; 9695 insn = new_prog->insnsi + i + delta; 9696 } 9697 9698 return 0; 9699 } 9700 9701 static int jit_subprogs(struct bpf_verifier_env *env) 9702 { 9703 struct bpf_prog *prog = env->prog, **func, *tmp; 9704 int i, j, subprog_start, subprog_end = 0, len, subprog; 9705 struct bpf_insn *insn; 9706 void *old_bpf_func; 9707 int err; 9708 9709 if (env->subprog_cnt <= 1) 9710 return 0; 9711 9712 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 9713 if (insn->code != (BPF_JMP | BPF_CALL) || 9714 insn->src_reg != BPF_PSEUDO_CALL) 9715 continue; 9716 /* Upon error here we cannot fall back to interpreter but 9717 * need a hard reject of the program. Thus -EFAULT is 9718 * propagated in any case. 9719 */ 9720 subprog = find_subprog(env, i + insn->imm + 1); 9721 if (subprog < 0) { 9722 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 9723 i + insn->imm + 1); 9724 return -EFAULT; 9725 } 9726 /* temporarily remember subprog id inside insn instead of 9727 * aux_data, since next loop will split up all insns into funcs 9728 */ 9729 insn->off = subprog; 9730 /* remember original imm in case JIT fails and fallback 9731 * to interpreter will be needed 9732 */ 9733 env->insn_aux_data[i].call_imm = insn->imm; 9734 /* point imm to __bpf_call_base+1 from JITs point of view */ 9735 insn->imm = 1; 9736 } 9737 9738 err = bpf_prog_alloc_jited_linfo(prog); 9739 if (err) 9740 goto out_undo_insn; 9741 9742 err = -ENOMEM; 9743 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 9744 if (!func) 9745 goto out_undo_insn; 9746 9747 for (i = 0; i < env->subprog_cnt; i++) { 9748 subprog_start = subprog_end; 9749 subprog_end = env->subprog_info[i + 1].start; 9750 9751 len = subprog_end - subprog_start; 9752 /* BPF_PROG_RUN doesn't call subprogs directly, 9753 * hence main prog stats include the runtime of subprogs. 9754 * subprogs don't have IDs and not reachable via prog_get_next_id 9755 * func[i]->aux->stats will never be accessed and stays NULL 9756 */ 9757 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 9758 if (!func[i]) 9759 goto out_free; 9760 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 9761 len * sizeof(struct bpf_insn)); 9762 func[i]->type = prog->type; 9763 func[i]->len = len; 9764 if (bpf_prog_calc_tag(func[i])) 9765 goto out_free; 9766 func[i]->is_func = 1; 9767 func[i]->aux->func_idx = i; 9768 /* the btf and func_info will be freed only at prog->aux */ 9769 func[i]->aux->btf = prog->aux->btf; 9770 func[i]->aux->func_info = prog->aux->func_info; 9771 9772 /* Use bpf_prog_F_tag to indicate functions in stack traces. 9773 * Long term would need debug info to populate names 9774 */ 9775 func[i]->aux->name[0] = 'F'; 9776 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 9777 func[i]->jit_requested = 1; 9778 func[i]->aux->linfo = prog->aux->linfo; 9779 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 9780 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 9781 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 9782 func[i] = bpf_int_jit_compile(func[i]); 9783 if (!func[i]->jited) { 9784 err = -ENOTSUPP; 9785 goto out_free; 9786 } 9787 cond_resched(); 9788 } 9789 /* at this point all bpf functions were successfully JITed 9790 * now populate all bpf_calls with correct addresses and 9791 * run last pass of JIT 9792 */ 9793 for (i = 0; i < env->subprog_cnt; i++) { 9794 insn = func[i]->insnsi; 9795 for (j = 0; j < func[i]->len; j++, insn++) { 9796 if (insn->code != (BPF_JMP | BPF_CALL) || 9797 insn->src_reg != BPF_PSEUDO_CALL) 9798 continue; 9799 subprog = insn->off; 9800 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) - 9801 __bpf_call_base; 9802 } 9803 9804 /* we use the aux data to keep a list of the start addresses 9805 * of the JITed images for each function in the program 9806 * 9807 * for some architectures, such as powerpc64, the imm field 9808 * might not be large enough to hold the offset of the start 9809 * address of the callee's JITed image from __bpf_call_base 9810 * 9811 * in such cases, we can lookup the start address of a callee 9812 * by using its subprog id, available from the off field of 9813 * the call instruction, as an index for this list 9814 */ 9815 func[i]->aux->func = func; 9816 func[i]->aux->func_cnt = env->subprog_cnt; 9817 } 9818 for (i = 0; i < env->subprog_cnt; i++) { 9819 old_bpf_func = func[i]->bpf_func; 9820 tmp = bpf_int_jit_compile(func[i]); 9821 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 9822 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 9823 err = -ENOTSUPP; 9824 goto out_free; 9825 } 9826 cond_resched(); 9827 } 9828 9829 /* finally lock prog and jit images for all functions and 9830 * populate kallsysm 9831 */ 9832 for (i = 0; i < env->subprog_cnt; i++) { 9833 bpf_prog_lock_ro(func[i]); 9834 bpf_prog_kallsyms_add(func[i]); 9835 } 9836 9837 /* Last step: make now unused interpreter insns from main 9838 * prog consistent for later dump requests, so they can 9839 * later look the same as if they were interpreted only. 9840 */ 9841 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 9842 if (insn->code != (BPF_JMP | BPF_CALL) || 9843 insn->src_reg != BPF_PSEUDO_CALL) 9844 continue; 9845 insn->off = env->insn_aux_data[i].call_imm; 9846 subprog = find_subprog(env, i + insn->off + 1); 9847 insn->imm = subprog; 9848 } 9849 9850 prog->jited = 1; 9851 prog->bpf_func = func[0]->bpf_func; 9852 prog->aux->func = func; 9853 prog->aux->func_cnt = env->subprog_cnt; 9854 bpf_prog_free_unused_jited_linfo(prog); 9855 return 0; 9856 out_free: 9857 for (i = 0; i < env->subprog_cnt; i++) 9858 if (func[i]) 9859 bpf_jit_free(func[i]); 9860 kfree(func); 9861 out_undo_insn: 9862 /* cleanup main prog to be interpreted */ 9863 prog->jit_requested = 0; 9864 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 9865 if (insn->code != (BPF_JMP | BPF_CALL) || 9866 insn->src_reg != BPF_PSEUDO_CALL) 9867 continue; 9868 insn->off = 0; 9869 insn->imm = env->insn_aux_data[i].call_imm; 9870 } 9871 bpf_prog_free_jited_linfo(prog); 9872 return err; 9873 } 9874 9875 static int fixup_call_args(struct bpf_verifier_env *env) 9876 { 9877 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 9878 struct bpf_prog *prog = env->prog; 9879 struct bpf_insn *insn = prog->insnsi; 9880 int i, depth; 9881 #endif 9882 int err = 0; 9883 9884 if (env->prog->jit_requested && 9885 !bpf_prog_is_dev_bound(env->prog->aux)) { 9886 err = jit_subprogs(env); 9887 if (err == 0) 9888 return 0; 9889 if (err == -EFAULT) 9890 return err; 9891 } 9892 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 9893 for (i = 0; i < prog->len; i++, insn++) { 9894 if (insn->code != (BPF_JMP | BPF_CALL) || 9895 insn->src_reg != BPF_PSEUDO_CALL) 9896 continue; 9897 depth = get_callee_stack_depth(env, insn, i); 9898 if (depth < 0) 9899 return depth; 9900 bpf_patch_call_args(insn, depth); 9901 } 9902 err = 0; 9903 #endif 9904 return err; 9905 } 9906 9907 /* fixup insn->imm field of bpf_call instructions 9908 * and inline eligible helpers as explicit sequence of BPF instructions 9909 * 9910 * this function is called after eBPF program passed verification 9911 */ 9912 static int fixup_bpf_calls(struct bpf_verifier_env *env) 9913 { 9914 struct bpf_prog *prog = env->prog; 9915 bool expect_blinding = bpf_jit_blinding_enabled(prog); 9916 struct bpf_insn *insn = prog->insnsi; 9917 const struct bpf_func_proto *fn; 9918 const int insn_cnt = prog->len; 9919 const struct bpf_map_ops *ops; 9920 struct bpf_insn_aux_data *aux; 9921 struct bpf_insn insn_buf[16]; 9922 struct bpf_prog *new_prog; 9923 struct bpf_map *map_ptr; 9924 int i, ret, cnt, delta = 0; 9925 9926 for (i = 0; i < insn_cnt; i++, insn++) { 9927 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 9928 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 9929 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 9930 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 9931 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 9932 struct bpf_insn mask_and_div[] = { 9933 BPF_MOV32_REG(insn->src_reg, insn->src_reg), 9934 /* Rx div 0 -> 0 */ 9935 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2), 9936 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 9937 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 9938 *insn, 9939 }; 9940 struct bpf_insn mask_and_mod[] = { 9941 BPF_MOV32_REG(insn->src_reg, insn->src_reg), 9942 /* Rx mod 0 -> Rx */ 9943 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1), 9944 *insn, 9945 }; 9946 struct bpf_insn *patchlet; 9947 9948 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 9949 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 9950 patchlet = mask_and_div + (is64 ? 1 : 0); 9951 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0); 9952 } else { 9953 patchlet = mask_and_mod + (is64 ? 1 : 0); 9954 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0); 9955 } 9956 9957 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 9958 if (!new_prog) 9959 return -ENOMEM; 9960 9961 delta += cnt - 1; 9962 env->prog = prog = new_prog; 9963 insn = new_prog->insnsi + i + delta; 9964 continue; 9965 } 9966 9967 if (BPF_CLASS(insn->code) == BPF_LD && 9968 (BPF_MODE(insn->code) == BPF_ABS || 9969 BPF_MODE(insn->code) == BPF_IND)) { 9970 cnt = env->ops->gen_ld_abs(insn, insn_buf); 9971 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 9972 verbose(env, "bpf verifier is misconfigured\n"); 9973 return -EINVAL; 9974 } 9975 9976 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 9977 if (!new_prog) 9978 return -ENOMEM; 9979 9980 delta += cnt - 1; 9981 env->prog = prog = new_prog; 9982 insn = new_prog->insnsi + i + delta; 9983 continue; 9984 } 9985 9986 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 9987 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 9988 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 9989 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 9990 struct bpf_insn insn_buf[16]; 9991 struct bpf_insn *patch = &insn_buf[0]; 9992 bool issrc, isneg; 9993 u32 off_reg; 9994 9995 aux = &env->insn_aux_data[i + delta]; 9996 if (!aux->alu_state || 9997 aux->alu_state == BPF_ALU_NON_POINTER) 9998 continue; 9999 10000 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 10001 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 10002 BPF_ALU_SANITIZE_SRC; 10003 10004 off_reg = issrc ? insn->src_reg : insn->dst_reg; 10005 if (isneg) 10006 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 10007 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1); 10008 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 10009 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 10010 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 10011 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 10012 if (issrc) { 10013 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, 10014 off_reg); 10015 insn->src_reg = BPF_REG_AX; 10016 } else { 10017 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg, 10018 BPF_REG_AX); 10019 } 10020 if (isneg) 10021 insn->code = insn->code == code_add ? 10022 code_sub : code_add; 10023 *patch++ = *insn; 10024 if (issrc && isneg) 10025 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 10026 cnt = patch - insn_buf; 10027 10028 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 10029 if (!new_prog) 10030 return -ENOMEM; 10031 10032 delta += cnt - 1; 10033 env->prog = prog = new_prog; 10034 insn = new_prog->insnsi + i + delta; 10035 continue; 10036 } 10037 10038 if (insn->code != (BPF_JMP | BPF_CALL)) 10039 continue; 10040 if (insn->src_reg == BPF_PSEUDO_CALL) 10041 continue; 10042 10043 if (insn->imm == BPF_FUNC_get_route_realm) 10044 prog->dst_needed = 1; 10045 if (insn->imm == BPF_FUNC_get_prandom_u32) 10046 bpf_user_rnd_init_once(); 10047 if (insn->imm == BPF_FUNC_override_return) 10048 prog->kprobe_override = 1; 10049 if (insn->imm == BPF_FUNC_tail_call) { 10050 /* If we tail call into other programs, we 10051 * cannot make any assumptions since they can 10052 * be replaced dynamically during runtime in 10053 * the program array. 10054 */ 10055 prog->cb_access = 1; 10056 env->prog->aux->stack_depth = MAX_BPF_STACK; 10057 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF; 10058 10059 /* mark bpf_tail_call as different opcode to avoid 10060 * conditional branch in the interpeter for every normal 10061 * call and to prevent accidental JITing by JIT compiler 10062 * that doesn't support bpf_tail_call yet 10063 */ 10064 insn->imm = 0; 10065 insn->code = BPF_JMP | BPF_TAIL_CALL; 10066 10067 aux = &env->insn_aux_data[i + delta]; 10068 if (env->bpf_capable && !expect_blinding && 10069 prog->jit_requested && 10070 !bpf_map_key_poisoned(aux) && 10071 !bpf_map_ptr_poisoned(aux) && 10072 !bpf_map_ptr_unpriv(aux)) { 10073 struct bpf_jit_poke_descriptor desc = { 10074 .reason = BPF_POKE_REASON_TAIL_CALL, 10075 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 10076 .tail_call.key = bpf_map_key_immediate(aux), 10077 }; 10078 10079 ret = bpf_jit_add_poke_descriptor(prog, &desc); 10080 if (ret < 0) { 10081 verbose(env, "adding tail call poke descriptor failed\n"); 10082 return ret; 10083 } 10084 10085 insn->imm = ret + 1; 10086 continue; 10087 } 10088 10089 if (!bpf_map_ptr_unpriv(aux)) 10090 continue; 10091 10092 /* instead of changing every JIT dealing with tail_call 10093 * emit two extra insns: 10094 * if (index >= max_entries) goto out; 10095 * index &= array->index_mask; 10096 * to avoid out-of-bounds cpu speculation 10097 */ 10098 if (bpf_map_ptr_poisoned(aux)) { 10099 verbose(env, "tail_call abusing map_ptr\n"); 10100 return -EINVAL; 10101 } 10102 10103 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 10104 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 10105 map_ptr->max_entries, 2); 10106 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 10107 container_of(map_ptr, 10108 struct bpf_array, 10109 map)->index_mask); 10110 insn_buf[2] = *insn; 10111 cnt = 3; 10112 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 10113 if (!new_prog) 10114 return -ENOMEM; 10115 10116 delta += cnt - 1; 10117 env->prog = prog = new_prog; 10118 insn = new_prog->insnsi + i + delta; 10119 continue; 10120 } 10121 10122 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 10123 * and other inlining handlers are currently limited to 64 bit 10124 * only. 10125 */ 10126 if (prog->jit_requested && BITS_PER_LONG == 64 && 10127 (insn->imm == BPF_FUNC_map_lookup_elem || 10128 insn->imm == BPF_FUNC_map_update_elem || 10129 insn->imm == BPF_FUNC_map_delete_elem || 10130 insn->imm == BPF_FUNC_map_push_elem || 10131 insn->imm == BPF_FUNC_map_pop_elem || 10132 insn->imm == BPF_FUNC_map_peek_elem)) { 10133 aux = &env->insn_aux_data[i + delta]; 10134 if (bpf_map_ptr_poisoned(aux)) 10135 goto patch_call_imm; 10136 10137 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 10138 ops = map_ptr->ops; 10139 if (insn->imm == BPF_FUNC_map_lookup_elem && 10140 ops->map_gen_lookup) { 10141 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 10142 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 10143 verbose(env, "bpf verifier is misconfigured\n"); 10144 return -EINVAL; 10145 } 10146 10147 new_prog = bpf_patch_insn_data(env, i + delta, 10148 insn_buf, cnt); 10149 if (!new_prog) 10150 return -ENOMEM; 10151 10152 delta += cnt - 1; 10153 env->prog = prog = new_prog; 10154 insn = new_prog->insnsi + i + delta; 10155 continue; 10156 } 10157 10158 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 10159 (void *(*)(struct bpf_map *map, void *key))NULL)); 10160 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 10161 (int (*)(struct bpf_map *map, void *key))NULL)); 10162 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 10163 (int (*)(struct bpf_map *map, void *key, void *value, 10164 u64 flags))NULL)); 10165 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 10166 (int (*)(struct bpf_map *map, void *value, 10167 u64 flags))NULL)); 10168 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 10169 (int (*)(struct bpf_map *map, void *value))NULL)); 10170 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 10171 (int (*)(struct bpf_map *map, void *value))NULL)); 10172 10173 switch (insn->imm) { 10174 case BPF_FUNC_map_lookup_elem: 10175 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - 10176 __bpf_call_base; 10177 continue; 10178 case BPF_FUNC_map_update_elem: 10179 insn->imm = BPF_CAST_CALL(ops->map_update_elem) - 10180 __bpf_call_base; 10181 continue; 10182 case BPF_FUNC_map_delete_elem: 10183 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - 10184 __bpf_call_base; 10185 continue; 10186 case BPF_FUNC_map_push_elem: 10187 insn->imm = BPF_CAST_CALL(ops->map_push_elem) - 10188 __bpf_call_base; 10189 continue; 10190 case BPF_FUNC_map_pop_elem: 10191 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) - 10192 __bpf_call_base; 10193 continue; 10194 case BPF_FUNC_map_peek_elem: 10195 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) - 10196 __bpf_call_base; 10197 continue; 10198 } 10199 10200 goto patch_call_imm; 10201 } 10202 10203 if (prog->jit_requested && BITS_PER_LONG == 64 && 10204 insn->imm == BPF_FUNC_jiffies64) { 10205 struct bpf_insn ld_jiffies_addr[2] = { 10206 BPF_LD_IMM64(BPF_REG_0, 10207 (unsigned long)&jiffies), 10208 }; 10209 10210 insn_buf[0] = ld_jiffies_addr[0]; 10211 insn_buf[1] = ld_jiffies_addr[1]; 10212 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 10213 BPF_REG_0, 0); 10214 cnt = 3; 10215 10216 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 10217 cnt); 10218 if (!new_prog) 10219 return -ENOMEM; 10220 10221 delta += cnt - 1; 10222 env->prog = prog = new_prog; 10223 insn = new_prog->insnsi + i + delta; 10224 continue; 10225 } 10226 10227 patch_call_imm: 10228 fn = env->ops->get_func_proto(insn->imm, env->prog); 10229 /* all functions that have prototype and verifier allowed 10230 * programs to call them, must be real in-kernel functions 10231 */ 10232 if (!fn->func) { 10233 verbose(env, 10234 "kernel subsystem misconfigured func %s#%d\n", 10235 func_id_name(insn->imm), insn->imm); 10236 return -EFAULT; 10237 } 10238 insn->imm = fn->func - __bpf_call_base; 10239 } 10240 10241 /* Since poke tab is now finalized, publish aux to tracker. */ 10242 for (i = 0; i < prog->aux->size_poke_tab; i++) { 10243 map_ptr = prog->aux->poke_tab[i].tail_call.map; 10244 if (!map_ptr->ops->map_poke_track || 10245 !map_ptr->ops->map_poke_untrack || 10246 !map_ptr->ops->map_poke_run) { 10247 verbose(env, "bpf verifier is misconfigured\n"); 10248 return -EINVAL; 10249 } 10250 10251 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 10252 if (ret < 0) { 10253 verbose(env, "tracking tail call prog failed\n"); 10254 return ret; 10255 } 10256 } 10257 10258 return 0; 10259 } 10260 10261 static void free_states(struct bpf_verifier_env *env) 10262 { 10263 struct bpf_verifier_state_list *sl, *sln; 10264 int i; 10265 10266 sl = env->free_list; 10267 while (sl) { 10268 sln = sl->next; 10269 free_verifier_state(&sl->state, false); 10270 kfree(sl); 10271 sl = sln; 10272 } 10273 env->free_list = NULL; 10274 10275 if (!env->explored_states) 10276 return; 10277 10278 for (i = 0; i < state_htab_size(env); i++) { 10279 sl = env->explored_states[i]; 10280 10281 while (sl) { 10282 sln = sl->next; 10283 free_verifier_state(&sl->state, false); 10284 kfree(sl); 10285 sl = sln; 10286 } 10287 env->explored_states[i] = NULL; 10288 } 10289 } 10290 10291 /* The verifier is using insn_aux_data[] to store temporary data during 10292 * verification and to store information for passes that run after the 10293 * verification like dead code sanitization. do_check_common() for subprogram N 10294 * may analyze many other subprograms. sanitize_insn_aux_data() clears all 10295 * temporary data after do_check_common() finds that subprogram N cannot be 10296 * verified independently. pass_cnt counts the number of times 10297 * do_check_common() was run and insn->aux->seen tells the pass number 10298 * insn_aux_data was touched. These variables are compared to clear temporary 10299 * data from failed pass. For testing and experiments do_check_common() can be 10300 * run multiple times even when prior attempt to verify is unsuccessful. 10301 */ 10302 static void sanitize_insn_aux_data(struct bpf_verifier_env *env) 10303 { 10304 struct bpf_insn *insn = env->prog->insnsi; 10305 struct bpf_insn_aux_data *aux; 10306 int i, class; 10307 10308 for (i = 0; i < env->prog->len; i++) { 10309 class = BPF_CLASS(insn[i].code); 10310 if (class != BPF_LDX && class != BPF_STX) 10311 continue; 10312 aux = &env->insn_aux_data[i]; 10313 if (aux->seen != env->pass_cnt) 10314 continue; 10315 memset(aux, 0, offsetof(typeof(*aux), orig_idx)); 10316 } 10317 } 10318 10319 static int do_check_common(struct bpf_verifier_env *env, int subprog) 10320 { 10321 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 10322 struct bpf_verifier_state *state; 10323 struct bpf_reg_state *regs; 10324 int ret, i; 10325 10326 env->prev_linfo = NULL; 10327 env->pass_cnt++; 10328 10329 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 10330 if (!state) 10331 return -ENOMEM; 10332 state->curframe = 0; 10333 state->speculative = false; 10334 state->branches = 1; 10335 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 10336 if (!state->frame[0]) { 10337 kfree(state); 10338 return -ENOMEM; 10339 } 10340 env->cur_state = state; 10341 init_func_state(env, state->frame[0], 10342 BPF_MAIN_FUNC /* callsite */, 10343 0 /* frameno */, 10344 subprog); 10345 10346 regs = state->frame[state->curframe]->regs; 10347 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 10348 ret = btf_prepare_func_args(env, subprog, regs); 10349 if (ret) 10350 goto out; 10351 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 10352 if (regs[i].type == PTR_TO_CTX) 10353 mark_reg_known_zero(env, regs, i); 10354 else if (regs[i].type == SCALAR_VALUE) 10355 mark_reg_unknown(env, regs, i); 10356 } 10357 } else { 10358 /* 1st arg to a function */ 10359 regs[BPF_REG_1].type = PTR_TO_CTX; 10360 mark_reg_known_zero(env, regs, BPF_REG_1); 10361 ret = btf_check_func_arg_match(env, subprog, regs); 10362 if (ret == -EFAULT) 10363 /* unlikely verifier bug. abort. 10364 * ret == 0 and ret < 0 are sadly acceptable for 10365 * main() function due to backward compatibility. 10366 * Like socket filter program may be written as: 10367 * int bpf_prog(struct pt_regs *ctx) 10368 * and never dereference that ctx in the program. 10369 * 'struct pt_regs' is a type mismatch for socket 10370 * filter that should be using 'struct __sk_buff'. 10371 */ 10372 goto out; 10373 } 10374 10375 ret = do_check(env); 10376 out: 10377 /* check for NULL is necessary, since cur_state can be freed inside 10378 * do_check() under memory pressure. 10379 */ 10380 if (env->cur_state) { 10381 free_verifier_state(env->cur_state, true); 10382 env->cur_state = NULL; 10383 } 10384 while (!pop_stack(env, NULL, NULL, false)); 10385 if (!ret && pop_log) 10386 bpf_vlog_reset(&env->log, 0); 10387 free_states(env); 10388 if (ret) 10389 /* clean aux data in case subprog was rejected */ 10390 sanitize_insn_aux_data(env); 10391 return ret; 10392 } 10393 10394 /* Verify all global functions in a BPF program one by one based on their BTF. 10395 * All global functions must pass verification. Otherwise the whole program is rejected. 10396 * Consider: 10397 * int bar(int); 10398 * int foo(int f) 10399 * { 10400 * return bar(f); 10401 * } 10402 * int bar(int b) 10403 * { 10404 * ... 10405 * } 10406 * foo() will be verified first for R1=any_scalar_value. During verification it 10407 * will be assumed that bar() already verified successfully and call to bar() 10408 * from foo() will be checked for type match only. Later bar() will be verified 10409 * independently to check that it's safe for R1=any_scalar_value. 10410 */ 10411 static int do_check_subprogs(struct bpf_verifier_env *env) 10412 { 10413 struct bpf_prog_aux *aux = env->prog->aux; 10414 int i, ret; 10415 10416 if (!aux->func_info) 10417 return 0; 10418 10419 for (i = 1; i < env->subprog_cnt; i++) { 10420 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 10421 continue; 10422 env->insn_idx = env->subprog_info[i].start; 10423 WARN_ON_ONCE(env->insn_idx == 0); 10424 ret = do_check_common(env, i); 10425 if (ret) { 10426 return ret; 10427 } else if (env->log.level & BPF_LOG_LEVEL) { 10428 verbose(env, 10429 "Func#%d is safe for any args that match its prototype\n", 10430 i); 10431 } 10432 } 10433 return 0; 10434 } 10435 10436 static int do_check_main(struct bpf_verifier_env *env) 10437 { 10438 int ret; 10439 10440 env->insn_idx = 0; 10441 ret = do_check_common(env, 0); 10442 if (!ret) 10443 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 10444 return ret; 10445 } 10446 10447 10448 static void print_verification_stats(struct bpf_verifier_env *env) 10449 { 10450 int i; 10451 10452 if (env->log.level & BPF_LOG_STATS) { 10453 verbose(env, "verification time %lld usec\n", 10454 div_u64(env->verification_time, 1000)); 10455 verbose(env, "stack depth "); 10456 for (i = 0; i < env->subprog_cnt; i++) { 10457 u32 depth = env->subprog_info[i].stack_depth; 10458 10459 verbose(env, "%d", depth); 10460 if (i + 1 < env->subprog_cnt) 10461 verbose(env, "+"); 10462 } 10463 verbose(env, "\n"); 10464 } 10465 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 10466 "total_states %d peak_states %d mark_read %d\n", 10467 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 10468 env->max_states_per_insn, env->total_states, 10469 env->peak_states, env->longest_mark_read_walk); 10470 } 10471 10472 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 10473 { 10474 const struct btf_type *t, *func_proto; 10475 const struct bpf_struct_ops *st_ops; 10476 const struct btf_member *member; 10477 struct bpf_prog *prog = env->prog; 10478 u32 btf_id, member_idx; 10479 const char *mname; 10480 10481 btf_id = prog->aux->attach_btf_id; 10482 st_ops = bpf_struct_ops_find(btf_id); 10483 if (!st_ops) { 10484 verbose(env, "attach_btf_id %u is not a supported struct\n", 10485 btf_id); 10486 return -ENOTSUPP; 10487 } 10488 10489 t = st_ops->type; 10490 member_idx = prog->expected_attach_type; 10491 if (member_idx >= btf_type_vlen(t)) { 10492 verbose(env, "attach to invalid member idx %u of struct %s\n", 10493 member_idx, st_ops->name); 10494 return -EINVAL; 10495 } 10496 10497 member = &btf_type_member(t)[member_idx]; 10498 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 10499 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 10500 NULL); 10501 if (!func_proto) { 10502 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 10503 mname, member_idx, st_ops->name); 10504 return -EINVAL; 10505 } 10506 10507 if (st_ops->check_member) { 10508 int err = st_ops->check_member(t, member); 10509 10510 if (err) { 10511 verbose(env, "attach to unsupported member %s of struct %s\n", 10512 mname, st_ops->name); 10513 return err; 10514 } 10515 } 10516 10517 prog->aux->attach_func_proto = func_proto; 10518 prog->aux->attach_func_name = mname; 10519 env->ops = st_ops->verifier_ops; 10520 10521 return 0; 10522 } 10523 #define SECURITY_PREFIX "security_" 10524 10525 static int check_attach_modify_return(struct bpf_verifier_env *env) 10526 { 10527 struct bpf_prog *prog = env->prog; 10528 unsigned long addr = (unsigned long) prog->aux->trampoline->func.addr; 10529 10530 /* This is expected to be cleaned up in the future with the KRSI effort 10531 * introducing the LSM_HOOK macro for cleaning up lsm_hooks.h. 10532 */ 10533 if (within_error_injection_list(addr) || 10534 !strncmp(SECURITY_PREFIX, prog->aux->attach_func_name, 10535 sizeof(SECURITY_PREFIX) - 1)) 10536 return 0; 10537 10538 verbose(env, "fmod_ret attach_btf_id %u (%s) is not modifiable\n", 10539 prog->aux->attach_btf_id, prog->aux->attach_func_name); 10540 10541 return -EINVAL; 10542 } 10543 10544 static int check_attach_btf_id(struct bpf_verifier_env *env) 10545 { 10546 struct bpf_prog *prog = env->prog; 10547 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 10548 struct bpf_prog *tgt_prog = prog->aux->linked_prog; 10549 u32 btf_id = prog->aux->attach_btf_id; 10550 const char prefix[] = "btf_trace_"; 10551 struct btf_func_model fmodel; 10552 int ret = 0, subprog = -1, i; 10553 struct bpf_trampoline *tr; 10554 const struct btf_type *t; 10555 bool conservative = true; 10556 const char *tname; 10557 struct btf *btf; 10558 long addr; 10559 u64 key; 10560 10561 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 10562 return check_struct_ops_btf_id(env); 10563 10564 if (prog->type != BPF_PROG_TYPE_TRACING && 10565 prog->type != BPF_PROG_TYPE_LSM && 10566 !prog_extension) 10567 return 0; 10568 10569 if (!btf_id) { 10570 verbose(env, "Tracing programs must provide btf_id\n"); 10571 return -EINVAL; 10572 } 10573 btf = bpf_prog_get_target_btf(prog); 10574 if (!btf) { 10575 verbose(env, 10576 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 10577 return -EINVAL; 10578 } 10579 t = btf_type_by_id(btf, btf_id); 10580 if (!t) { 10581 verbose(env, "attach_btf_id %u is invalid\n", btf_id); 10582 return -EINVAL; 10583 } 10584 tname = btf_name_by_offset(btf, t->name_off); 10585 if (!tname) { 10586 verbose(env, "attach_btf_id %u doesn't have a name\n", btf_id); 10587 return -EINVAL; 10588 } 10589 if (tgt_prog) { 10590 struct bpf_prog_aux *aux = tgt_prog->aux; 10591 10592 for (i = 0; i < aux->func_info_cnt; i++) 10593 if (aux->func_info[i].type_id == btf_id) { 10594 subprog = i; 10595 break; 10596 } 10597 if (subprog == -1) { 10598 verbose(env, "Subprog %s doesn't exist\n", tname); 10599 return -EINVAL; 10600 } 10601 conservative = aux->func_info_aux[subprog].unreliable; 10602 if (prog_extension) { 10603 if (conservative) { 10604 verbose(env, 10605 "Cannot replace static functions\n"); 10606 return -EINVAL; 10607 } 10608 if (!prog->jit_requested) { 10609 verbose(env, 10610 "Extension programs should be JITed\n"); 10611 return -EINVAL; 10612 } 10613 env->ops = bpf_verifier_ops[tgt_prog->type]; 10614 prog->expected_attach_type = tgt_prog->expected_attach_type; 10615 } 10616 if (!tgt_prog->jited) { 10617 verbose(env, "Can attach to only JITed progs\n"); 10618 return -EINVAL; 10619 } 10620 if (tgt_prog->type == prog->type) { 10621 /* Cannot fentry/fexit another fentry/fexit program. 10622 * Cannot attach program extension to another extension. 10623 * It's ok to attach fentry/fexit to extension program. 10624 */ 10625 verbose(env, "Cannot recursively attach\n"); 10626 return -EINVAL; 10627 } 10628 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 10629 prog_extension && 10630 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 10631 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 10632 /* Program extensions can extend all program types 10633 * except fentry/fexit. The reason is the following. 10634 * The fentry/fexit programs are used for performance 10635 * analysis, stats and can be attached to any program 10636 * type except themselves. When extension program is 10637 * replacing XDP function it is necessary to allow 10638 * performance analysis of all functions. Both original 10639 * XDP program and its program extension. Hence 10640 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 10641 * allowed. If extending of fentry/fexit was allowed it 10642 * would be possible to create long call chain 10643 * fentry->extension->fentry->extension beyond 10644 * reasonable stack size. Hence extending fentry is not 10645 * allowed. 10646 */ 10647 verbose(env, "Cannot extend fentry/fexit\n"); 10648 return -EINVAL; 10649 } 10650 key = ((u64)aux->id) << 32 | btf_id; 10651 } else { 10652 if (prog_extension) { 10653 verbose(env, "Cannot replace kernel functions\n"); 10654 return -EINVAL; 10655 } 10656 key = btf_id; 10657 } 10658 10659 switch (prog->expected_attach_type) { 10660 case BPF_TRACE_RAW_TP: 10661 if (tgt_prog) { 10662 verbose(env, 10663 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 10664 return -EINVAL; 10665 } 10666 if (!btf_type_is_typedef(t)) { 10667 verbose(env, "attach_btf_id %u is not a typedef\n", 10668 btf_id); 10669 return -EINVAL; 10670 } 10671 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 10672 verbose(env, "attach_btf_id %u points to wrong type name %s\n", 10673 btf_id, tname); 10674 return -EINVAL; 10675 } 10676 tname += sizeof(prefix) - 1; 10677 t = btf_type_by_id(btf, t->type); 10678 if (!btf_type_is_ptr(t)) 10679 /* should never happen in valid vmlinux build */ 10680 return -EINVAL; 10681 t = btf_type_by_id(btf, t->type); 10682 if (!btf_type_is_func_proto(t)) 10683 /* should never happen in valid vmlinux build */ 10684 return -EINVAL; 10685 10686 /* remember two read only pointers that are valid for 10687 * the life time of the kernel 10688 */ 10689 prog->aux->attach_func_name = tname; 10690 prog->aux->attach_func_proto = t; 10691 prog->aux->attach_btf_trace = true; 10692 return 0; 10693 case BPF_TRACE_ITER: 10694 if (!btf_type_is_func(t)) { 10695 verbose(env, "attach_btf_id %u is not a function\n", 10696 btf_id); 10697 return -EINVAL; 10698 } 10699 t = btf_type_by_id(btf, t->type); 10700 if (!btf_type_is_func_proto(t)) 10701 return -EINVAL; 10702 prog->aux->attach_func_name = tname; 10703 prog->aux->attach_func_proto = t; 10704 if (!bpf_iter_prog_supported(prog)) 10705 return -EINVAL; 10706 ret = btf_distill_func_proto(&env->log, btf, t, 10707 tname, &fmodel); 10708 return ret; 10709 default: 10710 if (!prog_extension) 10711 return -EINVAL; 10712 /* fallthrough */ 10713 case BPF_MODIFY_RETURN: 10714 case BPF_LSM_MAC: 10715 case BPF_TRACE_FENTRY: 10716 case BPF_TRACE_FEXIT: 10717 prog->aux->attach_func_name = tname; 10718 if (prog->type == BPF_PROG_TYPE_LSM) { 10719 ret = bpf_lsm_verify_prog(&env->log, prog); 10720 if (ret < 0) 10721 return ret; 10722 } 10723 10724 if (!btf_type_is_func(t)) { 10725 verbose(env, "attach_btf_id %u is not a function\n", 10726 btf_id); 10727 return -EINVAL; 10728 } 10729 if (prog_extension && 10730 btf_check_type_match(env, prog, btf, t)) 10731 return -EINVAL; 10732 t = btf_type_by_id(btf, t->type); 10733 if (!btf_type_is_func_proto(t)) 10734 return -EINVAL; 10735 tr = bpf_trampoline_lookup(key); 10736 if (!tr) 10737 return -ENOMEM; 10738 /* t is either vmlinux type or another program's type */ 10739 prog->aux->attach_func_proto = t; 10740 mutex_lock(&tr->mutex); 10741 if (tr->func.addr) { 10742 prog->aux->trampoline = tr; 10743 goto out; 10744 } 10745 if (tgt_prog && conservative) { 10746 prog->aux->attach_func_proto = NULL; 10747 t = NULL; 10748 } 10749 ret = btf_distill_func_proto(&env->log, btf, t, 10750 tname, &tr->func.model); 10751 if (ret < 0) 10752 goto out; 10753 if (tgt_prog) { 10754 if (subprog == 0) 10755 addr = (long) tgt_prog->bpf_func; 10756 else 10757 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 10758 } else { 10759 addr = kallsyms_lookup_name(tname); 10760 if (!addr) { 10761 verbose(env, 10762 "The address of function %s cannot be found\n", 10763 tname); 10764 ret = -ENOENT; 10765 goto out; 10766 } 10767 } 10768 tr->func.addr = (void *)addr; 10769 prog->aux->trampoline = tr; 10770 10771 if (prog->expected_attach_type == BPF_MODIFY_RETURN) 10772 ret = check_attach_modify_return(env); 10773 out: 10774 mutex_unlock(&tr->mutex); 10775 if (ret) 10776 bpf_trampoline_put(tr); 10777 return ret; 10778 } 10779 } 10780 10781 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, 10782 union bpf_attr __user *uattr) 10783 { 10784 u64 start_time = ktime_get_ns(); 10785 struct bpf_verifier_env *env; 10786 struct bpf_verifier_log *log; 10787 int i, len, ret = -EINVAL; 10788 bool is_priv; 10789 10790 /* no program is valid */ 10791 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 10792 return -EINVAL; 10793 10794 /* 'struct bpf_verifier_env' can be global, but since it's not small, 10795 * allocate/free it every time bpf_check() is called 10796 */ 10797 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 10798 if (!env) 10799 return -ENOMEM; 10800 log = &env->log; 10801 10802 len = (*prog)->len; 10803 env->insn_aux_data = 10804 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 10805 ret = -ENOMEM; 10806 if (!env->insn_aux_data) 10807 goto err_free_env; 10808 for (i = 0; i < len; i++) 10809 env->insn_aux_data[i].orig_idx = i; 10810 env->prog = *prog; 10811 env->ops = bpf_verifier_ops[env->prog->type]; 10812 is_priv = bpf_capable(); 10813 10814 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 10815 mutex_lock(&bpf_verifier_lock); 10816 if (!btf_vmlinux) 10817 btf_vmlinux = btf_parse_vmlinux(); 10818 mutex_unlock(&bpf_verifier_lock); 10819 } 10820 10821 /* grab the mutex to protect few globals used by verifier */ 10822 if (!is_priv) 10823 mutex_lock(&bpf_verifier_lock); 10824 10825 if (attr->log_level || attr->log_buf || attr->log_size) { 10826 /* user requested verbose verifier output 10827 * and supplied buffer to store the verification trace 10828 */ 10829 log->level = attr->log_level; 10830 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 10831 log->len_total = attr->log_size; 10832 10833 ret = -EINVAL; 10834 /* log attributes have to be sane */ 10835 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 || 10836 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK) 10837 goto err_unlock; 10838 } 10839 10840 if (IS_ERR(btf_vmlinux)) { 10841 /* Either gcc or pahole or kernel are broken. */ 10842 verbose(env, "in-kernel BTF is malformed\n"); 10843 ret = PTR_ERR(btf_vmlinux); 10844 goto skip_full_check; 10845 } 10846 10847 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 10848 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 10849 env->strict_alignment = true; 10850 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 10851 env->strict_alignment = false; 10852 10853 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 10854 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 10855 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 10856 env->bpf_capable = bpf_capable(); 10857 10858 if (is_priv) 10859 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 10860 10861 ret = replace_map_fd_with_map_ptr(env); 10862 if (ret < 0) 10863 goto skip_full_check; 10864 10865 if (bpf_prog_is_dev_bound(env->prog->aux)) { 10866 ret = bpf_prog_offload_verifier_prep(env->prog); 10867 if (ret) 10868 goto skip_full_check; 10869 } 10870 10871 env->explored_states = kvcalloc(state_htab_size(env), 10872 sizeof(struct bpf_verifier_state_list *), 10873 GFP_USER); 10874 ret = -ENOMEM; 10875 if (!env->explored_states) 10876 goto skip_full_check; 10877 10878 ret = check_subprogs(env); 10879 if (ret < 0) 10880 goto skip_full_check; 10881 10882 ret = check_btf_info(env, attr, uattr); 10883 if (ret < 0) 10884 goto skip_full_check; 10885 10886 ret = check_attach_btf_id(env); 10887 if (ret) 10888 goto skip_full_check; 10889 10890 ret = check_cfg(env); 10891 if (ret < 0) 10892 goto skip_full_check; 10893 10894 ret = do_check_subprogs(env); 10895 ret = ret ?: do_check_main(env); 10896 10897 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux)) 10898 ret = bpf_prog_offload_finalize(env); 10899 10900 skip_full_check: 10901 kvfree(env->explored_states); 10902 10903 if (ret == 0) 10904 ret = check_max_stack_depth(env); 10905 10906 /* instruction rewrites happen after this point */ 10907 if (is_priv) { 10908 if (ret == 0) 10909 opt_hard_wire_dead_code_branches(env); 10910 if (ret == 0) 10911 ret = opt_remove_dead_code(env); 10912 if (ret == 0) 10913 ret = opt_remove_nops(env); 10914 } else { 10915 if (ret == 0) 10916 sanitize_dead_code(env); 10917 } 10918 10919 if (ret == 0) 10920 /* program is valid, convert *(u32*)(ctx + off) accesses */ 10921 ret = convert_ctx_accesses(env); 10922 10923 if (ret == 0) 10924 ret = fixup_bpf_calls(env); 10925 10926 /* do 32-bit optimization after insn patching has done so those patched 10927 * insns could be handled correctly. 10928 */ 10929 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) { 10930 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 10931 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 10932 : false; 10933 } 10934 10935 if (ret == 0) 10936 ret = fixup_call_args(env); 10937 10938 env->verification_time = ktime_get_ns() - start_time; 10939 print_verification_stats(env); 10940 10941 if (log->level && bpf_verifier_log_full(log)) 10942 ret = -ENOSPC; 10943 if (log->level && !log->ubuf) { 10944 ret = -EFAULT; 10945 goto err_release_maps; 10946 } 10947 10948 if (ret == 0 && env->used_map_cnt) { 10949 /* if program passed verifier, update used_maps in bpf_prog_info */ 10950 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 10951 sizeof(env->used_maps[0]), 10952 GFP_KERNEL); 10953 10954 if (!env->prog->aux->used_maps) { 10955 ret = -ENOMEM; 10956 goto err_release_maps; 10957 } 10958 10959 memcpy(env->prog->aux->used_maps, env->used_maps, 10960 sizeof(env->used_maps[0]) * env->used_map_cnt); 10961 env->prog->aux->used_map_cnt = env->used_map_cnt; 10962 10963 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 10964 * bpf_ld_imm64 instructions 10965 */ 10966 convert_pseudo_ld_imm64(env); 10967 } 10968 10969 if (ret == 0) 10970 adjust_btf_func(env); 10971 10972 err_release_maps: 10973 if (!env->prog->aux->used_maps) 10974 /* if we didn't copy map pointers into bpf_prog_info, release 10975 * them now. Otherwise free_used_maps() will release them. 10976 */ 10977 release_maps(env); 10978 10979 /* extension progs temporarily inherit the attach_type of their targets 10980 for verification purposes, so set it back to zero before returning 10981 */ 10982 if (env->prog->type == BPF_PROG_TYPE_EXT) 10983 env->prog->expected_attach_type = 0; 10984 10985 *prog = env->prog; 10986 err_unlock: 10987 if (!is_priv) 10988 mutex_unlock(&bpf_verifier_lock); 10989 vfree(env->insn_aux_data); 10990 err_free_env: 10991 kfree(env); 10992 return ret; 10993 } 10994