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