1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */ 3 #include <linux/bpf.h> 4 #include <linux/bpf_verifier.h> 5 #include <linux/cnum.h> 6 #include <linux/filter.h> 7 8 #define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args) 9 10 #define BPF_COMPLEXITY_LIMIT_STATES 64 11 12 static bool is_may_goto_insn_at(struct bpf_verifier_env *env, int insn_idx) 13 { 14 return bpf_is_may_goto_insn(&env->prog->insnsi[insn_idx]); 15 } 16 17 static bool is_iter_next_insn(struct bpf_verifier_env *env, int insn_idx) 18 { 19 return env->insn_aux_data[insn_idx].is_iter_next; 20 } 21 22 static void update_peak_states(struct bpf_verifier_env *env) 23 { 24 u32 cur_states; 25 26 cur_states = env->explored_states_size + env->free_list_size + env->num_backedges; 27 env->peak_states = max(env->peak_states, cur_states); 28 } 29 30 /* struct bpf_verifier_state->parent refers to states 31 * that are in either of env->{expored_states,free_list}. 32 * In both cases the state is contained in struct bpf_verifier_state_list. 33 */ 34 static struct bpf_verifier_state_list *state_parent_as_list(struct bpf_verifier_state *st) 35 { 36 if (st->parent) 37 return container_of(st->parent, struct bpf_verifier_state_list, state); 38 return NULL; 39 } 40 41 static bool incomplete_read_marks(struct bpf_verifier_env *env, 42 struct bpf_verifier_state *st); 43 44 /* A state can be freed if it is no longer referenced: 45 * - is in the env->free_list; 46 * - has no children states; 47 */ 48 static void maybe_free_verifier_state(struct bpf_verifier_env *env, 49 struct bpf_verifier_state_list *sl) 50 { 51 if (!sl->in_free_list 52 || sl->state.branches != 0 53 || incomplete_read_marks(env, &sl->state)) 54 return; 55 list_del(&sl->node); 56 bpf_free_verifier_state(&sl->state, false); 57 kfree(sl); 58 env->free_list_size--; 59 } 60 61 /* For state @st look for a topmost frame with frame_insn_idx() in some SCC, 62 * if such frame exists form a corresponding @callchain as an array of 63 * call sites leading to this frame and SCC id. 64 * E.g.: 65 * 66 * void foo() { A: loop {... SCC#1 ...}; } 67 * void bar() { B: loop { C: foo(); ... SCC#2 ... } 68 * D: loop { E: foo(); ... SCC#3 ... } } 69 * void main() { F: bar(); } 70 * 71 * @callchain at (A) would be either (F,SCC#2) or (F,SCC#3) depending 72 * on @st frame call sites being (F,C,A) or (F,E,A). 73 */ 74 static bool compute_scc_callchain(struct bpf_verifier_env *env, 75 struct bpf_verifier_state *st, 76 struct bpf_scc_callchain *callchain) 77 { 78 u32 i, scc, insn_idx; 79 80 memset(callchain, 0, sizeof(*callchain)); 81 for (i = 0; i <= st->curframe; i++) { 82 insn_idx = bpf_frame_insn_idx(st, i); 83 scc = env->insn_aux_data[insn_idx].scc; 84 if (scc) { 85 callchain->scc = scc; 86 break; 87 } else if (i < st->curframe) { 88 callchain->callsites[i] = insn_idx; 89 } else { 90 return false; 91 } 92 } 93 return true; 94 } 95 96 /* Check if bpf_scc_visit instance for @callchain exists. */ 97 static struct bpf_scc_visit *scc_visit_lookup(struct bpf_verifier_env *env, 98 struct bpf_scc_callchain *callchain) 99 { 100 struct bpf_scc_info *info = env->scc_info[callchain->scc]; 101 struct bpf_scc_visit *visits = info->visits; 102 u32 i; 103 104 if (!info) 105 return NULL; 106 for (i = 0; i < info->num_visits; i++) 107 if (memcmp(callchain, &visits[i].callchain, sizeof(*callchain)) == 0) 108 return &visits[i]; 109 return NULL; 110 } 111 112 /* Allocate a new bpf_scc_visit instance corresponding to @callchain. 113 * Allocated instances are alive for a duration of the do_check_common() 114 * call and are freed by free_states(). 115 */ 116 static struct bpf_scc_visit *scc_visit_alloc(struct bpf_verifier_env *env, 117 struct bpf_scc_callchain *callchain) 118 { 119 struct bpf_scc_visit *visit; 120 struct bpf_scc_info *info; 121 u32 scc, num_visits; 122 u64 new_sz; 123 124 scc = callchain->scc; 125 info = env->scc_info[scc]; 126 num_visits = info ? info->num_visits : 0; 127 new_sz = sizeof(*info) + sizeof(struct bpf_scc_visit) * (num_visits + 1); 128 info = kvrealloc(env->scc_info[scc], new_sz, GFP_KERNEL_ACCOUNT); 129 if (!info) 130 return NULL; 131 env->scc_info[scc] = info; 132 info->num_visits = num_visits + 1; 133 visit = &info->visits[num_visits]; 134 memset(visit, 0, sizeof(*visit)); 135 memcpy(&visit->callchain, callchain, sizeof(*callchain)); 136 return visit; 137 } 138 139 /* Form a string '(callsite#1,callsite#2,...,scc)' in env->tmp_str_buf */ 140 static char *format_callchain(struct bpf_verifier_env *env, struct bpf_scc_callchain *callchain) 141 { 142 char *buf = env->tmp_str_buf; 143 int i, delta = 0; 144 145 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "("); 146 for (i = 0; i < ARRAY_SIZE(callchain->callsites); i++) { 147 if (!callchain->callsites[i]) 148 break; 149 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u,", 150 callchain->callsites[i]); 151 } 152 delta += snprintf(buf + delta, TMP_STR_BUF_LEN - delta, "%u)", callchain->scc); 153 return env->tmp_str_buf; 154 } 155 156 /* If callchain for @st exists (@st is in some SCC), ensure that 157 * bpf_scc_visit instance for this callchain exists. 158 * If instance does not exist or is empty, assign visit->entry_state to @st. 159 */ 160 static int maybe_enter_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 161 { 162 struct bpf_scc_callchain *callchain = &env->callchain_buf; 163 struct bpf_scc_visit *visit; 164 165 if (!compute_scc_callchain(env, st, callchain)) 166 return 0; 167 visit = scc_visit_lookup(env, callchain); 168 visit = visit ?: scc_visit_alloc(env, callchain); 169 if (!visit) 170 return -ENOMEM; 171 if (!visit->entry_state) { 172 visit->entry_state = st; 173 if (env->log.level & BPF_LOG_LEVEL2) 174 verbose(env, "SCC enter %s\n", format_callchain(env, callchain)); 175 } 176 return 0; 177 } 178 179 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit); 180 181 /* If callchain for @st exists (@st is in some SCC), make it empty: 182 * - set visit->entry_state to NULL; 183 * - flush accumulated backedges. 184 */ 185 static int maybe_exit_scc(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 186 { 187 struct bpf_scc_callchain *callchain = &env->callchain_buf; 188 struct bpf_scc_visit *visit; 189 190 if (!compute_scc_callchain(env, st, callchain)) 191 return 0; 192 visit = scc_visit_lookup(env, callchain); 193 if (!visit) { 194 /* 195 * If path traversal stops inside an SCC, corresponding bpf_scc_visit 196 * must exist for non-speculative paths. For non-speculative paths 197 * traversal stops when: 198 * a. Verification error is found, maybe_exit_scc() is not called. 199 * b. Top level BPF_EXIT is reached. Top level BPF_EXIT is not a member 200 * of any SCC. 201 * c. A checkpoint is reached and matched. Checkpoints are created by 202 * is_state_visited(), which calls maybe_enter_scc(), which allocates 203 * bpf_scc_visit instances for checkpoints within SCCs. 204 * (c) is the only case that can reach this point. 205 */ 206 if (!st->speculative) { 207 verifier_bug(env, "scc exit: no visit info for call chain %s", 208 format_callchain(env, callchain)); 209 return -EFAULT; 210 } 211 return 0; 212 } 213 if (visit->entry_state != st) 214 return 0; 215 if (env->log.level & BPF_LOG_LEVEL2) 216 verbose(env, "SCC exit %s\n", format_callchain(env, callchain)); 217 visit->entry_state = NULL; 218 env->num_backedges -= visit->num_backedges; 219 visit->num_backedges = 0; 220 update_peak_states(env); 221 return propagate_backedges(env, visit); 222 } 223 224 /* Lookup an bpf_scc_visit instance corresponding to @st callchain 225 * and add @backedge to visit->backedges. @st callchain must exist. 226 */ 227 static int add_scc_backedge(struct bpf_verifier_env *env, 228 struct bpf_verifier_state *st, 229 struct bpf_scc_backedge *backedge) 230 { 231 struct bpf_scc_callchain *callchain = &env->callchain_buf; 232 struct bpf_scc_visit *visit; 233 234 if (!compute_scc_callchain(env, st, callchain)) { 235 verifier_bug(env, "add backedge: no SCC in verification path, insn_idx %d", 236 st->insn_idx); 237 return -EFAULT; 238 } 239 visit = scc_visit_lookup(env, callchain); 240 if (!visit) { 241 verifier_bug(env, "add backedge: no visit info for call chain %s", 242 format_callchain(env, callchain)); 243 return -EFAULT; 244 } 245 if (env->log.level & BPF_LOG_LEVEL2) 246 verbose(env, "SCC backedge %s\n", format_callchain(env, callchain)); 247 backedge->next = visit->backedges; 248 visit->backedges = backedge; 249 visit->num_backedges++; 250 env->num_backedges++; 251 update_peak_states(env); 252 return 0; 253 } 254 255 /* bpf_reg_state->live marks for registers in a state @st are incomplete, 256 * if state @st is in some SCC and not all execution paths starting at this 257 * SCC are fully explored. 258 */ 259 static bool incomplete_read_marks(struct bpf_verifier_env *env, 260 struct bpf_verifier_state *st) 261 { 262 struct bpf_scc_callchain *callchain = &env->callchain_buf; 263 struct bpf_scc_visit *visit; 264 265 if (!compute_scc_callchain(env, st, callchain)) 266 return false; 267 visit = scc_visit_lookup(env, callchain); 268 if (!visit) 269 return false; 270 return !!visit->backedges; 271 } 272 273 int bpf_update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 274 { 275 struct bpf_verifier_state_list *sl = NULL, *parent_sl; 276 struct bpf_verifier_state *parent; 277 int err; 278 279 while (st) { 280 u32 br = --st->branches; 281 282 /* verifier_bug_if(br > 1, ...) technically makes sense here, 283 * but see comment in push_stack(), hence: 284 */ 285 verifier_bug_if((int)br < 0, env, "%s:branches_to_explore=%d", __func__, br); 286 if (br) 287 break; 288 err = maybe_exit_scc(env, st); 289 if (err) 290 return err; 291 parent = st->parent; 292 parent_sl = state_parent_as_list(st); 293 if (sl) 294 maybe_free_verifier_state(env, sl); 295 st = parent; 296 sl = parent_sl; 297 } 298 return 0; 299 } 300 301 /* check %cur's range satisfies %old's */ 302 static bool range_within(const struct bpf_reg_state *old, 303 const struct bpf_reg_state *cur) 304 { 305 if (!cnum64_is_subset(old->r64, cur->r64) || 306 !cnum32_is_subset(old->r32, cur->r32)) 307 return false; 308 309 if (old->step <= 1) 310 return true; 311 312 if (cnum64_is_const(cur->r64)) 313 return imod((s64)cnum64_smin(cur->r64), old->step) == old->base; 314 315 /* 316 * Both `old` and `cur` define some sets of points. 317 * Return true, if points defined by `cur` are a subset of points defined by `old`: 318 * - bounds for `cur` should be within bounds for `old`; 319 * - cur->step should be dividable by old->step; 320 * - cur->base should start at integer number of old->step 321 * steps from old->base. 322 * 323 * E.g. the following ranges are compatible: 324 * - old [0, 10] step 2 325 * - new [2, 10] step 4 326 */ 327 return cur->step % old->step == 0 && 328 (cur->base - old->base) % old->step == 0; 329 } 330 331 /* If in the old state two registers had the same id, then they need to have 332 * the same id in the new state as well. But that id could be different from 333 * the old state, so we need to track the mapping from old to new ids. 334 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 335 * regs with old id 5 must also have new id 9 for the new state to be safe. But 336 * regs with a different old id could still have new id 9, we don't care about 337 * that. 338 * So we look through our idmap to see if this old id has been seen before. If 339 * so, we require the new id to match; otherwise, we add the id pair to the map. 340 */ 341 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 342 { 343 struct bpf_id_pair *map = idmap->map; 344 unsigned int i; 345 346 /* either both IDs should be set or both should be zero */ 347 if (!!old_id != !!cur_id) 348 return false; 349 350 if (old_id == 0) /* cur_id == 0 as well */ 351 return true; 352 353 for (i = 0; i < idmap->cnt; i++) { 354 if (map[i].old == old_id) 355 return map[i].cur == cur_id; 356 if (map[i].cur == cur_id) 357 return false; 358 } 359 360 /* Reached the end of known mappings; haven't seen this id before */ 361 if (idmap->cnt < BPF_ID_MAP_SIZE) { 362 map[idmap->cnt].old = old_id; 363 map[idmap->cnt].cur = cur_id; 364 idmap->cnt++; 365 return true; 366 } 367 368 /* 369 * idmap slots are bounded by the number of registers and stack slots. 370 * Since referenced dynptrs acquire intermediate references that do 371 * not live in either, so the map can be exhausted. Since it is unlikely, 372 * fail the verification by treating the states as not equivalent. 373 */ 374 return false; 375 } 376 377 /* 378 * Compare scalar register IDs for state equivalence. 379 * 380 * When old_id == 0, the old register is independent - not linked to any 381 * other register. Any linking in the current state only adds constraints, 382 * making it more restrictive. Since the old state didn't rely on any ID 383 * relationships for this register, it's always safe to accept cur regardless 384 * of its ID. Hence, return true immediately. 385 * 386 * When old_id != 0 but cur_id == 0, we need to ensure that different 387 * independent registers in cur don't incorrectly satisfy the ID matching 388 * requirements of linked registers in old. 389 * 390 * Example: if old has r6.id=X and r7.id=X (linked), but cur has r6.id=0 391 * and r7.id=0 (both independent), without temp IDs both would map old_id=X 392 * to cur_id=0 and pass. With temp IDs: r6 maps X->temp1, r7 tries to map 393 * X->temp2, but X is already mapped to temp1, so the check fails correctly. 394 * 395 * When old_id has BPF_ADD_CONST set, the compound id (base | flag) and the 396 * base id (flag stripped) must both map consistently. Example: old has 397 * r2.id=A, r3.id=A|flag (r3 = r2 + delta), cur has r2.id=B, r3.id=C|flag 398 * (r3 derived from unrelated r4). Without the base check, idmap gets two 399 * independent entries A->B and A|flag->C|flag, missing that A->C conflicts 400 * with A->B. The base ID cross-check catches this. 401 */ 402 static bool check_scalar_ids(u32 old_id, u32 cur_id, struct bpf_idmap *idmap) 403 { 404 if (!old_id) 405 return true; 406 407 cur_id = cur_id ? cur_id : ++idmap->tmp_id_gen; 408 409 if (!check_ids(old_id, cur_id, idmap)) 410 return false; 411 if (old_id & BPF_ADD_CONST) { 412 old_id &= ~BPF_ADD_CONST; 413 cur_id &= ~BPF_ADD_CONST; 414 if (!check_ids(old_id, cur_id, idmap)) 415 return false; 416 } 417 return true; 418 } 419 420 static void __clean_func_state(struct bpf_verifier_env *env, 421 struct bpf_func_state *st, 422 u16 live_regs, int frame) 423 { 424 int i, j; 425 426 for (i = 0; i < BPF_REG_FP; i++) { 427 /* liveness must not touch this register anymore */ 428 if (!(live_regs & BIT(i))) 429 /* since the register is unused, clear its state 430 * to make further comparison simpler 431 */ 432 bpf_mark_reg_not_init(env, &st->regs[i]); 433 } 434 435 /* 436 * Clean dead 4-byte halves within each SPI independently. 437 * half_spi 2*i → lower half: slot_type[0..3] (closer to FP) 438 * half_spi 2*i+1 → upper half: slot_type[4..7] (farther from FP) 439 */ 440 for (i = 0; i < bpf_stack_nr_slots(st); i++) { 441 bool lo_live = bpf_stack_slot_alive(env, frame, i * 2); 442 bool hi_live = bpf_stack_slot_alive(env, frame, i * 2 + 1); 443 444 if (!hi_live || !lo_live) { 445 int start = !lo_live ? 0 : BPF_REG_SIZE / 2; 446 int end = !hi_live ? BPF_REG_SIZE : BPF_REG_SIZE / 2; 447 u8 stype = bpf_stack_slot(st, i)->slot_type[7]; 448 449 /* 450 * Don't clear special slots. 451 * destroy_if_dynptr_stack_slot() needs STACK_DYNPTR to 452 * detect overwrites and invalidate associated data slices. 453 * is_iter_reg_valid_uninit() and is_irq_flag_reg_valid_uninit() 454 * check for their respective slot types to detect double-create. 455 */ 456 if (stype == STACK_DYNPTR || stype == STACK_ITER || 457 stype == STACK_IRQ_FLAG) 458 continue; 459 460 /* 461 * Only scalar spills can be degraded to raw stack bytes 462 * when their high half is dead. Pointer spills need the 463 * saved spilled_ptr metadata so partial fills keep 464 * rejecting as non-scalar register fills. 465 */ 466 if (!hi_live) { 467 struct bpf_reg_state *spill = &bpf_stack_slot(st, i)->spilled_ptr; 468 469 if (lo_live && stype == STACK_SPILL) { 470 if (spill->type != SCALAR_VALUE) 471 continue; 472 /* 473 * Can't replace with STACK_ZERO, because 474 * that requires bpf_mark_chain_precision(). 475 */ 476 if (bpf_register_is_null(spill)) 477 continue; 478 for (j = 0; j < 4; j++) { 479 u8 *t = &bpf_stack_slot(st, i)->slot_type[j]; 480 481 if (*t == STACK_SPILL) 482 *t = STACK_MISC; 483 } 484 } 485 bpf_mark_reg_not_init(env, spill); 486 } 487 for (j = start; j < end; j++) 488 bpf_stack_slot(st, i)->slot_type[j] = STACK_POISON; 489 } 490 } 491 } 492 493 static int clean_verifier_state(struct bpf_verifier_env *env, 494 struct bpf_verifier_state *st) 495 { 496 int i, err; 497 498 err = bpf_live_stack_query_init(env, st); 499 if (err) 500 return err; 501 for (i = 0; i <= st->curframe; i++) { 502 u32 ip = bpf_frame_insn_idx(st, i); 503 u16 live_regs = env->insn_aux_data[ip].live_regs_before; 504 505 __clean_func_state(env, st->frame[i], live_regs, i); 506 } 507 return 0; 508 } 509 510 static bool regs_exact(const struct bpf_reg_state *rold, 511 const struct bpf_reg_state *rcur, 512 struct bpf_idmap *idmap) 513 { 514 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 515 check_ids(rold->id, rcur->id, idmap) && 516 check_ids(rold->parent_id, rcur->parent_id, idmap) && 517 check_ids(rold->map_uid, rcur->map_uid, idmap); 518 } 519 520 enum exact_level { 521 NOT_EXACT, 522 EXACT, 523 RANGE_WITHIN 524 }; 525 526 /* Returns true if (rold safe implies rcur safe) */ 527 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 528 struct bpf_reg_state *rcur, struct bpf_idmap *idmap, 529 enum exact_level exact) 530 { 531 if (exact == EXACT) 532 return regs_exact(rold, rcur, idmap); 533 534 if (rold->type == NOT_INIT) 535 /* explored state can't have used this */ 536 return true; 537 538 /* Enforce that register types have to match exactly, including their 539 * modifiers (like PTR_MAYBE_NULL, MEM_RDONLY, etc), as a general 540 * rule. 541 * 542 * One can make a point that using a pointer register as unbounded 543 * SCALAR would be technically acceptable, but this could lead to 544 * pointer leaks because scalars are allowed to leak while pointers 545 * are not. We could make this safe in special cases if root is 546 * calling us, but it's probably not worth the hassle. 547 * 548 * Also, register types that are *not* MAYBE_NULL could technically be 549 * safe to use as their MAYBE_NULL variants (e.g., PTR_TO_MAP_VALUE 550 * is safe to be used as PTR_TO_MAP_VALUE_OR_NULL, provided both point 551 * to the same map). 552 * However, if the old MAYBE_NULL register then got NULL checked, 553 * doing so could have affected others with the same id, and we can't 554 * check for that because we lost the id when we converted to 555 * a non-MAYBE_NULL variant. 556 * So, as a general rule we don't allow mixing MAYBE_NULL and 557 * non-MAYBE_NULL registers as well. 558 */ 559 if (rold->type != rcur->type) 560 return false; 561 562 switch (base_type(rold->type)) { 563 case SCALAR_VALUE: 564 if (env->explore_alu_limits) { 565 /* explore_alu_limits disables tnum_in() and range_within() 566 * logic and requires everything to be strict 567 */ 568 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 569 check_scalar_ids(rold->id, rcur->id, idmap); 570 } 571 if (!rold->precise && exact == NOT_EXACT) 572 return true; 573 /* 574 * Linked register tracking uses rold->id to detect relationships. 575 * When rold->id == 0, the register is independent and any linking 576 * in rcur only adds constraints. When rold->id != 0, we must verify 577 * id mapping and (for BPF_ADD_CONST) offset consistency. 578 * 579 * +------------------+-----------+------------------+---------------+ 580 * | | rold->id | rold + ADD_CONST | rold->id == 0 | 581 * |------------------+-----------+------------------+---------------| 582 * | rcur->id | range,ids | false | range | 583 * | rcur + ADD_CONST | false | range,ids,off | range | 584 * | rcur->id == 0 | range,ids | false | range | 585 * +------------------+-----------+------------------+---------------+ 586 * 587 * Why check_ids() for scalar registers? 588 * 589 * Consider the following BPF code: 590 * 1: r6 = ... unbound scalar, ID=a ... 591 * 2: r7 = ... unbound scalar, ID=b ... 592 * 3: if (r6 > r7) goto +1 593 * 4: r6 = r7 594 * 5: if (r6 > X) goto ... 595 * 6: ... memory operation using r7 ... 596 * 597 * First verification path is [1-6]: 598 * - at (4) same bpf_reg_state::id (b) would be assigned to r6 and r7; 599 * - at (5) r6 would be marked <= X, sync_linked_regs() would also mark 600 * r7 <= X, because r6 and r7 share same id. 601 * Next verification path is [1-4, 6]. 602 * 603 * Instruction (6) would be reached in two states: 604 * I. r6{.id=b}, r7{.id=b} via path 1-6; 605 * II. r6{.id=a}, r7{.id=b} via path 1-4, 6. 606 * 607 * Use check_ids() to distinguish these states. 608 * --- 609 * Also verify that new value satisfies old value range knowledge. 610 */ 611 612 /* 613 * ADD_CONST flags must match exactly: BPF_ADD_CONST32 and 614 * BPF_ADD_CONST64 have different linking semantics in 615 * sync_linked_regs() (alu32 zero-extends, alu64 does not), 616 * so pruning across different flag types is unsafe. 617 */ 618 if (rold->id && 619 (rold->id & BPF_ADD_CONST) != (rcur->id & BPF_ADD_CONST)) 620 return false; 621 622 /* Both have offset linkage: offsets must match */ 623 if ((rold->id & BPF_ADD_CONST) && rold->delta != rcur->delta) 624 return false; 625 626 if (!check_scalar_ids(rold->id, rcur->id, idmap)) 627 return false; 628 629 return range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); 630 case PTR_TO_MAP_KEY: 631 case PTR_TO_MAP_VALUE: 632 case PTR_TO_MEM: 633 case PTR_TO_BUF: 634 case PTR_TO_TP_BUFFER: 635 case PTR_TO_STACK: 636 case PTR_TO_BTF_ID: 637 /* If the new min/max/var_off satisfy the old ones and 638 * everything else matches, we are OK. 639 */ 640 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 641 range_within(rold, rcur) && 642 tnum_in(rold->var_off, rcur->var_off) && 643 check_ids(rold->id, rcur->id, idmap) && 644 check_ids(rold->parent_id, rcur->parent_id, idmap) && 645 check_ids(rold->map_uid, rcur->map_uid, idmap); 646 case PTR_TO_PACKET_META: 647 case PTR_TO_PACKET: 648 /* We must have at least as much range as the old ptr 649 * did, so that any accesses which were safe before are 650 * still safe. This is true even if old range < old off, 651 * since someone could have accessed through (ptr - k), or 652 * even done ptr -= k in a register, to get a safe access. 653 */ 654 if (rold->range < 0 || rcur->range < 0) { 655 /* special case for [BEYOND|AT]_PKT_END */ 656 if (rold->range != rcur->range) 657 return false; 658 } else if (rold->range > rcur->range) { 659 return false; 660 } 661 /* id relations must be preserved */ 662 if (!check_ids(rold->id, rcur->id, idmap)) 663 return false; 664 /* Preserve displacements between pointers sharing an ID. */ 665 if (rold->id && rold->r64.base != rcur->r64.base) 666 return false; 667 /* new val must satisfy old val knowledge */ 668 return range_within(rold, rcur) && 669 tnum_in(rold->var_off, rcur->var_off); 670 case PTR_TO_ARENA: 671 return true; 672 case PTR_TO_INSN: 673 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, var_off)) == 0 && 674 range_within(rold, rcur) && tnum_in(rold->var_off, rcur->var_off); 675 default: 676 return regs_exact(rold, rcur, idmap); 677 } 678 } 679 680 static struct bpf_reg_state unbound_reg; 681 682 static __init int unbound_reg_init(void) 683 { 684 bpf_mark_reg_unknown_imprecise(&unbound_reg); 685 return 0; 686 } 687 late_initcall(unbound_reg_init); 688 689 static bool is_spilled_scalar_after(const struct bpf_stack_state *stack, int im) 690 { 691 return stack->slot_type[im] == STACK_SPILL && 692 stack->spilled_ptr.type == SCALAR_VALUE; 693 } 694 695 static bool is_stack_misc_after(struct bpf_verifier_env *env, 696 struct bpf_stack_state *stack, int im) 697 { 698 u32 i; 699 700 for (i = im; i < ARRAY_SIZE(stack->slot_type); ++i) { 701 if ((stack->slot_type[i] == STACK_MISC) || 702 ((stack->slot_type[i] == STACK_INVALID || stack->slot_type[i] == STACK_POISON) && 703 env->allow_uninit_stack)) 704 continue; 705 return false; 706 } 707 708 return true; 709 } 710 711 static struct bpf_reg_state *scalar_reg_for_stack(struct bpf_verifier_env *env, 712 struct bpf_stack_state *stack, int im) 713 { 714 if (is_spilled_scalar_after(stack, im)) 715 return &stack->spilled_ptr; 716 717 if (is_stack_misc_after(env, stack, im)) 718 return &unbound_reg; 719 720 return NULL; 721 } 722 723 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 724 struct bpf_func_state *cur, struct bpf_idmap *idmap, 725 enum exact_level exact) 726 { 727 int i, spi; 728 729 /* walk slots of the explored stack and ignore any additional 730 * slots in the current stack, since explored(safe) state 731 * didn't use them 732 */ 733 for (i = 0; i < old->allocated_stack; i++) { 734 struct bpf_stack_state *old_slot, *cur_slot; 735 struct bpf_reg_state *old_reg, *cur_reg; 736 int im = i % BPF_REG_SIZE; 737 u8 old_type; 738 739 spi = i / BPF_REG_SIZE; 740 old_slot = bpf_stack_slot(old, spi); 741 old_type = old_slot->slot_type[im]; 742 cur_slot = i < cur->allocated_stack ? bpf_stack_slot(cur, spi) : NULL; 743 744 if (exact == EXACT) { 745 u8 cur_type = cur_slot ? cur_slot->slot_type[im] : STACK_INVALID; 746 747 /* STACK_INVALID and STACK_POISON are equivalent for pruning */ 748 if (old_type == STACK_POISON) 749 old_type = STACK_INVALID; 750 if (cur_type == STACK_POISON) 751 cur_type = STACK_INVALID; 752 if (!cur_slot || old_type != cur_type) 753 return false; 754 } 755 756 if (old_type == STACK_INVALID || old_type == STACK_POISON) 757 continue; 758 759 if (env->allow_uninit_stack && old_type == STACK_MISC) 760 continue; 761 762 /* explored stack has more populated slots than current stack 763 * and these slots were used 764 */ 765 if (!cur_slot) 766 return false; 767 768 /* 769 * 64 and 32-bit scalar spills vs MISC/INVALID slots and vice versa. 770 * Load from MISC/INVALID slots produces unbound scalar. 771 * Construct a fake register for such stack and call 772 * regsafe() to ensure scalar ids are compared. 773 */ 774 if (im == 0 || im == 4) { 775 old_reg = scalar_reg_for_stack(env, old_slot, im); 776 cur_reg = scalar_reg_for_stack(env, cur_slot, im); 777 if (old_reg && cur_reg) { 778 if (!regsafe(env, old_reg, cur_reg, idmap, exact)) 779 return false; 780 i += (im == 0 ? BPF_REG_SIZE - 1 : 3); 781 continue; 782 } 783 } 784 785 /* if old state was safe with misc data in the stack 786 * it will be safe with zero-initialized stack. 787 * The opposite is not true 788 */ 789 if (old_type == STACK_MISC && cur_slot->slot_type[im] == STACK_ZERO) 790 continue; 791 if (old_type != cur_slot->slot_type[im]) 792 /* Ex: old explored (safe) state has STACK_SPILL in 793 * this stack slot, but current has STACK_MISC -> 794 * this verifier states are not equivalent, 795 * return false to continue verification of this path 796 */ 797 return false; 798 if (im != BPF_REG_SIZE - 1) 799 continue; 800 /* Both old and cur are having same slot_type */ 801 switch (old_type) { 802 case STACK_SPILL: 803 /* when explored and current stack slot are both storing 804 * spilled registers, check that stored pointers types 805 * are the same as well. 806 * Ex: explored safe path could have stored 807 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 808 * but current path has stored: 809 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 810 * such verifier states are not equivalent. 811 * return false to continue verification of this path 812 */ 813 if (!regsafe(env, &old_slot->spilled_ptr, &cur_slot->spilled_ptr, 814 idmap, exact)) 815 return false; 816 break; 817 case STACK_DYNPTR: 818 old_reg = &old_slot->spilled_ptr; 819 cur_reg = &cur_slot->spilled_ptr; 820 if (old_reg->dynptr.type != cur_reg->dynptr.type || 821 old_reg->dynptr.first_slot != cur_reg->dynptr.first_slot || 822 !check_ids(old_reg->id, cur_reg->id, idmap) || 823 !check_ids(old_reg->parent_id, cur_reg->parent_id, idmap)) 824 return false; 825 break; 826 case STACK_ITER: 827 old_reg = &old_slot->spilled_ptr; 828 cur_reg = &cur_slot->spilled_ptr; 829 /* iter.depth is not compared between states as it 830 * doesn't matter for correctness and would otherwise 831 * prevent convergence; we maintain it only to prevent 832 * infinite loop check triggering, see 833 * iter_active_depths_differ() 834 */ 835 if (old_reg->type != cur_reg->type || 836 old_reg->iter.btf != cur_reg->iter.btf || 837 old_reg->iter.btf_id != cur_reg->iter.btf_id || 838 old_reg->iter.state != cur_reg->iter.state || 839 /* ignore {old_reg,cur_reg}->iter.depth, see above */ 840 !check_ids(old_reg->id, cur_reg->id, idmap)) 841 return false; 842 break; 843 case STACK_IRQ_FLAG: 844 old_reg = &old_slot->spilled_ptr; 845 cur_reg = &cur_slot->spilled_ptr; 846 if (!check_ids(old_reg->id, cur_reg->id, idmap) || 847 old_reg->irq.kfunc_class != cur_reg->irq.kfunc_class) 848 return false; 849 break; 850 case STACK_MISC: 851 case STACK_ZERO: 852 case STACK_INVALID: 853 case STACK_POISON: 854 continue; 855 /* Ensure that new unhandled slot types return false by default */ 856 default: 857 return false; 858 } 859 } 860 return true; 861 } 862 863 /* 864 * Compare stack arg slots between old and current states. 865 * Outgoing stack args are path-local state and must agree for pruning. 866 */ 867 static bool stack_arg_safe(struct bpf_verifier_env *env, struct bpf_func_state *old, 868 struct bpf_func_state *cur, struct bpf_idmap *idmap, 869 enum exact_level exact) 870 { 871 int i, nslots; 872 873 nslots = max(old->out_stack_arg_cnt, cur->out_stack_arg_cnt); 874 for (i = 0; i < nslots; i++) { 875 struct bpf_reg_state *old_arg, *cur_arg; 876 struct bpf_reg_state not_init = { .type = NOT_INIT }; 877 878 old_arg = i < old->out_stack_arg_cnt ? 879 &old->stack_arg_regs[i] : ¬_init; 880 cur_arg = i < cur->out_stack_arg_cnt ? 881 &cur->stack_arg_regs[i] : ¬_init; 882 if (!regsafe(env, old_arg, cur_arg, idmap, exact)) 883 return false; 884 } 885 886 return true; 887 } 888 889 static bool refsafe(struct bpf_verifier_state *old, struct bpf_verifier_state *cur, 890 struct bpf_idmap *idmap) 891 { 892 int i; 893 894 if (old->acquired_refs != cur->acquired_refs) 895 return false; 896 897 if (old->active_locks != cur->active_locks) 898 return false; 899 900 if (old->active_preempt_locks != cur->active_preempt_locks) 901 return false; 902 903 if (old->active_rcu_locks != cur->active_rcu_locks) 904 return false; 905 906 if (!check_ids(old->active_irq_id, cur->active_irq_id, idmap)) 907 return false; 908 909 if (!check_ids(old->active_lock_id, cur->active_lock_id, idmap) || 910 old->active_lock_ptr != cur->active_lock_ptr) 911 return false; 912 913 for (i = 0; i < old->acquired_refs; i++) { 914 if (!check_ids(old->refs[i].id, cur->refs[i].id, idmap) || 915 old->refs[i].type != cur->refs[i].type) 916 return false; 917 switch (old->refs[i].type) { 918 case REF_TYPE_PTR: 919 if (!check_ids(old->refs[i].parent_id, cur->refs[i].parent_id, idmap)) 920 return false; 921 break; 922 case REF_TYPE_IRQ: 923 break; 924 case REF_TYPE_LOCK: 925 case REF_TYPE_RES_LOCK: 926 case REF_TYPE_RES_LOCK_IRQ: 927 if (old->refs[i].ptr != cur->refs[i].ptr) 928 return false; 929 break; 930 default: 931 WARN_ONCE(1, "Unhandled enum type for reference state: %d\n", old->refs[i].type); 932 return false; 933 } 934 } 935 936 return true; 937 } 938 939 static bool loop_stack_safe(struct bpf_verifier_env *env, struct bpf_func_state *old, 940 struct bpf_func_state *cur) 941 { 942 struct loop_stack_entry *old_stack = old->loop_stack; 943 struct loop_stack_entry *cur_stack = cur->loop_stack; 944 u32 i; 945 946 if (old->loop_stack_cnt != cur->loop_stack_cnt) 947 return false; 948 949 for (i = 0; i < old->loop_stack_cnt; i++) { 950 if (old_stack[i].loop_id == cur_stack[i].loop_id && 951 old_stack[i].max_header_count == cur_stack[i].max_header_count && 952 old_stack[i].terminates == cur_stack[i].terminates) 953 continue; 954 return false; 955 } 956 957 return true; 958 } 959 960 /* compare two verifier states 961 * 962 * all states stored in state_list are known to be valid, since 963 * verifier reached 'bpf_exit' instruction through them 964 * 965 * this function is called when verifier exploring different branches of 966 * execution popped from the state stack. If it sees an old state that has 967 * more strict register state and more strict stack state then this execution 968 * branch doesn't need to be explored further, since verifier already 969 * concluded that more strict state leads to valid finish. 970 * 971 * Therefore two states are equivalent if register state is more conservative 972 * and explored stack state is more conservative than the current one. 973 * Example: 974 * explored current 975 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 976 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 977 * 978 * In other words if current stack state (one being explored) has more 979 * valid slots than old one that already passed validation, it means 980 * the verifier can stop exploring and conclude that current state is valid too 981 * 982 * Similarly with registers. If explored state has register type as invalid 983 * whereas register type in current state is meaningful, it means that 984 * the current state will reach 'bpf_exit' instruction safely 985 */ 986 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 987 struct bpf_func_state *cur, u32 insn_idx, enum exact_level exact) 988 { 989 u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before; 990 u16 i; 991 992 if (old->callback_depth > cur->callback_depth) 993 return false; 994 995 if (!old->no_stack_arg_load && cur->no_stack_arg_load) 996 return false; 997 998 if (old->in_rcu_callback_fn != cur->in_rcu_callback_fn) 999 return false; 1000 1001 for (i = 0; i < MAX_BPF_REG; i++) 1002 if (((1 << i) & live_regs) && 1003 !regsafe(env, &old->regs[i], &cur->regs[i], 1004 &env->idmap_scratch, exact)) 1005 return false; 1006 1007 if (!stacksafe(env, old, cur, &env->idmap_scratch, exact)) 1008 return false; 1009 1010 if (!stack_arg_safe(env, old, cur, &env->idmap_scratch, exact)) 1011 return false; 1012 1013 if (!loop_stack_safe(env, old, cur)) 1014 return false; 1015 1016 return true; 1017 } 1018 1019 static void reset_idmap_scratch(struct bpf_verifier_env *env) 1020 { 1021 struct bpf_idmap *idmap = &env->idmap_scratch; 1022 1023 idmap->tmp_id_gen = env->id_gen; 1024 idmap->cnt = 0; 1025 } 1026 1027 static bool states_equal(struct bpf_verifier_env *env, 1028 struct bpf_verifier_state *old, 1029 struct bpf_verifier_state *cur, 1030 enum exact_level exact) 1031 { 1032 u32 insn_idx; 1033 int i; 1034 1035 if (old->curframe != cur->curframe) 1036 return false; 1037 1038 reset_idmap_scratch(env); 1039 1040 /* Verification state from speculative execution simulation 1041 * must never prune a non-speculative execution one. 1042 */ 1043 if (old->speculative && !cur->speculative) 1044 return false; 1045 1046 if (old->in_sleepable != cur->in_sleepable) 1047 return false; 1048 1049 if (old->unwound != cur->unwound) 1050 return false; 1051 1052 if (!refsafe(old, cur, &env->idmap_scratch)) 1053 return false; 1054 1055 /* for states to be equal callsites have to be the same 1056 * and all frame states need to be equivalent 1057 */ 1058 for (i = 0; i <= old->curframe; i++) { 1059 insn_idx = bpf_frame_insn_idx(old, i); 1060 if (old->frame[i]->callsite != cur->frame[i]->callsite) 1061 return false; 1062 if (!func_states_equal(env, old->frame[i], cur->frame[i], insn_idx, exact)) 1063 return false; 1064 } 1065 1066 return true; 1067 } 1068 1069 /* find precise scalars in the previous equivalent state and 1070 * propagate them into the current state 1071 */ 1072 static int propagate_precision(struct bpf_verifier_env *env, 1073 const struct bpf_verifier_state *old, 1074 struct bpf_verifier_state *cur, 1075 bool *changed) 1076 { 1077 struct bpf_reg_state *state_reg; 1078 struct bpf_func_state *state; 1079 int i, err = 0, fr; 1080 bool first; 1081 1082 for (fr = old->curframe; fr >= 0; fr--) { 1083 state = old->frame[fr]; 1084 state_reg = state->regs; 1085 first = true; 1086 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 1087 if (state_reg->type != SCALAR_VALUE || 1088 !state_reg->precise) 1089 continue; 1090 if (env->log.level & BPF_LOG_LEVEL2) { 1091 if (first) 1092 verbose(env, "frame %d: propagating r%d", fr, i); 1093 else 1094 verbose(env, ",r%d", i); 1095 } 1096 bpf_bt_set_frame_reg(&env->bt, fr, i); 1097 first = false; 1098 } 1099 1100 for (i = 0; i < bpf_stack_nr_slots(state); i++) { 1101 struct bpf_stack_state *ss = bpf_stack_slot(state, i); 1102 1103 if (!bpf_is_spilled_reg(ss)) 1104 continue; 1105 state_reg = &ss->spilled_ptr; 1106 if (state_reg->type != SCALAR_VALUE || 1107 !state_reg->precise) 1108 continue; 1109 if (env->log.level & BPF_LOG_LEVEL2) { 1110 if (first) 1111 verbose(env, "frame %d: propagating fp%d", 1112 fr, (-i - 1) * BPF_REG_SIZE); 1113 else 1114 verbose(env, ",fp%d", (-i - 1) * BPF_REG_SIZE); 1115 } 1116 bpf_bt_set_frame_slot(&env->bt, fr, i); 1117 first = false; 1118 } 1119 if (!first && (env->log.level & BPF_LOG_LEVEL2)) 1120 verbose(env, "\n"); 1121 } 1122 1123 err = bpf_mark_chain_precision(env, cur, -1, changed); 1124 if (err < 0) 1125 return err; 1126 1127 return 0; 1128 } 1129 1130 #define MAX_BACKEDGE_ITERS 64 1131 1132 /* Propagate read and precision marks from visit->backedges[*].state->equal_state 1133 * to corresponding parent states of visit->backedges[*].state until fixed point is reached, 1134 * then free visit->backedges. 1135 * After execution of this function incomplete_read_marks() will return false 1136 * for all states corresponding to @visit->callchain. 1137 */ 1138 static int propagate_backedges(struct bpf_verifier_env *env, struct bpf_scc_visit *visit) 1139 { 1140 struct bpf_scc_backedge *backedge; 1141 struct bpf_verifier_state *st; 1142 bool changed; 1143 int i, err; 1144 1145 i = 0; 1146 do { 1147 if (i++ > MAX_BACKEDGE_ITERS) { 1148 if (env->log.level & BPF_LOG_LEVEL2) 1149 verbose(env, "%s: too many iterations\n", __func__); 1150 for (backedge = visit->backedges; backedge; backedge = backedge->next) 1151 bpf_mark_all_scalars_precise(env, &backedge->state); 1152 break; 1153 } 1154 changed = false; 1155 for (backedge = visit->backedges; backedge; backedge = backedge->next) { 1156 st = &backedge->state; 1157 err = propagate_precision(env, st->equal_state, st, &changed); 1158 if (err) 1159 return err; 1160 } 1161 } while (changed); 1162 1163 bpf_free_backedges(visit); 1164 return 0; 1165 } 1166 1167 static bool states_maybe_looping(struct bpf_verifier_state *old, 1168 struct bpf_verifier_state *cur) 1169 { 1170 struct bpf_func_state *fold, *fcur; 1171 int i, fr = cur->curframe; 1172 1173 if (old->curframe != fr) 1174 return false; 1175 1176 fold = old->frame[fr]; 1177 fcur = cur->frame[fr]; 1178 for (i = 0; i < MAX_BPF_REG; i++) 1179 if (memcmp(&fold->regs[i], &fcur->regs[i], 1180 offsetofend(struct bpf_reg_state, step))) 1181 return false; 1182 return true; 1183 } 1184 1185 /* is_state_visited() handles iter_next() (see process_iter_next_call() for 1186 * terminology) calls specially: as opposed to bounded BPF loops, it *expects* 1187 * states to match, which otherwise would look like an infinite loop. So while 1188 * iter_next() calls are taken care of, we still need to be careful and 1189 * prevent erroneous and too eager declaration of "infinite loop", when 1190 * iterators are involved. 1191 * 1192 * Here's a situation in pseudo-BPF assembly form: 1193 * 1194 * 0: again: ; set up iter_next() call args 1195 * 1: r1 = &it ; <CHECKPOINT HERE> 1196 * 2: call bpf_iter_num_next ; this is iter_next() call 1197 * 3: if r0 == 0 goto done 1198 * 4: ... something useful here ... 1199 * 5: goto again ; another iteration 1200 * 6: done: 1201 * 7: r1 = &it 1202 * 8: call bpf_iter_num_destroy ; clean up iter state 1203 * 9: exit 1204 * 1205 * This is a typical loop. Let's assume that we have a prune point at 1:, 1206 * before we get to `call bpf_iter_num_next` (e.g., because of that `goto 1207 * again`, assuming other heuristics don't get in a way). 1208 * 1209 * When we first time come to 1:, let's say we have some state X. We proceed 1210 * to 2:, fork states, enqueue ACTIVE, validate NULL case successfully, exit. 1211 * Now we come back to validate that forked ACTIVE state. We proceed through 1212 * 3-5, come to goto, jump to 1:. Let's assume our state didn't change, so we 1213 * are converging. But the problem is that we don't know that yet, as this 1214 * convergence has to happen at iter_next() call site only. So if nothing is 1215 * done, at 1: verifier will use bounded loop logic and declare infinite 1216 * looping (and would be *technically* correct, if not for iterator's 1217 * "eventual sticky NULL" contract, see process_iter_next_call()). But we 1218 * don't want that. So what we do in process_iter_next_call() when we go on 1219 * another ACTIVE iteration, we bump slot->iter.depth, to mark that it's 1220 * a different iteration. So when we suspect an infinite loop, we additionally 1221 * check if any of the *ACTIVE* iterator states depths differ. If yes, we 1222 * pretend we are not looping and wait for next iter_next() call. 1223 * 1224 * This only applies to ACTIVE state. In DRAINED state we don't expect to 1225 * loop, because that would actually mean infinite loop, as DRAINED state is 1226 * "sticky", and so we'll keep returning into the same instruction with the 1227 * same state (at least in one of possible code paths). 1228 * 1229 * This approach allows to keep infinite loop heuristic even in the face of 1230 * active iterator. E.g., C snippet below is and will be detected as 1231 * infinitely looping: 1232 * 1233 * struct bpf_iter_num it; 1234 * int *p, x; 1235 * 1236 * bpf_iter_num_new(&it, 0, 10); 1237 * while ((p = bpf_iter_num_next(&t))) { 1238 * x = p; 1239 * while (x--) {} // <<-- infinite loop here 1240 * } 1241 * 1242 */ 1243 static bool iter_active_depths_differ(struct bpf_verifier_state *old, struct bpf_verifier_state *cur) 1244 { 1245 struct bpf_reg_state *slot, *cur_slot; 1246 struct bpf_func_state *state; 1247 int i, fr; 1248 1249 for (fr = old->curframe; fr >= 0; fr--) { 1250 state = old->frame[fr]; 1251 for (i = 0; i < bpf_stack_nr_slots(state); i++) { 1252 struct bpf_stack_state *ss = bpf_stack_slot(state, i); 1253 1254 if (ss->slot_type[0] != STACK_ITER) 1255 continue; 1256 1257 slot = &ss->spilled_ptr; 1258 if (slot->iter.state != BPF_ITER_STATE_ACTIVE) 1259 continue; 1260 1261 cur_slot = &bpf_stack_slot(cur->frame[fr], i)->spilled_ptr; 1262 if (cur_slot->iter.depth != slot->iter.depth) 1263 return true; 1264 } 1265 } 1266 return false; 1267 } 1268 1269 static void mark_all_scalars_imprecise(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 1270 { 1271 struct bpf_func_state *func; 1272 struct bpf_reg_state *reg; 1273 int i, j; 1274 1275 for (i = 0; i <= st->curframe; i++) { 1276 func = st->frame[i]; 1277 for (j = 0; j < BPF_REG_FP; j++) { 1278 reg = &func->regs[j]; 1279 if (reg->type != SCALAR_VALUE) 1280 continue; 1281 reg->precise = false; 1282 } 1283 for (j = 0; j < bpf_stack_nr_slots(func); j++) { 1284 struct bpf_stack_state *ss = bpf_stack_slot(func, j); 1285 1286 if (!bpf_is_spilled_reg(ss)) 1287 continue; 1288 reg = &ss->spilled_ptr; 1289 if (reg->type != SCALAR_VALUE) 1290 continue; 1291 reg->precise = false; 1292 } 1293 } 1294 } 1295 1296 int bpf_split_cur_state(struct bpf_verifier_env *env) 1297 { 1298 struct bpf_verifier_state *cur = env->cur_state, *new; 1299 struct bpf_verifier_state_list *new_sl; 1300 struct list_head *head; 1301 int insn_idx = cur->insn_idx; 1302 int err; 1303 1304 head = bpf_explored_state(env, insn_idx); 1305 new_sl = kzalloc_obj(struct bpf_verifier_state_list, GFP_KERNEL_ACCOUNT); 1306 if (!new_sl) 1307 return -ENOMEM; 1308 env->total_states++; 1309 env->explored_states_size++; 1310 update_peak_states(env); 1311 env->prev_jmps_processed = env->jmps_processed; 1312 env->prev_insn_processed = env->insn_processed; 1313 1314 /* forget precise markings we inherited, see __mark_chain_precision */ 1315 if (env->bpf_capable) 1316 mark_all_scalars_imprecise(env, cur); 1317 1318 bpf_clear_singular_ids(env, cur); 1319 1320 /* add new state to the head of linked list */ 1321 new = &new_sl->state; 1322 err = bpf_copy_verifier_state(new, cur); 1323 if (err) { 1324 bpf_free_verifier_state(new, false); 1325 kfree(new_sl); 1326 return err; 1327 } 1328 new->insn_idx = insn_idx; 1329 verifier_bug_if(new->branches != 1, env, 1330 "%s:branches_to_explore=%d insn %d", 1331 __func__, new->branches, insn_idx); 1332 err = maybe_enter_scc(env, new); 1333 if (err) { 1334 bpf_free_verifier_state(new, false); 1335 kfree(new_sl); 1336 return err; 1337 } 1338 1339 cur->parent = new; 1340 cur->last_insn_idx = -1; 1341 cur->first_insn_idx = insn_idx; 1342 cur->dfs_depth = new->dfs_depth + 1; 1343 bpf_clear_jmp_history(cur); 1344 list_add(&new_sl->node, head); 1345 return 0; 1346 } 1347 1348 /* Force a checkpoint upon reaching a loop header for a terminating loop. */ 1349 static bool need_loop_checkpoint(struct bpf_verifier_env *env, int insn_idx) 1350 { 1351 struct bpf_verifier_state *cur = env->cur_state; 1352 struct bpf_func_state *frame = cur->frame[cur->curframe]; 1353 struct loop_stack_entry *top; 1354 1355 if (bpf_loop_at_index(env, insn_idx) != insn_idx || !frame->loop_stack_cnt) 1356 return false; 1357 top = &frame->loop_stack[frame->loop_stack_cnt - 1]; 1358 return top->loop_id == insn_idx && top->terminates; 1359 } 1360 1361 static struct loop_stack_entry *current_loop(struct bpf_verifier_state *st) 1362 { 1363 struct bpf_func_state *frame = st->frame[st->curframe]; 1364 1365 if (frame->loop_stack_cnt == 0) 1366 return NULL; 1367 return &frame->loop_stack[frame->loop_stack_cnt - 1]; 1368 } 1369 1370 int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx) 1371 { 1372 struct loop_stack_entry *old_loop, *cur_loop; 1373 struct bpf_verifier_state_list *sl; 1374 struct bpf_verifier_state *cur = env->cur_state; 1375 bool force_new_state, add_new_state, loop, loop_checkpoint; 1376 int n, err, states_cnt = 0; 1377 struct list_head *pos, *tmp, *head; 1378 1379 loop_checkpoint = need_loop_checkpoint(env, insn_idx); 1380 force_new_state = env->test_state_freq || bpf_is_force_checkpoint(env, insn_idx) || 1381 loop_checkpoint || 1382 /* Avoid accumulating infinitely long jmp history */ 1383 cur->jmp_history_cnt > 40; 1384 1385 /* bpf progs typically have pruning point every 4 instructions 1386 * http://vger.kernel.org/bpfconf2019.html#session-1 1387 * Do not add new state for future pruning if the verifier hasn't seen 1388 * at least 2 jumps and at least 8 instructions. 1389 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 1390 * In tests that amounts to up to 50% reduction into total verifier 1391 * memory consumption and 20% verifier time speedup. 1392 */ 1393 add_new_state = force_new_state; 1394 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 1395 env->insn_processed - env->prev_insn_processed >= 8) 1396 add_new_state = true; 1397 1398 /* keep cleaning the current state as registers/stack become dead */ 1399 err = clean_verifier_state(env, cur); 1400 if (err) 1401 return err; 1402 1403 loop = false; 1404 head = bpf_explored_state(env, insn_idx); 1405 list_for_each_safe(pos, tmp, head) { 1406 sl = container_of(pos, struct bpf_verifier_state_list, node); 1407 states_cnt++; 1408 if (sl->state.insn_idx != insn_idx) 1409 continue; 1410 1411 if (sl->state.branches) { 1412 struct bpf_func_state *old_top_frame = sl->state.frame[0]; 1413 1414 if (old_top_frame->in_async_callback_fn && 1415 old_top_frame->async_entry_cnt != cur->frame[0]->async_entry_cnt) { 1416 /* Different async_entry_cnt means that the verifier is 1417 * processing another entry into async callback. 1418 * Seeing the same state is not an indication of infinite 1419 * loop or infinite recursion. 1420 * But finding the same state doesn't mean that it's safe 1421 * to stop processing the current state. The previous state 1422 * hasn't yet reached bpf_exit, since state.branches > 0. 1423 * Checking in_async_callback_fn alone is not enough either. 1424 * Since the verifier still needs to catch infinite loops 1425 * inside async callbacks. 1426 */ 1427 goto skip_inf_loop_check; 1428 } 1429 /* BPF open-coded iterators loop detection is special. 1430 * states_maybe_looping() logic is too simplistic in detecting 1431 * states that *might* be equivalent, because it doesn't know 1432 * about ID remapping, so don't even perform it. 1433 * See process_iter_next_call() and iter_active_depths_differ() 1434 * for overview of the logic. When current and one of parent 1435 * states are detected as equivalent, it's a good thing: we prove 1436 * convergence and can stop simulating further iterations. 1437 * It's safe to assume that iterator loop will finish, taking into 1438 * account iter_next() contract of eventually returning 1439 * sticky NULL result. 1440 * 1441 * Note, that states have to be compared exactly in this case because 1442 * read and precision marks might not be finalized inside the loop. 1443 * E.g. as in the program below: 1444 * 1445 * 1. r7 = -16 1446 * 2. r6 = bpf_get_prandom_u32() 1447 * 3. while (bpf_iter_num_next(&fp[-8])) { 1448 * 4. if (r6 != 42) { 1449 * 5. r7 = -32 1450 * 6. r6 = bpf_get_prandom_u32() 1451 * 7. continue 1452 * 8. } 1453 * 9. r0 = r10 1454 * 10. r0 += r7 1455 * 11. r8 = *(u64 *)(r0 + 0) 1456 * 12. r6 = bpf_get_prandom_u32() 1457 * 13. } 1458 * 1459 * Here verifier would first visit path 1-3, create a checkpoint at 3 1460 * with r7=-16, continue to 4-7,3. Existing checkpoint at 3 does 1461 * not have read or precision mark for r7 yet, thus inexact states 1462 * comparison would discard current state with r7=-32 1463 * => unsafe memory access at 11 would not be caught. 1464 */ 1465 if (is_iter_next_insn(env, insn_idx)) { 1466 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 1467 struct bpf_func_state *cur_frame, *iter_frame, *old_frame; 1468 struct bpf_reg_state *iter_state, *iter_reg; 1469 struct bpf_reg_state *old_iter; 1470 int spi; 1471 1472 cur_frame = cur->frame[cur->curframe]; 1473 /* btf_check_iter_kfuncs() enforces that 1474 * iter state pointer is always the first arg 1475 */ 1476 iter_reg = &cur_frame->regs[BPF_REG_1]; 1477 /* current state is valid due to states_equal(), 1478 * so we can assume valid iter and reg state, 1479 * no need for extra (re-)validations 1480 */ 1481 spi = bpf_get_spi(iter_reg->var_off.value); 1482 iter_frame = bpf_func(env, iter_reg); 1483 iter_state = &bpf_stack_slot(iter_frame, spi)->spilled_ptr; 1484 old_frame = sl->state.frame[iter_reg->frameno]; 1485 old_iter = &bpf_stack_slot(old_frame, spi)->spilled_ptr; 1486 /* 1487 * states_equal() matches ids through idmap. 1488 * The loop converged only if it's the same 1489 * iterator. The one that was destroyed and 1490 * created again starts from the beginning. 1491 */ 1492 if (iter_state->iter.state == BPF_ITER_STATE_ACTIVE && 1493 iter_state->id == old_iter->id) { 1494 loop = true; 1495 goto hit; 1496 } 1497 } 1498 goto skip_inf_loop_check; 1499 } 1500 if (is_may_goto_insn_at(env, insn_idx)) { 1501 if (sl->state.may_goto_depth != cur->may_goto_depth && 1502 states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 1503 loop = true; 1504 goto hit; 1505 } 1506 } 1507 if (bpf_calls_callback(env, insn_idx)) { 1508 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 1509 loop = true; 1510 goto hit; 1511 } 1512 goto skip_inf_loop_check; 1513 } 1514 /* 1515 * If old state belongs to a control flow loop that we know terminates, 1516 * it should be safe to prune current state. However, account for the 1517 * following situation: 1518 * 1519 * for (;;) { 1520 * for (i = 0; i < 10; i++) 1521 * ... 1522 * } 1523 * 1524 * Here a backedge to a non-terminating outer loop is dominated by an exit 1525 * from the inner loop. Pruning at a re-entry to the inner loop therefore 1526 * would hide the fact that outer loop is non-terminating. 1527 * Hence, only allow pruning states within the same entry state. 1528 */ 1529 old_loop = current_loop(&sl->state); 1530 cur_loop = current_loop(cur); 1531 if (old_loop && cur_loop && 1532 old_loop->terminates && cur_loop->terminates && 1533 old_loop->entry_state == cur_loop->entry_state) { 1534 if (states_equal(env, &sl->state, cur, RANGE_WITHIN)) { 1535 loop = true; 1536 goto hit; 1537 } 1538 goto skip_inf_loop_check; 1539 } 1540 1541 /* attempt to detect infinite loop to avoid unnecessary doomed work */ 1542 if (states_maybe_looping(&sl->state, cur) && 1543 states_equal(env, &sl->state, cur, EXACT) && 1544 !iter_active_depths_differ(&sl->state, cur) && 1545 sl->state.may_goto_depth == cur->may_goto_depth && 1546 sl->state.callback_unroll_depth == cur->callback_unroll_depth) { 1547 verbose_linfo(env, insn_idx, "; "); 1548 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 1549 verbose(env, "cur state:"); 1550 print_verifier_state(env, cur, cur->curframe, true); 1551 verbose(env, "old state:"); 1552 print_verifier_state(env, &sl->state, cur->curframe, true); 1553 return -EINVAL; 1554 } 1555 /* if the verifier is processing a loop, avoid adding new state 1556 * too often, since different loop iterations have distinct 1557 * states and may not help future pruning. 1558 * This threshold shouldn't be too low to make sure that 1559 * a loop with large bound will be rejected quickly. 1560 * The most abusive loop will be: 1561 * r1 += 1 1562 * if r1 < 1000000 goto pc-2 1563 * 1M insn_procssed limit / 100 == 10k peak states. 1564 * This threshold shouldn't be too high either, since states 1565 * at the end of the loop are likely to be useful in pruning. 1566 */ 1567 skip_inf_loop_check: 1568 if (!force_new_state && 1569 env->jmps_processed - env->prev_jmps_processed < 20 && 1570 env->insn_processed - env->prev_insn_processed < 100) 1571 add_new_state = false; 1572 goto miss; 1573 } 1574 /* See comments for mark_all_regs_read_and_precise() */ 1575 loop = incomplete_read_marks(env, &sl->state); 1576 if (states_equal(env, &sl->state, cur, loop ? RANGE_WITHIN : NOT_EXACT)) { 1577 hit: 1578 sl->hit_cnt++; 1579 1580 /* if previous state reached the exit with precision and 1581 * current state is equivalent to it (except precision marks) 1582 * the precision needs to be propagated back in 1583 * the current state. 1584 */ 1585 err = 0; 1586 if (bpf_is_jmp_point(env, env->insn_idx)) 1587 err = bpf_push_jmp_history(env, cur, 0, 0, 0, NULL, 0); 1588 err = err ? : propagate_precision(env, &sl->state, cur, NULL); 1589 if (err) 1590 return err; 1591 /* When processing iterator based loops above propagate_liveness and 1592 * propagate_precision calls are not sufficient to transfer all relevant 1593 * read and precision marks. E.g. consider the following case: 1594 * 1595 * .-> A --. Assume the states are visited in the order A, B, C. 1596 * | | | Assume that state B reaches a state equivalent to state A. 1597 * | v v At this point, state C is not processed yet, so state A 1598 * '-- B C has not received any read or precision marks from C. 1599 * Thus, marks propagated from A to B are incomplete. 1600 * 1601 * The verifier mitigates this by performing the following steps: 1602 * 1603 * - Prior to the main verification pass, strongly connected components 1604 * (SCCs) are computed over the program's control flow graph, 1605 * intraprocedurally. 1606 * 1607 * - During the main verification pass, `maybe_enter_scc()` checks 1608 * whether the current verifier state is entering an SCC. If so, an 1609 * instance of a `bpf_scc_visit` object is created, and the state 1610 * entering the SCC is recorded as the entry state. 1611 * 1612 * - This instance is associated not with the SCC itself, but with a 1613 * `bpf_scc_callchain`: a tuple consisting of the call sites leading to 1614 * the SCC and the SCC id. See `compute_scc_callchain()`. 1615 * 1616 * - When a verification path encounters a `states_equal(..., 1617 * RANGE_WITHIN)` condition, there exists a call chain describing the 1618 * current state and a corresponding `bpf_scc_visit` instance. A copy 1619 * of the current state is created and added to 1620 * `bpf_scc_visit->backedges`. 1621 * 1622 * - When a verification path terminates, `maybe_exit_scc()` is called 1623 * from `bpf_update_branch_counts()`. For states with `branches == 0`, it 1624 * checks whether the state is the entry state of any `bpf_scc_visit` 1625 * instance. If it is, this indicates that all paths originating from 1626 * this SCC visit have been explored. `propagate_backedges()` is then 1627 * called, which propagates read and precision marks through the 1628 * backedges until a fixed point is reached. 1629 * (In the earlier example, this would propagate marks from A to B, 1630 * from C to A, and then again from A to B.) 1631 * 1632 * A note on callchains 1633 * -------------------- 1634 * 1635 * Consider the following example: 1636 * 1637 * void foo() { loop { ... SCC#1 ... } } 1638 * void main() { 1639 * A: foo(); 1640 * B: ... 1641 * C: foo(); 1642 * } 1643 * 1644 * Here, there are two distinct callchains leading to SCC#1: 1645 * - (A, SCC#1) 1646 * - (C, SCC#1) 1647 * 1648 * Each callchain identifies a separate `bpf_scc_visit` instance that 1649 * accumulates backedge states. The `propagate_{liveness,precision}()` 1650 * functions traverse the parent state of each backedge state, which 1651 * means these parent states must remain valid (i.e., not freed) while 1652 * the corresponding `bpf_scc_visit` instance exists. 1653 * 1654 * Associating `bpf_scc_visit` instances directly with SCCs instead of 1655 * callchains would break this invariant: 1656 * - States explored during `C: foo()` would contribute backedges to 1657 * SCC#1, but SCC#1 would only be exited once the exploration of 1658 * `A: foo()` completes. 1659 * - By that time, the states explored between `A: foo()` and `C: foo()` 1660 * (i.e., `B: ...`) may have already been freed, causing the parent 1661 * links for states from `C: foo()` to become invalid. 1662 */ 1663 if (loop) { 1664 struct bpf_scc_backedge *backedge; 1665 1666 backedge = kzalloc_obj(*backedge, 1667 GFP_KERNEL_ACCOUNT); 1668 if (!backedge) 1669 return -ENOMEM; 1670 err = bpf_copy_verifier_state(&backedge->state, cur); 1671 backedge->state.equal_state = &sl->state; 1672 backedge->state.insn_idx = insn_idx; 1673 err = err ?: add_scc_backedge(env, &sl->state, backedge); 1674 if (err) { 1675 bpf_free_verifier_state(&backedge->state, false); 1676 kfree(backedge); 1677 return err; 1678 } 1679 } 1680 return 1; 1681 } 1682 miss: 1683 /* when new state is not going to be added do not increase miss count. 1684 * Otherwise several loop iterations will remove the state 1685 * recorded earlier. The goal of these heuristics is to have 1686 * states from some iterations of the loop (some in the beginning 1687 * and some at the end) to help pruning. 1688 */ 1689 if (add_new_state) 1690 sl->miss_cnt++; 1691 /* heuristic to determine whether this state is beneficial 1692 * to keep checking from state equivalence point of view. 1693 * Higher numbers increase max_states_per_insn and verification time, 1694 * but do not meaningfully decrease insn_processed. 1695 * 'n' controls how many times state could miss before eviction. 1696 * Use bigger 'n' for checkpoints because evicting checkpoint states 1697 * too early would hinder iterator convergence. 1698 */ 1699 n = (bpf_is_force_checkpoint(env, insn_idx) || loop_checkpoint) && 1700 sl->state.branches > 0 ? 64 : 3; 1701 if (sl->miss_cnt > sl->hit_cnt * n + n) { 1702 /* the state is unlikely to be useful. Remove it to 1703 * speed up verification 1704 */ 1705 sl->in_free_list = true; 1706 list_del(&sl->node); 1707 list_add(&sl->node, &env->free_list); 1708 env->free_list_size++; 1709 env->explored_states_size--; 1710 maybe_free_verifier_state(env, sl); 1711 } 1712 } 1713 1714 if (env->max_states_per_insn < states_cnt) 1715 env->max_states_per_insn = states_cnt; 1716 1717 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 1718 return 0; 1719 1720 if (!add_new_state) 1721 return 0; 1722 1723 /* There were no equivalent states, remember the current one. 1724 * Technically the current state is not proven to be safe yet, 1725 * but it will either reach outer most bpf_exit (which means it's safe) 1726 * or it will be rejected. When there are no loops the verifier won't be 1727 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 1728 * again on the way to bpf_exit. 1729 * When looping the sl->state.branches will be > 0 and this state 1730 * will not be considered for equivalence until branches == 0. 1731 */ 1732 return bpf_split_cur_state(env); 1733 } 1734