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