1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 2 * Copyright (c) 2016 Facebook 3 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 4 * 5 * This program is free software; you can redistribute it and/or 6 * modify it under the terms of version 2 of the GNU General Public 7 * License as published by the Free Software Foundation. 8 * 9 * This program is distributed in the hope that it will be useful, but 10 * WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 * General Public License for more details. 13 */ 14 #include <linux/kernel.h> 15 #include <linux/types.h> 16 #include <linux/slab.h> 17 #include <linux/bpf.h> 18 #include <linux/bpf_verifier.h> 19 #include <linux/filter.h> 20 #include <net/netlink.h> 21 #include <linux/file.h> 22 #include <linux/vmalloc.h> 23 #include <linux/stringify.h> 24 #include <linux/bsearch.h> 25 #include <linux/sort.h> 26 #include <linux/perf_event.h> 27 28 #include "disasm.h" 29 30 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 31 #define BPF_PROG_TYPE(_id, _name) \ 32 [_id] = & _name ## _verifier_ops, 33 #define BPF_MAP_TYPE(_id, _ops) 34 #include <linux/bpf_types.h> 35 #undef BPF_PROG_TYPE 36 #undef BPF_MAP_TYPE 37 }; 38 39 /* bpf_check() is a static code analyzer that walks eBPF program 40 * instruction by instruction and updates register/stack state. 41 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 42 * 43 * The first pass is depth-first-search to check that the program is a DAG. 44 * It rejects the following programs: 45 * - larger than BPF_MAXINSNS insns 46 * - if loop is present (detected via back-edge) 47 * - unreachable insns exist (shouldn't be a forest. program = one function) 48 * - out of bounds or malformed jumps 49 * The second pass is all possible path descent from the 1st insn. 50 * Since it's analyzing all pathes through the program, the length of the 51 * analysis is limited to 64k insn, which may be hit even if total number of 52 * insn is less then 4K, but there are too many branches that change stack/regs. 53 * Number of 'branches to be analyzed' is limited to 1k 54 * 55 * On entry to each instruction, each register has a type, and the instruction 56 * changes the types of the registers depending on instruction semantics. 57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 58 * copied to R1. 59 * 60 * All registers are 64-bit. 61 * R0 - return register 62 * R1-R5 argument passing registers 63 * R6-R9 callee saved registers 64 * R10 - frame pointer read-only 65 * 66 * At the start of BPF program the register R1 contains a pointer to bpf_context 67 * and has type PTR_TO_CTX. 68 * 69 * Verifier tracks arithmetic operations on pointers in case: 70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 72 * 1st insn copies R10 (which has FRAME_PTR) type into R1 73 * and 2nd arithmetic instruction is pattern matched to recognize 74 * that it wants to construct a pointer to some element within stack. 75 * So after 2nd insn, the register R1 has type PTR_TO_STACK 76 * (and -20 constant is saved for further stack bounds checking). 77 * Meaning that this reg is a pointer to stack plus known immediate constant. 78 * 79 * Most of the time the registers have SCALAR_VALUE type, which 80 * means the register has some value, but it's not a valid pointer. 81 * (like pointer plus pointer becomes SCALAR_VALUE type) 82 * 83 * When verifier sees load or store instructions the type of base register 84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 85 * four pointer types recognized by check_mem_access() function. 86 * 87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 88 * and the range of [ptr, ptr + map's value_size) is accessible. 89 * 90 * registers used to pass values to function calls are checked against 91 * function argument constraints. 92 * 93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 94 * It means that the register type passed to this function must be 95 * PTR_TO_STACK and it will be used inside the function as 96 * 'pointer to map element key' 97 * 98 * For example the argument constraints for bpf_map_lookup_elem(): 99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 100 * .arg1_type = ARG_CONST_MAP_PTR, 101 * .arg2_type = ARG_PTR_TO_MAP_KEY, 102 * 103 * ret_type says that this function returns 'pointer to map elem value or null' 104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 105 * 2nd argument should be a pointer to stack, which will be used inside 106 * the helper function as a pointer to map element key. 107 * 108 * On the kernel side the helper function looks like: 109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 110 * { 111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 112 * void *key = (void *) (unsigned long) r2; 113 * void *value; 114 * 115 * here kernel can access 'key' and 'map' pointers safely, knowing that 116 * [key, key + map->key_size) bytes are valid and were initialized on 117 * the stack of eBPF program. 118 * } 119 * 120 * Corresponding eBPF program may look like: 121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 125 * here verifier looks at prototype of map_lookup_elem() and sees: 126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 128 * 129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 131 * and were initialized prior to this call. 132 * If it's ok, then verifier allows this BPF_CALL insn and looks at 133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 135 * returns ether pointer to map value or NULL. 136 * 137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 138 * insn, the register holding that pointer in the true branch changes state to 139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 140 * branch. See check_cond_jmp_op(). 141 * 142 * After the call R0 is set to return type of the function and registers R1-R5 143 * are set to NOT_INIT to indicate that they are no longer readable. 144 * 145 * The following reference types represent a potential reference to a kernel 146 * resource which, after first being allocated, must be checked and freed by 147 * the BPF program: 148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 149 * 150 * When the verifier sees a helper call return a reference type, it allocates a 151 * pointer id for the reference and stores it in the current function state. 152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 154 * passes through a NULL-check conditional. For the branch wherein the state is 155 * changed to CONST_IMM, the verifier releases the reference. 156 * 157 * For each helper function that allocates a reference, such as 158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 159 * bpf_sk_release(). When a reference type passes into the release function, 160 * the verifier also releases the reference. If any unchecked or unreleased 161 * reference remains at the end of the program, the verifier rejects it. 162 */ 163 164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 165 struct bpf_verifier_stack_elem { 166 /* verifer state is 'st' 167 * before processing instruction 'insn_idx' 168 * and after processing instruction 'prev_insn_idx' 169 */ 170 struct bpf_verifier_state st; 171 int insn_idx; 172 int prev_insn_idx; 173 struct bpf_verifier_stack_elem *next; 174 }; 175 176 #define BPF_COMPLEXITY_LIMIT_INSNS 131072 177 #define BPF_COMPLEXITY_LIMIT_STACK 1024 178 179 #define BPF_MAP_PTR_UNPRIV 1UL 180 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 181 POISON_POINTER_DELTA)) 182 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 183 184 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 185 { 186 return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON; 187 } 188 189 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 190 { 191 return aux->map_state & BPF_MAP_PTR_UNPRIV; 192 } 193 194 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 195 const struct bpf_map *map, bool unpriv) 196 { 197 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 198 unpriv |= bpf_map_ptr_unpriv(aux); 199 aux->map_state = (unsigned long)map | 200 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 201 } 202 203 struct bpf_call_arg_meta { 204 struct bpf_map *map_ptr; 205 bool raw_mode; 206 bool pkt_access; 207 int regno; 208 int access_size; 209 s64 msize_smax_value; 210 u64 msize_umax_value; 211 int ptr_id; 212 }; 213 214 static DEFINE_MUTEX(bpf_verifier_lock); 215 216 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, 217 va_list args) 218 { 219 unsigned int n; 220 221 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); 222 223 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, 224 "verifier log line truncated - local buffer too short\n"); 225 226 n = min(log->len_total - log->len_used - 1, n); 227 log->kbuf[n] = '\0'; 228 229 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) 230 log->len_used += n; 231 else 232 log->ubuf = NULL; 233 } 234 235 /* log_level controls verbosity level of eBPF verifier. 236 * bpf_verifier_log_write() is used to dump the verification trace to the log, 237 * so the user can figure out what's wrong with the program 238 */ 239 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 240 const char *fmt, ...) 241 { 242 va_list args; 243 244 if (!bpf_verifier_log_needed(&env->log)) 245 return; 246 247 va_start(args, fmt); 248 bpf_verifier_vlog(&env->log, fmt, args); 249 va_end(args); 250 } 251 EXPORT_SYMBOL_GPL(bpf_verifier_log_write); 252 253 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 254 { 255 struct bpf_verifier_env *env = private_data; 256 va_list args; 257 258 if (!bpf_verifier_log_needed(&env->log)) 259 return; 260 261 va_start(args, fmt); 262 bpf_verifier_vlog(&env->log, fmt, args); 263 va_end(args); 264 } 265 266 static bool type_is_pkt_pointer(enum bpf_reg_type type) 267 { 268 return type == PTR_TO_PACKET || 269 type == PTR_TO_PACKET_META; 270 } 271 272 static bool reg_type_may_be_null(enum bpf_reg_type type) 273 { 274 return type == PTR_TO_MAP_VALUE_OR_NULL || 275 type == PTR_TO_SOCKET_OR_NULL; 276 } 277 278 static bool type_is_refcounted(enum bpf_reg_type type) 279 { 280 return type == PTR_TO_SOCKET; 281 } 282 283 static bool type_is_refcounted_or_null(enum bpf_reg_type type) 284 { 285 return type == PTR_TO_SOCKET || type == PTR_TO_SOCKET_OR_NULL; 286 } 287 288 static bool reg_is_refcounted(const struct bpf_reg_state *reg) 289 { 290 return type_is_refcounted(reg->type); 291 } 292 293 static bool reg_is_refcounted_or_null(const struct bpf_reg_state *reg) 294 { 295 return type_is_refcounted_or_null(reg->type); 296 } 297 298 static bool arg_type_is_refcounted(enum bpf_arg_type type) 299 { 300 return type == ARG_PTR_TO_SOCKET; 301 } 302 303 /* Determine whether the function releases some resources allocated by another 304 * function call. The first reference type argument will be assumed to be 305 * released by release_reference(). 306 */ 307 static bool is_release_function(enum bpf_func_id func_id) 308 { 309 return func_id == BPF_FUNC_sk_release; 310 } 311 312 /* string representation of 'enum bpf_reg_type' */ 313 static const char * const reg_type_str[] = { 314 [NOT_INIT] = "?", 315 [SCALAR_VALUE] = "inv", 316 [PTR_TO_CTX] = "ctx", 317 [CONST_PTR_TO_MAP] = "map_ptr", 318 [PTR_TO_MAP_VALUE] = "map_value", 319 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", 320 [PTR_TO_STACK] = "fp", 321 [PTR_TO_PACKET] = "pkt", 322 [PTR_TO_PACKET_META] = "pkt_meta", 323 [PTR_TO_PACKET_END] = "pkt_end", 324 [PTR_TO_FLOW_KEYS] = "flow_keys", 325 [PTR_TO_SOCKET] = "sock", 326 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null", 327 }; 328 329 static char slot_type_char[] = { 330 [STACK_INVALID] = '?', 331 [STACK_SPILL] = 'r', 332 [STACK_MISC] = 'm', 333 [STACK_ZERO] = '0', 334 }; 335 336 static void print_liveness(struct bpf_verifier_env *env, 337 enum bpf_reg_liveness live) 338 { 339 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN)) 340 verbose(env, "_"); 341 if (live & REG_LIVE_READ) 342 verbose(env, "r"); 343 if (live & REG_LIVE_WRITTEN) 344 verbose(env, "w"); 345 } 346 347 static struct bpf_func_state *func(struct bpf_verifier_env *env, 348 const struct bpf_reg_state *reg) 349 { 350 struct bpf_verifier_state *cur = env->cur_state; 351 352 return cur->frame[reg->frameno]; 353 } 354 355 static void print_verifier_state(struct bpf_verifier_env *env, 356 const struct bpf_func_state *state) 357 { 358 const struct bpf_reg_state *reg; 359 enum bpf_reg_type t; 360 int i; 361 362 if (state->frameno) 363 verbose(env, " frame%d:", state->frameno); 364 for (i = 0; i < MAX_BPF_REG; i++) { 365 reg = &state->regs[i]; 366 t = reg->type; 367 if (t == NOT_INIT) 368 continue; 369 verbose(env, " R%d", i); 370 print_liveness(env, reg->live); 371 verbose(env, "=%s", reg_type_str[t]); 372 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 373 tnum_is_const(reg->var_off)) { 374 /* reg->off should be 0 for SCALAR_VALUE */ 375 verbose(env, "%lld", reg->var_off.value + reg->off); 376 if (t == PTR_TO_STACK) 377 verbose(env, ",call_%d", func(env, reg)->callsite); 378 } else { 379 verbose(env, "(id=%d", reg->id); 380 if (t != SCALAR_VALUE) 381 verbose(env, ",off=%d", reg->off); 382 if (type_is_pkt_pointer(t)) 383 verbose(env, ",r=%d", reg->range); 384 else if (t == CONST_PTR_TO_MAP || 385 t == PTR_TO_MAP_VALUE || 386 t == PTR_TO_MAP_VALUE_OR_NULL) 387 verbose(env, ",ks=%d,vs=%d", 388 reg->map_ptr->key_size, 389 reg->map_ptr->value_size); 390 if (tnum_is_const(reg->var_off)) { 391 /* Typically an immediate SCALAR_VALUE, but 392 * could be a pointer whose offset is too big 393 * for reg->off 394 */ 395 verbose(env, ",imm=%llx", reg->var_off.value); 396 } else { 397 if (reg->smin_value != reg->umin_value && 398 reg->smin_value != S64_MIN) 399 verbose(env, ",smin_value=%lld", 400 (long long)reg->smin_value); 401 if (reg->smax_value != reg->umax_value && 402 reg->smax_value != S64_MAX) 403 verbose(env, ",smax_value=%lld", 404 (long long)reg->smax_value); 405 if (reg->umin_value != 0) 406 verbose(env, ",umin_value=%llu", 407 (unsigned long long)reg->umin_value); 408 if (reg->umax_value != U64_MAX) 409 verbose(env, ",umax_value=%llu", 410 (unsigned long long)reg->umax_value); 411 if (!tnum_is_unknown(reg->var_off)) { 412 char tn_buf[48]; 413 414 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 415 verbose(env, ",var_off=%s", tn_buf); 416 } 417 } 418 verbose(env, ")"); 419 } 420 } 421 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 422 char types_buf[BPF_REG_SIZE + 1]; 423 bool valid = false; 424 int j; 425 426 for (j = 0; j < BPF_REG_SIZE; j++) { 427 if (state->stack[i].slot_type[j] != STACK_INVALID) 428 valid = true; 429 types_buf[j] = slot_type_char[ 430 state->stack[i].slot_type[j]]; 431 } 432 types_buf[BPF_REG_SIZE] = 0; 433 if (!valid) 434 continue; 435 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 436 print_liveness(env, state->stack[i].spilled_ptr.live); 437 if (state->stack[i].slot_type[0] == STACK_SPILL) 438 verbose(env, "=%s", 439 reg_type_str[state->stack[i].spilled_ptr.type]); 440 else 441 verbose(env, "=%s", types_buf); 442 } 443 if (state->acquired_refs && state->refs[0].id) { 444 verbose(env, " refs=%d", state->refs[0].id); 445 for (i = 1; i < state->acquired_refs; i++) 446 if (state->refs[i].id) 447 verbose(env, ",%d", state->refs[i].id); 448 } 449 verbose(env, "\n"); 450 } 451 452 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \ 453 static int copy_##NAME##_state(struct bpf_func_state *dst, \ 454 const struct bpf_func_state *src) \ 455 { \ 456 if (!src->FIELD) \ 457 return 0; \ 458 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \ 459 /* internal bug, make state invalid to reject the program */ \ 460 memset(dst, 0, sizeof(*dst)); \ 461 return -EFAULT; \ 462 } \ 463 memcpy(dst->FIELD, src->FIELD, \ 464 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \ 465 return 0; \ 466 } 467 /* copy_reference_state() */ 468 COPY_STATE_FN(reference, acquired_refs, refs, 1) 469 /* copy_stack_state() */ 470 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE) 471 #undef COPY_STATE_FN 472 473 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \ 474 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \ 475 bool copy_old) \ 476 { \ 477 u32 old_size = state->COUNT; \ 478 struct bpf_##NAME##_state *new_##FIELD; \ 479 int slot = size / SIZE; \ 480 \ 481 if (size <= old_size || !size) { \ 482 if (copy_old) \ 483 return 0; \ 484 state->COUNT = slot * SIZE; \ 485 if (!size && old_size) { \ 486 kfree(state->FIELD); \ 487 state->FIELD = NULL; \ 488 } \ 489 return 0; \ 490 } \ 491 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \ 492 GFP_KERNEL); \ 493 if (!new_##FIELD) \ 494 return -ENOMEM; \ 495 if (copy_old) { \ 496 if (state->FIELD) \ 497 memcpy(new_##FIELD, state->FIELD, \ 498 sizeof(*new_##FIELD) * (old_size / SIZE)); \ 499 memset(new_##FIELD + old_size / SIZE, 0, \ 500 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \ 501 } \ 502 state->COUNT = slot * SIZE; \ 503 kfree(state->FIELD); \ 504 state->FIELD = new_##FIELD; \ 505 return 0; \ 506 } 507 /* realloc_reference_state() */ 508 REALLOC_STATE_FN(reference, acquired_refs, refs, 1) 509 /* realloc_stack_state() */ 510 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE) 511 #undef REALLOC_STATE_FN 512 513 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to 514 * make it consume minimal amount of memory. check_stack_write() access from 515 * the program calls into realloc_func_state() to grow the stack size. 516 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state 517 * which realloc_stack_state() copies over. It points to previous 518 * bpf_verifier_state which is never reallocated. 519 */ 520 static int realloc_func_state(struct bpf_func_state *state, int stack_size, 521 int refs_size, bool copy_old) 522 { 523 int err = realloc_reference_state(state, refs_size, copy_old); 524 if (err) 525 return err; 526 return realloc_stack_state(state, stack_size, copy_old); 527 } 528 529 /* Acquire a pointer id from the env and update the state->refs to include 530 * this new pointer reference. 531 * On success, returns a valid pointer id to associate with the register 532 * On failure, returns a negative errno. 533 */ 534 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 535 { 536 struct bpf_func_state *state = cur_func(env); 537 int new_ofs = state->acquired_refs; 538 int id, err; 539 540 err = realloc_reference_state(state, state->acquired_refs + 1, true); 541 if (err) 542 return err; 543 id = ++env->id_gen; 544 state->refs[new_ofs].id = id; 545 state->refs[new_ofs].insn_idx = insn_idx; 546 547 return id; 548 } 549 550 /* release function corresponding to acquire_reference_state(). Idempotent. */ 551 static int __release_reference_state(struct bpf_func_state *state, int ptr_id) 552 { 553 int i, last_idx; 554 555 if (!ptr_id) 556 return -EFAULT; 557 558 last_idx = state->acquired_refs - 1; 559 for (i = 0; i < state->acquired_refs; i++) { 560 if (state->refs[i].id == ptr_id) { 561 if (last_idx && i != last_idx) 562 memcpy(&state->refs[i], &state->refs[last_idx], 563 sizeof(*state->refs)); 564 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 565 state->acquired_refs--; 566 return 0; 567 } 568 } 569 return -EFAULT; 570 } 571 572 /* variation on the above for cases where we expect that there must be an 573 * outstanding reference for the specified ptr_id. 574 */ 575 static int release_reference_state(struct bpf_verifier_env *env, int ptr_id) 576 { 577 struct bpf_func_state *state = cur_func(env); 578 int err; 579 580 err = __release_reference_state(state, ptr_id); 581 if (WARN_ON_ONCE(err != 0)) 582 verbose(env, "verifier internal error: can't release reference\n"); 583 return err; 584 } 585 586 static int transfer_reference_state(struct bpf_func_state *dst, 587 struct bpf_func_state *src) 588 { 589 int err = realloc_reference_state(dst, src->acquired_refs, false); 590 if (err) 591 return err; 592 err = copy_reference_state(dst, src); 593 if (err) 594 return err; 595 return 0; 596 } 597 598 static void free_func_state(struct bpf_func_state *state) 599 { 600 if (!state) 601 return; 602 kfree(state->refs); 603 kfree(state->stack); 604 kfree(state); 605 } 606 607 static void free_verifier_state(struct bpf_verifier_state *state, 608 bool free_self) 609 { 610 int i; 611 612 for (i = 0; i <= state->curframe; i++) { 613 free_func_state(state->frame[i]); 614 state->frame[i] = NULL; 615 } 616 if (free_self) 617 kfree(state); 618 } 619 620 /* copy verifier state from src to dst growing dst stack space 621 * when necessary to accommodate larger src stack 622 */ 623 static int copy_func_state(struct bpf_func_state *dst, 624 const struct bpf_func_state *src) 625 { 626 int err; 627 628 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs, 629 false); 630 if (err) 631 return err; 632 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 633 err = copy_reference_state(dst, src); 634 if (err) 635 return err; 636 return copy_stack_state(dst, src); 637 } 638 639 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 640 const struct bpf_verifier_state *src) 641 { 642 struct bpf_func_state *dst; 643 int i, err; 644 645 /* if dst has more stack frames then src frame, free them */ 646 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 647 free_func_state(dst_state->frame[i]); 648 dst_state->frame[i] = NULL; 649 } 650 dst_state->curframe = src->curframe; 651 for (i = 0; i <= src->curframe; i++) { 652 dst = dst_state->frame[i]; 653 if (!dst) { 654 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 655 if (!dst) 656 return -ENOMEM; 657 dst_state->frame[i] = dst; 658 } 659 err = copy_func_state(dst, src->frame[i]); 660 if (err) 661 return err; 662 } 663 return 0; 664 } 665 666 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 667 int *insn_idx) 668 { 669 struct bpf_verifier_state *cur = env->cur_state; 670 struct bpf_verifier_stack_elem *elem, *head = env->head; 671 int err; 672 673 if (env->head == NULL) 674 return -ENOENT; 675 676 if (cur) { 677 err = copy_verifier_state(cur, &head->st); 678 if (err) 679 return err; 680 } 681 if (insn_idx) 682 *insn_idx = head->insn_idx; 683 if (prev_insn_idx) 684 *prev_insn_idx = head->prev_insn_idx; 685 elem = head->next; 686 free_verifier_state(&head->st, false); 687 kfree(head); 688 env->head = elem; 689 env->stack_size--; 690 return 0; 691 } 692 693 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 694 int insn_idx, int prev_insn_idx) 695 { 696 struct bpf_verifier_state *cur = env->cur_state; 697 struct bpf_verifier_stack_elem *elem; 698 int err; 699 700 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 701 if (!elem) 702 goto err; 703 704 elem->insn_idx = insn_idx; 705 elem->prev_insn_idx = prev_insn_idx; 706 elem->next = env->head; 707 env->head = elem; 708 env->stack_size++; 709 err = copy_verifier_state(&elem->st, cur); 710 if (err) 711 goto err; 712 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) { 713 verbose(env, "BPF program is too complex\n"); 714 goto err; 715 } 716 return &elem->st; 717 err: 718 free_verifier_state(env->cur_state, true); 719 env->cur_state = NULL; 720 /* pop all elements and return */ 721 while (!pop_stack(env, NULL, NULL)); 722 return NULL; 723 } 724 725 #define CALLER_SAVED_REGS 6 726 static const int caller_saved[CALLER_SAVED_REGS] = { 727 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 728 }; 729 730 static void __mark_reg_not_init(struct bpf_reg_state *reg); 731 732 /* Mark the unknown part of a register (variable offset or scalar value) as 733 * known to have the value @imm. 734 */ 735 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 736 { 737 /* Clear id, off, and union(map_ptr, range) */ 738 memset(((u8 *)reg) + sizeof(reg->type), 0, 739 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 740 reg->var_off = tnum_const(imm); 741 reg->smin_value = (s64)imm; 742 reg->smax_value = (s64)imm; 743 reg->umin_value = imm; 744 reg->umax_value = imm; 745 } 746 747 /* Mark the 'variable offset' part of a register as zero. This should be 748 * used only on registers holding a pointer type. 749 */ 750 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 751 { 752 __mark_reg_known(reg, 0); 753 } 754 755 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 756 { 757 __mark_reg_known(reg, 0); 758 reg->type = SCALAR_VALUE; 759 } 760 761 static void mark_reg_known_zero(struct bpf_verifier_env *env, 762 struct bpf_reg_state *regs, u32 regno) 763 { 764 if (WARN_ON(regno >= MAX_BPF_REG)) { 765 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 766 /* Something bad happened, let's kill all regs */ 767 for (regno = 0; regno < MAX_BPF_REG; regno++) 768 __mark_reg_not_init(regs + regno); 769 return; 770 } 771 __mark_reg_known_zero(regs + regno); 772 } 773 774 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 775 { 776 return type_is_pkt_pointer(reg->type); 777 } 778 779 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 780 { 781 return reg_is_pkt_pointer(reg) || 782 reg->type == PTR_TO_PACKET_END; 783 } 784 785 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 786 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 787 enum bpf_reg_type which) 788 { 789 /* The register can already have a range from prior markings. 790 * This is fine as long as it hasn't been advanced from its 791 * origin. 792 */ 793 return reg->type == which && 794 reg->id == 0 && 795 reg->off == 0 && 796 tnum_equals_const(reg->var_off, 0); 797 } 798 799 /* Attempts to improve min/max values based on var_off information */ 800 static void __update_reg_bounds(struct bpf_reg_state *reg) 801 { 802 /* min signed is max(sign bit) | min(other bits) */ 803 reg->smin_value = max_t(s64, reg->smin_value, 804 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 805 /* max signed is min(sign bit) | max(other bits) */ 806 reg->smax_value = min_t(s64, reg->smax_value, 807 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 808 reg->umin_value = max(reg->umin_value, reg->var_off.value); 809 reg->umax_value = min(reg->umax_value, 810 reg->var_off.value | reg->var_off.mask); 811 } 812 813 /* Uses signed min/max values to inform unsigned, and vice-versa */ 814 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 815 { 816 /* Learn sign from signed bounds. 817 * If we cannot cross the sign boundary, then signed and unsigned bounds 818 * are the same, so combine. This works even in the negative case, e.g. 819 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 820 */ 821 if (reg->smin_value >= 0 || reg->smax_value < 0) { 822 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 823 reg->umin_value); 824 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 825 reg->umax_value); 826 return; 827 } 828 /* Learn sign from unsigned bounds. Signed bounds cross the sign 829 * boundary, so we must be careful. 830 */ 831 if ((s64)reg->umax_value >= 0) { 832 /* Positive. We can't learn anything from the smin, but smax 833 * is positive, hence safe. 834 */ 835 reg->smin_value = reg->umin_value; 836 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 837 reg->umax_value); 838 } else if ((s64)reg->umin_value < 0) { 839 /* Negative. We can't learn anything from the smax, but smin 840 * is negative, hence safe. 841 */ 842 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 843 reg->umin_value); 844 reg->smax_value = reg->umax_value; 845 } 846 } 847 848 /* Attempts to improve var_off based on unsigned min/max information */ 849 static void __reg_bound_offset(struct bpf_reg_state *reg) 850 { 851 reg->var_off = tnum_intersect(reg->var_off, 852 tnum_range(reg->umin_value, 853 reg->umax_value)); 854 } 855 856 /* Reset the min/max bounds of a register */ 857 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 858 { 859 reg->smin_value = S64_MIN; 860 reg->smax_value = S64_MAX; 861 reg->umin_value = 0; 862 reg->umax_value = U64_MAX; 863 } 864 865 /* Mark a register as having a completely unknown (scalar) value. */ 866 static void __mark_reg_unknown(struct bpf_reg_state *reg) 867 { 868 /* 869 * Clear type, id, off, and union(map_ptr, range) and 870 * padding between 'type' and union 871 */ 872 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 873 reg->type = SCALAR_VALUE; 874 reg->var_off = tnum_unknown; 875 reg->frameno = 0; 876 __mark_reg_unbounded(reg); 877 } 878 879 static void mark_reg_unknown(struct bpf_verifier_env *env, 880 struct bpf_reg_state *regs, u32 regno) 881 { 882 if (WARN_ON(regno >= MAX_BPF_REG)) { 883 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 884 /* Something bad happened, let's kill all regs except FP */ 885 for (regno = 0; regno < BPF_REG_FP; regno++) 886 __mark_reg_not_init(regs + regno); 887 return; 888 } 889 __mark_reg_unknown(regs + regno); 890 } 891 892 static void __mark_reg_not_init(struct bpf_reg_state *reg) 893 { 894 __mark_reg_unknown(reg); 895 reg->type = NOT_INIT; 896 } 897 898 static void mark_reg_not_init(struct bpf_verifier_env *env, 899 struct bpf_reg_state *regs, u32 regno) 900 { 901 if (WARN_ON(regno >= MAX_BPF_REG)) { 902 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 903 /* Something bad happened, let's kill all regs except FP */ 904 for (regno = 0; regno < BPF_REG_FP; regno++) 905 __mark_reg_not_init(regs + regno); 906 return; 907 } 908 __mark_reg_not_init(regs + regno); 909 } 910 911 static void init_reg_state(struct bpf_verifier_env *env, 912 struct bpf_func_state *state) 913 { 914 struct bpf_reg_state *regs = state->regs; 915 int i; 916 917 for (i = 0; i < MAX_BPF_REG; i++) { 918 mark_reg_not_init(env, regs, i); 919 regs[i].live = REG_LIVE_NONE; 920 regs[i].parent = NULL; 921 } 922 923 /* frame pointer */ 924 regs[BPF_REG_FP].type = PTR_TO_STACK; 925 mark_reg_known_zero(env, regs, BPF_REG_FP); 926 regs[BPF_REG_FP].frameno = state->frameno; 927 928 /* 1st arg to a function */ 929 regs[BPF_REG_1].type = PTR_TO_CTX; 930 mark_reg_known_zero(env, regs, BPF_REG_1); 931 } 932 933 #define BPF_MAIN_FUNC (-1) 934 static void init_func_state(struct bpf_verifier_env *env, 935 struct bpf_func_state *state, 936 int callsite, int frameno, int subprogno) 937 { 938 state->callsite = callsite; 939 state->frameno = frameno; 940 state->subprogno = subprogno; 941 init_reg_state(env, state); 942 } 943 944 enum reg_arg_type { 945 SRC_OP, /* register is used as source operand */ 946 DST_OP, /* register is used as destination operand */ 947 DST_OP_NO_MARK /* same as above, check only, don't mark */ 948 }; 949 950 static int cmp_subprogs(const void *a, const void *b) 951 { 952 return ((struct bpf_subprog_info *)a)->start - 953 ((struct bpf_subprog_info *)b)->start; 954 } 955 956 static int find_subprog(struct bpf_verifier_env *env, int off) 957 { 958 struct bpf_subprog_info *p; 959 960 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 961 sizeof(env->subprog_info[0]), cmp_subprogs); 962 if (!p) 963 return -ENOENT; 964 return p - env->subprog_info; 965 966 } 967 968 static int add_subprog(struct bpf_verifier_env *env, int off) 969 { 970 int insn_cnt = env->prog->len; 971 int ret; 972 973 if (off >= insn_cnt || off < 0) { 974 verbose(env, "call to invalid destination\n"); 975 return -EINVAL; 976 } 977 ret = find_subprog(env, off); 978 if (ret >= 0) 979 return 0; 980 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 981 verbose(env, "too many subprograms\n"); 982 return -E2BIG; 983 } 984 env->subprog_info[env->subprog_cnt++].start = off; 985 sort(env->subprog_info, env->subprog_cnt, 986 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 987 return 0; 988 } 989 990 static int check_subprogs(struct bpf_verifier_env *env) 991 { 992 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0; 993 struct bpf_subprog_info *subprog = env->subprog_info; 994 struct bpf_insn *insn = env->prog->insnsi; 995 int insn_cnt = env->prog->len; 996 997 /* Add entry function. */ 998 ret = add_subprog(env, 0); 999 if (ret < 0) 1000 return ret; 1001 1002 /* determine subprog starts. The end is one before the next starts */ 1003 for (i = 0; i < insn_cnt; i++) { 1004 if (insn[i].code != (BPF_JMP | BPF_CALL)) 1005 continue; 1006 if (insn[i].src_reg != BPF_PSEUDO_CALL) 1007 continue; 1008 if (!env->allow_ptr_leaks) { 1009 verbose(env, "function calls to other bpf functions are allowed for root only\n"); 1010 return -EPERM; 1011 } 1012 ret = add_subprog(env, i + insn[i].imm + 1); 1013 if (ret < 0) 1014 return ret; 1015 } 1016 1017 /* Add a fake 'exit' subprog which could simplify subprog iteration 1018 * logic. 'subprog_cnt' should not be increased. 1019 */ 1020 subprog[env->subprog_cnt].start = insn_cnt; 1021 1022 if (env->log.level > 1) 1023 for (i = 0; i < env->subprog_cnt; i++) 1024 verbose(env, "func#%d @%d\n", i, subprog[i].start); 1025 1026 /* now check that all jumps are within the same subprog */ 1027 subprog_start = subprog[cur_subprog].start; 1028 subprog_end = subprog[cur_subprog + 1].start; 1029 for (i = 0; i < insn_cnt; i++) { 1030 u8 code = insn[i].code; 1031 1032 if (BPF_CLASS(code) != BPF_JMP) 1033 goto next; 1034 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 1035 goto next; 1036 off = i + insn[i].off + 1; 1037 if (off < subprog_start || off >= subprog_end) { 1038 verbose(env, "jump out of range from insn %d to %d\n", i, off); 1039 return -EINVAL; 1040 } 1041 next: 1042 if (i == subprog_end - 1) { 1043 /* to avoid fall-through from one subprog into another 1044 * the last insn of the subprog should be either exit 1045 * or unconditional jump back 1046 */ 1047 if (code != (BPF_JMP | BPF_EXIT) && 1048 code != (BPF_JMP | BPF_JA)) { 1049 verbose(env, "last insn is not an exit or jmp\n"); 1050 return -EINVAL; 1051 } 1052 subprog_start = subprog_end; 1053 cur_subprog++; 1054 if (cur_subprog < env->subprog_cnt) 1055 subprog_end = subprog[cur_subprog + 1].start; 1056 } 1057 } 1058 return 0; 1059 } 1060 1061 /* Parentage chain of this register (or stack slot) should take care of all 1062 * issues like callee-saved registers, stack slot allocation time, etc. 1063 */ 1064 static int mark_reg_read(struct bpf_verifier_env *env, 1065 const struct bpf_reg_state *state, 1066 struct bpf_reg_state *parent) 1067 { 1068 bool writes = parent == state->parent; /* Observe write marks */ 1069 1070 while (parent) { 1071 /* if read wasn't screened by an earlier write ... */ 1072 if (writes && state->live & REG_LIVE_WRITTEN) 1073 break; 1074 /* ... then we depend on parent's value */ 1075 parent->live |= REG_LIVE_READ; 1076 state = parent; 1077 parent = state->parent; 1078 writes = true; 1079 } 1080 return 0; 1081 } 1082 1083 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 1084 enum reg_arg_type t) 1085 { 1086 struct bpf_verifier_state *vstate = env->cur_state; 1087 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 1088 struct bpf_reg_state *regs = state->regs; 1089 1090 if (regno >= MAX_BPF_REG) { 1091 verbose(env, "R%d is invalid\n", regno); 1092 return -EINVAL; 1093 } 1094 1095 if (t == SRC_OP) { 1096 /* check whether register used as source operand can be read */ 1097 if (regs[regno].type == NOT_INIT) { 1098 verbose(env, "R%d !read_ok\n", regno); 1099 return -EACCES; 1100 } 1101 /* We don't need to worry about FP liveness because it's read-only */ 1102 if (regno != BPF_REG_FP) 1103 return mark_reg_read(env, ®s[regno], 1104 regs[regno].parent); 1105 } else { 1106 /* check whether register used as dest operand can be written to */ 1107 if (regno == BPF_REG_FP) { 1108 verbose(env, "frame pointer is read only\n"); 1109 return -EACCES; 1110 } 1111 regs[regno].live |= REG_LIVE_WRITTEN; 1112 if (t == DST_OP) 1113 mark_reg_unknown(env, regs, regno); 1114 } 1115 return 0; 1116 } 1117 1118 static bool is_spillable_regtype(enum bpf_reg_type type) 1119 { 1120 switch (type) { 1121 case PTR_TO_MAP_VALUE: 1122 case PTR_TO_MAP_VALUE_OR_NULL: 1123 case PTR_TO_STACK: 1124 case PTR_TO_CTX: 1125 case PTR_TO_PACKET: 1126 case PTR_TO_PACKET_META: 1127 case PTR_TO_PACKET_END: 1128 case PTR_TO_FLOW_KEYS: 1129 case CONST_PTR_TO_MAP: 1130 case PTR_TO_SOCKET: 1131 case PTR_TO_SOCKET_OR_NULL: 1132 return true; 1133 default: 1134 return false; 1135 } 1136 } 1137 1138 /* Does this register contain a constant zero? */ 1139 static bool register_is_null(struct bpf_reg_state *reg) 1140 { 1141 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 1142 } 1143 1144 /* check_stack_read/write functions track spill/fill of registers, 1145 * stack boundary and alignment are checked in check_mem_access() 1146 */ 1147 static int check_stack_write(struct bpf_verifier_env *env, 1148 struct bpf_func_state *state, /* func where register points to */ 1149 int off, int size, int value_regno, int insn_idx) 1150 { 1151 struct bpf_func_state *cur; /* state of the current function */ 1152 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 1153 enum bpf_reg_type type; 1154 1155 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE), 1156 state->acquired_refs, true); 1157 if (err) 1158 return err; 1159 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 1160 * so it's aligned access and [off, off + size) are within stack limits 1161 */ 1162 if (!env->allow_ptr_leaks && 1163 state->stack[spi].slot_type[0] == STACK_SPILL && 1164 size != BPF_REG_SIZE) { 1165 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 1166 return -EACCES; 1167 } 1168 1169 cur = env->cur_state->frame[env->cur_state->curframe]; 1170 if (value_regno >= 0 && 1171 is_spillable_regtype((type = cur->regs[value_regno].type))) { 1172 1173 /* register containing pointer is being spilled into stack */ 1174 if (size != BPF_REG_SIZE) { 1175 verbose(env, "invalid size of register spill\n"); 1176 return -EACCES; 1177 } 1178 1179 if (state != cur && type == PTR_TO_STACK) { 1180 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 1181 return -EINVAL; 1182 } 1183 1184 /* save register state */ 1185 state->stack[spi].spilled_ptr = cur->regs[value_regno]; 1186 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1187 1188 for (i = 0; i < BPF_REG_SIZE; i++) { 1189 if (state->stack[spi].slot_type[i] == STACK_MISC && 1190 !env->allow_ptr_leaks) { 1191 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off; 1192 int soff = (-spi - 1) * BPF_REG_SIZE; 1193 1194 /* detected reuse of integer stack slot with a pointer 1195 * which means either llvm is reusing stack slot or 1196 * an attacker is trying to exploit CVE-2018-3639 1197 * (speculative store bypass) 1198 * Have to sanitize that slot with preemptive 1199 * store of zero. 1200 */ 1201 if (*poff && *poff != soff) { 1202 /* disallow programs where single insn stores 1203 * into two different stack slots, since verifier 1204 * cannot sanitize them 1205 */ 1206 verbose(env, 1207 "insn %d cannot access two stack slots fp%d and fp%d", 1208 insn_idx, *poff, soff); 1209 return -EINVAL; 1210 } 1211 *poff = soff; 1212 } 1213 state->stack[spi].slot_type[i] = STACK_SPILL; 1214 } 1215 } else { 1216 u8 type = STACK_MISC; 1217 1218 /* regular write of data into stack destroys any spilled ptr */ 1219 state->stack[spi].spilled_ptr.type = NOT_INIT; 1220 1221 /* only mark the slot as written if all 8 bytes were written 1222 * otherwise read propagation may incorrectly stop too soon 1223 * when stack slots are partially written. 1224 * This heuristic means that read propagation will be 1225 * conservative, since it will add reg_live_read marks 1226 * to stack slots all the way to first state when programs 1227 * writes+reads less than 8 bytes 1228 */ 1229 if (size == BPF_REG_SIZE) 1230 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1231 1232 /* when we zero initialize stack slots mark them as such */ 1233 if (value_regno >= 0 && 1234 register_is_null(&cur->regs[value_regno])) 1235 type = STACK_ZERO; 1236 1237 for (i = 0; i < size; i++) 1238 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 1239 type; 1240 } 1241 return 0; 1242 } 1243 1244 static int check_stack_read(struct bpf_verifier_env *env, 1245 struct bpf_func_state *reg_state /* func where register points to */, 1246 int off, int size, int value_regno) 1247 { 1248 struct bpf_verifier_state *vstate = env->cur_state; 1249 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 1250 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 1251 u8 *stype; 1252 1253 if (reg_state->allocated_stack <= slot) { 1254 verbose(env, "invalid read from stack off %d+0 size %d\n", 1255 off, size); 1256 return -EACCES; 1257 } 1258 stype = reg_state->stack[spi].slot_type; 1259 1260 if (stype[0] == STACK_SPILL) { 1261 if (size != BPF_REG_SIZE) { 1262 verbose(env, "invalid size of register spill\n"); 1263 return -EACCES; 1264 } 1265 for (i = 1; i < BPF_REG_SIZE; i++) { 1266 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { 1267 verbose(env, "corrupted spill memory\n"); 1268 return -EACCES; 1269 } 1270 } 1271 1272 if (value_regno >= 0) { 1273 /* restore register state from stack */ 1274 state->regs[value_regno] = reg_state->stack[spi].spilled_ptr; 1275 /* mark reg as written since spilled pointer state likely 1276 * has its liveness marks cleared by is_state_visited() 1277 * which resets stack/reg liveness for state transitions 1278 */ 1279 state->regs[value_regno].live |= REG_LIVE_WRITTEN; 1280 } 1281 mark_reg_read(env, ®_state->stack[spi].spilled_ptr, 1282 reg_state->stack[spi].spilled_ptr.parent); 1283 return 0; 1284 } else { 1285 int zeros = 0; 1286 1287 for (i = 0; i < size; i++) { 1288 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC) 1289 continue; 1290 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) { 1291 zeros++; 1292 continue; 1293 } 1294 verbose(env, "invalid read from stack off %d+%d size %d\n", 1295 off, i, size); 1296 return -EACCES; 1297 } 1298 mark_reg_read(env, ®_state->stack[spi].spilled_ptr, 1299 reg_state->stack[spi].spilled_ptr.parent); 1300 if (value_regno >= 0) { 1301 if (zeros == size) { 1302 /* any size read into register is zero extended, 1303 * so the whole register == const_zero 1304 */ 1305 __mark_reg_const_zero(&state->regs[value_regno]); 1306 } else { 1307 /* have read misc data from the stack */ 1308 mark_reg_unknown(env, state->regs, value_regno); 1309 } 1310 state->regs[value_regno].live |= REG_LIVE_WRITTEN; 1311 } 1312 return 0; 1313 } 1314 } 1315 1316 /* check read/write into map element returned by bpf_map_lookup_elem() */ 1317 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off, 1318 int size, bool zero_size_allowed) 1319 { 1320 struct bpf_reg_state *regs = cur_regs(env); 1321 struct bpf_map *map = regs[regno].map_ptr; 1322 1323 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || 1324 off + size > map->value_size) { 1325 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 1326 map->value_size, off, size); 1327 return -EACCES; 1328 } 1329 return 0; 1330 } 1331 1332 /* check read/write into a map element with possible variable offset */ 1333 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 1334 int off, int size, bool zero_size_allowed) 1335 { 1336 struct bpf_verifier_state *vstate = env->cur_state; 1337 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 1338 struct bpf_reg_state *reg = &state->regs[regno]; 1339 int err; 1340 1341 /* We may have adjusted the register to this map value, so we 1342 * need to try adding each of min_value and max_value to off 1343 * to make sure our theoretical access will be safe. 1344 */ 1345 if (env->log.level) 1346 print_verifier_state(env, state); 1347 /* The minimum value is only important with signed 1348 * comparisons where we can't assume the floor of a 1349 * value is 0. If we are using signed variables for our 1350 * index'es we need to make sure that whatever we use 1351 * will have a set floor within our range. 1352 */ 1353 if (reg->smin_value < 0) { 1354 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 1355 regno); 1356 return -EACCES; 1357 } 1358 err = __check_map_access(env, regno, reg->smin_value + off, size, 1359 zero_size_allowed); 1360 if (err) { 1361 verbose(env, "R%d min value is outside of the array range\n", 1362 regno); 1363 return err; 1364 } 1365 1366 /* If we haven't set a max value then we need to bail since we can't be 1367 * sure we won't do bad things. 1368 * If reg->umax_value + off could overflow, treat that as unbounded too. 1369 */ 1370 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 1371 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n", 1372 regno); 1373 return -EACCES; 1374 } 1375 err = __check_map_access(env, regno, reg->umax_value + off, size, 1376 zero_size_allowed); 1377 if (err) 1378 verbose(env, "R%d max value is outside of the array range\n", 1379 regno); 1380 return err; 1381 } 1382 1383 #define MAX_PACKET_OFF 0xffff 1384 1385 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 1386 const struct bpf_call_arg_meta *meta, 1387 enum bpf_access_type t) 1388 { 1389 switch (env->prog->type) { 1390 case BPF_PROG_TYPE_LWT_IN: 1391 case BPF_PROG_TYPE_LWT_OUT: 1392 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 1393 case BPF_PROG_TYPE_SK_REUSEPORT: 1394 /* dst_input() and dst_output() can't write for now */ 1395 if (t == BPF_WRITE) 1396 return false; 1397 /* fallthrough */ 1398 case BPF_PROG_TYPE_SCHED_CLS: 1399 case BPF_PROG_TYPE_SCHED_ACT: 1400 case BPF_PROG_TYPE_XDP: 1401 case BPF_PROG_TYPE_LWT_XMIT: 1402 case BPF_PROG_TYPE_SK_SKB: 1403 case BPF_PROG_TYPE_SK_MSG: 1404 case BPF_PROG_TYPE_FLOW_DISSECTOR: 1405 if (meta) 1406 return meta->pkt_access; 1407 1408 env->seen_direct_write = true; 1409 return true; 1410 default: 1411 return false; 1412 } 1413 } 1414 1415 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno, 1416 int off, int size, bool zero_size_allowed) 1417 { 1418 struct bpf_reg_state *regs = cur_regs(env); 1419 struct bpf_reg_state *reg = ®s[regno]; 1420 1421 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || 1422 (u64)off + size > reg->range) { 1423 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 1424 off, size, regno, reg->id, reg->off, reg->range); 1425 return -EACCES; 1426 } 1427 return 0; 1428 } 1429 1430 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 1431 int size, bool zero_size_allowed) 1432 { 1433 struct bpf_reg_state *regs = cur_regs(env); 1434 struct bpf_reg_state *reg = ®s[regno]; 1435 int err; 1436 1437 /* We may have added a variable offset to the packet pointer; but any 1438 * reg->range we have comes after that. We are only checking the fixed 1439 * offset. 1440 */ 1441 1442 /* We don't allow negative numbers, because we aren't tracking enough 1443 * detail to prove they're safe. 1444 */ 1445 if (reg->smin_value < 0) { 1446 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 1447 regno); 1448 return -EACCES; 1449 } 1450 err = __check_packet_access(env, regno, off, size, zero_size_allowed); 1451 if (err) { 1452 verbose(env, "R%d offset is outside of the packet\n", regno); 1453 return err; 1454 } 1455 return err; 1456 } 1457 1458 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 1459 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 1460 enum bpf_access_type t, enum bpf_reg_type *reg_type) 1461 { 1462 struct bpf_insn_access_aux info = { 1463 .reg_type = *reg_type, 1464 }; 1465 1466 if (env->ops->is_valid_access && 1467 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 1468 /* A non zero info.ctx_field_size indicates that this field is a 1469 * candidate for later verifier transformation to load the whole 1470 * field and then apply a mask when accessed with a narrower 1471 * access than actual ctx access size. A zero info.ctx_field_size 1472 * will only allow for whole field access and rejects any other 1473 * type of narrower access. 1474 */ 1475 *reg_type = info.reg_type; 1476 1477 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 1478 /* remember the offset of last byte accessed in ctx */ 1479 if (env->prog->aux->max_ctx_offset < off + size) 1480 env->prog->aux->max_ctx_offset = off + size; 1481 return 0; 1482 } 1483 1484 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 1485 return -EACCES; 1486 } 1487 1488 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 1489 int size) 1490 { 1491 if (size < 0 || off < 0 || 1492 (u64)off + size > sizeof(struct bpf_flow_keys)) { 1493 verbose(env, "invalid access to flow keys off=%d size=%d\n", 1494 off, size); 1495 return -EACCES; 1496 } 1497 return 0; 1498 } 1499 1500 static int check_sock_access(struct bpf_verifier_env *env, u32 regno, int off, 1501 int size, enum bpf_access_type t) 1502 { 1503 struct bpf_reg_state *regs = cur_regs(env); 1504 struct bpf_reg_state *reg = ®s[regno]; 1505 struct bpf_insn_access_aux info; 1506 1507 if (reg->smin_value < 0) { 1508 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 1509 regno); 1510 return -EACCES; 1511 } 1512 1513 if (!bpf_sock_is_valid_access(off, size, t, &info)) { 1514 verbose(env, "invalid bpf_sock access off=%d size=%d\n", 1515 off, size); 1516 return -EACCES; 1517 } 1518 1519 return 0; 1520 } 1521 1522 static bool __is_pointer_value(bool allow_ptr_leaks, 1523 const struct bpf_reg_state *reg) 1524 { 1525 if (allow_ptr_leaks) 1526 return false; 1527 1528 return reg->type != SCALAR_VALUE; 1529 } 1530 1531 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 1532 { 1533 return __is_pointer_value(env->allow_ptr_leaks, cur_regs(env) + regno); 1534 } 1535 1536 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 1537 { 1538 const struct bpf_reg_state *reg = cur_regs(env) + regno; 1539 1540 return reg->type == PTR_TO_CTX || 1541 reg->type == PTR_TO_SOCKET; 1542 } 1543 1544 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 1545 { 1546 const struct bpf_reg_state *reg = cur_regs(env) + regno; 1547 1548 return type_is_pkt_pointer(reg->type); 1549 } 1550 1551 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 1552 const struct bpf_reg_state *reg, 1553 int off, int size, bool strict) 1554 { 1555 struct tnum reg_off; 1556 int ip_align; 1557 1558 /* Byte size accesses are always allowed. */ 1559 if (!strict || size == 1) 1560 return 0; 1561 1562 /* For platforms that do not have a Kconfig enabling 1563 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 1564 * NET_IP_ALIGN is universally set to '2'. And on platforms 1565 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 1566 * to this code only in strict mode where we want to emulate 1567 * the NET_IP_ALIGN==2 checking. Therefore use an 1568 * unconditional IP align value of '2'. 1569 */ 1570 ip_align = 2; 1571 1572 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 1573 if (!tnum_is_aligned(reg_off, size)) { 1574 char tn_buf[48]; 1575 1576 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1577 verbose(env, 1578 "misaligned packet access off %d+%s+%d+%d size %d\n", 1579 ip_align, tn_buf, reg->off, off, size); 1580 return -EACCES; 1581 } 1582 1583 return 0; 1584 } 1585 1586 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 1587 const struct bpf_reg_state *reg, 1588 const char *pointer_desc, 1589 int off, int size, bool strict) 1590 { 1591 struct tnum reg_off; 1592 1593 /* Byte size accesses are always allowed. */ 1594 if (!strict || size == 1) 1595 return 0; 1596 1597 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 1598 if (!tnum_is_aligned(reg_off, size)) { 1599 char tn_buf[48]; 1600 1601 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1602 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 1603 pointer_desc, tn_buf, reg->off, off, size); 1604 return -EACCES; 1605 } 1606 1607 return 0; 1608 } 1609 1610 static int check_ptr_alignment(struct bpf_verifier_env *env, 1611 const struct bpf_reg_state *reg, int off, 1612 int size, bool strict_alignment_once) 1613 { 1614 bool strict = env->strict_alignment || strict_alignment_once; 1615 const char *pointer_desc = ""; 1616 1617 switch (reg->type) { 1618 case PTR_TO_PACKET: 1619 case PTR_TO_PACKET_META: 1620 /* Special case, because of NET_IP_ALIGN. Given metadata sits 1621 * right in front, treat it the very same way. 1622 */ 1623 return check_pkt_ptr_alignment(env, reg, off, size, strict); 1624 case PTR_TO_FLOW_KEYS: 1625 pointer_desc = "flow keys "; 1626 break; 1627 case PTR_TO_MAP_VALUE: 1628 pointer_desc = "value "; 1629 break; 1630 case PTR_TO_CTX: 1631 pointer_desc = "context "; 1632 break; 1633 case PTR_TO_STACK: 1634 pointer_desc = "stack "; 1635 /* The stack spill tracking logic in check_stack_write() 1636 * and check_stack_read() relies on stack accesses being 1637 * aligned. 1638 */ 1639 strict = true; 1640 break; 1641 case PTR_TO_SOCKET: 1642 pointer_desc = "sock "; 1643 break; 1644 default: 1645 break; 1646 } 1647 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 1648 strict); 1649 } 1650 1651 static int update_stack_depth(struct bpf_verifier_env *env, 1652 const struct bpf_func_state *func, 1653 int off) 1654 { 1655 u16 stack = env->subprog_info[func->subprogno].stack_depth; 1656 1657 if (stack >= -off) 1658 return 0; 1659 1660 /* update known max for given subprogram */ 1661 env->subprog_info[func->subprogno].stack_depth = -off; 1662 return 0; 1663 } 1664 1665 /* starting from main bpf function walk all instructions of the function 1666 * and recursively walk all callees that given function can call. 1667 * Ignore jump and exit insns. 1668 * Since recursion is prevented by check_cfg() this algorithm 1669 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 1670 */ 1671 static int check_max_stack_depth(struct bpf_verifier_env *env) 1672 { 1673 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 1674 struct bpf_subprog_info *subprog = env->subprog_info; 1675 struct bpf_insn *insn = env->prog->insnsi; 1676 int ret_insn[MAX_CALL_FRAMES]; 1677 int ret_prog[MAX_CALL_FRAMES]; 1678 1679 process_func: 1680 /* round up to 32-bytes, since this is granularity 1681 * of interpreter stack size 1682 */ 1683 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 1684 if (depth > MAX_BPF_STACK) { 1685 verbose(env, "combined stack size of %d calls is %d. Too large\n", 1686 frame + 1, depth); 1687 return -EACCES; 1688 } 1689 continue_func: 1690 subprog_end = subprog[idx + 1].start; 1691 for (; i < subprog_end; i++) { 1692 if (insn[i].code != (BPF_JMP | BPF_CALL)) 1693 continue; 1694 if (insn[i].src_reg != BPF_PSEUDO_CALL) 1695 continue; 1696 /* remember insn and function to return to */ 1697 ret_insn[frame] = i + 1; 1698 ret_prog[frame] = idx; 1699 1700 /* find the callee */ 1701 i = i + insn[i].imm + 1; 1702 idx = find_subprog(env, i); 1703 if (idx < 0) { 1704 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 1705 i); 1706 return -EFAULT; 1707 } 1708 frame++; 1709 if (frame >= MAX_CALL_FRAMES) { 1710 WARN_ONCE(1, "verifier bug. Call stack is too deep\n"); 1711 return -EFAULT; 1712 } 1713 goto process_func; 1714 } 1715 /* end of for() loop means the last insn of the 'subprog' 1716 * was reached. Doesn't matter whether it was JA or EXIT 1717 */ 1718 if (frame == 0) 1719 return 0; 1720 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 1721 frame--; 1722 i = ret_insn[frame]; 1723 idx = ret_prog[frame]; 1724 goto continue_func; 1725 } 1726 1727 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 1728 static int get_callee_stack_depth(struct bpf_verifier_env *env, 1729 const struct bpf_insn *insn, int idx) 1730 { 1731 int start = idx + insn->imm + 1, subprog; 1732 1733 subprog = find_subprog(env, start); 1734 if (subprog < 0) { 1735 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 1736 start); 1737 return -EFAULT; 1738 } 1739 return env->subprog_info[subprog].stack_depth; 1740 } 1741 #endif 1742 1743 static int check_ctx_reg(struct bpf_verifier_env *env, 1744 const struct bpf_reg_state *reg, int regno) 1745 { 1746 /* Access to ctx or passing it to a helper is only allowed in 1747 * its original, unmodified form. 1748 */ 1749 1750 if (reg->off) { 1751 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n", 1752 regno, reg->off); 1753 return -EACCES; 1754 } 1755 1756 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 1757 char tn_buf[48]; 1758 1759 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1760 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf); 1761 return -EACCES; 1762 } 1763 1764 return 0; 1765 } 1766 1767 /* truncate register to smaller size (in bytes) 1768 * must be called with size < BPF_REG_SIZE 1769 */ 1770 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 1771 { 1772 u64 mask; 1773 1774 /* clear high bits in bit representation */ 1775 reg->var_off = tnum_cast(reg->var_off, size); 1776 1777 /* fix arithmetic bounds */ 1778 mask = ((u64)1 << (size * 8)) - 1; 1779 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 1780 reg->umin_value &= mask; 1781 reg->umax_value &= mask; 1782 } else { 1783 reg->umin_value = 0; 1784 reg->umax_value = mask; 1785 } 1786 reg->smin_value = reg->umin_value; 1787 reg->smax_value = reg->umax_value; 1788 } 1789 1790 /* check whether memory at (regno + off) is accessible for t = (read | write) 1791 * if t==write, value_regno is a register which value is stored into memory 1792 * if t==read, value_regno is a register which will receive the value from memory 1793 * if t==write && value_regno==-1, some unknown value is stored into memory 1794 * if t==read && value_regno==-1, don't care what we read from memory 1795 */ 1796 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 1797 int off, int bpf_size, enum bpf_access_type t, 1798 int value_regno, bool strict_alignment_once) 1799 { 1800 struct bpf_reg_state *regs = cur_regs(env); 1801 struct bpf_reg_state *reg = regs + regno; 1802 struct bpf_func_state *state; 1803 int size, err = 0; 1804 1805 size = bpf_size_to_bytes(bpf_size); 1806 if (size < 0) 1807 return size; 1808 1809 /* alignment checks will add in reg->off themselves */ 1810 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 1811 if (err) 1812 return err; 1813 1814 /* for access checks, reg->off is just part of off */ 1815 off += reg->off; 1816 1817 if (reg->type == PTR_TO_MAP_VALUE) { 1818 if (t == BPF_WRITE && value_regno >= 0 && 1819 is_pointer_value(env, value_regno)) { 1820 verbose(env, "R%d leaks addr into map\n", value_regno); 1821 return -EACCES; 1822 } 1823 1824 err = check_map_access(env, regno, off, size, false); 1825 if (!err && t == BPF_READ && value_regno >= 0) 1826 mark_reg_unknown(env, regs, value_regno); 1827 1828 } else if (reg->type == PTR_TO_CTX) { 1829 enum bpf_reg_type reg_type = SCALAR_VALUE; 1830 1831 if (t == BPF_WRITE && value_regno >= 0 && 1832 is_pointer_value(env, value_regno)) { 1833 verbose(env, "R%d leaks addr into ctx\n", value_regno); 1834 return -EACCES; 1835 } 1836 1837 err = check_ctx_reg(env, reg, regno); 1838 if (err < 0) 1839 return err; 1840 1841 err = check_ctx_access(env, insn_idx, off, size, t, ®_type); 1842 if (!err && t == BPF_READ && value_regno >= 0) { 1843 /* ctx access returns either a scalar, or a 1844 * PTR_TO_PACKET[_META,_END]. In the latter 1845 * case, we know the offset is zero. 1846 */ 1847 if (reg_type == SCALAR_VALUE) 1848 mark_reg_unknown(env, regs, value_regno); 1849 else 1850 mark_reg_known_zero(env, regs, 1851 value_regno); 1852 regs[value_regno].type = reg_type; 1853 } 1854 1855 } else if (reg->type == PTR_TO_STACK) { 1856 /* stack accesses must be at a fixed offset, so that we can 1857 * determine what type of data were returned. 1858 * See check_stack_read(). 1859 */ 1860 if (!tnum_is_const(reg->var_off)) { 1861 char tn_buf[48]; 1862 1863 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1864 verbose(env, "variable stack access var_off=%s off=%d size=%d", 1865 tn_buf, off, size); 1866 return -EACCES; 1867 } 1868 off += reg->var_off.value; 1869 if (off >= 0 || off < -MAX_BPF_STACK) { 1870 verbose(env, "invalid stack off=%d size=%d\n", off, 1871 size); 1872 return -EACCES; 1873 } 1874 1875 state = func(env, reg); 1876 err = update_stack_depth(env, state, off); 1877 if (err) 1878 return err; 1879 1880 if (t == BPF_WRITE) 1881 err = check_stack_write(env, state, off, size, 1882 value_regno, insn_idx); 1883 else 1884 err = check_stack_read(env, state, off, size, 1885 value_regno); 1886 } else if (reg_is_pkt_pointer(reg)) { 1887 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 1888 verbose(env, "cannot write into packet\n"); 1889 return -EACCES; 1890 } 1891 if (t == BPF_WRITE && value_regno >= 0 && 1892 is_pointer_value(env, value_regno)) { 1893 verbose(env, "R%d leaks addr into packet\n", 1894 value_regno); 1895 return -EACCES; 1896 } 1897 err = check_packet_access(env, regno, off, size, false); 1898 if (!err && t == BPF_READ && value_regno >= 0) 1899 mark_reg_unknown(env, regs, value_regno); 1900 } else if (reg->type == PTR_TO_FLOW_KEYS) { 1901 if (t == BPF_WRITE && value_regno >= 0 && 1902 is_pointer_value(env, value_regno)) { 1903 verbose(env, "R%d leaks addr into flow keys\n", 1904 value_regno); 1905 return -EACCES; 1906 } 1907 1908 err = check_flow_keys_access(env, off, size); 1909 if (!err && t == BPF_READ && value_regno >= 0) 1910 mark_reg_unknown(env, regs, value_regno); 1911 } else if (reg->type == PTR_TO_SOCKET) { 1912 if (t == BPF_WRITE) { 1913 verbose(env, "cannot write into socket\n"); 1914 return -EACCES; 1915 } 1916 err = check_sock_access(env, regno, off, size, t); 1917 if (!err && value_regno >= 0) 1918 mark_reg_unknown(env, regs, value_regno); 1919 } else { 1920 verbose(env, "R%d invalid mem access '%s'\n", regno, 1921 reg_type_str[reg->type]); 1922 return -EACCES; 1923 } 1924 1925 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 1926 regs[value_regno].type == SCALAR_VALUE) { 1927 /* b/h/w load zero-extends, mark upper bits as known 0 */ 1928 coerce_reg_to_size(®s[value_regno], size); 1929 } 1930 return err; 1931 } 1932 1933 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 1934 { 1935 int err; 1936 1937 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) || 1938 insn->imm != 0) { 1939 verbose(env, "BPF_XADD uses reserved fields\n"); 1940 return -EINVAL; 1941 } 1942 1943 /* check src1 operand */ 1944 err = check_reg_arg(env, insn->src_reg, SRC_OP); 1945 if (err) 1946 return err; 1947 1948 /* check src2 operand */ 1949 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 1950 if (err) 1951 return err; 1952 1953 if (is_pointer_value(env, insn->src_reg)) { 1954 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 1955 return -EACCES; 1956 } 1957 1958 if (is_ctx_reg(env, insn->dst_reg) || 1959 is_pkt_reg(env, insn->dst_reg)) { 1960 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n", 1961 insn->dst_reg, reg_type_str[insn->dst_reg]); 1962 return -EACCES; 1963 } 1964 1965 /* check whether atomic_add can read the memory */ 1966 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 1967 BPF_SIZE(insn->code), BPF_READ, -1, true); 1968 if (err) 1969 return err; 1970 1971 /* check whether atomic_add can write into the same memory */ 1972 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 1973 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 1974 } 1975 1976 /* when register 'regno' is passed into function that will read 'access_size' 1977 * bytes from that pointer, make sure that it's within stack boundary 1978 * and all elements of stack are initialized. 1979 * Unlike most pointer bounds-checking functions, this one doesn't take an 1980 * 'off' argument, so it has to add in reg->off itself. 1981 */ 1982 static int check_stack_boundary(struct bpf_verifier_env *env, int regno, 1983 int access_size, bool zero_size_allowed, 1984 struct bpf_call_arg_meta *meta) 1985 { 1986 struct bpf_reg_state *reg = cur_regs(env) + regno; 1987 struct bpf_func_state *state = func(env, reg); 1988 int off, i, slot, spi; 1989 1990 if (reg->type != PTR_TO_STACK) { 1991 /* Allow zero-byte read from NULL, regardless of pointer type */ 1992 if (zero_size_allowed && access_size == 0 && 1993 register_is_null(reg)) 1994 return 0; 1995 1996 verbose(env, "R%d type=%s expected=%s\n", regno, 1997 reg_type_str[reg->type], 1998 reg_type_str[PTR_TO_STACK]); 1999 return -EACCES; 2000 } 2001 2002 /* Only allow fixed-offset stack reads */ 2003 if (!tnum_is_const(reg->var_off)) { 2004 char tn_buf[48]; 2005 2006 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2007 verbose(env, "invalid variable stack read R%d var_off=%s\n", 2008 regno, tn_buf); 2009 return -EACCES; 2010 } 2011 off = reg->off + reg->var_off.value; 2012 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || 2013 access_size < 0 || (access_size == 0 && !zero_size_allowed)) { 2014 verbose(env, "invalid stack type R%d off=%d access_size=%d\n", 2015 regno, off, access_size); 2016 return -EACCES; 2017 } 2018 2019 if (meta && meta->raw_mode) { 2020 meta->access_size = access_size; 2021 meta->regno = regno; 2022 return 0; 2023 } 2024 2025 for (i = 0; i < access_size; i++) { 2026 u8 *stype; 2027 2028 slot = -(off + i) - 1; 2029 spi = slot / BPF_REG_SIZE; 2030 if (state->allocated_stack <= slot) 2031 goto err; 2032 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 2033 if (*stype == STACK_MISC) 2034 goto mark; 2035 if (*stype == STACK_ZERO) { 2036 /* helper can write anything into the stack */ 2037 *stype = STACK_MISC; 2038 goto mark; 2039 } 2040 err: 2041 verbose(env, "invalid indirect read from stack off %d+%d size %d\n", 2042 off, i, access_size); 2043 return -EACCES; 2044 mark: 2045 /* reading any byte out of 8-byte 'spill_slot' will cause 2046 * the whole slot to be marked as 'read' 2047 */ 2048 mark_reg_read(env, &state->stack[spi].spilled_ptr, 2049 state->stack[spi].spilled_ptr.parent); 2050 } 2051 return update_stack_depth(env, state, off); 2052 } 2053 2054 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 2055 int access_size, bool zero_size_allowed, 2056 struct bpf_call_arg_meta *meta) 2057 { 2058 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 2059 2060 switch (reg->type) { 2061 case PTR_TO_PACKET: 2062 case PTR_TO_PACKET_META: 2063 return check_packet_access(env, regno, reg->off, access_size, 2064 zero_size_allowed); 2065 case PTR_TO_FLOW_KEYS: 2066 return check_flow_keys_access(env, reg->off, access_size); 2067 case PTR_TO_MAP_VALUE: 2068 return check_map_access(env, regno, reg->off, access_size, 2069 zero_size_allowed); 2070 default: /* scalar_value|ptr_to_stack or invalid ptr */ 2071 return check_stack_boundary(env, regno, access_size, 2072 zero_size_allowed, meta); 2073 } 2074 } 2075 2076 static bool arg_type_is_mem_ptr(enum bpf_arg_type type) 2077 { 2078 return type == ARG_PTR_TO_MEM || 2079 type == ARG_PTR_TO_MEM_OR_NULL || 2080 type == ARG_PTR_TO_UNINIT_MEM; 2081 } 2082 2083 static bool arg_type_is_mem_size(enum bpf_arg_type type) 2084 { 2085 return type == ARG_CONST_SIZE || 2086 type == ARG_CONST_SIZE_OR_ZERO; 2087 } 2088 2089 static int check_func_arg(struct bpf_verifier_env *env, u32 regno, 2090 enum bpf_arg_type arg_type, 2091 struct bpf_call_arg_meta *meta) 2092 { 2093 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 2094 enum bpf_reg_type expected_type, type = reg->type; 2095 int err = 0; 2096 2097 if (arg_type == ARG_DONTCARE) 2098 return 0; 2099 2100 err = check_reg_arg(env, regno, SRC_OP); 2101 if (err) 2102 return err; 2103 2104 if (arg_type == ARG_ANYTHING) { 2105 if (is_pointer_value(env, regno)) { 2106 verbose(env, "R%d leaks addr into helper function\n", 2107 regno); 2108 return -EACCES; 2109 } 2110 return 0; 2111 } 2112 2113 if (type_is_pkt_pointer(type) && 2114 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 2115 verbose(env, "helper access to the packet is not allowed\n"); 2116 return -EACCES; 2117 } 2118 2119 if (arg_type == ARG_PTR_TO_MAP_KEY || 2120 arg_type == ARG_PTR_TO_MAP_VALUE) { 2121 expected_type = PTR_TO_STACK; 2122 if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE && 2123 type != expected_type) 2124 goto err_type; 2125 } else if (arg_type == ARG_CONST_SIZE || 2126 arg_type == ARG_CONST_SIZE_OR_ZERO) { 2127 expected_type = SCALAR_VALUE; 2128 if (type != expected_type) 2129 goto err_type; 2130 } else if (arg_type == ARG_CONST_MAP_PTR) { 2131 expected_type = CONST_PTR_TO_MAP; 2132 if (type != expected_type) 2133 goto err_type; 2134 } else if (arg_type == ARG_PTR_TO_CTX) { 2135 expected_type = PTR_TO_CTX; 2136 if (type != expected_type) 2137 goto err_type; 2138 err = check_ctx_reg(env, reg, regno); 2139 if (err < 0) 2140 return err; 2141 } else if (arg_type == ARG_PTR_TO_SOCKET) { 2142 expected_type = PTR_TO_SOCKET; 2143 if (type != expected_type) 2144 goto err_type; 2145 if (meta->ptr_id || !reg->id) { 2146 verbose(env, "verifier internal error: mismatched references meta=%d, reg=%d\n", 2147 meta->ptr_id, reg->id); 2148 return -EFAULT; 2149 } 2150 meta->ptr_id = reg->id; 2151 } else if (arg_type_is_mem_ptr(arg_type)) { 2152 expected_type = PTR_TO_STACK; 2153 /* One exception here. In case function allows for NULL to be 2154 * passed in as argument, it's a SCALAR_VALUE type. Final test 2155 * happens during stack boundary checking. 2156 */ 2157 if (register_is_null(reg) && 2158 arg_type == ARG_PTR_TO_MEM_OR_NULL) 2159 /* final test in check_stack_boundary() */; 2160 else if (!type_is_pkt_pointer(type) && 2161 type != PTR_TO_MAP_VALUE && 2162 type != expected_type) 2163 goto err_type; 2164 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM; 2165 } else { 2166 verbose(env, "unsupported arg_type %d\n", arg_type); 2167 return -EFAULT; 2168 } 2169 2170 if (arg_type == ARG_CONST_MAP_PTR) { 2171 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 2172 meta->map_ptr = reg->map_ptr; 2173 } else if (arg_type == ARG_PTR_TO_MAP_KEY) { 2174 /* bpf_map_xxx(..., map_ptr, ..., key) call: 2175 * check that [key, key + map->key_size) are within 2176 * stack limits and initialized 2177 */ 2178 if (!meta->map_ptr) { 2179 /* in function declaration map_ptr must come before 2180 * map_key, so that it's verified and known before 2181 * we have to check map_key here. Otherwise it means 2182 * that kernel subsystem misconfigured verifier 2183 */ 2184 verbose(env, "invalid map_ptr to access map->key\n"); 2185 return -EACCES; 2186 } 2187 err = check_helper_mem_access(env, regno, 2188 meta->map_ptr->key_size, false, 2189 NULL); 2190 } else if (arg_type == ARG_PTR_TO_MAP_VALUE) { 2191 /* bpf_map_xxx(..., map_ptr, ..., value) call: 2192 * check [value, value + map->value_size) validity 2193 */ 2194 if (!meta->map_ptr) { 2195 /* kernel subsystem misconfigured verifier */ 2196 verbose(env, "invalid map_ptr to access map->value\n"); 2197 return -EACCES; 2198 } 2199 err = check_helper_mem_access(env, regno, 2200 meta->map_ptr->value_size, false, 2201 NULL); 2202 } else if (arg_type_is_mem_size(arg_type)) { 2203 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); 2204 2205 /* remember the mem_size which may be used later 2206 * to refine return values. 2207 */ 2208 meta->msize_smax_value = reg->smax_value; 2209 meta->msize_umax_value = reg->umax_value; 2210 2211 /* The register is SCALAR_VALUE; the access check 2212 * happens using its boundaries. 2213 */ 2214 if (!tnum_is_const(reg->var_off)) 2215 /* For unprivileged variable accesses, disable raw 2216 * mode so that the program is required to 2217 * initialize all the memory that the helper could 2218 * just partially fill up. 2219 */ 2220 meta = NULL; 2221 2222 if (reg->smin_value < 0) { 2223 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 2224 regno); 2225 return -EACCES; 2226 } 2227 2228 if (reg->umin_value == 0) { 2229 err = check_helper_mem_access(env, regno - 1, 0, 2230 zero_size_allowed, 2231 meta); 2232 if (err) 2233 return err; 2234 } 2235 2236 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 2237 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 2238 regno); 2239 return -EACCES; 2240 } 2241 err = check_helper_mem_access(env, regno - 1, 2242 reg->umax_value, 2243 zero_size_allowed, meta); 2244 } 2245 2246 return err; 2247 err_type: 2248 verbose(env, "R%d type=%s expected=%s\n", regno, 2249 reg_type_str[type], reg_type_str[expected_type]); 2250 return -EACCES; 2251 } 2252 2253 static int check_map_func_compatibility(struct bpf_verifier_env *env, 2254 struct bpf_map *map, int func_id) 2255 { 2256 if (!map) 2257 return 0; 2258 2259 /* We need a two way check, first is from map perspective ... */ 2260 switch (map->map_type) { 2261 case BPF_MAP_TYPE_PROG_ARRAY: 2262 if (func_id != BPF_FUNC_tail_call) 2263 goto error; 2264 break; 2265 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 2266 if (func_id != BPF_FUNC_perf_event_read && 2267 func_id != BPF_FUNC_perf_event_output && 2268 func_id != BPF_FUNC_perf_event_read_value) 2269 goto error; 2270 break; 2271 case BPF_MAP_TYPE_STACK_TRACE: 2272 if (func_id != BPF_FUNC_get_stackid) 2273 goto error; 2274 break; 2275 case BPF_MAP_TYPE_CGROUP_ARRAY: 2276 if (func_id != BPF_FUNC_skb_under_cgroup && 2277 func_id != BPF_FUNC_current_task_under_cgroup) 2278 goto error; 2279 break; 2280 case BPF_MAP_TYPE_CGROUP_STORAGE: 2281 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 2282 if (func_id != BPF_FUNC_get_local_storage) 2283 goto error; 2284 break; 2285 /* devmap returns a pointer to a live net_device ifindex that we cannot 2286 * allow to be modified from bpf side. So do not allow lookup elements 2287 * for now. 2288 */ 2289 case BPF_MAP_TYPE_DEVMAP: 2290 if (func_id != BPF_FUNC_redirect_map) 2291 goto error; 2292 break; 2293 /* Restrict bpf side of cpumap and xskmap, open when use-cases 2294 * appear. 2295 */ 2296 case BPF_MAP_TYPE_CPUMAP: 2297 case BPF_MAP_TYPE_XSKMAP: 2298 if (func_id != BPF_FUNC_redirect_map) 2299 goto error; 2300 break; 2301 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 2302 case BPF_MAP_TYPE_HASH_OF_MAPS: 2303 if (func_id != BPF_FUNC_map_lookup_elem) 2304 goto error; 2305 break; 2306 case BPF_MAP_TYPE_SOCKMAP: 2307 if (func_id != BPF_FUNC_sk_redirect_map && 2308 func_id != BPF_FUNC_sock_map_update && 2309 func_id != BPF_FUNC_map_delete_elem && 2310 func_id != BPF_FUNC_msg_redirect_map) 2311 goto error; 2312 break; 2313 case BPF_MAP_TYPE_SOCKHASH: 2314 if (func_id != BPF_FUNC_sk_redirect_hash && 2315 func_id != BPF_FUNC_sock_hash_update && 2316 func_id != BPF_FUNC_map_delete_elem && 2317 func_id != BPF_FUNC_msg_redirect_hash) 2318 goto error; 2319 break; 2320 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 2321 if (func_id != BPF_FUNC_sk_select_reuseport) 2322 goto error; 2323 break; 2324 default: 2325 break; 2326 } 2327 2328 /* ... and second from the function itself. */ 2329 switch (func_id) { 2330 case BPF_FUNC_tail_call: 2331 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 2332 goto error; 2333 if (env->subprog_cnt > 1) { 2334 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n"); 2335 return -EINVAL; 2336 } 2337 break; 2338 case BPF_FUNC_perf_event_read: 2339 case BPF_FUNC_perf_event_output: 2340 case BPF_FUNC_perf_event_read_value: 2341 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 2342 goto error; 2343 break; 2344 case BPF_FUNC_get_stackid: 2345 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 2346 goto error; 2347 break; 2348 case BPF_FUNC_current_task_under_cgroup: 2349 case BPF_FUNC_skb_under_cgroup: 2350 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 2351 goto error; 2352 break; 2353 case BPF_FUNC_redirect_map: 2354 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 2355 map->map_type != BPF_MAP_TYPE_CPUMAP && 2356 map->map_type != BPF_MAP_TYPE_XSKMAP) 2357 goto error; 2358 break; 2359 case BPF_FUNC_sk_redirect_map: 2360 case BPF_FUNC_msg_redirect_map: 2361 case BPF_FUNC_sock_map_update: 2362 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 2363 goto error; 2364 break; 2365 case BPF_FUNC_sk_redirect_hash: 2366 case BPF_FUNC_msg_redirect_hash: 2367 case BPF_FUNC_sock_hash_update: 2368 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 2369 goto error; 2370 break; 2371 case BPF_FUNC_get_local_storage: 2372 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 2373 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 2374 goto error; 2375 break; 2376 case BPF_FUNC_sk_select_reuseport: 2377 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) 2378 goto error; 2379 break; 2380 default: 2381 break; 2382 } 2383 2384 return 0; 2385 error: 2386 verbose(env, "cannot pass map_type %d into func %s#%d\n", 2387 map->map_type, func_id_name(func_id), func_id); 2388 return -EINVAL; 2389 } 2390 2391 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 2392 { 2393 int count = 0; 2394 2395 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 2396 count++; 2397 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 2398 count++; 2399 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 2400 count++; 2401 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 2402 count++; 2403 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 2404 count++; 2405 2406 /* We only support one arg being in raw mode at the moment, 2407 * which is sufficient for the helper functions we have 2408 * right now. 2409 */ 2410 return count <= 1; 2411 } 2412 2413 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr, 2414 enum bpf_arg_type arg_next) 2415 { 2416 return (arg_type_is_mem_ptr(arg_curr) && 2417 !arg_type_is_mem_size(arg_next)) || 2418 (!arg_type_is_mem_ptr(arg_curr) && 2419 arg_type_is_mem_size(arg_next)); 2420 } 2421 2422 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 2423 { 2424 /* bpf_xxx(..., buf, len) call will access 'len' 2425 * bytes from memory 'buf'. Both arg types need 2426 * to be paired, so make sure there's no buggy 2427 * helper function specification. 2428 */ 2429 if (arg_type_is_mem_size(fn->arg1_type) || 2430 arg_type_is_mem_ptr(fn->arg5_type) || 2431 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) || 2432 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) || 2433 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) || 2434 check_args_pair_invalid(fn->arg4_type, fn->arg5_type)) 2435 return false; 2436 2437 return true; 2438 } 2439 2440 static bool check_refcount_ok(const struct bpf_func_proto *fn) 2441 { 2442 int count = 0; 2443 2444 if (arg_type_is_refcounted(fn->arg1_type)) 2445 count++; 2446 if (arg_type_is_refcounted(fn->arg2_type)) 2447 count++; 2448 if (arg_type_is_refcounted(fn->arg3_type)) 2449 count++; 2450 if (arg_type_is_refcounted(fn->arg4_type)) 2451 count++; 2452 if (arg_type_is_refcounted(fn->arg5_type)) 2453 count++; 2454 2455 /* We only support one arg being unreferenced at the moment, 2456 * which is sufficient for the helper functions we have right now. 2457 */ 2458 return count <= 1; 2459 } 2460 2461 static int check_func_proto(const struct bpf_func_proto *fn) 2462 { 2463 return check_raw_mode_ok(fn) && 2464 check_arg_pair_ok(fn) && 2465 check_refcount_ok(fn) ? 0 : -EINVAL; 2466 } 2467 2468 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 2469 * are now invalid, so turn them into unknown SCALAR_VALUE. 2470 */ 2471 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env, 2472 struct bpf_func_state *state) 2473 { 2474 struct bpf_reg_state *regs = state->regs, *reg; 2475 int i; 2476 2477 for (i = 0; i < MAX_BPF_REG; i++) 2478 if (reg_is_pkt_pointer_any(®s[i])) 2479 mark_reg_unknown(env, regs, i); 2480 2481 bpf_for_each_spilled_reg(i, state, reg) { 2482 if (!reg) 2483 continue; 2484 if (reg_is_pkt_pointer_any(reg)) 2485 __mark_reg_unknown(reg); 2486 } 2487 } 2488 2489 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 2490 { 2491 struct bpf_verifier_state *vstate = env->cur_state; 2492 int i; 2493 2494 for (i = 0; i <= vstate->curframe; i++) 2495 __clear_all_pkt_pointers(env, vstate->frame[i]); 2496 } 2497 2498 static void release_reg_references(struct bpf_verifier_env *env, 2499 struct bpf_func_state *state, int id) 2500 { 2501 struct bpf_reg_state *regs = state->regs, *reg; 2502 int i; 2503 2504 for (i = 0; i < MAX_BPF_REG; i++) 2505 if (regs[i].id == id) 2506 mark_reg_unknown(env, regs, i); 2507 2508 bpf_for_each_spilled_reg(i, state, reg) { 2509 if (!reg) 2510 continue; 2511 if (reg_is_refcounted(reg) && reg->id == id) 2512 __mark_reg_unknown(reg); 2513 } 2514 } 2515 2516 /* The pointer with the specified id has released its reference to kernel 2517 * resources. Identify all copies of the same pointer and clear the reference. 2518 */ 2519 static int release_reference(struct bpf_verifier_env *env, 2520 struct bpf_call_arg_meta *meta) 2521 { 2522 struct bpf_verifier_state *vstate = env->cur_state; 2523 int i; 2524 2525 for (i = 0; i <= vstate->curframe; i++) 2526 release_reg_references(env, vstate->frame[i], meta->ptr_id); 2527 2528 return release_reference_state(env, meta->ptr_id); 2529 } 2530 2531 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 2532 int *insn_idx) 2533 { 2534 struct bpf_verifier_state *state = env->cur_state; 2535 struct bpf_func_state *caller, *callee; 2536 int i, err, subprog, target_insn; 2537 2538 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 2539 verbose(env, "the call stack of %d frames is too deep\n", 2540 state->curframe + 2); 2541 return -E2BIG; 2542 } 2543 2544 target_insn = *insn_idx + insn->imm; 2545 subprog = find_subprog(env, target_insn + 1); 2546 if (subprog < 0) { 2547 verbose(env, "verifier bug. No program starts at insn %d\n", 2548 target_insn + 1); 2549 return -EFAULT; 2550 } 2551 2552 caller = state->frame[state->curframe]; 2553 if (state->frame[state->curframe + 1]) { 2554 verbose(env, "verifier bug. Frame %d already allocated\n", 2555 state->curframe + 1); 2556 return -EFAULT; 2557 } 2558 2559 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 2560 if (!callee) 2561 return -ENOMEM; 2562 state->frame[state->curframe + 1] = callee; 2563 2564 /* callee cannot access r0, r6 - r9 for reading and has to write 2565 * into its own stack before reading from it. 2566 * callee can read/write into caller's stack 2567 */ 2568 init_func_state(env, callee, 2569 /* remember the callsite, it will be used by bpf_exit */ 2570 *insn_idx /* callsite */, 2571 state->curframe + 1 /* frameno within this callchain */, 2572 subprog /* subprog number within this prog */); 2573 2574 /* Transfer references to the callee */ 2575 err = transfer_reference_state(callee, caller); 2576 if (err) 2577 return err; 2578 2579 /* copy r1 - r5 args that callee can access. The copy includes parent 2580 * pointers, which connects us up to the liveness chain 2581 */ 2582 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 2583 callee->regs[i] = caller->regs[i]; 2584 2585 /* after the call registers r0 - r5 were scratched */ 2586 for (i = 0; i < CALLER_SAVED_REGS; i++) { 2587 mark_reg_not_init(env, caller->regs, caller_saved[i]); 2588 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 2589 } 2590 2591 /* only increment it after check_reg_arg() finished */ 2592 state->curframe++; 2593 2594 /* and go analyze first insn of the callee */ 2595 *insn_idx = target_insn; 2596 2597 if (env->log.level) { 2598 verbose(env, "caller:\n"); 2599 print_verifier_state(env, caller); 2600 verbose(env, "callee:\n"); 2601 print_verifier_state(env, callee); 2602 } 2603 return 0; 2604 } 2605 2606 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 2607 { 2608 struct bpf_verifier_state *state = env->cur_state; 2609 struct bpf_func_state *caller, *callee; 2610 struct bpf_reg_state *r0; 2611 int err; 2612 2613 callee = state->frame[state->curframe]; 2614 r0 = &callee->regs[BPF_REG_0]; 2615 if (r0->type == PTR_TO_STACK) { 2616 /* technically it's ok to return caller's stack pointer 2617 * (or caller's caller's pointer) back to the caller, 2618 * since these pointers are valid. Only current stack 2619 * pointer will be invalid as soon as function exits, 2620 * but let's be conservative 2621 */ 2622 verbose(env, "cannot return stack pointer to the caller\n"); 2623 return -EINVAL; 2624 } 2625 2626 state->curframe--; 2627 caller = state->frame[state->curframe]; 2628 /* return to the caller whatever r0 had in the callee */ 2629 caller->regs[BPF_REG_0] = *r0; 2630 2631 /* Transfer references to the caller */ 2632 err = transfer_reference_state(caller, callee); 2633 if (err) 2634 return err; 2635 2636 *insn_idx = callee->callsite + 1; 2637 if (env->log.level) { 2638 verbose(env, "returning from callee:\n"); 2639 print_verifier_state(env, callee); 2640 verbose(env, "to caller at %d:\n", *insn_idx); 2641 print_verifier_state(env, caller); 2642 } 2643 /* clear everything in the callee */ 2644 free_func_state(callee); 2645 state->frame[state->curframe + 1] = NULL; 2646 return 0; 2647 } 2648 2649 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 2650 int func_id, 2651 struct bpf_call_arg_meta *meta) 2652 { 2653 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 2654 2655 if (ret_type != RET_INTEGER || 2656 (func_id != BPF_FUNC_get_stack && 2657 func_id != BPF_FUNC_probe_read_str)) 2658 return; 2659 2660 ret_reg->smax_value = meta->msize_smax_value; 2661 ret_reg->umax_value = meta->msize_umax_value; 2662 __reg_deduce_bounds(ret_reg); 2663 __reg_bound_offset(ret_reg); 2664 } 2665 2666 static int 2667 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 2668 int func_id, int insn_idx) 2669 { 2670 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 2671 2672 if (func_id != BPF_FUNC_tail_call && 2673 func_id != BPF_FUNC_map_lookup_elem && 2674 func_id != BPF_FUNC_map_update_elem && 2675 func_id != BPF_FUNC_map_delete_elem) 2676 return 0; 2677 2678 if (meta->map_ptr == NULL) { 2679 verbose(env, "kernel subsystem misconfigured verifier\n"); 2680 return -EINVAL; 2681 } 2682 2683 if (!BPF_MAP_PTR(aux->map_state)) 2684 bpf_map_ptr_store(aux, meta->map_ptr, 2685 meta->map_ptr->unpriv_array); 2686 else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr) 2687 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 2688 meta->map_ptr->unpriv_array); 2689 return 0; 2690 } 2691 2692 static int check_reference_leak(struct bpf_verifier_env *env) 2693 { 2694 struct bpf_func_state *state = cur_func(env); 2695 int i; 2696 2697 for (i = 0; i < state->acquired_refs; i++) { 2698 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 2699 state->refs[i].id, state->refs[i].insn_idx); 2700 } 2701 return state->acquired_refs ? -EINVAL : 0; 2702 } 2703 2704 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx) 2705 { 2706 const struct bpf_func_proto *fn = NULL; 2707 struct bpf_reg_state *regs; 2708 struct bpf_call_arg_meta meta; 2709 bool changes_data; 2710 int i, err; 2711 2712 /* find function prototype */ 2713 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 2714 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 2715 func_id); 2716 return -EINVAL; 2717 } 2718 2719 if (env->ops->get_func_proto) 2720 fn = env->ops->get_func_proto(func_id, env->prog); 2721 if (!fn) { 2722 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 2723 func_id); 2724 return -EINVAL; 2725 } 2726 2727 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 2728 if (!env->prog->gpl_compatible && fn->gpl_only) { 2729 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 2730 return -EINVAL; 2731 } 2732 2733 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 2734 changes_data = bpf_helper_changes_pkt_data(fn->func); 2735 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 2736 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 2737 func_id_name(func_id), func_id); 2738 return -EINVAL; 2739 } 2740 2741 memset(&meta, 0, sizeof(meta)); 2742 meta.pkt_access = fn->pkt_access; 2743 2744 err = check_func_proto(fn); 2745 if (err) { 2746 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 2747 func_id_name(func_id), func_id); 2748 return err; 2749 } 2750 2751 /* check args */ 2752 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); 2753 if (err) 2754 return err; 2755 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); 2756 if (err) 2757 return err; 2758 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); 2759 if (err) 2760 return err; 2761 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); 2762 if (err) 2763 return err; 2764 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); 2765 if (err) 2766 return err; 2767 2768 err = record_func_map(env, &meta, func_id, insn_idx); 2769 if (err) 2770 return err; 2771 2772 /* Mark slots with STACK_MISC in case of raw mode, stack offset 2773 * is inferred from register state. 2774 */ 2775 for (i = 0; i < meta.access_size; i++) { 2776 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 2777 BPF_WRITE, -1, false); 2778 if (err) 2779 return err; 2780 } 2781 2782 if (func_id == BPF_FUNC_tail_call) { 2783 err = check_reference_leak(env); 2784 if (err) { 2785 verbose(env, "tail_call would lead to reference leak\n"); 2786 return err; 2787 } 2788 } else if (is_release_function(func_id)) { 2789 err = release_reference(env, &meta); 2790 if (err) 2791 return err; 2792 } 2793 2794 regs = cur_regs(env); 2795 2796 /* check that flags argument in get_local_storage(map, flags) is 0, 2797 * this is required because get_local_storage() can't return an error. 2798 */ 2799 if (func_id == BPF_FUNC_get_local_storage && 2800 !register_is_null(®s[BPF_REG_2])) { 2801 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 2802 return -EINVAL; 2803 } 2804 2805 /* reset caller saved regs */ 2806 for (i = 0; i < CALLER_SAVED_REGS; i++) { 2807 mark_reg_not_init(env, regs, caller_saved[i]); 2808 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 2809 } 2810 2811 /* update return register (already marked as written above) */ 2812 if (fn->ret_type == RET_INTEGER) { 2813 /* sets type to SCALAR_VALUE */ 2814 mark_reg_unknown(env, regs, BPF_REG_0); 2815 } else if (fn->ret_type == RET_VOID) { 2816 regs[BPF_REG_0].type = NOT_INIT; 2817 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL || 2818 fn->ret_type == RET_PTR_TO_MAP_VALUE) { 2819 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) 2820 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE; 2821 else 2822 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; 2823 /* There is no offset yet applied, variable or fixed */ 2824 mark_reg_known_zero(env, regs, BPF_REG_0); 2825 /* remember map_ptr, so that check_map_access() 2826 * can check 'value_size' boundary of memory access 2827 * to map element returned from bpf_map_lookup_elem() 2828 */ 2829 if (meta.map_ptr == NULL) { 2830 verbose(env, 2831 "kernel subsystem misconfigured verifier\n"); 2832 return -EINVAL; 2833 } 2834 regs[BPF_REG_0].map_ptr = meta.map_ptr; 2835 regs[BPF_REG_0].id = ++env->id_gen; 2836 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) { 2837 int id = acquire_reference_state(env, insn_idx); 2838 if (id < 0) 2839 return id; 2840 mark_reg_known_zero(env, regs, BPF_REG_0); 2841 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL; 2842 regs[BPF_REG_0].id = id; 2843 } else { 2844 verbose(env, "unknown return type %d of func %s#%d\n", 2845 fn->ret_type, func_id_name(func_id), func_id); 2846 return -EINVAL; 2847 } 2848 2849 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 2850 2851 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 2852 if (err) 2853 return err; 2854 2855 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) { 2856 const char *err_str; 2857 2858 #ifdef CONFIG_PERF_EVENTS 2859 err = get_callchain_buffers(sysctl_perf_event_max_stack); 2860 err_str = "cannot get callchain buffer for func %s#%d\n"; 2861 #else 2862 err = -ENOTSUPP; 2863 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 2864 #endif 2865 if (err) { 2866 verbose(env, err_str, func_id_name(func_id), func_id); 2867 return err; 2868 } 2869 2870 env->prog->has_callchain_buf = true; 2871 } 2872 2873 if (changes_data) 2874 clear_all_pkt_pointers(env); 2875 return 0; 2876 } 2877 2878 static bool signed_add_overflows(s64 a, s64 b) 2879 { 2880 /* Do the add in u64, where overflow is well-defined */ 2881 s64 res = (s64)((u64)a + (u64)b); 2882 2883 if (b < 0) 2884 return res > a; 2885 return res < a; 2886 } 2887 2888 static bool signed_sub_overflows(s64 a, s64 b) 2889 { 2890 /* Do the sub in u64, where overflow is well-defined */ 2891 s64 res = (s64)((u64)a - (u64)b); 2892 2893 if (b < 0) 2894 return res < a; 2895 return res > a; 2896 } 2897 2898 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 2899 const struct bpf_reg_state *reg, 2900 enum bpf_reg_type type) 2901 { 2902 bool known = tnum_is_const(reg->var_off); 2903 s64 val = reg->var_off.value; 2904 s64 smin = reg->smin_value; 2905 2906 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 2907 verbose(env, "math between %s pointer and %lld is not allowed\n", 2908 reg_type_str[type], val); 2909 return false; 2910 } 2911 2912 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 2913 verbose(env, "%s pointer offset %d is not allowed\n", 2914 reg_type_str[type], reg->off); 2915 return false; 2916 } 2917 2918 if (smin == S64_MIN) { 2919 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 2920 reg_type_str[type]); 2921 return false; 2922 } 2923 2924 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 2925 verbose(env, "value %lld makes %s pointer be out of bounds\n", 2926 smin, reg_type_str[type]); 2927 return false; 2928 } 2929 2930 return true; 2931 } 2932 2933 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 2934 * Caller should also handle BPF_MOV case separately. 2935 * If we return -EACCES, caller may want to try again treating pointer as a 2936 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 2937 */ 2938 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 2939 struct bpf_insn *insn, 2940 const struct bpf_reg_state *ptr_reg, 2941 const struct bpf_reg_state *off_reg) 2942 { 2943 struct bpf_verifier_state *vstate = env->cur_state; 2944 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2945 struct bpf_reg_state *regs = state->regs, *dst_reg; 2946 bool known = tnum_is_const(off_reg->var_off); 2947 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 2948 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 2949 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 2950 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 2951 u8 opcode = BPF_OP(insn->code); 2952 u32 dst = insn->dst_reg; 2953 2954 dst_reg = ®s[dst]; 2955 2956 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 2957 smin_val > smax_val || umin_val > umax_val) { 2958 /* Taint dst register if offset had invalid bounds derived from 2959 * e.g. dead branches. 2960 */ 2961 __mark_reg_unknown(dst_reg); 2962 return 0; 2963 } 2964 2965 if (BPF_CLASS(insn->code) != BPF_ALU64) { 2966 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 2967 verbose(env, 2968 "R%d 32-bit pointer arithmetic prohibited\n", 2969 dst); 2970 return -EACCES; 2971 } 2972 2973 switch (ptr_reg->type) { 2974 case PTR_TO_MAP_VALUE_OR_NULL: 2975 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 2976 dst, reg_type_str[ptr_reg->type]); 2977 return -EACCES; 2978 case CONST_PTR_TO_MAP: 2979 case PTR_TO_PACKET_END: 2980 case PTR_TO_SOCKET: 2981 case PTR_TO_SOCKET_OR_NULL: 2982 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 2983 dst, reg_type_str[ptr_reg->type]); 2984 return -EACCES; 2985 default: 2986 break; 2987 } 2988 2989 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 2990 * The id may be overwritten later if we create a new variable offset. 2991 */ 2992 dst_reg->type = ptr_reg->type; 2993 dst_reg->id = ptr_reg->id; 2994 2995 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 2996 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 2997 return -EINVAL; 2998 2999 switch (opcode) { 3000 case BPF_ADD: 3001 /* We can take a fixed offset as long as it doesn't overflow 3002 * the s32 'off' field 3003 */ 3004 if (known && (ptr_reg->off + smin_val == 3005 (s64)(s32)(ptr_reg->off + smin_val))) { 3006 /* pointer += K. Accumulate it into fixed offset */ 3007 dst_reg->smin_value = smin_ptr; 3008 dst_reg->smax_value = smax_ptr; 3009 dst_reg->umin_value = umin_ptr; 3010 dst_reg->umax_value = umax_ptr; 3011 dst_reg->var_off = ptr_reg->var_off; 3012 dst_reg->off = ptr_reg->off + smin_val; 3013 dst_reg->range = ptr_reg->range; 3014 break; 3015 } 3016 /* A new variable offset is created. Note that off_reg->off 3017 * == 0, since it's a scalar. 3018 * dst_reg gets the pointer type and since some positive 3019 * integer value was added to the pointer, give it a new 'id' 3020 * if it's a PTR_TO_PACKET. 3021 * this creates a new 'base' pointer, off_reg (variable) gets 3022 * added into the variable offset, and we copy the fixed offset 3023 * from ptr_reg. 3024 */ 3025 if (signed_add_overflows(smin_ptr, smin_val) || 3026 signed_add_overflows(smax_ptr, smax_val)) { 3027 dst_reg->smin_value = S64_MIN; 3028 dst_reg->smax_value = S64_MAX; 3029 } else { 3030 dst_reg->smin_value = smin_ptr + smin_val; 3031 dst_reg->smax_value = smax_ptr + smax_val; 3032 } 3033 if (umin_ptr + umin_val < umin_ptr || 3034 umax_ptr + umax_val < umax_ptr) { 3035 dst_reg->umin_value = 0; 3036 dst_reg->umax_value = U64_MAX; 3037 } else { 3038 dst_reg->umin_value = umin_ptr + umin_val; 3039 dst_reg->umax_value = umax_ptr + umax_val; 3040 } 3041 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 3042 dst_reg->off = ptr_reg->off; 3043 if (reg_is_pkt_pointer(ptr_reg)) { 3044 dst_reg->id = ++env->id_gen; 3045 /* something was added to pkt_ptr, set range to zero */ 3046 dst_reg->range = 0; 3047 } 3048 break; 3049 case BPF_SUB: 3050 if (dst_reg == off_reg) { 3051 /* scalar -= pointer. Creates an unknown scalar */ 3052 verbose(env, "R%d tried to subtract pointer from scalar\n", 3053 dst); 3054 return -EACCES; 3055 } 3056 /* We don't allow subtraction from FP, because (according to 3057 * test_verifier.c test "invalid fp arithmetic", JITs might not 3058 * be able to deal with it. 3059 */ 3060 if (ptr_reg->type == PTR_TO_STACK) { 3061 verbose(env, "R%d subtraction from stack pointer prohibited\n", 3062 dst); 3063 return -EACCES; 3064 } 3065 if (known && (ptr_reg->off - smin_val == 3066 (s64)(s32)(ptr_reg->off - smin_val))) { 3067 /* pointer -= K. Subtract it from fixed offset */ 3068 dst_reg->smin_value = smin_ptr; 3069 dst_reg->smax_value = smax_ptr; 3070 dst_reg->umin_value = umin_ptr; 3071 dst_reg->umax_value = umax_ptr; 3072 dst_reg->var_off = ptr_reg->var_off; 3073 dst_reg->id = ptr_reg->id; 3074 dst_reg->off = ptr_reg->off - smin_val; 3075 dst_reg->range = ptr_reg->range; 3076 break; 3077 } 3078 /* A new variable offset is created. If the subtrahend is known 3079 * nonnegative, then any reg->range we had before is still good. 3080 */ 3081 if (signed_sub_overflows(smin_ptr, smax_val) || 3082 signed_sub_overflows(smax_ptr, smin_val)) { 3083 /* Overflow possible, we know nothing */ 3084 dst_reg->smin_value = S64_MIN; 3085 dst_reg->smax_value = S64_MAX; 3086 } else { 3087 dst_reg->smin_value = smin_ptr - smax_val; 3088 dst_reg->smax_value = smax_ptr - smin_val; 3089 } 3090 if (umin_ptr < umax_val) { 3091 /* Overflow possible, we know nothing */ 3092 dst_reg->umin_value = 0; 3093 dst_reg->umax_value = U64_MAX; 3094 } else { 3095 /* Cannot overflow (as long as bounds are consistent) */ 3096 dst_reg->umin_value = umin_ptr - umax_val; 3097 dst_reg->umax_value = umax_ptr - umin_val; 3098 } 3099 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 3100 dst_reg->off = ptr_reg->off; 3101 if (reg_is_pkt_pointer(ptr_reg)) { 3102 dst_reg->id = ++env->id_gen; 3103 /* something was added to pkt_ptr, set range to zero */ 3104 if (smin_val < 0) 3105 dst_reg->range = 0; 3106 } 3107 break; 3108 case BPF_AND: 3109 case BPF_OR: 3110 case BPF_XOR: 3111 /* bitwise ops on pointers are troublesome, prohibit. */ 3112 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 3113 dst, bpf_alu_string[opcode >> 4]); 3114 return -EACCES; 3115 default: 3116 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 3117 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 3118 dst, bpf_alu_string[opcode >> 4]); 3119 return -EACCES; 3120 } 3121 3122 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 3123 return -EINVAL; 3124 3125 __update_reg_bounds(dst_reg); 3126 __reg_deduce_bounds(dst_reg); 3127 __reg_bound_offset(dst_reg); 3128 return 0; 3129 } 3130 3131 /* WARNING: This function does calculations on 64-bit values, but the actual 3132 * execution may occur on 32-bit values. Therefore, things like bitshifts 3133 * need extra checks in the 32-bit case. 3134 */ 3135 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 3136 struct bpf_insn *insn, 3137 struct bpf_reg_state *dst_reg, 3138 struct bpf_reg_state src_reg) 3139 { 3140 struct bpf_reg_state *regs = cur_regs(env); 3141 u8 opcode = BPF_OP(insn->code); 3142 bool src_known, dst_known; 3143 s64 smin_val, smax_val; 3144 u64 umin_val, umax_val; 3145 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 3146 3147 if (insn_bitness == 32) { 3148 /* Relevant for 32-bit RSH: Information can propagate towards 3149 * LSB, so it isn't sufficient to only truncate the output to 3150 * 32 bits. 3151 */ 3152 coerce_reg_to_size(dst_reg, 4); 3153 coerce_reg_to_size(&src_reg, 4); 3154 } 3155 3156 smin_val = src_reg.smin_value; 3157 smax_val = src_reg.smax_value; 3158 umin_val = src_reg.umin_value; 3159 umax_val = src_reg.umax_value; 3160 src_known = tnum_is_const(src_reg.var_off); 3161 dst_known = tnum_is_const(dst_reg->var_off); 3162 3163 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) || 3164 smin_val > smax_val || umin_val > umax_val) { 3165 /* Taint dst register if offset had invalid bounds derived from 3166 * e.g. dead branches. 3167 */ 3168 __mark_reg_unknown(dst_reg); 3169 return 0; 3170 } 3171 3172 if (!src_known && 3173 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 3174 __mark_reg_unknown(dst_reg); 3175 return 0; 3176 } 3177 3178 switch (opcode) { 3179 case BPF_ADD: 3180 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 3181 signed_add_overflows(dst_reg->smax_value, smax_val)) { 3182 dst_reg->smin_value = S64_MIN; 3183 dst_reg->smax_value = S64_MAX; 3184 } else { 3185 dst_reg->smin_value += smin_val; 3186 dst_reg->smax_value += smax_val; 3187 } 3188 if (dst_reg->umin_value + umin_val < umin_val || 3189 dst_reg->umax_value + umax_val < umax_val) { 3190 dst_reg->umin_value = 0; 3191 dst_reg->umax_value = U64_MAX; 3192 } else { 3193 dst_reg->umin_value += umin_val; 3194 dst_reg->umax_value += umax_val; 3195 } 3196 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 3197 break; 3198 case BPF_SUB: 3199 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 3200 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 3201 /* Overflow possible, we know nothing */ 3202 dst_reg->smin_value = S64_MIN; 3203 dst_reg->smax_value = S64_MAX; 3204 } else { 3205 dst_reg->smin_value -= smax_val; 3206 dst_reg->smax_value -= smin_val; 3207 } 3208 if (dst_reg->umin_value < umax_val) { 3209 /* Overflow possible, we know nothing */ 3210 dst_reg->umin_value = 0; 3211 dst_reg->umax_value = U64_MAX; 3212 } else { 3213 /* Cannot overflow (as long as bounds are consistent) */ 3214 dst_reg->umin_value -= umax_val; 3215 dst_reg->umax_value -= umin_val; 3216 } 3217 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 3218 break; 3219 case BPF_MUL: 3220 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 3221 if (smin_val < 0 || dst_reg->smin_value < 0) { 3222 /* Ain't nobody got time to multiply that sign */ 3223 __mark_reg_unbounded(dst_reg); 3224 __update_reg_bounds(dst_reg); 3225 break; 3226 } 3227 /* Both values are positive, so we can work with unsigned and 3228 * copy the result to signed (unless it exceeds S64_MAX). 3229 */ 3230 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 3231 /* Potential overflow, we know nothing */ 3232 __mark_reg_unbounded(dst_reg); 3233 /* (except what we can learn from the var_off) */ 3234 __update_reg_bounds(dst_reg); 3235 break; 3236 } 3237 dst_reg->umin_value *= umin_val; 3238 dst_reg->umax_value *= umax_val; 3239 if (dst_reg->umax_value > S64_MAX) { 3240 /* Overflow possible, we know nothing */ 3241 dst_reg->smin_value = S64_MIN; 3242 dst_reg->smax_value = S64_MAX; 3243 } else { 3244 dst_reg->smin_value = dst_reg->umin_value; 3245 dst_reg->smax_value = dst_reg->umax_value; 3246 } 3247 break; 3248 case BPF_AND: 3249 if (src_known && dst_known) { 3250 __mark_reg_known(dst_reg, dst_reg->var_off.value & 3251 src_reg.var_off.value); 3252 break; 3253 } 3254 /* We get our minimum from the var_off, since that's inherently 3255 * bitwise. Our maximum is the minimum of the operands' maxima. 3256 */ 3257 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 3258 dst_reg->umin_value = dst_reg->var_off.value; 3259 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 3260 if (dst_reg->smin_value < 0 || smin_val < 0) { 3261 /* Lose signed bounds when ANDing negative numbers, 3262 * ain't nobody got time for that. 3263 */ 3264 dst_reg->smin_value = S64_MIN; 3265 dst_reg->smax_value = S64_MAX; 3266 } else { 3267 /* ANDing two positives gives a positive, so safe to 3268 * cast result into s64. 3269 */ 3270 dst_reg->smin_value = dst_reg->umin_value; 3271 dst_reg->smax_value = dst_reg->umax_value; 3272 } 3273 /* We may learn something more from the var_off */ 3274 __update_reg_bounds(dst_reg); 3275 break; 3276 case BPF_OR: 3277 if (src_known && dst_known) { 3278 __mark_reg_known(dst_reg, dst_reg->var_off.value | 3279 src_reg.var_off.value); 3280 break; 3281 } 3282 /* We get our maximum from the var_off, and our minimum is the 3283 * maximum of the operands' minima 3284 */ 3285 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 3286 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 3287 dst_reg->umax_value = dst_reg->var_off.value | 3288 dst_reg->var_off.mask; 3289 if (dst_reg->smin_value < 0 || smin_val < 0) { 3290 /* Lose signed bounds when ORing negative numbers, 3291 * ain't nobody got time for that. 3292 */ 3293 dst_reg->smin_value = S64_MIN; 3294 dst_reg->smax_value = S64_MAX; 3295 } else { 3296 /* ORing two positives gives a positive, so safe to 3297 * cast result into s64. 3298 */ 3299 dst_reg->smin_value = dst_reg->umin_value; 3300 dst_reg->smax_value = dst_reg->umax_value; 3301 } 3302 /* We may learn something more from the var_off */ 3303 __update_reg_bounds(dst_reg); 3304 break; 3305 case BPF_LSH: 3306 if (umax_val >= insn_bitness) { 3307 /* Shifts greater than 31 or 63 are undefined. 3308 * This includes shifts by a negative number. 3309 */ 3310 mark_reg_unknown(env, regs, insn->dst_reg); 3311 break; 3312 } 3313 /* We lose all sign bit information (except what we can pick 3314 * up from var_off) 3315 */ 3316 dst_reg->smin_value = S64_MIN; 3317 dst_reg->smax_value = S64_MAX; 3318 /* If we might shift our top bit out, then we know nothing */ 3319 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 3320 dst_reg->umin_value = 0; 3321 dst_reg->umax_value = U64_MAX; 3322 } else { 3323 dst_reg->umin_value <<= umin_val; 3324 dst_reg->umax_value <<= umax_val; 3325 } 3326 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 3327 /* We may learn something more from the var_off */ 3328 __update_reg_bounds(dst_reg); 3329 break; 3330 case BPF_RSH: 3331 if (umax_val >= insn_bitness) { 3332 /* Shifts greater than 31 or 63 are undefined. 3333 * This includes shifts by a negative number. 3334 */ 3335 mark_reg_unknown(env, regs, insn->dst_reg); 3336 break; 3337 } 3338 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 3339 * be negative, then either: 3340 * 1) src_reg might be zero, so the sign bit of the result is 3341 * unknown, so we lose our signed bounds 3342 * 2) it's known negative, thus the unsigned bounds capture the 3343 * signed bounds 3344 * 3) the signed bounds cross zero, so they tell us nothing 3345 * about the result 3346 * If the value in dst_reg is known nonnegative, then again the 3347 * unsigned bounts capture the signed bounds. 3348 * Thus, in all cases it suffices to blow away our signed bounds 3349 * and rely on inferring new ones from the unsigned bounds and 3350 * var_off of the result. 3351 */ 3352 dst_reg->smin_value = S64_MIN; 3353 dst_reg->smax_value = S64_MAX; 3354 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 3355 dst_reg->umin_value >>= umax_val; 3356 dst_reg->umax_value >>= umin_val; 3357 /* We may learn something more from the var_off */ 3358 __update_reg_bounds(dst_reg); 3359 break; 3360 case BPF_ARSH: 3361 if (umax_val >= insn_bitness) { 3362 /* Shifts greater than 31 or 63 are undefined. 3363 * This includes shifts by a negative number. 3364 */ 3365 mark_reg_unknown(env, regs, insn->dst_reg); 3366 break; 3367 } 3368 3369 /* Upon reaching here, src_known is true and 3370 * umax_val is equal to umin_val. 3371 */ 3372 dst_reg->smin_value >>= umin_val; 3373 dst_reg->smax_value >>= umin_val; 3374 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val); 3375 3376 /* blow away the dst_reg umin_value/umax_value and rely on 3377 * dst_reg var_off to refine the result. 3378 */ 3379 dst_reg->umin_value = 0; 3380 dst_reg->umax_value = U64_MAX; 3381 __update_reg_bounds(dst_reg); 3382 break; 3383 default: 3384 mark_reg_unknown(env, regs, insn->dst_reg); 3385 break; 3386 } 3387 3388 if (BPF_CLASS(insn->code) != BPF_ALU64) { 3389 /* 32-bit ALU ops are (32,32)->32 */ 3390 coerce_reg_to_size(dst_reg, 4); 3391 } 3392 3393 __reg_deduce_bounds(dst_reg); 3394 __reg_bound_offset(dst_reg); 3395 return 0; 3396 } 3397 3398 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 3399 * and var_off. 3400 */ 3401 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 3402 struct bpf_insn *insn) 3403 { 3404 struct bpf_verifier_state *vstate = env->cur_state; 3405 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3406 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 3407 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 3408 u8 opcode = BPF_OP(insn->code); 3409 3410 dst_reg = ®s[insn->dst_reg]; 3411 src_reg = NULL; 3412 if (dst_reg->type != SCALAR_VALUE) 3413 ptr_reg = dst_reg; 3414 if (BPF_SRC(insn->code) == BPF_X) { 3415 src_reg = ®s[insn->src_reg]; 3416 if (src_reg->type != SCALAR_VALUE) { 3417 if (dst_reg->type != SCALAR_VALUE) { 3418 /* Combining two pointers by any ALU op yields 3419 * an arbitrary scalar. Disallow all math except 3420 * pointer subtraction 3421 */ 3422 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 3423 mark_reg_unknown(env, regs, insn->dst_reg); 3424 return 0; 3425 } 3426 verbose(env, "R%d pointer %s pointer prohibited\n", 3427 insn->dst_reg, 3428 bpf_alu_string[opcode >> 4]); 3429 return -EACCES; 3430 } else { 3431 /* scalar += pointer 3432 * This is legal, but we have to reverse our 3433 * src/dest handling in computing the range 3434 */ 3435 return adjust_ptr_min_max_vals(env, insn, 3436 src_reg, dst_reg); 3437 } 3438 } else if (ptr_reg) { 3439 /* pointer += scalar */ 3440 return adjust_ptr_min_max_vals(env, insn, 3441 dst_reg, src_reg); 3442 } 3443 } else { 3444 /* Pretend the src is a reg with a known value, since we only 3445 * need to be able to read from this state. 3446 */ 3447 off_reg.type = SCALAR_VALUE; 3448 __mark_reg_known(&off_reg, insn->imm); 3449 src_reg = &off_reg; 3450 if (ptr_reg) /* pointer += K */ 3451 return adjust_ptr_min_max_vals(env, insn, 3452 ptr_reg, src_reg); 3453 } 3454 3455 /* Got here implies adding two SCALAR_VALUEs */ 3456 if (WARN_ON_ONCE(ptr_reg)) { 3457 print_verifier_state(env, state); 3458 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 3459 return -EINVAL; 3460 } 3461 if (WARN_ON(!src_reg)) { 3462 print_verifier_state(env, state); 3463 verbose(env, "verifier internal error: no src_reg\n"); 3464 return -EINVAL; 3465 } 3466 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 3467 } 3468 3469 /* check validity of 32-bit and 64-bit arithmetic operations */ 3470 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 3471 { 3472 struct bpf_reg_state *regs = cur_regs(env); 3473 u8 opcode = BPF_OP(insn->code); 3474 int err; 3475 3476 if (opcode == BPF_END || opcode == BPF_NEG) { 3477 if (opcode == BPF_NEG) { 3478 if (BPF_SRC(insn->code) != 0 || 3479 insn->src_reg != BPF_REG_0 || 3480 insn->off != 0 || insn->imm != 0) { 3481 verbose(env, "BPF_NEG uses reserved fields\n"); 3482 return -EINVAL; 3483 } 3484 } else { 3485 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 3486 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 3487 BPF_CLASS(insn->code) == BPF_ALU64) { 3488 verbose(env, "BPF_END uses reserved fields\n"); 3489 return -EINVAL; 3490 } 3491 } 3492 3493 /* check src operand */ 3494 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 3495 if (err) 3496 return err; 3497 3498 if (is_pointer_value(env, insn->dst_reg)) { 3499 verbose(env, "R%d pointer arithmetic prohibited\n", 3500 insn->dst_reg); 3501 return -EACCES; 3502 } 3503 3504 /* check dest operand */ 3505 err = check_reg_arg(env, insn->dst_reg, DST_OP); 3506 if (err) 3507 return err; 3508 3509 } else if (opcode == BPF_MOV) { 3510 3511 if (BPF_SRC(insn->code) == BPF_X) { 3512 if (insn->imm != 0 || insn->off != 0) { 3513 verbose(env, "BPF_MOV uses reserved fields\n"); 3514 return -EINVAL; 3515 } 3516 3517 /* check src operand */ 3518 err = check_reg_arg(env, insn->src_reg, SRC_OP); 3519 if (err) 3520 return err; 3521 } else { 3522 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 3523 verbose(env, "BPF_MOV uses reserved fields\n"); 3524 return -EINVAL; 3525 } 3526 } 3527 3528 /* check dest operand, mark as required later */ 3529 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 3530 if (err) 3531 return err; 3532 3533 if (BPF_SRC(insn->code) == BPF_X) { 3534 if (BPF_CLASS(insn->code) == BPF_ALU64) { 3535 /* case: R1 = R2 3536 * copy register state to dest reg 3537 */ 3538 regs[insn->dst_reg] = regs[insn->src_reg]; 3539 regs[insn->dst_reg].live |= REG_LIVE_WRITTEN; 3540 } else { 3541 /* R1 = (u32) R2 */ 3542 if (is_pointer_value(env, insn->src_reg)) { 3543 verbose(env, 3544 "R%d partial copy of pointer\n", 3545 insn->src_reg); 3546 return -EACCES; 3547 } 3548 mark_reg_unknown(env, regs, insn->dst_reg); 3549 coerce_reg_to_size(®s[insn->dst_reg], 4); 3550 } 3551 } else { 3552 /* case: R = imm 3553 * remember the value we stored into this reg 3554 */ 3555 /* clear any state __mark_reg_known doesn't set */ 3556 mark_reg_unknown(env, regs, insn->dst_reg); 3557 regs[insn->dst_reg].type = SCALAR_VALUE; 3558 if (BPF_CLASS(insn->code) == BPF_ALU64) { 3559 __mark_reg_known(regs + insn->dst_reg, 3560 insn->imm); 3561 } else { 3562 __mark_reg_known(regs + insn->dst_reg, 3563 (u32)insn->imm); 3564 } 3565 } 3566 3567 } else if (opcode > BPF_END) { 3568 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 3569 return -EINVAL; 3570 3571 } else { /* all other ALU ops: and, sub, xor, add, ... */ 3572 3573 if (BPF_SRC(insn->code) == BPF_X) { 3574 if (insn->imm != 0 || insn->off != 0) { 3575 verbose(env, "BPF_ALU uses reserved fields\n"); 3576 return -EINVAL; 3577 } 3578 /* check src1 operand */ 3579 err = check_reg_arg(env, insn->src_reg, SRC_OP); 3580 if (err) 3581 return err; 3582 } else { 3583 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 3584 verbose(env, "BPF_ALU uses reserved fields\n"); 3585 return -EINVAL; 3586 } 3587 } 3588 3589 /* check src2 operand */ 3590 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 3591 if (err) 3592 return err; 3593 3594 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 3595 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 3596 verbose(env, "div by zero\n"); 3597 return -EINVAL; 3598 } 3599 3600 if (opcode == BPF_ARSH && BPF_CLASS(insn->code) != BPF_ALU64) { 3601 verbose(env, "BPF_ARSH not supported for 32 bit ALU\n"); 3602 return -EINVAL; 3603 } 3604 3605 if ((opcode == BPF_LSH || opcode == BPF_RSH || 3606 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 3607 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 3608 3609 if (insn->imm < 0 || insn->imm >= size) { 3610 verbose(env, "invalid shift %d\n", insn->imm); 3611 return -EINVAL; 3612 } 3613 } 3614 3615 /* check dest operand */ 3616 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 3617 if (err) 3618 return err; 3619 3620 return adjust_reg_min_max_vals(env, insn); 3621 } 3622 3623 return 0; 3624 } 3625 3626 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 3627 struct bpf_reg_state *dst_reg, 3628 enum bpf_reg_type type, 3629 bool range_right_open) 3630 { 3631 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3632 struct bpf_reg_state *regs = state->regs, *reg; 3633 u16 new_range; 3634 int i, j; 3635 3636 if (dst_reg->off < 0 || 3637 (dst_reg->off == 0 && range_right_open)) 3638 /* This doesn't give us any range */ 3639 return; 3640 3641 if (dst_reg->umax_value > MAX_PACKET_OFF || 3642 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 3643 /* Risk of overflow. For instance, ptr + (1<<63) may be less 3644 * than pkt_end, but that's because it's also less than pkt. 3645 */ 3646 return; 3647 3648 new_range = dst_reg->off; 3649 if (range_right_open) 3650 new_range--; 3651 3652 /* Examples for register markings: 3653 * 3654 * pkt_data in dst register: 3655 * 3656 * r2 = r3; 3657 * r2 += 8; 3658 * if (r2 > pkt_end) goto <handle exception> 3659 * <access okay> 3660 * 3661 * r2 = r3; 3662 * r2 += 8; 3663 * if (r2 < pkt_end) goto <access okay> 3664 * <handle exception> 3665 * 3666 * Where: 3667 * r2 == dst_reg, pkt_end == src_reg 3668 * r2=pkt(id=n,off=8,r=0) 3669 * r3=pkt(id=n,off=0,r=0) 3670 * 3671 * pkt_data in src register: 3672 * 3673 * r2 = r3; 3674 * r2 += 8; 3675 * if (pkt_end >= r2) goto <access okay> 3676 * <handle exception> 3677 * 3678 * r2 = r3; 3679 * r2 += 8; 3680 * if (pkt_end <= r2) goto <handle exception> 3681 * <access okay> 3682 * 3683 * Where: 3684 * pkt_end == dst_reg, r2 == src_reg 3685 * r2=pkt(id=n,off=8,r=0) 3686 * r3=pkt(id=n,off=0,r=0) 3687 * 3688 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 3689 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 3690 * and [r3, r3 + 8-1) respectively is safe to access depending on 3691 * the check. 3692 */ 3693 3694 /* If our ids match, then we must have the same max_value. And we 3695 * don't care about the other reg's fixed offset, since if it's too big 3696 * the range won't allow anything. 3697 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 3698 */ 3699 for (i = 0; i < MAX_BPF_REG; i++) 3700 if (regs[i].type == type && regs[i].id == dst_reg->id) 3701 /* keep the maximum range already checked */ 3702 regs[i].range = max(regs[i].range, new_range); 3703 3704 for (j = 0; j <= vstate->curframe; j++) { 3705 state = vstate->frame[j]; 3706 bpf_for_each_spilled_reg(i, state, reg) { 3707 if (!reg) 3708 continue; 3709 if (reg->type == type && reg->id == dst_reg->id) 3710 reg->range = max(reg->range, new_range); 3711 } 3712 } 3713 } 3714 3715 /* Adjusts the register min/max values in the case that the dst_reg is the 3716 * variable register that we are working on, and src_reg is a constant or we're 3717 * simply doing a BPF_K check. 3718 * In JEQ/JNE cases we also adjust the var_off values. 3719 */ 3720 static void reg_set_min_max(struct bpf_reg_state *true_reg, 3721 struct bpf_reg_state *false_reg, u64 val, 3722 u8 opcode) 3723 { 3724 /* If the dst_reg is a pointer, we can't learn anything about its 3725 * variable offset from the compare (unless src_reg were a pointer into 3726 * the same object, but we don't bother with that. 3727 * Since false_reg and true_reg have the same type by construction, we 3728 * only need to check one of them for pointerness. 3729 */ 3730 if (__is_pointer_value(false, false_reg)) 3731 return; 3732 3733 switch (opcode) { 3734 case BPF_JEQ: 3735 /* If this is false then we know nothing Jon Snow, but if it is 3736 * true then we know for sure. 3737 */ 3738 __mark_reg_known(true_reg, val); 3739 break; 3740 case BPF_JNE: 3741 /* If this is true we know nothing Jon Snow, but if it is false 3742 * we know the value for sure; 3743 */ 3744 __mark_reg_known(false_reg, val); 3745 break; 3746 case BPF_JGT: 3747 false_reg->umax_value = min(false_reg->umax_value, val); 3748 true_reg->umin_value = max(true_reg->umin_value, val + 1); 3749 break; 3750 case BPF_JSGT: 3751 false_reg->smax_value = min_t(s64, false_reg->smax_value, val); 3752 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); 3753 break; 3754 case BPF_JLT: 3755 false_reg->umin_value = max(false_reg->umin_value, val); 3756 true_reg->umax_value = min(true_reg->umax_value, val - 1); 3757 break; 3758 case BPF_JSLT: 3759 false_reg->smin_value = max_t(s64, false_reg->smin_value, val); 3760 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); 3761 break; 3762 case BPF_JGE: 3763 false_reg->umax_value = min(false_reg->umax_value, val - 1); 3764 true_reg->umin_value = max(true_reg->umin_value, val); 3765 break; 3766 case BPF_JSGE: 3767 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); 3768 true_reg->smin_value = max_t(s64, true_reg->smin_value, val); 3769 break; 3770 case BPF_JLE: 3771 false_reg->umin_value = max(false_reg->umin_value, val + 1); 3772 true_reg->umax_value = min(true_reg->umax_value, val); 3773 break; 3774 case BPF_JSLE: 3775 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); 3776 true_reg->smax_value = min_t(s64, true_reg->smax_value, val); 3777 break; 3778 default: 3779 break; 3780 } 3781 3782 __reg_deduce_bounds(false_reg); 3783 __reg_deduce_bounds(true_reg); 3784 /* We might have learned some bits from the bounds. */ 3785 __reg_bound_offset(false_reg); 3786 __reg_bound_offset(true_reg); 3787 /* Intersecting with the old var_off might have improved our bounds 3788 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 3789 * then new var_off is (0; 0x7f...fc) which improves our umax. 3790 */ 3791 __update_reg_bounds(false_reg); 3792 __update_reg_bounds(true_reg); 3793 } 3794 3795 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 3796 * the variable reg. 3797 */ 3798 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 3799 struct bpf_reg_state *false_reg, u64 val, 3800 u8 opcode) 3801 { 3802 if (__is_pointer_value(false, false_reg)) 3803 return; 3804 3805 switch (opcode) { 3806 case BPF_JEQ: 3807 /* If this is false then we know nothing Jon Snow, but if it is 3808 * true then we know for sure. 3809 */ 3810 __mark_reg_known(true_reg, val); 3811 break; 3812 case BPF_JNE: 3813 /* If this is true we know nothing Jon Snow, but if it is false 3814 * we know the value for sure; 3815 */ 3816 __mark_reg_known(false_reg, val); 3817 break; 3818 case BPF_JGT: 3819 true_reg->umax_value = min(true_reg->umax_value, val - 1); 3820 false_reg->umin_value = max(false_reg->umin_value, val); 3821 break; 3822 case BPF_JSGT: 3823 true_reg->smax_value = min_t(s64, true_reg->smax_value, val - 1); 3824 false_reg->smin_value = max_t(s64, false_reg->smin_value, val); 3825 break; 3826 case BPF_JLT: 3827 true_reg->umin_value = max(true_reg->umin_value, val + 1); 3828 false_reg->umax_value = min(false_reg->umax_value, val); 3829 break; 3830 case BPF_JSLT: 3831 true_reg->smin_value = max_t(s64, true_reg->smin_value, val + 1); 3832 false_reg->smax_value = min_t(s64, false_reg->smax_value, val); 3833 break; 3834 case BPF_JGE: 3835 true_reg->umax_value = min(true_reg->umax_value, val); 3836 false_reg->umin_value = max(false_reg->umin_value, val + 1); 3837 break; 3838 case BPF_JSGE: 3839 true_reg->smax_value = min_t(s64, true_reg->smax_value, val); 3840 false_reg->smin_value = max_t(s64, false_reg->smin_value, val + 1); 3841 break; 3842 case BPF_JLE: 3843 true_reg->umin_value = max(true_reg->umin_value, val); 3844 false_reg->umax_value = min(false_reg->umax_value, val - 1); 3845 break; 3846 case BPF_JSLE: 3847 true_reg->smin_value = max_t(s64, true_reg->smin_value, val); 3848 false_reg->smax_value = min_t(s64, false_reg->smax_value, val - 1); 3849 break; 3850 default: 3851 break; 3852 } 3853 3854 __reg_deduce_bounds(false_reg); 3855 __reg_deduce_bounds(true_reg); 3856 /* We might have learned some bits from the bounds. */ 3857 __reg_bound_offset(false_reg); 3858 __reg_bound_offset(true_reg); 3859 /* Intersecting with the old var_off might have improved our bounds 3860 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 3861 * then new var_off is (0; 0x7f...fc) which improves our umax. 3862 */ 3863 __update_reg_bounds(false_reg); 3864 __update_reg_bounds(true_reg); 3865 } 3866 3867 /* Regs are known to be equal, so intersect their min/max/var_off */ 3868 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 3869 struct bpf_reg_state *dst_reg) 3870 { 3871 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 3872 dst_reg->umin_value); 3873 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 3874 dst_reg->umax_value); 3875 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 3876 dst_reg->smin_value); 3877 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 3878 dst_reg->smax_value); 3879 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 3880 dst_reg->var_off); 3881 /* We might have learned new bounds from the var_off. */ 3882 __update_reg_bounds(src_reg); 3883 __update_reg_bounds(dst_reg); 3884 /* We might have learned something about the sign bit. */ 3885 __reg_deduce_bounds(src_reg); 3886 __reg_deduce_bounds(dst_reg); 3887 /* We might have learned some bits from the bounds. */ 3888 __reg_bound_offset(src_reg); 3889 __reg_bound_offset(dst_reg); 3890 /* Intersecting with the old var_off might have improved our bounds 3891 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 3892 * then new var_off is (0; 0x7f...fc) which improves our umax. 3893 */ 3894 __update_reg_bounds(src_reg); 3895 __update_reg_bounds(dst_reg); 3896 } 3897 3898 static void reg_combine_min_max(struct bpf_reg_state *true_src, 3899 struct bpf_reg_state *true_dst, 3900 struct bpf_reg_state *false_src, 3901 struct bpf_reg_state *false_dst, 3902 u8 opcode) 3903 { 3904 switch (opcode) { 3905 case BPF_JEQ: 3906 __reg_combine_min_max(true_src, true_dst); 3907 break; 3908 case BPF_JNE: 3909 __reg_combine_min_max(false_src, false_dst); 3910 break; 3911 } 3912 } 3913 3914 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 3915 struct bpf_reg_state *reg, u32 id, 3916 bool is_null) 3917 { 3918 if (reg_type_may_be_null(reg->type) && reg->id == id) { 3919 /* Old offset (both fixed and variable parts) should 3920 * have been known-zero, because we don't allow pointer 3921 * arithmetic on pointers that might be NULL. 3922 */ 3923 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || 3924 !tnum_equals_const(reg->var_off, 0) || 3925 reg->off)) { 3926 __mark_reg_known_zero(reg); 3927 reg->off = 0; 3928 } 3929 if (is_null) { 3930 reg->type = SCALAR_VALUE; 3931 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) { 3932 if (reg->map_ptr->inner_map_meta) { 3933 reg->type = CONST_PTR_TO_MAP; 3934 reg->map_ptr = reg->map_ptr->inner_map_meta; 3935 } else { 3936 reg->type = PTR_TO_MAP_VALUE; 3937 } 3938 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) { 3939 reg->type = PTR_TO_SOCKET; 3940 } 3941 if (is_null || !reg_is_refcounted(reg)) { 3942 /* We don't need id from this point onwards anymore, 3943 * thus we should better reset it, so that state 3944 * pruning has chances to take effect. 3945 */ 3946 reg->id = 0; 3947 } 3948 } 3949 } 3950 3951 /* The logic is similar to find_good_pkt_pointers(), both could eventually 3952 * be folded together at some point. 3953 */ 3954 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 3955 bool is_null) 3956 { 3957 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3958 struct bpf_reg_state *reg, *regs = state->regs; 3959 u32 id = regs[regno].id; 3960 int i, j; 3961 3962 if (reg_is_refcounted_or_null(®s[regno]) && is_null) 3963 __release_reference_state(state, id); 3964 3965 for (i = 0; i < MAX_BPF_REG; i++) 3966 mark_ptr_or_null_reg(state, ®s[i], id, is_null); 3967 3968 for (j = 0; j <= vstate->curframe; j++) { 3969 state = vstate->frame[j]; 3970 bpf_for_each_spilled_reg(i, state, reg) { 3971 if (!reg) 3972 continue; 3973 mark_ptr_or_null_reg(state, reg, id, is_null); 3974 } 3975 } 3976 } 3977 3978 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 3979 struct bpf_reg_state *dst_reg, 3980 struct bpf_reg_state *src_reg, 3981 struct bpf_verifier_state *this_branch, 3982 struct bpf_verifier_state *other_branch) 3983 { 3984 if (BPF_SRC(insn->code) != BPF_X) 3985 return false; 3986 3987 switch (BPF_OP(insn->code)) { 3988 case BPF_JGT: 3989 if ((dst_reg->type == PTR_TO_PACKET && 3990 src_reg->type == PTR_TO_PACKET_END) || 3991 (dst_reg->type == PTR_TO_PACKET_META && 3992 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 3993 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 3994 find_good_pkt_pointers(this_branch, dst_reg, 3995 dst_reg->type, false); 3996 } else if ((dst_reg->type == PTR_TO_PACKET_END && 3997 src_reg->type == PTR_TO_PACKET) || 3998 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 3999 src_reg->type == PTR_TO_PACKET_META)) { 4000 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 4001 find_good_pkt_pointers(other_branch, src_reg, 4002 src_reg->type, true); 4003 } else { 4004 return false; 4005 } 4006 break; 4007 case BPF_JLT: 4008 if ((dst_reg->type == PTR_TO_PACKET && 4009 src_reg->type == PTR_TO_PACKET_END) || 4010 (dst_reg->type == PTR_TO_PACKET_META && 4011 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 4012 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 4013 find_good_pkt_pointers(other_branch, dst_reg, 4014 dst_reg->type, true); 4015 } else if ((dst_reg->type == PTR_TO_PACKET_END && 4016 src_reg->type == PTR_TO_PACKET) || 4017 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 4018 src_reg->type == PTR_TO_PACKET_META)) { 4019 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 4020 find_good_pkt_pointers(this_branch, src_reg, 4021 src_reg->type, false); 4022 } else { 4023 return false; 4024 } 4025 break; 4026 case BPF_JGE: 4027 if ((dst_reg->type == PTR_TO_PACKET && 4028 src_reg->type == PTR_TO_PACKET_END) || 4029 (dst_reg->type == PTR_TO_PACKET_META && 4030 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 4031 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 4032 find_good_pkt_pointers(this_branch, dst_reg, 4033 dst_reg->type, true); 4034 } else if ((dst_reg->type == PTR_TO_PACKET_END && 4035 src_reg->type == PTR_TO_PACKET) || 4036 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 4037 src_reg->type == PTR_TO_PACKET_META)) { 4038 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 4039 find_good_pkt_pointers(other_branch, src_reg, 4040 src_reg->type, false); 4041 } else { 4042 return false; 4043 } 4044 break; 4045 case BPF_JLE: 4046 if ((dst_reg->type == PTR_TO_PACKET && 4047 src_reg->type == PTR_TO_PACKET_END) || 4048 (dst_reg->type == PTR_TO_PACKET_META && 4049 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 4050 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 4051 find_good_pkt_pointers(other_branch, dst_reg, 4052 dst_reg->type, false); 4053 } else if ((dst_reg->type == PTR_TO_PACKET_END && 4054 src_reg->type == PTR_TO_PACKET) || 4055 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 4056 src_reg->type == PTR_TO_PACKET_META)) { 4057 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 4058 find_good_pkt_pointers(this_branch, src_reg, 4059 src_reg->type, true); 4060 } else { 4061 return false; 4062 } 4063 break; 4064 default: 4065 return false; 4066 } 4067 4068 return true; 4069 } 4070 4071 static int check_cond_jmp_op(struct bpf_verifier_env *env, 4072 struct bpf_insn *insn, int *insn_idx) 4073 { 4074 struct bpf_verifier_state *this_branch = env->cur_state; 4075 struct bpf_verifier_state *other_branch; 4076 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 4077 struct bpf_reg_state *dst_reg, *other_branch_regs; 4078 u8 opcode = BPF_OP(insn->code); 4079 int err; 4080 4081 if (opcode > BPF_JSLE) { 4082 verbose(env, "invalid BPF_JMP opcode %x\n", opcode); 4083 return -EINVAL; 4084 } 4085 4086 if (BPF_SRC(insn->code) == BPF_X) { 4087 if (insn->imm != 0) { 4088 verbose(env, "BPF_JMP uses reserved fields\n"); 4089 return -EINVAL; 4090 } 4091 4092 /* check src1 operand */ 4093 err = check_reg_arg(env, insn->src_reg, SRC_OP); 4094 if (err) 4095 return err; 4096 4097 if (is_pointer_value(env, insn->src_reg)) { 4098 verbose(env, "R%d pointer comparison prohibited\n", 4099 insn->src_reg); 4100 return -EACCES; 4101 } 4102 } else { 4103 if (insn->src_reg != BPF_REG_0) { 4104 verbose(env, "BPF_JMP uses reserved fields\n"); 4105 return -EINVAL; 4106 } 4107 } 4108 4109 /* check src2 operand */ 4110 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 4111 if (err) 4112 return err; 4113 4114 dst_reg = ®s[insn->dst_reg]; 4115 4116 /* detect if R == 0 where R was initialized to zero earlier */ 4117 if (BPF_SRC(insn->code) == BPF_K && 4118 (opcode == BPF_JEQ || opcode == BPF_JNE) && 4119 dst_reg->type == SCALAR_VALUE && 4120 tnum_is_const(dst_reg->var_off)) { 4121 if ((opcode == BPF_JEQ && dst_reg->var_off.value == insn->imm) || 4122 (opcode == BPF_JNE && dst_reg->var_off.value != insn->imm)) { 4123 /* if (imm == imm) goto pc+off; 4124 * only follow the goto, ignore fall-through 4125 */ 4126 *insn_idx += insn->off; 4127 return 0; 4128 } else { 4129 /* if (imm != imm) goto pc+off; 4130 * only follow fall-through branch, since 4131 * that's where the program will go 4132 */ 4133 return 0; 4134 } 4135 } 4136 4137 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); 4138 if (!other_branch) 4139 return -EFAULT; 4140 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 4141 4142 /* detect if we are comparing against a constant value so we can adjust 4143 * our min/max values for our dst register. 4144 * this is only legit if both are scalars (or pointers to the same 4145 * object, I suppose, but we don't support that right now), because 4146 * otherwise the different base pointers mean the offsets aren't 4147 * comparable. 4148 */ 4149 if (BPF_SRC(insn->code) == BPF_X) { 4150 if (dst_reg->type == SCALAR_VALUE && 4151 regs[insn->src_reg].type == SCALAR_VALUE) { 4152 if (tnum_is_const(regs[insn->src_reg].var_off)) 4153 reg_set_min_max(&other_branch_regs[insn->dst_reg], 4154 dst_reg, regs[insn->src_reg].var_off.value, 4155 opcode); 4156 else if (tnum_is_const(dst_reg->var_off)) 4157 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 4158 ®s[insn->src_reg], 4159 dst_reg->var_off.value, opcode); 4160 else if (opcode == BPF_JEQ || opcode == BPF_JNE) 4161 /* Comparing for equality, we can combine knowledge */ 4162 reg_combine_min_max(&other_branch_regs[insn->src_reg], 4163 &other_branch_regs[insn->dst_reg], 4164 ®s[insn->src_reg], 4165 ®s[insn->dst_reg], opcode); 4166 } 4167 } else if (dst_reg->type == SCALAR_VALUE) { 4168 reg_set_min_max(&other_branch_regs[insn->dst_reg], 4169 dst_reg, insn->imm, opcode); 4170 } 4171 4172 /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ 4173 if (BPF_SRC(insn->code) == BPF_K && 4174 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 4175 reg_type_may_be_null(dst_reg->type)) { 4176 /* Mark all identical registers in each branch as either 4177 * safe or unknown depending R == 0 or R != 0 conditional. 4178 */ 4179 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 4180 opcode == BPF_JNE); 4181 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 4182 opcode == BPF_JEQ); 4183 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 4184 this_branch, other_branch) && 4185 is_pointer_value(env, insn->dst_reg)) { 4186 verbose(env, "R%d pointer comparison prohibited\n", 4187 insn->dst_reg); 4188 return -EACCES; 4189 } 4190 if (env->log.level) 4191 print_verifier_state(env, this_branch->frame[this_branch->curframe]); 4192 return 0; 4193 } 4194 4195 /* return the map pointer stored inside BPF_LD_IMM64 instruction */ 4196 static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn) 4197 { 4198 u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32; 4199 4200 return (struct bpf_map *) (unsigned long) imm64; 4201 } 4202 4203 /* verify BPF_LD_IMM64 instruction */ 4204 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 4205 { 4206 struct bpf_reg_state *regs = cur_regs(env); 4207 int err; 4208 4209 if (BPF_SIZE(insn->code) != BPF_DW) { 4210 verbose(env, "invalid BPF_LD_IMM insn\n"); 4211 return -EINVAL; 4212 } 4213 if (insn->off != 0) { 4214 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 4215 return -EINVAL; 4216 } 4217 4218 err = check_reg_arg(env, insn->dst_reg, DST_OP); 4219 if (err) 4220 return err; 4221 4222 if (insn->src_reg == 0) { 4223 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 4224 4225 regs[insn->dst_reg].type = SCALAR_VALUE; 4226 __mark_reg_known(®s[insn->dst_reg], imm); 4227 return 0; 4228 } 4229 4230 /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */ 4231 BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD); 4232 4233 regs[insn->dst_reg].type = CONST_PTR_TO_MAP; 4234 regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn); 4235 return 0; 4236 } 4237 4238 static bool may_access_skb(enum bpf_prog_type type) 4239 { 4240 switch (type) { 4241 case BPF_PROG_TYPE_SOCKET_FILTER: 4242 case BPF_PROG_TYPE_SCHED_CLS: 4243 case BPF_PROG_TYPE_SCHED_ACT: 4244 return true; 4245 default: 4246 return false; 4247 } 4248 } 4249 4250 /* verify safety of LD_ABS|LD_IND instructions: 4251 * - they can only appear in the programs where ctx == skb 4252 * - since they are wrappers of function calls, they scratch R1-R5 registers, 4253 * preserve R6-R9, and store return value into R0 4254 * 4255 * Implicit input: 4256 * ctx == skb == R6 == CTX 4257 * 4258 * Explicit input: 4259 * SRC == any register 4260 * IMM == 32-bit immediate 4261 * 4262 * Output: 4263 * R0 - 8/16/32-bit skb data converted to cpu endianness 4264 */ 4265 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 4266 { 4267 struct bpf_reg_state *regs = cur_regs(env); 4268 u8 mode = BPF_MODE(insn->code); 4269 int i, err; 4270 4271 if (!may_access_skb(env->prog->type)) { 4272 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 4273 return -EINVAL; 4274 } 4275 4276 if (!env->ops->gen_ld_abs) { 4277 verbose(env, "bpf verifier is misconfigured\n"); 4278 return -EINVAL; 4279 } 4280 4281 if (env->subprog_cnt > 1) { 4282 /* when program has LD_ABS insn JITs and interpreter assume 4283 * that r1 == ctx == skb which is not the case for callees 4284 * that can have arbitrary arguments. It's problematic 4285 * for main prog as well since JITs would need to analyze 4286 * all functions in order to make proper register save/restore 4287 * decisions in the main prog. Hence disallow LD_ABS with calls 4288 */ 4289 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n"); 4290 return -EINVAL; 4291 } 4292 4293 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 4294 BPF_SIZE(insn->code) == BPF_DW || 4295 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 4296 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 4297 return -EINVAL; 4298 } 4299 4300 /* check whether implicit source operand (register R6) is readable */ 4301 err = check_reg_arg(env, BPF_REG_6, SRC_OP); 4302 if (err) 4303 return err; 4304 4305 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 4306 * gen_ld_abs() may terminate the program at runtime, leading to 4307 * reference leak. 4308 */ 4309 err = check_reference_leak(env); 4310 if (err) { 4311 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 4312 return err; 4313 } 4314 4315 if (regs[BPF_REG_6].type != PTR_TO_CTX) { 4316 verbose(env, 4317 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 4318 return -EINVAL; 4319 } 4320 4321 if (mode == BPF_IND) { 4322 /* check explicit source operand */ 4323 err = check_reg_arg(env, insn->src_reg, SRC_OP); 4324 if (err) 4325 return err; 4326 } 4327 4328 /* reset caller saved regs to unreadable */ 4329 for (i = 0; i < CALLER_SAVED_REGS; i++) { 4330 mark_reg_not_init(env, regs, caller_saved[i]); 4331 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 4332 } 4333 4334 /* mark destination R0 register as readable, since it contains 4335 * the value fetched from the packet. 4336 * Already marked as written above. 4337 */ 4338 mark_reg_unknown(env, regs, BPF_REG_0); 4339 return 0; 4340 } 4341 4342 static int check_return_code(struct bpf_verifier_env *env) 4343 { 4344 struct bpf_reg_state *reg; 4345 struct tnum range = tnum_range(0, 1); 4346 4347 switch (env->prog->type) { 4348 case BPF_PROG_TYPE_CGROUP_SKB: 4349 case BPF_PROG_TYPE_CGROUP_SOCK: 4350 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 4351 case BPF_PROG_TYPE_SOCK_OPS: 4352 case BPF_PROG_TYPE_CGROUP_DEVICE: 4353 break; 4354 default: 4355 return 0; 4356 } 4357 4358 reg = cur_regs(env) + BPF_REG_0; 4359 if (reg->type != SCALAR_VALUE) { 4360 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 4361 reg_type_str[reg->type]); 4362 return -EINVAL; 4363 } 4364 4365 if (!tnum_in(range, reg->var_off)) { 4366 verbose(env, "At program exit the register R0 "); 4367 if (!tnum_is_unknown(reg->var_off)) { 4368 char tn_buf[48]; 4369 4370 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4371 verbose(env, "has value %s", tn_buf); 4372 } else { 4373 verbose(env, "has unknown scalar value"); 4374 } 4375 verbose(env, " should have been 0 or 1\n"); 4376 return -EINVAL; 4377 } 4378 return 0; 4379 } 4380 4381 /* non-recursive DFS pseudo code 4382 * 1 procedure DFS-iterative(G,v): 4383 * 2 label v as discovered 4384 * 3 let S be a stack 4385 * 4 S.push(v) 4386 * 5 while S is not empty 4387 * 6 t <- S.pop() 4388 * 7 if t is what we're looking for: 4389 * 8 return t 4390 * 9 for all edges e in G.adjacentEdges(t) do 4391 * 10 if edge e is already labelled 4392 * 11 continue with the next edge 4393 * 12 w <- G.adjacentVertex(t,e) 4394 * 13 if vertex w is not discovered and not explored 4395 * 14 label e as tree-edge 4396 * 15 label w as discovered 4397 * 16 S.push(w) 4398 * 17 continue at 5 4399 * 18 else if vertex w is discovered 4400 * 19 label e as back-edge 4401 * 20 else 4402 * 21 // vertex w is explored 4403 * 22 label e as forward- or cross-edge 4404 * 23 label t as explored 4405 * 24 S.pop() 4406 * 4407 * convention: 4408 * 0x10 - discovered 4409 * 0x11 - discovered and fall-through edge labelled 4410 * 0x12 - discovered and fall-through and branch edges labelled 4411 * 0x20 - explored 4412 */ 4413 4414 enum { 4415 DISCOVERED = 0x10, 4416 EXPLORED = 0x20, 4417 FALLTHROUGH = 1, 4418 BRANCH = 2, 4419 }; 4420 4421 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L) 4422 4423 static int *insn_stack; /* stack of insns to process */ 4424 static int cur_stack; /* current stack index */ 4425 static int *insn_state; 4426 4427 /* t, w, e - match pseudo-code above: 4428 * t - index of current instruction 4429 * w - next instruction 4430 * e - edge 4431 */ 4432 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 4433 { 4434 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 4435 return 0; 4436 4437 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 4438 return 0; 4439 4440 if (w < 0 || w >= env->prog->len) { 4441 verbose(env, "jump out of range from insn %d to %d\n", t, w); 4442 return -EINVAL; 4443 } 4444 4445 if (e == BRANCH) 4446 /* mark branch target for state pruning */ 4447 env->explored_states[w] = STATE_LIST_MARK; 4448 4449 if (insn_state[w] == 0) { 4450 /* tree-edge */ 4451 insn_state[t] = DISCOVERED | e; 4452 insn_state[w] = DISCOVERED; 4453 if (cur_stack >= env->prog->len) 4454 return -E2BIG; 4455 insn_stack[cur_stack++] = w; 4456 return 1; 4457 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 4458 verbose(env, "back-edge from insn %d to %d\n", t, w); 4459 return -EINVAL; 4460 } else if (insn_state[w] == EXPLORED) { 4461 /* forward- or cross-edge */ 4462 insn_state[t] = DISCOVERED | e; 4463 } else { 4464 verbose(env, "insn state internal bug\n"); 4465 return -EFAULT; 4466 } 4467 return 0; 4468 } 4469 4470 /* non-recursive depth-first-search to detect loops in BPF program 4471 * loop == back-edge in directed graph 4472 */ 4473 static int check_cfg(struct bpf_verifier_env *env) 4474 { 4475 struct bpf_insn *insns = env->prog->insnsi; 4476 int insn_cnt = env->prog->len; 4477 int ret = 0; 4478 int i, t; 4479 4480 ret = check_subprogs(env); 4481 if (ret < 0) 4482 return ret; 4483 4484 insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 4485 if (!insn_state) 4486 return -ENOMEM; 4487 4488 insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 4489 if (!insn_stack) { 4490 kfree(insn_state); 4491 return -ENOMEM; 4492 } 4493 4494 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 4495 insn_stack[0] = 0; /* 0 is the first instruction */ 4496 cur_stack = 1; 4497 4498 peek_stack: 4499 if (cur_stack == 0) 4500 goto check_state; 4501 t = insn_stack[cur_stack - 1]; 4502 4503 if (BPF_CLASS(insns[t].code) == BPF_JMP) { 4504 u8 opcode = BPF_OP(insns[t].code); 4505 4506 if (opcode == BPF_EXIT) { 4507 goto mark_explored; 4508 } else if (opcode == BPF_CALL) { 4509 ret = push_insn(t, t + 1, FALLTHROUGH, env); 4510 if (ret == 1) 4511 goto peek_stack; 4512 else if (ret < 0) 4513 goto err_free; 4514 if (t + 1 < insn_cnt) 4515 env->explored_states[t + 1] = STATE_LIST_MARK; 4516 if (insns[t].src_reg == BPF_PSEUDO_CALL) { 4517 env->explored_states[t] = STATE_LIST_MARK; 4518 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 4519 if (ret == 1) 4520 goto peek_stack; 4521 else if (ret < 0) 4522 goto err_free; 4523 } 4524 } else if (opcode == BPF_JA) { 4525 if (BPF_SRC(insns[t].code) != BPF_K) { 4526 ret = -EINVAL; 4527 goto err_free; 4528 } 4529 /* unconditional jump with single edge */ 4530 ret = push_insn(t, t + insns[t].off + 1, 4531 FALLTHROUGH, env); 4532 if (ret == 1) 4533 goto peek_stack; 4534 else if (ret < 0) 4535 goto err_free; 4536 /* tell verifier to check for equivalent states 4537 * after every call and jump 4538 */ 4539 if (t + 1 < insn_cnt) 4540 env->explored_states[t + 1] = STATE_LIST_MARK; 4541 } else { 4542 /* conditional jump with two edges */ 4543 env->explored_states[t] = STATE_LIST_MARK; 4544 ret = push_insn(t, t + 1, FALLTHROUGH, env); 4545 if (ret == 1) 4546 goto peek_stack; 4547 else if (ret < 0) 4548 goto err_free; 4549 4550 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env); 4551 if (ret == 1) 4552 goto peek_stack; 4553 else if (ret < 0) 4554 goto err_free; 4555 } 4556 } else { 4557 /* all other non-branch instructions with single 4558 * fall-through edge 4559 */ 4560 ret = push_insn(t, t + 1, FALLTHROUGH, env); 4561 if (ret == 1) 4562 goto peek_stack; 4563 else if (ret < 0) 4564 goto err_free; 4565 } 4566 4567 mark_explored: 4568 insn_state[t] = EXPLORED; 4569 if (cur_stack-- <= 0) { 4570 verbose(env, "pop stack internal bug\n"); 4571 ret = -EFAULT; 4572 goto err_free; 4573 } 4574 goto peek_stack; 4575 4576 check_state: 4577 for (i = 0; i < insn_cnt; i++) { 4578 if (insn_state[i] != EXPLORED) { 4579 verbose(env, "unreachable insn %d\n", i); 4580 ret = -EINVAL; 4581 goto err_free; 4582 } 4583 } 4584 ret = 0; /* cfg looks good */ 4585 4586 err_free: 4587 kfree(insn_state); 4588 kfree(insn_stack); 4589 return ret; 4590 } 4591 4592 /* check %cur's range satisfies %old's */ 4593 static bool range_within(struct bpf_reg_state *old, 4594 struct bpf_reg_state *cur) 4595 { 4596 return old->umin_value <= cur->umin_value && 4597 old->umax_value >= cur->umax_value && 4598 old->smin_value <= cur->smin_value && 4599 old->smax_value >= cur->smax_value; 4600 } 4601 4602 /* Maximum number of register states that can exist at once */ 4603 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) 4604 struct idpair { 4605 u32 old; 4606 u32 cur; 4607 }; 4608 4609 /* If in the old state two registers had the same id, then they need to have 4610 * the same id in the new state as well. But that id could be different from 4611 * the old state, so we need to track the mapping from old to new ids. 4612 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 4613 * regs with old id 5 must also have new id 9 for the new state to be safe. But 4614 * regs with a different old id could still have new id 9, we don't care about 4615 * that. 4616 * So we look through our idmap to see if this old id has been seen before. If 4617 * so, we require the new id to match; otherwise, we add the id pair to the map. 4618 */ 4619 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) 4620 { 4621 unsigned int i; 4622 4623 for (i = 0; i < ID_MAP_SIZE; i++) { 4624 if (!idmap[i].old) { 4625 /* Reached an empty slot; haven't seen this id before */ 4626 idmap[i].old = old_id; 4627 idmap[i].cur = cur_id; 4628 return true; 4629 } 4630 if (idmap[i].old == old_id) 4631 return idmap[i].cur == cur_id; 4632 } 4633 /* We ran out of idmap slots, which should be impossible */ 4634 WARN_ON_ONCE(1); 4635 return false; 4636 } 4637 4638 /* Returns true if (rold safe implies rcur safe) */ 4639 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 4640 struct idpair *idmap) 4641 { 4642 bool equal; 4643 4644 if (!(rold->live & REG_LIVE_READ)) 4645 /* explored state didn't use this */ 4646 return true; 4647 4648 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0; 4649 4650 if (rold->type == PTR_TO_STACK) 4651 /* two stack pointers are equal only if they're pointing to 4652 * the same stack frame, since fp-8 in foo != fp-8 in bar 4653 */ 4654 return equal && rold->frameno == rcur->frameno; 4655 4656 if (equal) 4657 return true; 4658 4659 if (rold->type == NOT_INIT) 4660 /* explored state can't have used this */ 4661 return true; 4662 if (rcur->type == NOT_INIT) 4663 return false; 4664 switch (rold->type) { 4665 case SCALAR_VALUE: 4666 if (rcur->type == SCALAR_VALUE) { 4667 /* new val must satisfy old val knowledge */ 4668 return range_within(rold, rcur) && 4669 tnum_in(rold->var_off, rcur->var_off); 4670 } else { 4671 /* We're trying to use a pointer in place of a scalar. 4672 * Even if the scalar was unbounded, this could lead to 4673 * pointer leaks because scalars are allowed to leak 4674 * while pointers are not. We could make this safe in 4675 * special cases if root is calling us, but it's 4676 * probably not worth the hassle. 4677 */ 4678 return false; 4679 } 4680 case PTR_TO_MAP_VALUE: 4681 /* If the new min/max/var_off satisfy the old ones and 4682 * everything else matches, we are OK. 4683 * We don't care about the 'id' value, because nothing 4684 * uses it for PTR_TO_MAP_VALUE (only for ..._OR_NULL) 4685 */ 4686 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 4687 range_within(rold, rcur) && 4688 tnum_in(rold->var_off, rcur->var_off); 4689 case PTR_TO_MAP_VALUE_OR_NULL: 4690 /* a PTR_TO_MAP_VALUE could be safe to use as a 4691 * PTR_TO_MAP_VALUE_OR_NULL into the same map. 4692 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- 4693 * checked, doing so could have affected others with the same 4694 * id, and we can't check for that because we lost the id when 4695 * we converted to a PTR_TO_MAP_VALUE. 4696 */ 4697 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) 4698 return false; 4699 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) 4700 return false; 4701 /* Check our ids match any regs they're supposed to */ 4702 return check_ids(rold->id, rcur->id, idmap); 4703 case PTR_TO_PACKET_META: 4704 case PTR_TO_PACKET: 4705 if (rcur->type != rold->type) 4706 return false; 4707 /* We must have at least as much range as the old ptr 4708 * did, so that any accesses which were safe before are 4709 * still safe. This is true even if old range < old off, 4710 * since someone could have accessed through (ptr - k), or 4711 * even done ptr -= k in a register, to get a safe access. 4712 */ 4713 if (rold->range > rcur->range) 4714 return false; 4715 /* If the offsets don't match, we can't trust our alignment; 4716 * nor can we be sure that we won't fall out of range. 4717 */ 4718 if (rold->off != rcur->off) 4719 return false; 4720 /* id relations must be preserved */ 4721 if (rold->id && !check_ids(rold->id, rcur->id, idmap)) 4722 return false; 4723 /* new val must satisfy old val knowledge */ 4724 return range_within(rold, rcur) && 4725 tnum_in(rold->var_off, rcur->var_off); 4726 case PTR_TO_CTX: 4727 case CONST_PTR_TO_MAP: 4728 case PTR_TO_PACKET_END: 4729 case PTR_TO_FLOW_KEYS: 4730 case PTR_TO_SOCKET: 4731 case PTR_TO_SOCKET_OR_NULL: 4732 /* Only valid matches are exact, which memcmp() above 4733 * would have accepted 4734 */ 4735 default: 4736 /* Don't know what's going on, just say it's not safe */ 4737 return false; 4738 } 4739 4740 /* Shouldn't get here; if we do, say it's not safe */ 4741 WARN_ON_ONCE(1); 4742 return false; 4743 } 4744 4745 static bool stacksafe(struct bpf_func_state *old, 4746 struct bpf_func_state *cur, 4747 struct idpair *idmap) 4748 { 4749 int i, spi; 4750 4751 /* if explored stack has more populated slots than current stack 4752 * such stacks are not equivalent 4753 */ 4754 if (old->allocated_stack > cur->allocated_stack) 4755 return false; 4756 4757 /* walk slots of the explored stack and ignore any additional 4758 * slots in the current stack, since explored(safe) state 4759 * didn't use them 4760 */ 4761 for (i = 0; i < old->allocated_stack; i++) { 4762 spi = i / BPF_REG_SIZE; 4763 4764 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) 4765 /* explored state didn't use this */ 4766 continue; 4767 4768 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 4769 continue; 4770 /* if old state was safe with misc data in the stack 4771 * it will be safe with zero-initialized stack. 4772 * The opposite is not true 4773 */ 4774 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 4775 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 4776 continue; 4777 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 4778 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 4779 /* Ex: old explored (safe) state has STACK_SPILL in 4780 * this stack slot, but current has has STACK_MISC -> 4781 * this verifier states are not equivalent, 4782 * return false to continue verification of this path 4783 */ 4784 return false; 4785 if (i % BPF_REG_SIZE) 4786 continue; 4787 if (old->stack[spi].slot_type[0] != STACK_SPILL) 4788 continue; 4789 if (!regsafe(&old->stack[spi].spilled_ptr, 4790 &cur->stack[spi].spilled_ptr, 4791 idmap)) 4792 /* when explored and current stack slot are both storing 4793 * spilled registers, check that stored pointers types 4794 * are the same as well. 4795 * Ex: explored safe path could have stored 4796 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 4797 * but current path has stored: 4798 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 4799 * such verifier states are not equivalent. 4800 * return false to continue verification of this path 4801 */ 4802 return false; 4803 } 4804 return true; 4805 } 4806 4807 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur) 4808 { 4809 if (old->acquired_refs != cur->acquired_refs) 4810 return false; 4811 return !memcmp(old->refs, cur->refs, 4812 sizeof(*old->refs) * old->acquired_refs); 4813 } 4814 4815 /* compare two verifier states 4816 * 4817 * all states stored in state_list are known to be valid, since 4818 * verifier reached 'bpf_exit' instruction through them 4819 * 4820 * this function is called when verifier exploring different branches of 4821 * execution popped from the state stack. If it sees an old state that has 4822 * more strict register state and more strict stack state then this execution 4823 * branch doesn't need to be explored further, since verifier already 4824 * concluded that more strict state leads to valid finish. 4825 * 4826 * Therefore two states are equivalent if register state is more conservative 4827 * and explored stack state is more conservative than the current one. 4828 * Example: 4829 * explored current 4830 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 4831 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 4832 * 4833 * In other words if current stack state (one being explored) has more 4834 * valid slots than old one that already passed validation, it means 4835 * the verifier can stop exploring and conclude that current state is valid too 4836 * 4837 * Similarly with registers. If explored state has register type as invalid 4838 * whereas register type in current state is meaningful, it means that 4839 * the current state will reach 'bpf_exit' instruction safely 4840 */ 4841 static bool func_states_equal(struct bpf_func_state *old, 4842 struct bpf_func_state *cur) 4843 { 4844 struct idpair *idmap; 4845 bool ret = false; 4846 int i; 4847 4848 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); 4849 /* If we failed to allocate the idmap, just say it's not safe */ 4850 if (!idmap) 4851 return false; 4852 4853 for (i = 0; i < MAX_BPF_REG; i++) { 4854 if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) 4855 goto out_free; 4856 } 4857 4858 if (!stacksafe(old, cur, idmap)) 4859 goto out_free; 4860 4861 if (!refsafe(old, cur)) 4862 goto out_free; 4863 ret = true; 4864 out_free: 4865 kfree(idmap); 4866 return ret; 4867 } 4868 4869 static bool states_equal(struct bpf_verifier_env *env, 4870 struct bpf_verifier_state *old, 4871 struct bpf_verifier_state *cur) 4872 { 4873 int i; 4874 4875 if (old->curframe != cur->curframe) 4876 return false; 4877 4878 /* for states to be equal callsites have to be the same 4879 * and all frame states need to be equivalent 4880 */ 4881 for (i = 0; i <= old->curframe; i++) { 4882 if (old->frame[i]->callsite != cur->frame[i]->callsite) 4883 return false; 4884 if (!func_states_equal(old->frame[i], cur->frame[i])) 4885 return false; 4886 } 4887 return true; 4888 } 4889 4890 /* A write screens off any subsequent reads; but write marks come from the 4891 * straight-line code between a state and its parent. When we arrive at an 4892 * equivalent state (jump target or such) we didn't arrive by the straight-line 4893 * code, so read marks in the state must propagate to the parent regardless 4894 * of the state's write marks. That's what 'parent == state->parent' comparison 4895 * in mark_reg_read() is for. 4896 */ 4897 static int propagate_liveness(struct bpf_verifier_env *env, 4898 const struct bpf_verifier_state *vstate, 4899 struct bpf_verifier_state *vparent) 4900 { 4901 int i, frame, err = 0; 4902 struct bpf_func_state *state, *parent; 4903 4904 if (vparent->curframe != vstate->curframe) { 4905 WARN(1, "propagate_live: parent frame %d current frame %d\n", 4906 vparent->curframe, vstate->curframe); 4907 return -EFAULT; 4908 } 4909 /* Propagate read liveness of registers... */ 4910 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 4911 /* We don't need to worry about FP liveness because it's read-only */ 4912 for (i = 0; i < BPF_REG_FP; i++) { 4913 if (vparent->frame[vparent->curframe]->regs[i].live & REG_LIVE_READ) 4914 continue; 4915 if (vstate->frame[vstate->curframe]->regs[i].live & REG_LIVE_READ) { 4916 err = mark_reg_read(env, &vstate->frame[vstate->curframe]->regs[i], 4917 &vparent->frame[vstate->curframe]->regs[i]); 4918 if (err) 4919 return err; 4920 } 4921 } 4922 4923 /* ... and stack slots */ 4924 for (frame = 0; frame <= vstate->curframe; frame++) { 4925 state = vstate->frame[frame]; 4926 parent = vparent->frame[frame]; 4927 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 4928 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 4929 if (parent->stack[i].spilled_ptr.live & REG_LIVE_READ) 4930 continue; 4931 if (state->stack[i].spilled_ptr.live & REG_LIVE_READ) 4932 mark_reg_read(env, &state->stack[i].spilled_ptr, 4933 &parent->stack[i].spilled_ptr); 4934 } 4935 } 4936 return err; 4937 } 4938 4939 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 4940 { 4941 struct bpf_verifier_state_list *new_sl; 4942 struct bpf_verifier_state_list *sl; 4943 struct bpf_verifier_state *cur = env->cur_state, *new; 4944 int i, j, err; 4945 4946 sl = env->explored_states[insn_idx]; 4947 if (!sl) 4948 /* this 'insn_idx' instruction wasn't marked, so we will not 4949 * be doing state search here 4950 */ 4951 return 0; 4952 4953 while (sl != STATE_LIST_MARK) { 4954 if (states_equal(env, &sl->state, cur)) { 4955 /* reached equivalent register/stack state, 4956 * prune the search. 4957 * Registers read by the continuation are read by us. 4958 * If we have any write marks in env->cur_state, they 4959 * will prevent corresponding reads in the continuation 4960 * from reaching our parent (an explored_state). Our 4961 * own state will get the read marks recorded, but 4962 * they'll be immediately forgotten as we're pruning 4963 * this state and will pop a new one. 4964 */ 4965 err = propagate_liveness(env, &sl->state, cur); 4966 if (err) 4967 return err; 4968 return 1; 4969 } 4970 sl = sl->next; 4971 } 4972 4973 /* there were no equivalent states, remember current one. 4974 * technically the current state is not proven to be safe yet, 4975 * but it will either reach outer most bpf_exit (which means it's safe) 4976 * or it will be rejected. Since there are no loops, we won't be 4977 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 4978 * again on the way to bpf_exit 4979 */ 4980 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 4981 if (!new_sl) 4982 return -ENOMEM; 4983 4984 /* add new state to the head of linked list */ 4985 new = &new_sl->state; 4986 err = copy_verifier_state(new, cur); 4987 if (err) { 4988 free_verifier_state(new, false); 4989 kfree(new_sl); 4990 return err; 4991 } 4992 new_sl->next = env->explored_states[insn_idx]; 4993 env->explored_states[insn_idx] = new_sl; 4994 /* connect new state to parentage chain */ 4995 for (i = 0; i < BPF_REG_FP; i++) 4996 cur_regs(env)[i].parent = &new->frame[new->curframe]->regs[i]; 4997 /* clear write marks in current state: the writes we did are not writes 4998 * our child did, so they don't screen off its reads from us. 4999 * (There are no read marks in current state, because reads always mark 5000 * their parent and current state never has children yet. Only 5001 * explored_states can get read marks.) 5002 */ 5003 for (i = 0; i < BPF_REG_FP; i++) 5004 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE; 5005 5006 /* all stack frames are accessible from callee, clear them all */ 5007 for (j = 0; j <= cur->curframe; j++) { 5008 struct bpf_func_state *frame = cur->frame[j]; 5009 struct bpf_func_state *newframe = new->frame[j]; 5010 5011 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 5012 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 5013 frame->stack[i].spilled_ptr.parent = 5014 &newframe->stack[i].spilled_ptr; 5015 } 5016 } 5017 return 0; 5018 } 5019 5020 /* Return true if it's OK to have the same insn return a different type. */ 5021 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 5022 { 5023 switch (type) { 5024 case PTR_TO_CTX: 5025 case PTR_TO_SOCKET: 5026 case PTR_TO_SOCKET_OR_NULL: 5027 return false; 5028 default: 5029 return true; 5030 } 5031 } 5032 5033 /* If an instruction was previously used with particular pointer types, then we 5034 * need to be careful to avoid cases such as the below, where it may be ok 5035 * for one branch accessing the pointer, but not ok for the other branch: 5036 * 5037 * R1 = sock_ptr 5038 * goto X; 5039 * ... 5040 * R1 = some_other_valid_ptr; 5041 * goto X; 5042 * ... 5043 * R2 = *(u32 *)(R1 + 0); 5044 */ 5045 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 5046 { 5047 return src != prev && (!reg_type_mismatch_ok(src) || 5048 !reg_type_mismatch_ok(prev)); 5049 } 5050 5051 static int do_check(struct bpf_verifier_env *env) 5052 { 5053 struct bpf_verifier_state *state; 5054 struct bpf_insn *insns = env->prog->insnsi; 5055 struct bpf_reg_state *regs; 5056 int insn_cnt = env->prog->len, i; 5057 int insn_idx, prev_insn_idx = 0; 5058 int insn_processed = 0; 5059 bool do_print_state = false; 5060 5061 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 5062 if (!state) 5063 return -ENOMEM; 5064 state->curframe = 0; 5065 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 5066 if (!state->frame[0]) { 5067 kfree(state); 5068 return -ENOMEM; 5069 } 5070 env->cur_state = state; 5071 init_func_state(env, state->frame[0], 5072 BPF_MAIN_FUNC /* callsite */, 5073 0 /* frameno */, 5074 0 /* subprogno, zero == main subprog */); 5075 insn_idx = 0; 5076 for (;;) { 5077 struct bpf_insn *insn; 5078 u8 class; 5079 int err; 5080 5081 if (insn_idx >= insn_cnt) { 5082 verbose(env, "invalid insn idx %d insn_cnt %d\n", 5083 insn_idx, insn_cnt); 5084 return -EFAULT; 5085 } 5086 5087 insn = &insns[insn_idx]; 5088 class = BPF_CLASS(insn->code); 5089 5090 if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 5091 verbose(env, 5092 "BPF program is too large. Processed %d insn\n", 5093 insn_processed); 5094 return -E2BIG; 5095 } 5096 5097 err = is_state_visited(env, insn_idx); 5098 if (err < 0) 5099 return err; 5100 if (err == 1) { 5101 /* found equivalent state, can prune the search */ 5102 if (env->log.level) { 5103 if (do_print_state) 5104 verbose(env, "\nfrom %d to %d: safe\n", 5105 prev_insn_idx, insn_idx); 5106 else 5107 verbose(env, "%d: safe\n", insn_idx); 5108 } 5109 goto process_bpf_exit; 5110 } 5111 5112 if (need_resched()) 5113 cond_resched(); 5114 5115 if (env->log.level > 1 || (env->log.level && do_print_state)) { 5116 if (env->log.level > 1) 5117 verbose(env, "%d:", insn_idx); 5118 else 5119 verbose(env, "\nfrom %d to %d:", 5120 prev_insn_idx, insn_idx); 5121 print_verifier_state(env, state->frame[state->curframe]); 5122 do_print_state = false; 5123 } 5124 5125 if (env->log.level) { 5126 const struct bpf_insn_cbs cbs = { 5127 .cb_print = verbose, 5128 .private_data = env, 5129 }; 5130 5131 verbose(env, "%d: ", insn_idx); 5132 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 5133 } 5134 5135 if (bpf_prog_is_dev_bound(env->prog->aux)) { 5136 err = bpf_prog_offload_verify_insn(env, insn_idx, 5137 prev_insn_idx); 5138 if (err) 5139 return err; 5140 } 5141 5142 regs = cur_regs(env); 5143 env->insn_aux_data[insn_idx].seen = true; 5144 5145 if (class == BPF_ALU || class == BPF_ALU64) { 5146 err = check_alu_op(env, insn); 5147 if (err) 5148 return err; 5149 5150 } else if (class == BPF_LDX) { 5151 enum bpf_reg_type *prev_src_type, src_reg_type; 5152 5153 /* check for reserved fields is already done */ 5154 5155 /* check src operand */ 5156 err = check_reg_arg(env, insn->src_reg, SRC_OP); 5157 if (err) 5158 return err; 5159 5160 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 5161 if (err) 5162 return err; 5163 5164 src_reg_type = regs[insn->src_reg].type; 5165 5166 /* check that memory (src_reg + off) is readable, 5167 * the state of dst_reg will be updated by this func 5168 */ 5169 err = check_mem_access(env, insn_idx, insn->src_reg, insn->off, 5170 BPF_SIZE(insn->code), BPF_READ, 5171 insn->dst_reg, false); 5172 if (err) 5173 return err; 5174 5175 prev_src_type = &env->insn_aux_data[insn_idx].ptr_type; 5176 5177 if (*prev_src_type == NOT_INIT) { 5178 /* saw a valid insn 5179 * dst_reg = *(u32 *)(src_reg + off) 5180 * save type to validate intersecting paths 5181 */ 5182 *prev_src_type = src_reg_type; 5183 5184 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 5185 /* ABuser program is trying to use the same insn 5186 * dst_reg = *(u32*) (src_reg + off) 5187 * with different pointer types: 5188 * src_reg == ctx in one branch and 5189 * src_reg == stack|map in some other branch. 5190 * Reject it. 5191 */ 5192 verbose(env, "same insn cannot be used with different pointers\n"); 5193 return -EINVAL; 5194 } 5195 5196 } else if (class == BPF_STX) { 5197 enum bpf_reg_type *prev_dst_type, dst_reg_type; 5198 5199 if (BPF_MODE(insn->code) == BPF_XADD) { 5200 err = check_xadd(env, insn_idx, insn); 5201 if (err) 5202 return err; 5203 insn_idx++; 5204 continue; 5205 } 5206 5207 /* check src1 operand */ 5208 err = check_reg_arg(env, insn->src_reg, SRC_OP); 5209 if (err) 5210 return err; 5211 /* check src2 operand */ 5212 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 5213 if (err) 5214 return err; 5215 5216 dst_reg_type = regs[insn->dst_reg].type; 5217 5218 /* check that memory (dst_reg + off) is writeable */ 5219 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5220 BPF_SIZE(insn->code), BPF_WRITE, 5221 insn->src_reg, false); 5222 if (err) 5223 return err; 5224 5225 prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type; 5226 5227 if (*prev_dst_type == NOT_INIT) { 5228 *prev_dst_type = dst_reg_type; 5229 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 5230 verbose(env, "same insn cannot be used with different pointers\n"); 5231 return -EINVAL; 5232 } 5233 5234 } else if (class == BPF_ST) { 5235 if (BPF_MODE(insn->code) != BPF_MEM || 5236 insn->src_reg != BPF_REG_0) { 5237 verbose(env, "BPF_ST uses reserved fields\n"); 5238 return -EINVAL; 5239 } 5240 /* check src operand */ 5241 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 5242 if (err) 5243 return err; 5244 5245 if (is_ctx_reg(env, insn->dst_reg)) { 5246 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 5247 insn->dst_reg, reg_type_str[insn->dst_reg]); 5248 return -EACCES; 5249 } 5250 5251 /* check that memory (dst_reg + off) is writeable */ 5252 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 5253 BPF_SIZE(insn->code), BPF_WRITE, 5254 -1, false); 5255 if (err) 5256 return err; 5257 5258 } else if (class == BPF_JMP) { 5259 u8 opcode = BPF_OP(insn->code); 5260 5261 if (opcode == BPF_CALL) { 5262 if (BPF_SRC(insn->code) != BPF_K || 5263 insn->off != 0 || 5264 (insn->src_reg != BPF_REG_0 && 5265 insn->src_reg != BPF_PSEUDO_CALL) || 5266 insn->dst_reg != BPF_REG_0) { 5267 verbose(env, "BPF_CALL uses reserved fields\n"); 5268 return -EINVAL; 5269 } 5270 5271 if (insn->src_reg == BPF_PSEUDO_CALL) 5272 err = check_func_call(env, insn, &insn_idx); 5273 else 5274 err = check_helper_call(env, insn->imm, insn_idx); 5275 if (err) 5276 return err; 5277 5278 } else if (opcode == BPF_JA) { 5279 if (BPF_SRC(insn->code) != BPF_K || 5280 insn->imm != 0 || 5281 insn->src_reg != BPF_REG_0 || 5282 insn->dst_reg != BPF_REG_0) { 5283 verbose(env, "BPF_JA uses reserved fields\n"); 5284 return -EINVAL; 5285 } 5286 5287 insn_idx += insn->off + 1; 5288 continue; 5289 5290 } else if (opcode == BPF_EXIT) { 5291 if (BPF_SRC(insn->code) != BPF_K || 5292 insn->imm != 0 || 5293 insn->src_reg != BPF_REG_0 || 5294 insn->dst_reg != BPF_REG_0) { 5295 verbose(env, "BPF_EXIT uses reserved fields\n"); 5296 return -EINVAL; 5297 } 5298 5299 if (state->curframe) { 5300 /* exit from nested function */ 5301 prev_insn_idx = insn_idx; 5302 err = prepare_func_exit(env, &insn_idx); 5303 if (err) 5304 return err; 5305 do_print_state = true; 5306 continue; 5307 } 5308 5309 err = check_reference_leak(env); 5310 if (err) 5311 return err; 5312 5313 /* eBPF calling convetion is such that R0 is used 5314 * to return the value from eBPF program. 5315 * Make sure that it's readable at this time 5316 * of bpf_exit, which means that program wrote 5317 * something into it earlier 5318 */ 5319 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 5320 if (err) 5321 return err; 5322 5323 if (is_pointer_value(env, BPF_REG_0)) { 5324 verbose(env, "R0 leaks addr as return value\n"); 5325 return -EACCES; 5326 } 5327 5328 err = check_return_code(env); 5329 if (err) 5330 return err; 5331 process_bpf_exit: 5332 err = pop_stack(env, &prev_insn_idx, &insn_idx); 5333 if (err < 0) { 5334 if (err != -ENOENT) 5335 return err; 5336 break; 5337 } else { 5338 do_print_state = true; 5339 continue; 5340 } 5341 } else { 5342 err = check_cond_jmp_op(env, insn, &insn_idx); 5343 if (err) 5344 return err; 5345 } 5346 } else if (class == BPF_LD) { 5347 u8 mode = BPF_MODE(insn->code); 5348 5349 if (mode == BPF_ABS || mode == BPF_IND) { 5350 err = check_ld_abs(env, insn); 5351 if (err) 5352 return err; 5353 5354 } else if (mode == BPF_IMM) { 5355 err = check_ld_imm(env, insn); 5356 if (err) 5357 return err; 5358 5359 insn_idx++; 5360 env->insn_aux_data[insn_idx].seen = true; 5361 } else { 5362 verbose(env, "invalid BPF_LD mode\n"); 5363 return -EINVAL; 5364 } 5365 } else { 5366 verbose(env, "unknown insn class %d\n", class); 5367 return -EINVAL; 5368 } 5369 5370 insn_idx++; 5371 } 5372 5373 verbose(env, "processed %d insns (limit %d), stack depth ", 5374 insn_processed, BPF_COMPLEXITY_LIMIT_INSNS); 5375 for (i = 0; i < env->subprog_cnt; i++) { 5376 u32 depth = env->subprog_info[i].stack_depth; 5377 5378 verbose(env, "%d", depth); 5379 if (i + 1 < env->subprog_cnt) 5380 verbose(env, "+"); 5381 } 5382 verbose(env, "\n"); 5383 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 5384 return 0; 5385 } 5386 5387 static int check_map_prealloc(struct bpf_map *map) 5388 { 5389 return (map->map_type != BPF_MAP_TYPE_HASH && 5390 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 5391 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || 5392 !(map->map_flags & BPF_F_NO_PREALLOC); 5393 } 5394 5395 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 5396 struct bpf_map *map, 5397 struct bpf_prog *prog) 5398 5399 { 5400 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use 5401 * preallocated hash maps, since doing memory allocation 5402 * in overflow_handler can crash depending on where nmi got 5403 * triggered. 5404 */ 5405 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) { 5406 if (!check_map_prealloc(map)) { 5407 verbose(env, "perf_event programs can only use preallocated hash map\n"); 5408 return -EINVAL; 5409 } 5410 if (map->inner_map_meta && 5411 !check_map_prealloc(map->inner_map_meta)) { 5412 verbose(env, "perf_event programs can only use preallocated inner hash map\n"); 5413 return -EINVAL; 5414 } 5415 } 5416 5417 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) && 5418 !bpf_offload_prog_map_match(prog, map)) { 5419 verbose(env, "offload device mismatch between prog and map\n"); 5420 return -EINVAL; 5421 } 5422 5423 return 0; 5424 } 5425 5426 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 5427 { 5428 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 5429 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 5430 } 5431 5432 /* look for pseudo eBPF instructions that access map FDs and 5433 * replace them with actual map pointers 5434 */ 5435 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) 5436 { 5437 struct bpf_insn *insn = env->prog->insnsi; 5438 int insn_cnt = env->prog->len; 5439 int i, j, err; 5440 5441 err = bpf_prog_calc_tag(env->prog); 5442 if (err) 5443 return err; 5444 5445 for (i = 0; i < insn_cnt; i++, insn++) { 5446 if (BPF_CLASS(insn->code) == BPF_LDX && 5447 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 5448 verbose(env, "BPF_LDX uses reserved fields\n"); 5449 return -EINVAL; 5450 } 5451 5452 if (BPF_CLASS(insn->code) == BPF_STX && 5453 ((BPF_MODE(insn->code) != BPF_MEM && 5454 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { 5455 verbose(env, "BPF_STX uses reserved fields\n"); 5456 return -EINVAL; 5457 } 5458 5459 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 5460 struct bpf_map *map; 5461 struct fd f; 5462 5463 if (i == insn_cnt - 1 || insn[1].code != 0 || 5464 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 5465 insn[1].off != 0) { 5466 verbose(env, "invalid bpf_ld_imm64 insn\n"); 5467 return -EINVAL; 5468 } 5469 5470 if (insn->src_reg == 0) 5471 /* valid generic load 64-bit imm */ 5472 goto next_insn; 5473 5474 if (insn->src_reg != BPF_PSEUDO_MAP_FD) { 5475 verbose(env, 5476 "unrecognized bpf_ld_imm64 insn\n"); 5477 return -EINVAL; 5478 } 5479 5480 f = fdget(insn->imm); 5481 map = __bpf_map_get(f); 5482 if (IS_ERR(map)) { 5483 verbose(env, "fd %d is not pointing to valid bpf_map\n", 5484 insn->imm); 5485 return PTR_ERR(map); 5486 } 5487 5488 err = check_map_prog_compatibility(env, map, env->prog); 5489 if (err) { 5490 fdput(f); 5491 return err; 5492 } 5493 5494 /* store map pointer inside BPF_LD_IMM64 instruction */ 5495 insn[0].imm = (u32) (unsigned long) map; 5496 insn[1].imm = ((u64) (unsigned long) map) >> 32; 5497 5498 /* check whether we recorded this map already */ 5499 for (j = 0; j < env->used_map_cnt; j++) 5500 if (env->used_maps[j] == map) { 5501 fdput(f); 5502 goto next_insn; 5503 } 5504 5505 if (env->used_map_cnt >= MAX_USED_MAPS) { 5506 fdput(f); 5507 return -E2BIG; 5508 } 5509 5510 /* hold the map. If the program is rejected by verifier, 5511 * the map will be released by release_maps() or it 5512 * will be used by the valid program until it's unloaded 5513 * and all maps are released in free_used_maps() 5514 */ 5515 map = bpf_map_inc(map, false); 5516 if (IS_ERR(map)) { 5517 fdput(f); 5518 return PTR_ERR(map); 5519 } 5520 env->used_maps[env->used_map_cnt++] = map; 5521 5522 if (bpf_map_is_cgroup_storage(map) && 5523 bpf_cgroup_storage_assign(env->prog, map)) { 5524 verbose(env, "only one cgroup storage of each type is allowed\n"); 5525 fdput(f); 5526 return -EBUSY; 5527 } 5528 5529 fdput(f); 5530 next_insn: 5531 insn++; 5532 i++; 5533 continue; 5534 } 5535 5536 /* Basic sanity check before we invest more work here. */ 5537 if (!bpf_opcode_in_insntable(insn->code)) { 5538 verbose(env, "unknown opcode %02x\n", insn->code); 5539 return -EINVAL; 5540 } 5541 } 5542 5543 /* now all pseudo BPF_LD_IMM64 instructions load valid 5544 * 'struct bpf_map *' into a register instead of user map_fd. 5545 * These pointers will be used later by verifier to validate map access. 5546 */ 5547 return 0; 5548 } 5549 5550 /* drop refcnt of maps used by the rejected program */ 5551 static void release_maps(struct bpf_verifier_env *env) 5552 { 5553 enum bpf_cgroup_storage_type stype; 5554 int i; 5555 5556 for_each_cgroup_storage_type(stype) { 5557 if (!env->prog->aux->cgroup_storage[stype]) 5558 continue; 5559 bpf_cgroup_storage_release(env->prog, 5560 env->prog->aux->cgroup_storage[stype]); 5561 } 5562 5563 for (i = 0; i < env->used_map_cnt; i++) 5564 bpf_map_put(env->used_maps[i]); 5565 } 5566 5567 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 5568 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 5569 { 5570 struct bpf_insn *insn = env->prog->insnsi; 5571 int insn_cnt = env->prog->len; 5572 int i; 5573 5574 for (i = 0; i < insn_cnt; i++, insn++) 5575 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW)) 5576 insn->src_reg = 0; 5577 } 5578 5579 /* single env->prog->insni[off] instruction was replaced with the range 5580 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 5581 * [0, off) and [off, end) to new locations, so the patched range stays zero 5582 */ 5583 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, 5584 u32 off, u32 cnt) 5585 { 5586 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; 5587 int i; 5588 5589 if (cnt == 1) 5590 return 0; 5591 new_data = vzalloc(array_size(prog_len, 5592 sizeof(struct bpf_insn_aux_data))); 5593 if (!new_data) 5594 return -ENOMEM; 5595 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 5596 memcpy(new_data + off + cnt - 1, old_data + off, 5597 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 5598 for (i = off; i < off + cnt - 1; i++) 5599 new_data[i].seen = true; 5600 env->insn_aux_data = new_data; 5601 vfree(old_data); 5602 return 0; 5603 } 5604 5605 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 5606 { 5607 int i; 5608 5609 if (len == 1) 5610 return; 5611 /* NOTE: fake 'exit' subprog should be updated as well. */ 5612 for (i = 0; i <= env->subprog_cnt; i++) { 5613 if (env->subprog_info[i].start < off) 5614 continue; 5615 env->subprog_info[i].start += len - 1; 5616 } 5617 } 5618 5619 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 5620 const struct bpf_insn *patch, u32 len) 5621 { 5622 struct bpf_prog *new_prog; 5623 5624 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 5625 if (!new_prog) 5626 return NULL; 5627 if (adjust_insn_aux_data(env, new_prog->len, off, len)) 5628 return NULL; 5629 adjust_subprog_starts(env, off, len); 5630 return new_prog; 5631 } 5632 5633 /* The verifier does more data flow analysis than llvm and will not 5634 * explore branches that are dead at run time. Malicious programs can 5635 * have dead code too. Therefore replace all dead at-run-time code 5636 * with 'ja -1'. 5637 * 5638 * Just nops are not optimal, e.g. if they would sit at the end of the 5639 * program and through another bug we would manage to jump there, then 5640 * we'd execute beyond program memory otherwise. Returning exception 5641 * code also wouldn't work since we can have subprogs where the dead 5642 * code could be located. 5643 */ 5644 static void sanitize_dead_code(struct bpf_verifier_env *env) 5645 { 5646 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 5647 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 5648 struct bpf_insn *insn = env->prog->insnsi; 5649 const int insn_cnt = env->prog->len; 5650 int i; 5651 5652 for (i = 0; i < insn_cnt; i++) { 5653 if (aux_data[i].seen) 5654 continue; 5655 memcpy(insn + i, &trap, sizeof(trap)); 5656 } 5657 } 5658 5659 /* convert load instructions that access fields of a context type into a 5660 * sequence of instructions that access fields of the underlying structure: 5661 * struct __sk_buff -> struct sk_buff 5662 * struct bpf_sock_ops -> struct sock 5663 */ 5664 static int convert_ctx_accesses(struct bpf_verifier_env *env) 5665 { 5666 const struct bpf_verifier_ops *ops = env->ops; 5667 int i, cnt, size, ctx_field_size, delta = 0; 5668 const int insn_cnt = env->prog->len; 5669 struct bpf_insn insn_buf[16], *insn; 5670 struct bpf_prog *new_prog; 5671 enum bpf_access_type type; 5672 bool is_narrower_load; 5673 u32 target_size; 5674 5675 if (ops->gen_prologue) { 5676 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 5677 env->prog); 5678 if (cnt >= ARRAY_SIZE(insn_buf)) { 5679 verbose(env, "bpf verifier is misconfigured\n"); 5680 return -EINVAL; 5681 } else if (cnt) { 5682 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 5683 if (!new_prog) 5684 return -ENOMEM; 5685 5686 env->prog = new_prog; 5687 delta += cnt - 1; 5688 } 5689 } 5690 5691 if (bpf_prog_is_dev_bound(env->prog->aux)) 5692 return 0; 5693 5694 insn = env->prog->insnsi + delta; 5695 5696 for (i = 0; i < insn_cnt; i++, insn++) { 5697 bpf_convert_ctx_access_t convert_ctx_access; 5698 5699 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 5700 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 5701 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 5702 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) 5703 type = BPF_READ; 5704 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 5705 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 5706 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 5707 insn->code == (BPF_STX | BPF_MEM | BPF_DW)) 5708 type = BPF_WRITE; 5709 else 5710 continue; 5711 5712 if (type == BPF_WRITE && 5713 env->insn_aux_data[i + delta].sanitize_stack_off) { 5714 struct bpf_insn patch[] = { 5715 /* Sanitize suspicious stack slot with zero. 5716 * There are no memory dependencies for this store, 5717 * since it's only using frame pointer and immediate 5718 * constant of zero 5719 */ 5720 BPF_ST_MEM(BPF_DW, BPF_REG_FP, 5721 env->insn_aux_data[i + delta].sanitize_stack_off, 5722 0), 5723 /* the original STX instruction will immediately 5724 * overwrite the same stack slot with appropriate value 5725 */ 5726 *insn, 5727 }; 5728 5729 cnt = ARRAY_SIZE(patch); 5730 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 5731 if (!new_prog) 5732 return -ENOMEM; 5733 5734 delta += cnt - 1; 5735 env->prog = new_prog; 5736 insn = new_prog->insnsi + i + delta; 5737 continue; 5738 } 5739 5740 switch (env->insn_aux_data[i + delta].ptr_type) { 5741 case PTR_TO_CTX: 5742 if (!ops->convert_ctx_access) 5743 continue; 5744 convert_ctx_access = ops->convert_ctx_access; 5745 break; 5746 case PTR_TO_SOCKET: 5747 convert_ctx_access = bpf_sock_convert_ctx_access; 5748 break; 5749 default: 5750 continue; 5751 } 5752 5753 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 5754 size = BPF_LDST_BYTES(insn); 5755 5756 /* If the read access is a narrower load of the field, 5757 * convert to a 4/8-byte load, to minimum program type specific 5758 * convert_ctx_access changes. If conversion is successful, 5759 * we will apply proper mask to the result. 5760 */ 5761 is_narrower_load = size < ctx_field_size; 5762 if (is_narrower_load) { 5763 u32 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 5764 u32 off = insn->off; 5765 u8 size_code; 5766 5767 if (type == BPF_WRITE) { 5768 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 5769 return -EINVAL; 5770 } 5771 5772 size_code = BPF_H; 5773 if (ctx_field_size == 4) 5774 size_code = BPF_W; 5775 else if (ctx_field_size == 8) 5776 size_code = BPF_DW; 5777 5778 insn->off = off & ~(size_default - 1); 5779 insn->code = BPF_LDX | BPF_MEM | size_code; 5780 } 5781 5782 target_size = 0; 5783 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 5784 &target_size); 5785 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 5786 (ctx_field_size && !target_size)) { 5787 verbose(env, "bpf verifier is misconfigured\n"); 5788 return -EINVAL; 5789 } 5790 5791 if (is_narrower_load && size < target_size) { 5792 if (ctx_field_size <= 4) 5793 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 5794 (1 << size * 8) - 1); 5795 else 5796 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 5797 (1 << size * 8) - 1); 5798 } 5799 5800 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 5801 if (!new_prog) 5802 return -ENOMEM; 5803 5804 delta += cnt - 1; 5805 5806 /* keep walking new program and skip insns we just inserted */ 5807 env->prog = new_prog; 5808 insn = new_prog->insnsi + i + delta; 5809 } 5810 5811 return 0; 5812 } 5813 5814 static int jit_subprogs(struct bpf_verifier_env *env) 5815 { 5816 struct bpf_prog *prog = env->prog, **func, *tmp; 5817 int i, j, subprog_start, subprog_end = 0, len, subprog; 5818 struct bpf_insn *insn; 5819 void *old_bpf_func; 5820 int err = -ENOMEM; 5821 5822 if (env->subprog_cnt <= 1) 5823 return 0; 5824 5825 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 5826 if (insn->code != (BPF_JMP | BPF_CALL) || 5827 insn->src_reg != BPF_PSEUDO_CALL) 5828 continue; 5829 /* Upon error here we cannot fall back to interpreter but 5830 * need a hard reject of the program. Thus -EFAULT is 5831 * propagated in any case. 5832 */ 5833 subprog = find_subprog(env, i + insn->imm + 1); 5834 if (subprog < 0) { 5835 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 5836 i + insn->imm + 1); 5837 return -EFAULT; 5838 } 5839 /* temporarily remember subprog id inside insn instead of 5840 * aux_data, since next loop will split up all insns into funcs 5841 */ 5842 insn->off = subprog; 5843 /* remember original imm in case JIT fails and fallback 5844 * to interpreter will be needed 5845 */ 5846 env->insn_aux_data[i].call_imm = insn->imm; 5847 /* point imm to __bpf_call_base+1 from JITs point of view */ 5848 insn->imm = 1; 5849 } 5850 5851 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 5852 if (!func) 5853 goto out_undo_insn; 5854 5855 for (i = 0; i < env->subprog_cnt; i++) { 5856 subprog_start = subprog_end; 5857 subprog_end = env->subprog_info[i + 1].start; 5858 5859 len = subprog_end - subprog_start; 5860 func[i] = bpf_prog_alloc(bpf_prog_size(len), GFP_USER); 5861 if (!func[i]) 5862 goto out_free; 5863 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 5864 len * sizeof(struct bpf_insn)); 5865 func[i]->type = prog->type; 5866 func[i]->len = len; 5867 if (bpf_prog_calc_tag(func[i])) 5868 goto out_free; 5869 func[i]->is_func = 1; 5870 /* Use bpf_prog_F_tag to indicate functions in stack traces. 5871 * Long term would need debug info to populate names 5872 */ 5873 func[i]->aux->name[0] = 'F'; 5874 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 5875 func[i]->jit_requested = 1; 5876 func[i] = bpf_int_jit_compile(func[i]); 5877 if (!func[i]->jited) { 5878 err = -ENOTSUPP; 5879 goto out_free; 5880 } 5881 cond_resched(); 5882 } 5883 /* at this point all bpf functions were successfully JITed 5884 * now populate all bpf_calls with correct addresses and 5885 * run last pass of JIT 5886 */ 5887 for (i = 0; i < env->subprog_cnt; i++) { 5888 insn = func[i]->insnsi; 5889 for (j = 0; j < func[i]->len; j++, insn++) { 5890 if (insn->code != (BPF_JMP | BPF_CALL) || 5891 insn->src_reg != BPF_PSEUDO_CALL) 5892 continue; 5893 subprog = insn->off; 5894 insn->imm = (u64 (*)(u64, u64, u64, u64, u64)) 5895 func[subprog]->bpf_func - 5896 __bpf_call_base; 5897 } 5898 5899 /* we use the aux data to keep a list of the start addresses 5900 * of the JITed images for each function in the program 5901 * 5902 * for some architectures, such as powerpc64, the imm field 5903 * might not be large enough to hold the offset of the start 5904 * address of the callee's JITed image from __bpf_call_base 5905 * 5906 * in such cases, we can lookup the start address of a callee 5907 * by using its subprog id, available from the off field of 5908 * the call instruction, as an index for this list 5909 */ 5910 func[i]->aux->func = func; 5911 func[i]->aux->func_cnt = env->subprog_cnt; 5912 } 5913 for (i = 0; i < env->subprog_cnt; i++) { 5914 old_bpf_func = func[i]->bpf_func; 5915 tmp = bpf_int_jit_compile(func[i]); 5916 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 5917 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 5918 err = -ENOTSUPP; 5919 goto out_free; 5920 } 5921 cond_resched(); 5922 } 5923 5924 /* finally lock prog and jit images for all functions and 5925 * populate kallsysm 5926 */ 5927 for (i = 0; i < env->subprog_cnt; i++) { 5928 bpf_prog_lock_ro(func[i]); 5929 bpf_prog_kallsyms_add(func[i]); 5930 } 5931 5932 /* Last step: make now unused interpreter insns from main 5933 * prog consistent for later dump requests, so they can 5934 * later look the same as if they were interpreted only. 5935 */ 5936 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 5937 if (insn->code != (BPF_JMP | BPF_CALL) || 5938 insn->src_reg != BPF_PSEUDO_CALL) 5939 continue; 5940 insn->off = env->insn_aux_data[i].call_imm; 5941 subprog = find_subprog(env, i + insn->off + 1); 5942 insn->imm = subprog; 5943 } 5944 5945 prog->jited = 1; 5946 prog->bpf_func = func[0]->bpf_func; 5947 prog->aux->func = func; 5948 prog->aux->func_cnt = env->subprog_cnt; 5949 return 0; 5950 out_free: 5951 for (i = 0; i < env->subprog_cnt; i++) 5952 if (func[i]) 5953 bpf_jit_free(func[i]); 5954 kfree(func); 5955 out_undo_insn: 5956 /* cleanup main prog to be interpreted */ 5957 prog->jit_requested = 0; 5958 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 5959 if (insn->code != (BPF_JMP | BPF_CALL) || 5960 insn->src_reg != BPF_PSEUDO_CALL) 5961 continue; 5962 insn->off = 0; 5963 insn->imm = env->insn_aux_data[i].call_imm; 5964 } 5965 return err; 5966 } 5967 5968 static int fixup_call_args(struct bpf_verifier_env *env) 5969 { 5970 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5971 struct bpf_prog *prog = env->prog; 5972 struct bpf_insn *insn = prog->insnsi; 5973 int i, depth; 5974 #endif 5975 int err = 0; 5976 5977 if (env->prog->jit_requested && 5978 !bpf_prog_is_dev_bound(env->prog->aux)) { 5979 err = jit_subprogs(env); 5980 if (err == 0) 5981 return 0; 5982 if (err == -EFAULT) 5983 return err; 5984 } 5985 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 5986 for (i = 0; i < prog->len; i++, insn++) { 5987 if (insn->code != (BPF_JMP | BPF_CALL) || 5988 insn->src_reg != BPF_PSEUDO_CALL) 5989 continue; 5990 depth = get_callee_stack_depth(env, insn, i); 5991 if (depth < 0) 5992 return depth; 5993 bpf_patch_call_args(insn, depth); 5994 } 5995 err = 0; 5996 #endif 5997 return err; 5998 } 5999 6000 /* fixup insn->imm field of bpf_call instructions 6001 * and inline eligible helpers as explicit sequence of BPF instructions 6002 * 6003 * this function is called after eBPF program passed verification 6004 */ 6005 static int fixup_bpf_calls(struct bpf_verifier_env *env) 6006 { 6007 struct bpf_prog *prog = env->prog; 6008 struct bpf_insn *insn = prog->insnsi; 6009 const struct bpf_func_proto *fn; 6010 const int insn_cnt = prog->len; 6011 const struct bpf_map_ops *ops; 6012 struct bpf_insn_aux_data *aux; 6013 struct bpf_insn insn_buf[16]; 6014 struct bpf_prog *new_prog; 6015 struct bpf_map *map_ptr; 6016 int i, cnt, delta = 0; 6017 6018 for (i = 0; i < insn_cnt; i++, insn++) { 6019 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 6020 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 6021 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 6022 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 6023 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 6024 struct bpf_insn mask_and_div[] = { 6025 BPF_MOV32_REG(insn->src_reg, insn->src_reg), 6026 /* Rx div 0 -> 0 */ 6027 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2), 6028 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 6029 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 6030 *insn, 6031 }; 6032 struct bpf_insn mask_and_mod[] = { 6033 BPF_MOV32_REG(insn->src_reg, insn->src_reg), 6034 /* Rx mod 0 -> Rx */ 6035 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1), 6036 *insn, 6037 }; 6038 struct bpf_insn *patchlet; 6039 6040 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 6041 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 6042 patchlet = mask_and_div + (is64 ? 1 : 0); 6043 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0); 6044 } else { 6045 patchlet = mask_and_mod + (is64 ? 1 : 0); 6046 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0); 6047 } 6048 6049 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 6050 if (!new_prog) 6051 return -ENOMEM; 6052 6053 delta += cnt - 1; 6054 env->prog = prog = new_prog; 6055 insn = new_prog->insnsi + i + delta; 6056 continue; 6057 } 6058 6059 if (BPF_CLASS(insn->code) == BPF_LD && 6060 (BPF_MODE(insn->code) == BPF_ABS || 6061 BPF_MODE(insn->code) == BPF_IND)) { 6062 cnt = env->ops->gen_ld_abs(insn, insn_buf); 6063 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 6064 verbose(env, "bpf verifier is misconfigured\n"); 6065 return -EINVAL; 6066 } 6067 6068 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 6069 if (!new_prog) 6070 return -ENOMEM; 6071 6072 delta += cnt - 1; 6073 env->prog = prog = new_prog; 6074 insn = new_prog->insnsi + i + delta; 6075 continue; 6076 } 6077 6078 if (insn->code != (BPF_JMP | BPF_CALL)) 6079 continue; 6080 if (insn->src_reg == BPF_PSEUDO_CALL) 6081 continue; 6082 6083 if (insn->imm == BPF_FUNC_get_route_realm) 6084 prog->dst_needed = 1; 6085 if (insn->imm == BPF_FUNC_get_prandom_u32) 6086 bpf_user_rnd_init_once(); 6087 if (insn->imm == BPF_FUNC_override_return) 6088 prog->kprobe_override = 1; 6089 if (insn->imm == BPF_FUNC_tail_call) { 6090 /* If we tail call into other programs, we 6091 * cannot make any assumptions since they can 6092 * be replaced dynamically during runtime in 6093 * the program array. 6094 */ 6095 prog->cb_access = 1; 6096 env->prog->aux->stack_depth = MAX_BPF_STACK; 6097 6098 /* mark bpf_tail_call as different opcode to avoid 6099 * conditional branch in the interpeter for every normal 6100 * call and to prevent accidental JITing by JIT compiler 6101 * that doesn't support bpf_tail_call yet 6102 */ 6103 insn->imm = 0; 6104 insn->code = BPF_JMP | BPF_TAIL_CALL; 6105 6106 aux = &env->insn_aux_data[i + delta]; 6107 if (!bpf_map_ptr_unpriv(aux)) 6108 continue; 6109 6110 /* instead of changing every JIT dealing with tail_call 6111 * emit two extra insns: 6112 * if (index >= max_entries) goto out; 6113 * index &= array->index_mask; 6114 * to avoid out-of-bounds cpu speculation 6115 */ 6116 if (bpf_map_ptr_poisoned(aux)) { 6117 verbose(env, "tail_call abusing map_ptr\n"); 6118 return -EINVAL; 6119 } 6120 6121 map_ptr = BPF_MAP_PTR(aux->map_state); 6122 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 6123 map_ptr->max_entries, 2); 6124 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 6125 container_of(map_ptr, 6126 struct bpf_array, 6127 map)->index_mask); 6128 insn_buf[2] = *insn; 6129 cnt = 3; 6130 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 6131 if (!new_prog) 6132 return -ENOMEM; 6133 6134 delta += cnt - 1; 6135 env->prog = prog = new_prog; 6136 insn = new_prog->insnsi + i + delta; 6137 continue; 6138 } 6139 6140 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 6141 * and other inlining handlers are currently limited to 64 bit 6142 * only. 6143 */ 6144 if (prog->jit_requested && BITS_PER_LONG == 64 && 6145 (insn->imm == BPF_FUNC_map_lookup_elem || 6146 insn->imm == BPF_FUNC_map_update_elem || 6147 insn->imm == BPF_FUNC_map_delete_elem)) { 6148 aux = &env->insn_aux_data[i + delta]; 6149 if (bpf_map_ptr_poisoned(aux)) 6150 goto patch_call_imm; 6151 6152 map_ptr = BPF_MAP_PTR(aux->map_state); 6153 ops = map_ptr->ops; 6154 if (insn->imm == BPF_FUNC_map_lookup_elem && 6155 ops->map_gen_lookup) { 6156 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 6157 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 6158 verbose(env, "bpf verifier is misconfigured\n"); 6159 return -EINVAL; 6160 } 6161 6162 new_prog = bpf_patch_insn_data(env, i + delta, 6163 insn_buf, cnt); 6164 if (!new_prog) 6165 return -ENOMEM; 6166 6167 delta += cnt - 1; 6168 env->prog = prog = new_prog; 6169 insn = new_prog->insnsi + i + delta; 6170 continue; 6171 } 6172 6173 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 6174 (void *(*)(struct bpf_map *map, void *key))NULL)); 6175 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 6176 (int (*)(struct bpf_map *map, void *key))NULL)); 6177 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 6178 (int (*)(struct bpf_map *map, void *key, void *value, 6179 u64 flags))NULL)); 6180 switch (insn->imm) { 6181 case BPF_FUNC_map_lookup_elem: 6182 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - 6183 __bpf_call_base; 6184 continue; 6185 case BPF_FUNC_map_update_elem: 6186 insn->imm = BPF_CAST_CALL(ops->map_update_elem) - 6187 __bpf_call_base; 6188 continue; 6189 case BPF_FUNC_map_delete_elem: 6190 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - 6191 __bpf_call_base; 6192 continue; 6193 } 6194 6195 goto patch_call_imm; 6196 } 6197 6198 patch_call_imm: 6199 fn = env->ops->get_func_proto(insn->imm, env->prog); 6200 /* all functions that have prototype and verifier allowed 6201 * programs to call them, must be real in-kernel functions 6202 */ 6203 if (!fn->func) { 6204 verbose(env, 6205 "kernel subsystem misconfigured func %s#%d\n", 6206 func_id_name(insn->imm), insn->imm); 6207 return -EFAULT; 6208 } 6209 insn->imm = fn->func - __bpf_call_base; 6210 } 6211 6212 return 0; 6213 } 6214 6215 static void free_states(struct bpf_verifier_env *env) 6216 { 6217 struct bpf_verifier_state_list *sl, *sln; 6218 int i; 6219 6220 if (!env->explored_states) 6221 return; 6222 6223 for (i = 0; i < env->prog->len; i++) { 6224 sl = env->explored_states[i]; 6225 6226 if (sl) 6227 while (sl != STATE_LIST_MARK) { 6228 sln = sl->next; 6229 free_verifier_state(&sl->state, false); 6230 kfree(sl); 6231 sl = sln; 6232 } 6233 } 6234 6235 kfree(env->explored_states); 6236 } 6237 6238 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) 6239 { 6240 struct bpf_verifier_env *env; 6241 struct bpf_verifier_log *log; 6242 int ret = -EINVAL; 6243 6244 /* no program is valid */ 6245 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 6246 return -EINVAL; 6247 6248 /* 'struct bpf_verifier_env' can be global, but since it's not small, 6249 * allocate/free it every time bpf_check() is called 6250 */ 6251 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 6252 if (!env) 6253 return -ENOMEM; 6254 log = &env->log; 6255 6256 env->insn_aux_data = 6257 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), 6258 (*prog)->len)); 6259 ret = -ENOMEM; 6260 if (!env->insn_aux_data) 6261 goto err_free_env; 6262 env->prog = *prog; 6263 env->ops = bpf_verifier_ops[env->prog->type]; 6264 6265 /* grab the mutex to protect few globals used by verifier */ 6266 mutex_lock(&bpf_verifier_lock); 6267 6268 if (attr->log_level || attr->log_buf || attr->log_size) { 6269 /* user requested verbose verifier output 6270 * and supplied buffer to store the verification trace 6271 */ 6272 log->level = attr->log_level; 6273 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 6274 log->len_total = attr->log_size; 6275 6276 ret = -EINVAL; 6277 /* log attributes have to be sane */ 6278 if (log->len_total < 128 || log->len_total > UINT_MAX >> 8 || 6279 !log->level || !log->ubuf) 6280 goto err_unlock; 6281 } 6282 6283 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 6284 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 6285 env->strict_alignment = true; 6286 6287 ret = replace_map_fd_with_map_ptr(env); 6288 if (ret < 0) 6289 goto skip_full_check; 6290 6291 if (bpf_prog_is_dev_bound(env->prog->aux)) { 6292 ret = bpf_prog_offload_verifier_prep(env); 6293 if (ret) 6294 goto skip_full_check; 6295 } 6296 6297 env->explored_states = kcalloc(env->prog->len, 6298 sizeof(struct bpf_verifier_state_list *), 6299 GFP_USER); 6300 ret = -ENOMEM; 6301 if (!env->explored_states) 6302 goto skip_full_check; 6303 6304 env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); 6305 6306 ret = check_cfg(env); 6307 if (ret < 0) 6308 goto skip_full_check; 6309 6310 ret = do_check(env); 6311 if (env->cur_state) { 6312 free_verifier_state(env->cur_state, true); 6313 env->cur_state = NULL; 6314 } 6315 6316 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux)) 6317 ret = bpf_prog_offload_finalize(env); 6318 6319 skip_full_check: 6320 while (!pop_stack(env, NULL, NULL)); 6321 free_states(env); 6322 6323 if (ret == 0) 6324 sanitize_dead_code(env); 6325 6326 if (ret == 0) 6327 ret = check_max_stack_depth(env); 6328 6329 if (ret == 0) 6330 /* program is valid, convert *(u32*)(ctx + off) accesses */ 6331 ret = convert_ctx_accesses(env); 6332 6333 if (ret == 0) 6334 ret = fixup_bpf_calls(env); 6335 6336 if (ret == 0) 6337 ret = fixup_call_args(env); 6338 6339 if (log->level && bpf_verifier_log_full(log)) 6340 ret = -ENOSPC; 6341 if (log->level && !log->ubuf) { 6342 ret = -EFAULT; 6343 goto err_release_maps; 6344 } 6345 6346 if (ret == 0 && env->used_map_cnt) { 6347 /* if program passed verifier, update used_maps in bpf_prog_info */ 6348 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 6349 sizeof(env->used_maps[0]), 6350 GFP_KERNEL); 6351 6352 if (!env->prog->aux->used_maps) { 6353 ret = -ENOMEM; 6354 goto err_release_maps; 6355 } 6356 6357 memcpy(env->prog->aux->used_maps, env->used_maps, 6358 sizeof(env->used_maps[0]) * env->used_map_cnt); 6359 env->prog->aux->used_map_cnt = env->used_map_cnt; 6360 6361 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 6362 * bpf_ld_imm64 instructions 6363 */ 6364 convert_pseudo_ld_imm64(env); 6365 } 6366 6367 err_release_maps: 6368 if (!env->prog->aux->used_maps) 6369 /* if we didn't copy map pointers into bpf_prog_info, release 6370 * them now. Otherwise free_used_maps() will release them. 6371 */ 6372 release_maps(env); 6373 *prog = env->prog; 6374 err_unlock: 6375 mutex_unlock(&bpf_verifier_lock); 6376 vfree(env->insn_aux_data); 6377 err_free_env: 6378 kfree(env); 6379 return ret; 6380 } 6381