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