1 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 2 * Copyright (c) 2016 Facebook 3 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 4 * 5 * This program is free software; you can redistribute it and/or 6 * modify it under the terms of version 2 of the GNU General Public 7 * License as published by the Free Software Foundation. 8 * 9 * This program is distributed in the hope that it will be useful, but 10 * WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 * General Public License for more details. 13 */ 14 #include <uapi/linux/btf.h> 15 #include <linux/kernel.h> 16 #include <linux/types.h> 17 #include <linux/slab.h> 18 #include <linux/bpf.h> 19 #include <linux/btf.h> 20 #include <linux/bpf_verifier.h> 21 #include <linux/filter.h> 22 #include <net/netlink.h> 23 #include <linux/file.h> 24 #include <linux/vmalloc.h> 25 #include <linux/stringify.h> 26 #include <linux/bsearch.h> 27 #include <linux/sort.h> 28 #include <linux/perf_event.h> 29 #include <linux/ctype.h> 30 31 #include "disasm.h" 32 33 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 34 #define BPF_PROG_TYPE(_id, _name) \ 35 [_id] = & _name ## _verifier_ops, 36 #define BPF_MAP_TYPE(_id, _ops) 37 #include <linux/bpf_types.h> 38 #undef BPF_PROG_TYPE 39 #undef BPF_MAP_TYPE 40 }; 41 42 /* bpf_check() is a static code analyzer that walks eBPF program 43 * instruction by instruction and updates register/stack state. 44 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 45 * 46 * The first pass is depth-first-search to check that the program is a DAG. 47 * It rejects the following programs: 48 * - larger than BPF_MAXINSNS insns 49 * - if loop is present (detected via back-edge) 50 * - unreachable insns exist (shouldn't be a forest. program = one function) 51 * - out of bounds or malformed jumps 52 * The second pass is all possible path descent from the 1st insn. 53 * Since it's analyzing all pathes through the program, the length of the 54 * analysis is limited to 64k insn, which may be hit even if total number of 55 * insn is less then 4K, but there are too many branches that change stack/regs. 56 * Number of 'branches to be analyzed' is limited to 1k 57 * 58 * On entry to each instruction, each register has a type, and the instruction 59 * changes the types of the registers depending on instruction semantics. 60 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 61 * copied to R1. 62 * 63 * All registers are 64-bit. 64 * R0 - return register 65 * R1-R5 argument passing registers 66 * R6-R9 callee saved registers 67 * R10 - frame pointer read-only 68 * 69 * At the start of BPF program the register R1 contains a pointer to bpf_context 70 * and has type PTR_TO_CTX. 71 * 72 * Verifier tracks arithmetic operations on pointers in case: 73 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 74 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 75 * 1st insn copies R10 (which has FRAME_PTR) type into R1 76 * and 2nd arithmetic instruction is pattern matched to recognize 77 * that it wants to construct a pointer to some element within stack. 78 * So after 2nd insn, the register R1 has type PTR_TO_STACK 79 * (and -20 constant is saved for further stack bounds checking). 80 * Meaning that this reg is a pointer to stack plus known immediate constant. 81 * 82 * Most of the time the registers have SCALAR_VALUE type, which 83 * means the register has some value, but it's not a valid pointer. 84 * (like pointer plus pointer becomes SCALAR_VALUE type) 85 * 86 * When verifier sees load or store instructions the type of base register 87 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 88 * four pointer types recognized by check_mem_access() function. 89 * 90 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 91 * and the range of [ptr, ptr + map's value_size) is accessible. 92 * 93 * registers used to pass values to function calls are checked against 94 * function argument constraints. 95 * 96 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 97 * It means that the register type passed to this function must be 98 * PTR_TO_STACK and it will be used inside the function as 99 * 'pointer to map element key' 100 * 101 * For example the argument constraints for bpf_map_lookup_elem(): 102 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 103 * .arg1_type = ARG_CONST_MAP_PTR, 104 * .arg2_type = ARG_PTR_TO_MAP_KEY, 105 * 106 * ret_type says that this function returns 'pointer to map elem value or null' 107 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 108 * 2nd argument should be a pointer to stack, which will be used inside 109 * the helper function as a pointer to map element key. 110 * 111 * On the kernel side the helper function looks like: 112 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 113 * { 114 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 115 * void *key = (void *) (unsigned long) r2; 116 * void *value; 117 * 118 * here kernel can access 'key' and 'map' pointers safely, knowing that 119 * [key, key + map->key_size) bytes are valid and were initialized on 120 * the stack of eBPF program. 121 * } 122 * 123 * Corresponding eBPF program may look like: 124 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 125 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 126 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 127 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 128 * here verifier looks at prototype of map_lookup_elem() and sees: 129 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 130 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 131 * 132 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 133 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 134 * and were initialized prior to this call. 135 * If it's ok, then verifier allows this BPF_CALL insn and looks at 136 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 137 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 138 * returns ether pointer to map value or NULL. 139 * 140 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 141 * insn, the register holding that pointer in the true branch changes state to 142 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 143 * branch. See check_cond_jmp_op(). 144 * 145 * After the call R0 is set to return type of the function and registers R1-R5 146 * are set to NOT_INIT to indicate that they are no longer readable. 147 * 148 * The following reference types represent a potential reference to a kernel 149 * resource which, after first being allocated, must be checked and freed by 150 * the BPF program: 151 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 152 * 153 * When the verifier sees a helper call return a reference type, it allocates a 154 * pointer id for the reference and stores it in the current function state. 155 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 156 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 157 * passes through a NULL-check conditional. For the branch wherein the state is 158 * changed to CONST_IMM, the verifier releases the reference. 159 * 160 * For each helper function that allocates a reference, such as 161 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 162 * bpf_sk_release(). When a reference type passes into the release function, 163 * the verifier also releases the reference. If any unchecked or unreleased 164 * reference remains at the end of the program, the verifier rejects it. 165 */ 166 167 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 168 struct bpf_verifier_stack_elem { 169 /* verifer state is 'st' 170 * before processing instruction 'insn_idx' 171 * and after processing instruction 'prev_insn_idx' 172 */ 173 struct bpf_verifier_state st; 174 int insn_idx; 175 int prev_insn_idx; 176 struct bpf_verifier_stack_elem *next; 177 }; 178 179 #define BPF_COMPLEXITY_LIMIT_STACK 1024 180 #define BPF_COMPLEXITY_LIMIT_STATES 64 181 182 #define BPF_MAP_PTR_UNPRIV 1UL 183 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 184 POISON_POINTER_DELTA)) 185 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 186 187 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 188 { 189 return BPF_MAP_PTR(aux->map_state) == BPF_MAP_PTR_POISON; 190 } 191 192 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 193 { 194 return aux->map_state & BPF_MAP_PTR_UNPRIV; 195 } 196 197 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 198 const struct bpf_map *map, bool unpriv) 199 { 200 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 201 unpriv |= bpf_map_ptr_unpriv(aux); 202 aux->map_state = (unsigned long)map | 203 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 204 } 205 206 struct bpf_call_arg_meta { 207 struct bpf_map *map_ptr; 208 bool raw_mode; 209 bool pkt_access; 210 int regno; 211 int access_size; 212 s64 msize_smax_value; 213 u64 msize_umax_value; 214 int ref_obj_id; 215 int func_id; 216 }; 217 218 static DEFINE_MUTEX(bpf_verifier_lock); 219 220 static const struct bpf_line_info * 221 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 222 { 223 const struct bpf_line_info *linfo; 224 const struct bpf_prog *prog; 225 u32 i, nr_linfo; 226 227 prog = env->prog; 228 nr_linfo = prog->aux->nr_linfo; 229 230 if (!nr_linfo || insn_off >= prog->len) 231 return NULL; 232 233 linfo = prog->aux->linfo; 234 for (i = 1; i < nr_linfo; i++) 235 if (insn_off < linfo[i].insn_off) 236 break; 237 238 return &linfo[i - 1]; 239 } 240 241 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, 242 va_list args) 243 { 244 unsigned int n; 245 246 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); 247 248 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, 249 "verifier log line truncated - local buffer too short\n"); 250 251 n = min(log->len_total - log->len_used - 1, n); 252 log->kbuf[n] = '\0'; 253 254 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) 255 log->len_used += n; 256 else 257 log->ubuf = NULL; 258 } 259 260 /* log_level controls verbosity level of eBPF verifier. 261 * bpf_verifier_log_write() is used to dump the verification trace to the log, 262 * so the user can figure out what's wrong with the program 263 */ 264 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 265 const char *fmt, ...) 266 { 267 va_list args; 268 269 if (!bpf_verifier_log_needed(&env->log)) 270 return; 271 272 va_start(args, fmt); 273 bpf_verifier_vlog(&env->log, fmt, args); 274 va_end(args); 275 } 276 EXPORT_SYMBOL_GPL(bpf_verifier_log_write); 277 278 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 279 { 280 struct bpf_verifier_env *env = private_data; 281 va_list args; 282 283 if (!bpf_verifier_log_needed(&env->log)) 284 return; 285 286 va_start(args, fmt); 287 bpf_verifier_vlog(&env->log, fmt, args); 288 va_end(args); 289 } 290 291 static const char *ltrim(const char *s) 292 { 293 while (isspace(*s)) 294 s++; 295 296 return s; 297 } 298 299 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 300 u32 insn_off, 301 const char *prefix_fmt, ...) 302 { 303 const struct bpf_line_info *linfo; 304 305 if (!bpf_verifier_log_needed(&env->log)) 306 return; 307 308 linfo = find_linfo(env, insn_off); 309 if (!linfo || linfo == env->prev_linfo) 310 return; 311 312 if (prefix_fmt) { 313 va_list args; 314 315 va_start(args, prefix_fmt); 316 bpf_verifier_vlog(&env->log, prefix_fmt, args); 317 va_end(args); 318 } 319 320 verbose(env, "%s\n", 321 ltrim(btf_name_by_offset(env->prog->aux->btf, 322 linfo->line_off))); 323 324 env->prev_linfo = linfo; 325 } 326 327 static bool type_is_pkt_pointer(enum bpf_reg_type type) 328 { 329 return type == PTR_TO_PACKET || 330 type == PTR_TO_PACKET_META; 331 } 332 333 static bool type_is_sk_pointer(enum bpf_reg_type type) 334 { 335 return type == PTR_TO_SOCKET || 336 type == PTR_TO_SOCK_COMMON || 337 type == PTR_TO_TCP_SOCK; 338 } 339 340 static bool reg_type_may_be_null(enum bpf_reg_type type) 341 { 342 return type == PTR_TO_MAP_VALUE_OR_NULL || 343 type == PTR_TO_SOCKET_OR_NULL || 344 type == PTR_TO_SOCK_COMMON_OR_NULL || 345 type == PTR_TO_TCP_SOCK_OR_NULL; 346 } 347 348 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 349 { 350 return reg->type == PTR_TO_MAP_VALUE && 351 map_value_has_spin_lock(reg->map_ptr); 352 } 353 354 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type) 355 { 356 return type == PTR_TO_SOCKET || 357 type == PTR_TO_SOCKET_OR_NULL || 358 type == PTR_TO_TCP_SOCK || 359 type == PTR_TO_TCP_SOCK_OR_NULL; 360 } 361 362 static bool arg_type_may_be_refcounted(enum bpf_arg_type type) 363 { 364 return type == ARG_PTR_TO_SOCK_COMMON; 365 } 366 367 /* Determine whether the function releases some resources allocated by another 368 * function call. The first reference type argument will be assumed to be 369 * released by release_reference(). 370 */ 371 static bool is_release_function(enum bpf_func_id func_id) 372 { 373 return func_id == BPF_FUNC_sk_release; 374 } 375 376 static bool is_acquire_function(enum bpf_func_id func_id) 377 { 378 return func_id == BPF_FUNC_sk_lookup_tcp || 379 func_id == BPF_FUNC_sk_lookup_udp || 380 func_id == BPF_FUNC_skc_lookup_tcp; 381 } 382 383 static bool is_ptr_cast_function(enum bpf_func_id func_id) 384 { 385 return func_id == BPF_FUNC_tcp_sock || 386 func_id == BPF_FUNC_sk_fullsock; 387 } 388 389 /* string representation of 'enum bpf_reg_type' */ 390 static const char * const reg_type_str[] = { 391 [NOT_INIT] = "?", 392 [SCALAR_VALUE] = "inv", 393 [PTR_TO_CTX] = "ctx", 394 [CONST_PTR_TO_MAP] = "map_ptr", 395 [PTR_TO_MAP_VALUE] = "map_value", 396 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", 397 [PTR_TO_STACK] = "fp", 398 [PTR_TO_PACKET] = "pkt", 399 [PTR_TO_PACKET_META] = "pkt_meta", 400 [PTR_TO_PACKET_END] = "pkt_end", 401 [PTR_TO_FLOW_KEYS] = "flow_keys", 402 [PTR_TO_SOCKET] = "sock", 403 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null", 404 [PTR_TO_SOCK_COMMON] = "sock_common", 405 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null", 406 [PTR_TO_TCP_SOCK] = "tcp_sock", 407 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null", 408 }; 409 410 static char slot_type_char[] = { 411 [STACK_INVALID] = '?', 412 [STACK_SPILL] = 'r', 413 [STACK_MISC] = 'm', 414 [STACK_ZERO] = '0', 415 }; 416 417 static void print_liveness(struct bpf_verifier_env *env, 418 enum bpf_reg_liveness live) 419 { 420 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 421 verbose(env, "_"); 422 if (live & REG_LIVE_READ) 423 verbose(env, "r"); 424 if (live & REG_LIVE_WRITTEN) 425 verbose(env, "w"); 426 if (live & REG_LIVE_DONE) 427 verbose(env, "D"); 428 } 429 430 static struct bpf_func_state *func(struct bpf_verifier_env *env, 431 const struct bpf_reg_state *reg) 432 { 433 struct bpf_verifier_state *cur = env->cur_state; 434 435 return cur->frame[reg->frameno]; 436 } 437 438 static void print_verifier_state(struct bpf_verifier_env *env, 439 const struct bpf_func_state *state) 440 { 441 const struct bpf_reg_state *reg; 442 enum bpf_reg_type t; 443 int i; 444 445 if (state->frameno) 446 verbose(env, " frame%d:", state->frameno); 447 for (i = 0; i < MAX_BPF_REG; i++) { 448 reg = &state->regs[i]; 449 t = reg->type; 450 if (t == NOT_INIT) 451 continue; 452 verbose(env, " R%d", i); 453 print_liveness(env, reg->live); 454 verbose(env, "=%s", reg_type_str[t]); 455 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 456 tnum_is_const(reg->var_off)) { 457 /* reg->off should be 0 for SCALAR_VALUE */ 458 verbose(env, "%lld", reg->var_off.value + reg->off); 459 if (t == PTR_TO_STACK) 460 verbose(env, ",call_%d", func(env, reg)->callsite); 461 } else { 462 verbose(env, "(id=%d", reg->id); 463 if (reg_type_may_be_refcounted_or_null(t)) 464 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id); 465 if (t != SCALAR_VALUE) 466 verbose(env, ",off=%d", reg->off); 467 if (type_is_pkt_pointer(t)) 468 verbose(env, ",r=%d", reg->range); 469 else if (t == CONST_PTR_TO_MAP || 470 t == PTR_TO_MAP_VALUE || 471 t == PTR_TO_MAP_VALUE_OR_NULL) 472 verbose(env, ",ks=%d,vs=%d", 473 reg->map_ptr->key_size, 474 reg->map_ptr->value_size); 475 if (tnum_is_const(reg->var_off)) { 476 /* Typically an immediate SCALAR_VALUE, but 477 * could be a pointer whose offset is too big 478 * for reg->off 479 */ 480 verbose(env, ",imm=%llx", reg->var_off.value); 481 } else { 482 if (reg->smin_value != reg->umin_value && 483 reg->smin_value != S64_MIN) 484 verbose(env, ",smin_value=%lld", 485 (long long)reg->smin_value); 486 if (reg->smax_value != reg->umax_value && 487 reg->smax_value != S64_MAX) 488 verbose(env, ",smax_value=%lld", 489 (long long)reg->smax_value); 490 if (reg->umin_value != 0) 491 verbose(env, ",umin_value=%llu", 492 (unsigned long long)reg->umin_value); 493 if (reg->umax_value != U64_MAX) 494 verbose(env, ",umax_value=%llu", 495 (unsigned long long)reg->umax_value); 496 if (!tnum_is_unknown(reg->var_off)) { 497 char tn_buf[48]; 498 499 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 500 verbose(env, ",var_off=%s", tn_buf); 501 } 502 } 503 verbose(env, ")"); 504 } 505 } 506 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 507 char types_buf[BPF_REG_SIZE + 1]; 508 bool valid = false; 509 int j; 510 511 for (j = 0; j < BPF_REG_SIZE; j++) { 512 if (state->stack[i].slot_type[j] != STACK_INVALID) 513 valid = true; 514 types_buf[j] = slot_type_char[ 515 state->stack[i].slot_type[j]]; 516 } 517 types_buf[BPF_REG_SIZE] = 0; 518 if (!valid) 519 continue; 520 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 521 print_liveness(env, state->stack[i].spilled_ptr.live); 522 if (state->stack[i].slot_type[0] == STACK_SPILL) 523 verbose(env, "=%s", 524 reg_type_str[state->stack[i].spilled_ptr.type]); 525 else 526 verbose(env, "=%s", types_buf); 527 } 528 if (state->acquired_refs && state->refs[0].id) { 529 verbose(env, " refs=%d", state->refs[0].id); 530 for (i = 1; i < state->acquired_refs; i++) 531 if (state->refs[i].id) 532 verbose(env, ",%d", state->refs[i].id); 533 } 534 verbose(env, "\n"); 535 } 536 537 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \ 538 static int copy_##NAME##_state(struct bpf_func_state *dst, \ 539 const struct bpf_func_state *src) \ 540 { \ 541 if (!src->FIELD) \ 542 return 0; \ 543 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \ 544 /* internal bug, make state invalid to reject the program */ \ 545 memset(dst, 0, sizeof(*dst)); \ 546 return -EFAULT; \ 547 } \ 548 memcpy(dst->FIELD, src->FIELD, \ 549 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \ 550 return 0; \ 551 } 552 /* copy_reference_state() */ 553 COPY_STATE_FN(reference, acquired_refs, refs, 1) 554 /* copy_stack_state() */ 555 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE) 556 #undef COPY_STATE_FN 557 558 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \ 559 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \ 560 bool copy_old) \ 561 { \ 562 u32 old_size = state->COUNT; \ 563 struct bpf_##NAME##_state *new_##FIELD; \ 564 int slot = size / SIZE; \ 565 \ 566 if (size <= old_size || !size) { \ 567 if (copy_old) \ 568 return 0; \ 569 state->COUNT = slot * SIZE; \ 570 if (!size && old_size) { \ 571 kfree(state->FIELD); \ 572 state->FIELD = NULL; \ 573 } \ 574 return 0; \ 575 } \ 576 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \ 577 GFP_KERNEL); \ 578 if (!new_##FIELD) \ 579 return -ENOMEM; \ 580 if (copy_old) { \ 581 if (state->FIELD) \ 582 memcpy(new_##FIELD, state->FIELD, \ 583 sizeof(*new_##FIELD) * (old_size / SIZE)); \ 584 memset(new_##FIELD + old_size / SIZE, 0, \ 585 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \ 586 } \ 587 state->COUNT = slot * SIZE; \ 588 kfree(state->FIELD); \ 589 state->FIELD = new_##FIELD; \ 590 return 0; \ 591 } 592 /* realloc_reference_state() */ 593 REALLOC_STATE_FN(reference, acquired_refs, refs, 1) 594 /* realloc_stack_state() */ 595 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE) 596 #undef REALLOC_STATE_FN 597 598 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to 599 * make it consume minimal amount of memory. check_stack_write() access from 600 * the program calls into realloc_func_state() to grow the stack size. 601 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state 602 * which realloc_stack_state() copies over. It points to previous 603 * bpf_verifier_state which is never reallocated. 604 */ 605 static int realloc_func_state(struct bpf_func_state *state, int stack_size, 606 int refs_size, bool copy_old) 607 { 608 int err = realloc_reference_state(state, refs_size, copy_old); 609 if (err) 610 return err; 611 return realloc_stack_state(state, stack_size, copy_old); 612 } 613 614 /* Acquire a pointer id from the env and update the state->refs to include 615 * this new pointer reference. 616 * On success, returns a valid pointer id to associate with the register 617 * On failure, returns a negative errno. 618 */ 619 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 620 { 621 struct bpf_func_state *state = cur_func(env); 622 int new_ofs = state->acquired_refs; 623 int id, err; 624 625 err = realloc_reference_state(state, state->acquired_refs + 1, true); 626 if (err) 627 return err; 628 id = ++env->id_gen; 629 state->refs[new_ofs].id = id; 630 state->refs[new_ofs].insn_idx = insn_idx; 631 632 return id; 633 } 634 635 /* release function corresponding to acquire_reference_state(). Idempotent. */ 636 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 637 { 638 int i, last_idx; 639 640 last_idx = state->acquired_refs - 1; 641 for (i = 0; i < state->acquired_refs; i++) { 642 if (state->refs[i].id == ptr_id) { 643 if (last_idx && i != last_idx) 644 memcpy(&state->refs[i], &state->refs[last_idx], 645 sizeof(*state->refs)); 646 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 647 state->acquired_refs--; 648 return 0; 649 } 650 } 651 return -EINVAL; 652 } 653 654 static int transfer_reference_state(struct bpf_func_state *dst, 655 struct bpf_func_state *src) 656 { 657 int err = realloc_reference_state(dst, src->acquired_refs, false); 658 if (err) 659 return err; 660 err = copy_reference_state(dst, src); 661 if (err) 662 return err; 663 return 0; 664 } 665 666 static void free_func_state(struct bpf_func_state *state) 667 { 668 if (!state) 669 return; 670 kfree(state->refs); 671 kfree(state->stack); 672 kfree(state); 673 } 674 675 static void free_verifier_state(struct bpf_verifier_state *state, 676 bool free_self) 677 { 678 int i; 679 680 for (i = 0; i <= state->curframe; i++) { 681 free_func_state(state->frame[i]); 682 state->frame[i] = NULL; 683 } 684 if (free_self) 685 kfree(state); 686 } 687 688 /* copy verifier state from src to dst growing dst stack space 689 * when necessary to accommodate larger src stack 690 */ 691 static int copy_func_state(struct bpf_func_state *dst, 692 const struct bpf_func_state *src) 693 { 694 int err; 695 696 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs, 697 false); 698 if (err) 699 return err; 700 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 701 err = copy_reference_state(dst, src); 702 if (err) 703 return err; 704 return copy_stack_state(dst, src); 705 } 706 707 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 708 const struct bpf_verifier_state *src) 709 { 710 struct bpf_func_state *dst; 711 int i, err; 712 713 /* if dst has more stack frames then src frame, free them */ 714 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 715 free_func_state(dst_state->frame[i]); 716 dst_state->frame[i] = NULL; 717 } 718 dst_state->speculative = src->speculative; 719 dst_state->curframe = src->curframe; 720 dst_state->active_spin_lock = src->active_spin_lock; 721 for (i = 0; i <= src->curframe; i++) { 722 dst = dst_state->frame[i]; 723 if (!dst) { 724 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 725 if (!dst) 726 return -ENOMEM; 727 dst_state->frame[i] = dst; 728 } 729 err = copy_func_state(dst, src->frame[i]); 730 if (err) 731 return err; 732 } 733 return 0; 734 } 735 736 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 737 int *insn_idx) 738 { 739 struct bpf_verifier_state *cur = env->cur_state; 740 struct bpf_verifier_stack_elem *elem, *head = env->head; 741 int err; 742 743 if (env->head == NULL) 744 return -ENOENT; 745 746 if (cur) { 747 err = copy_verifier_state(cur, &head->st); 748 if (err) 749 return err; 750 } 751 if (insn_idx) 752 *insn_idx = head->insn_idx; 753 if (prev_insn_idx) 754 *prev_insn_idx = head->prev_insn_idx; 755 elem = head->next; 756 free_verifier_state(&head->st, false); 757 kfree(head); 758 env->head = elem; 759 env->stack_size--; 760 return 0; 761 } 762 763 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 764 int insn_idx, int prev_insn_idx, 765 bool speculative) 766 { 767 struct bpf_verifier_state *cur = env->cur_state; 768 struct bpf_verifier_stack_elem *elem; 769 int err; 770 771 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 772 if (!elem) 773 goto err; 774 775 elem->insn_idx = insn_idx; 776 elem->prev_insn_idx = prev_insn_idx; 777 elem->next = env->head; 778 env->head = elem; 779 env->stack_size++; 780 err = copy_verifier_state(&elem->st, cur); 781 if (err) 782 goto err; 783 elem->st.speculative |= speculative; 784 if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) { 785 verbose(env, "BPF program is too complex\n"); 786 goto err; 787 } 788 return &elem->st; 789 err: 790 free_verifier_state(env->cur_state, true); 791 env->cur_state = NULL; 792 /* pop all elements and return */ 793 while (!pop_stack(env, NULL, NULL)); 794 return NULL; 795 } 796 797 #define CALLER_SAVED_REGS 6 798 static const int caller_saved[CALLER_SAVED_REGS] = { 799 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 800 }; 801 802 static void __mark_reg_not_init(struct bpf_reg_state *reg); 803 804 /* Mark the unknown part of a register (variable offset or scalar value) as 805 * known to have the value @imm. 806 */ 807 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 808 { 809 /* Clear id, off, and union(map_ptr, range) */ 810 memset(((u8 *)reg) + sizeof(reg->type), 0, 811 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 812 reg->var_off = tnum_const(imm); 813 reg->smin_value = (s64)imm; 814 reg->smax_value = (s64)imm; 815 reg->umin_value = imm; 816 reg->umax_value = imm; 817 } 818 819 /* Mark the 'variable offset' part of a register as zero. This should be 820 * used only on registers holding a pointer type. 821 */ 822 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 823 { 824 __mark_reg_known(reg, 0); 825 } 826 827 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 828 { 829 __mark_reg_known(reg, 0); 830 reg->type = SCALAR_VALUE; 831 } 832 833 static void mark_reg_known_zero(struct bpf_verifier_env *env, 834 struct bpf_reg_state *regs, u32 regno) 835 { 836 if (WARN_ON(regno >= MAX_BPF_REG)) { 837 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 838 /* Something bad happened, let's kill all regs */ 839 for (regno = 0; regno < MAX_BPF_REG; regno++) 840 __mark_reg_not_init(regs + regno); 841 return; 842 } 843 __mark_reg_known_zero(regs + regno); 844 } 845 846 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 847 { 848 return type_is_pkt_pointer(reg->type); 849 } 850 851 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 852 { 853 return reg_is_pkt_pointer(reg) || 854 reg->type == PTR_TO_PACKET_END; 855 } 856 857 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 858 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 859 enum bpf_reg_type which) 860 { 861 /* The register can already have a range from prior markings. 862 * This is fine as long as it hasn't been advanced from its 863 * origin. 864 */ 865 return reg->type == which && 866 reg->id == 0 && 867 reg->off == 0 && 868 tnum_equals_const(reg->var_off, 0); 869 } 870 871 /* Attempts to improve min/max values based on var_off information */ 872 static void __update_reg_bounds(struct bpf_reg_state *reg) 873 { 874 /* min signed is max(sign bit) | min(other bits) */ 875 reg->smin_value = max_t(s64, reg->smin_value, 876 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 877 /* max signed is min(sign bit) | max(other bits) */ 878 reg->smax_value = min_t(s64, reg->smax_value, 879 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 880 reg->umin_value = max(reg->umin_value, reg->var_off.value); 881 reg->umax_value = min(reg->umax_value, 882 reg->var_off.value | reg->var_off.mask); 883 } 884 885 /* Uses signed min/max values to inform unsigned, and vice-versa */ 886 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 887 { 888 /* Learn sign from signed bounds. 889 * If we cannot cross the sign boundary, then signed and unsigned bounds 890 * are the same, so combine. This works even in the negative case, e.g. 891 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 892 */ 893 if (reg->smin_value >= 0 || reg->smax_value < 0) { 894 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 895 reg->umin_value); 896 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 897 reg->umax_value); 898 return; 899 } 900 /* Learn sign from unsigned bounds. Signed bounds cross the sign 901 * boundary, so we must be careful. 902 */ 903 if ((s64)reg->umax_value >= 0) { 904 /* Positive. We can't learn anything from the smin, but smax 905 * is positive, hence safe. 906 */ 907 reg->smin_value = reg->umin_value; 908 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 909 reg->umax_value); 910 } else if ((s64)reg->umin_value < 0) { 911 /* Negative. We can't learn anything from the smax, but smin 912 * is negative, hence safe. 913 */ 914 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 915 reg->umin_value); 916 reg->smax_value = reg->umax_value; 917 } 918 } 919 920 /* Attempts to improve var_off based on unsigned min/max information */ 921 static void __reg_bound_offset(struct bpf_reg_state *reg) 922 { 923 reg->var_off = tnum_intersect(reg->var_off, 924 tnum_range(reg->umin_value, 925 reg->umax_value)); 926 } 927 928 /* Reset the min/max bounds of a register */ 929 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 930 { 931 reg->smin_value = S64_MIN; 932 reg->smax_value = S64_MAX; 933 reg->umin_value = 0; 934 reg->umax_value = U64_MAX; 935 } 936 937 /* Mark a register as having a completely unknown (scalar) value. */ 938 static void __mark_reg_unknown(struct bpf_reg_state *reg) 939 { 940 /* 941 * Clear type, id, off, and union(map_ptr, range) and 942 * padding between 'type' and union 943 */ 944 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 945 reg->type = SCALAR_VALUE; 946 reg->var_off = tnum_unknown; 947 reg->frameno = 0; 948 __mark_reg_unbounded(reg); 949 } 950 951 static void mark_reg_unknown(struct bpf_verifier_env *env, 952 struct bpf_reg_state *regs, u32 regno) 953 { 954 if (WARN_ON(regno >= MAX_BPF_REG)) { 955 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 956 /* Something bad happened, let's kill all regs except FP */ 957 for (regno = 0; regno < BPF_REG_FP; regno++) 958 __mark_reg_not_init(regs + regno); 959 return; 960 } 961 __mark_reg_unknown(regs + regno); 962 } 963 964 static void __mark_reg_not_init(struct bpf_reg_state *reg) 965 { 966 __mark_reg_unknown(reg); 967 reg->type = NOT_INIT; 968 } 969 970 static void mark_reg_not_init(struct bpf_verifier_env *env, 971 struct bpf_reg_state *regs, u32 regno) 972 { 973 if (WARN_ON(regno >= MAX_BPF_REG)) { 974 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 975 /* Something bad happened, let's kill all regs except FP */ 976 for (regno = 0; regno < BPF_REG_FP; regno++) 977 __mark_reg_not_init(regs + regno); 978 return; 979 } 980 __mark_reg_not_init(regs + regno); 981 } 982 983 static void init_reg_state(struct bpf_verifier_env *env, 984 struct bpf_func_state *state) 985 { 986 struct bpf_reg_state *regs = state->regs; 987 int i; 988 989 for (i = 0; i < MAX_BPF_REG; i++) { 990 mark_reg_not_init(env, regs, i); 991 regs[i].live = REG_LIVE_NONE; 992 regs[i].parent = NULL; 993 } 994 995 /* frame pointer */ 996 regs[BPF_REG_FP].type = PTR_TO_STACK; 997 mark_reg_known_zero(env, regs, BPF_REG_FP); 998 regs[BPF_REG_FP].frameno = state->frameno; 999 1000 /* 1st arg to a function */ 1001 regs[BPF_REG_1].type = PTR_TO_CTX; 1002 mark_reg_known_zero(env, regs, BPF_REG_1); 1003 } 1004 1005 #define BPF_MAIN_FUNC (-1) 1006 static void init_func_state(struct bpf_verifier_env *env, 1007 struct bpf_func_state *state, 1008 int callsite, int frameno, int subprogno) 1009 { 1010 state->callsite = callsite; 1011 state->frameno = frameno; 1012 state->subprogno = subprogno; 1013 init_reg_state(env, state); 1014 } 1015 1016 enum reg_arg_type { 1017 SRC_OP, /* register is used as source operand */ 1018 DST_OP, /* register is used as destination operand */ 1019 DST_OP_NO_MARK /* same as above, check only, don't mark */ 1020 }; 1021 1022 static int cmp_subprogs(const void *a, const void *b) 1023 { 1024 return ((struct bpf_subprog_info *)a)->start - 1025 ((struct bpf_subprog_info *)b)->start; 1026 } 1027 1028 static int find_subprog(struct bpf_verifier_env *env, int off) 1029 { 1030 struct bpf_subprog_info *p; 1031 1032 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 1033 sizeof(env->subprog_info[0]), cmp_subprogs); 1034 if (!p) 1035 return -ENOENT; 1036 return p - env->subprog_info; 1037 1038 } 1039 1040 static int add_subprog(struct bpf_verifier_env *env, int off) 1041 { 1042 int insn_cnt = env->prog->len; 1043 int ret; 1044 1045 if (off >= insn_cnt || off < 0) { 1046 verbose(env, "call to invalid destination\n"); 1047 return -EINVAL; 1048 } 1049 ret = find_subprog(env, off); 1050 if (ret >= 0) 1051 return 0; 1052 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 1053 verbose(env, "too many subprograms\n"); 1054 return -E2BIG; 1055 } 1056 env->subprog_info[env->subprog_cnt++].start = off; 1057 sort(env->subprog_info, env->subprog_cnt, 1058 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 1059 return 0; 1060 } 1061 1062 static int check_subprogs(struct bpf_verifier_env *env) 1063 { 1064 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0; 1065 struct bpf_subprog_info *subprog = env->subprog_info; 1066 struct bpf_insn *insn = env->prog->insnsi; 1067 int insn_cnt = env->prog->len; 1068 1069 /* Add entry function. */ 1070 ret = add_subprog(env, 0); 1071 if (ret < 0) 1072 return ret; 1073 1074 /* determine subprog starts. The end is one before the next starts */ 1075 for (i = 0; i < insn_cnt; i++) { 1076 if (insn[i].code != (BPF_JMP | BPF_CALL)) 1077 continue; 1078 if (insn[i].src_reg != BPF_PSEUDO_CALL) 1079 continue; 1080 if (!env->allow_ptr_leaks) { 1081 verbose(env, "function calls to other bpf functions are allowed for root only\n"); 1082 return -EPERM; 1083 } 1084 ret = add_subprog(env, i + insn[i].imm + 1); 1085 if (ret < 0) 1086 return ret; 1087 } 1088 1089 /* Add a fake 'exit' subprog which could simplify subprog iteration 1090 * logic. 'subprog_cnt' should not be increased. 1091 */ 1092 subprog[env->subprog_cnt].start = insn_cnt; 1093 1094 if (env->log.level & BPF_LOG_LEVEL2) 1095 for (i = 0; i < env->subprog_cnt; i++) 1096 verbose(env, "func#%d @%d\n", i, subprog[i].start); 1097 1098 /* now check that all jumps are within the same subprog */ 1099 subprog_start = subprog[cur_subprog].start; 1100 subprog_end = subprog[cur_subprog + 1].start; 1101 for (i = 0; i < insn_cnt; i++) { 1102 u8 code = insn[i].code; 1103 1104 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 1105 goto next; 1106 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 1107 goto next; 1108 off = i + insn[i].off + 1; 1109 if (off < subprog_start || off >= subprog_end) { 1110 verbose(env, "jump out of range from insn %d to %d\n", i, off); 1111 return -EINVAL; 1112 } 1113 next: 1114 if (i == subprog_end - 1) { 1115 /* to avoid fall-through from one subprog into another 1116 * the last insn of the subprog should be either exit 1117 * or unconditional jump back 1118 */ 1119 if (code != (BPF_JMP | BPF_EXIT) && 1120 code != (BPF_JMP | BPF_JA)) { 1121 verbose(env, "last insn is not an exit or jmp\n"); 1122 return -EINVAL; 1123 } 1124 subprog_start = subprog_end; 1125 cur_subprog++; 1126 if (cur_subprog < env->subprog_cnt) 1127 subprog_end = subprog[cur_subprog + 1].start; 1128 } 1129 } 1130 return 0; 1131 } 1132 1133 /* Parentage chain of this register (or stack slot) should take care of all 1134 * issues like callee-saved registers, stack slot allocation time, etc. 1135 */ 1136 static int mark_reg_read(struct bpf_verifier_env *env, 1137 const struct bpf_reg_state *state, 1138 struct bpf_reg_state *parent) 1139 { 1140 bool writes = parent == state->parent; /* Observe write marks */ 1141 int cnt = 0; 1142 1143 while (parent) { 1144 /* if read wasn't screened by an earlier write ... */ 1145 if (writes && state->live & REG_LIVE_WRITTEN) 1146 break; 1147 if (parent->live & REG_LIVE_DONE) { 1148 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 1149 reg_type_str[parent->type], 1150 parent->var_off.value, parent->off); 1151 return -EFAULT; 1152 } 1153 if (parent->live & REG_LIVE_READ) 1154 /* The parentage chain never changes and 1155 * this parent was already marked as LIVE_READ. 1156 * There is no need to keep walking the chain again and 1157 * keep re-marking all parents as LIVE_READ. 1158 * This case happens when the same register is read 1159 * multiple times without writes into it in-between. 1160 */ 1161 break; 1162 /* ... then we depend on parent's value */ 1163 parent->live |= REG_LIVE_READ; 1164 state = parent; 1165 parent = state->parent; 1166 writes = true; 1167 cnt++; 1168 } 1169 1170 if (env->longest_mark_read_walk < cnt) 1171 env->longest_mark_read_walk = cnt; 1172 return 0; 1173 } 1174 1175 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 1176 enum reg_arg_type t) 1177 { 1178 struct bpf_verifier_state *vstate = env->cur_state; 1179 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 1180 struct bpf_reg_state *reg, *regs = state->regs; 1181 1182 if (regno >= MAX_BPF_REG) { 1183 verbose(env, "R%d is invalid\n", regno); 1184 return -EINVAL; 1185 } 1186 1187 reg = ®s[regno]; 1188 if (t == SRC_OP) { 1189 /* check whether register used as source operand can be read */ 1190 if (reg->type == NOT_INIT) { 1191 verbose(env, "R%d !read_ok\n", regno); 1192 return -EACCES; 1193 } 1194 /* We don't need to worry about FP liveness because it's read-only */ 1195 if (regno == BPF_REG_FP) 1196 return 0; 1197 1198 return mark_reg_read(env, reg, reg->parent); 1199 } else { 1200 /* check whether register used as dest operand can be written to */ 1201 if (regno == BPF_REG_FP) { 1202 verbose(env, "frame pointer is read only\n"); 1203 return -EACCES; 1204 } 1205 reg->live |= REG_LIVE_WRITTEN; 1206 if (t == DST_OP) 1207 mark_reg_unknown(env, regs, regno); 1208 } 1209 return 0; 1210 } 1211 1212 static bool is_spillable_regtype(enum bpf_reg_type type) 1213 { 1214 switch (type) { 1215 case PTR_TO_MAP_VALUE: 1216 case PTR_TO_MAP_VALUE_OR_NULL: 1217 case PTR_TO_STACK: 1218 case PTR_TO_CTX: 1219 case PTR_TO_PACKET: 1220 case PTR_TO_PACKET_META: 1221 case PTR_TO_PACKET_END: 1222 case PTR_TO_FLOW_KEYS: 1223 case CONST_PTR_TO_MAP: 1224 case PTR_TO_SOCKET: 1225 case PTR_TO_SOCKET_OR_NULL: 1226 case PTR_TO_SOCK_COMMON: 1227 case PTR_TO_SOCK_COMMON_OR_NULL: 1228 case PTR_TO_TCP_SOCK: 1229 case PTR_TO_TCP_SOCK_OR_NULL: 1230 return true; 1231 default: 1232 return false; 1233 } 1234 } 1235 1236 /* Does this register contain a constant zero? */ 1237 static bool register_is_null(struct bpf_reg_state *reg) 1238 { 1239 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 1240 } 1241 1242 /* check_stack_read/write functions track spill/fill of registers, 1243 * stack boundary and alignment are checked in check_mem_access() 1244 */ 1245 static int check_stack_write(struct bpf_verifier_env *env, 1246 struct bpf_func_state *state, /* func where register points to */ 1247 int off, int size, int value_regno, int insn_idx) 1248 { 1249 struct bpf_func_state *cur; /* state of the current function */ 1250 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 1251 enum bpf_reg_type type; 1252 1253 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE), 1254 state->acquired_refs, true); 1255 if (err) 1256 return err; 1257 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 1258 * so it's aligned access and [off, off + size) are within stack limits 1259 */ 1260 if (!env->allow_ptr_leaks && 1261 state->stack[spi].slot_type[0] == STACK_SPILL && 1262 size != BPF_REG_SIZE) { 1263 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 1264 return -EACCES; 1265 } 1266 1267 cur = env->cur_state->frame[env->cur_state->curframe]; 1268 if (value_regno >= 0 && 1269 is_spillable_regtype((type = cur->regs[value_regno].type))) { 1270 1271 /* register containing pointer is being spilled into stack */ 1272 if (size != BPF_REG_SIZE) { 1273 verbose(env, "invalid size of register spill\n"); 1274 return -EACCES; 1275 } 1276 1277 if (state != cur && type == PTR_TO_STACK) { 1278 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 1279 return -EINVAL; 1280 } 1281 1282 /* save register state */ 1283 state->stack[spi].spilled_ptr = cur->regs[value_regno]; 1284 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1285 1286 for (i = 0; i < BPF_REG_SIZE; i++) { 1287 if (state->stack[spi].slot_type[i] == STACK_MISC && 1288 !env->allow_ptr_leaks) { 1289 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off; 1290 int soff = (-spi - 1) * BPF_REG_SIZE; 1291 1292 /* detected reuse of integer stack slot with a pointer 1293 * which means either llvm is reusing stack slot or 1294 * an attacker is trying to exploit CVE-2018-3639 1295 * (speculative store bypass) 1296 * Have to sanitize that slot with preemptive 1297 * store of zero. 1298 */ 1299 if (*poff && *poff != soff) { 1300 /* disallow programs where single insn stores 1301 * into two different stack slots, since verifier 1302 * cannot sanitize them 1303 */ 1304 verbose(env, 1305 "insn %d cannot access two stack slots fp%d and fp%d", 1306 insn_idx, *poff, soff); 1307 return -EINVAL; 1308 } 1309 *poff = soff; 1310 } 1311 state->stack[spi].slot_type[i] = STACK_SPILL; 1312 } 1313 } else { 1314 u8 type = STACK_MISC; 1315 1316 /* regular write of data into stack destroys any spilled ptr */ 1317 state->stack[spi].spilled_ptr.type = NOT_INIT; 1318 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */ 1319 if (state->stack[spi].slot_type[0] == STACK_SPILL) 1320 for (i = 0; i < BPF_REG_SIZE; i++) 1321 state->stack[spi].slot_type[i] = STACK_MISC; 1322 1323 /* only mark the slot as written if all 8 bytes were written 1324 * otherwise read propagation may incorrectly stop too soon 1325 * when stack slots are partially written. 1326 * This heuristic means that read propagation will be 1327 * conservative, since it will add reg_live_read marks 1328 * to stack slots all the way to first state when programs 1329 * writes+reads less than 8 bytes 1330 */ 1331 if (size == BPF_REG_SIZE) 1332 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 1333 1334 /* when we zero initialize stack slots mark them as such */ 1335 if (value_regno >= 0 && 1336 register_is_null(&cur->regs[value_regno])) 1337 type = STACK_ZERO; 1338 1339 /* Mark slots affected by this stack write. */ 1340 for (i = 0; i < size; i++) 1341 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 1342 type; 1343 } 1344 return 0; 1345 } 1346 1347 static int check_stack_read(struct bpf_verifier_env *env, 1348 struct bpf_func_state *reg_state /* func where register points to */, 1349 int off, int size, int value_regno) 1350 { 1351 struct bpf_verifier_state *vstate = env->cur_state; 1352 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 1353 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 1354 u8 *stype; 1355 1356 if (reg_state->allocated_stack <= slot) { 1357 verbose(env, "invalid read from stack off %d+0 size %d\n", 1358 off, size); 1359 return -EACCES; 1360 } 1361 stype = reg_state->stack[spi].slot_type; 1362 1363 if (stype[0] == STACK_SPILL) { 1364 if (size != BPF_REG_SIZE) { 1365 verbose(env, "invalid size of register spill\n"); 1366 return -EACCES; 1367 } 1368 for (i = 1; i < BPF_REG_SIZE; i++) { 1369 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { 1370 verbose(env, "corrupted spill memory\n"); 1371 return -EACCES; 1372 } 1373 } 1374 1375 if (value_regno >= 0) { 1376 /* restore register state from stack */ 1377 state->regs[value_regno] = reg_state->stack[spi].spilled_ptr; 1378 /* mark reg as written since spilled pointer state likely 1379 * has its liveness marks cleared by is_state_visited() 1380 * which resets stack/reg liveness for state transitions 1381 */ 1382 state->regs[value_regno].live |= REG_LIVE_WRITTEN; 1383 } 1384 mark_reg_read(env, ®_state->stack[spi].spilled_ptr, 1385 reg_state->stack[spi].spilled_ptr.parent); 1386 return 0; 1387 } else { 1388 int zeros = 0; 1389 1390 for (i = 0; i < size; i++) { 1391 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_MISC) 1392 continue; 1393 if (stype[(slot - i) % BPF_REG_SIZE] == STACK_ZERO) { 1394 zeros++; 1395 continue; 1396 } 1397 verbose(env, "invalid read from stack off %d+%d size %d\n", 1398 off, i, size); 1399 return -EACCES; 1400 } 1401 mark_reg_read(env, ®_state->stack[spi].spilled_ptr, 1402 reg_state->stack[spi].spilled_ptr.parent); 1403 if (value_regno >= 0) { 1404 if (zeros == size) { 1405 /* any size read into register is zero extended, 1406 * so the whole register == const_zero 1407 */ 1408 __mark_reg_const_zero(&state->regs[value_regno]); 1409 } else { 1410 /* have read misc data from the stack */ 1411 mark_reg_unknown(env, state->regs, value_regno); 1412 } 1413 state->regs[value_regno].live |= REG_LIVE_WRITTEN; 1414 } 1415 return 0; 1416 } 1417 } 1418 1419 static int check_stack_access(struct bpf_verifier_env *env, 1420 const struct bpf_reg_state *reg, 1421 int off, int size) 1422 { 1423 /* Stack accesses must be at a fixed offset, so that we 1424 * can determine what type of data were returned. See 1425 * check_stack_read(). 1426 */ 1427 if (!tnum_is_const(reg->var_off)) { 1428 char tn_buf[48]; 1429 1430 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1431 verbose(env, "variable stack access var_off=%s off=%d size=%d\n", 1432 tn_buf, off, size); 1433 return -EACCES; 1434 } 1435 1436 if (off >= 0 || off < -MAX_BPF_STACK) { 1437 verbose(env, "invalid stack off=%d size=%d\n", off, size); 1438 return -EACCES; 1439 } 1440 1441 return 0; 1442 } 1443 1444 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 1445 int off, int size, enum bpf_access_type type) 1446 { 1447 struct bpf_reg_state *regs = cur_regs(env); 1448 struct bpf_map *map = regs[regno].map_ptr; 1449 u32 cap = bpf_map_flags_to_cap(map); 1450 1451 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 1452 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 1453 map->value_size, off, size); 1454 return -EACCES; 1455 } 1456 1457 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 1458 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 1459 map->value_size, off, size); 1460 return -EACCES; 1461 } 1462 1463 return 0; 1464 } 1465 1466 /* check read/write into map element returned by bpf_map_lookup_elem() */ 1467 static int __check_map_access(struct bpf_verifier_env *env, u32 regno, int off, 1468 int size, bool zero_size_allowed) 1469 { 1470 struct bpf_reg_state *regs = cur_regs(env); 1471 struct bpf_map *map = regs[regno].map_ptr; 1472 1473 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || 1474 off + size > map->value_size) { 1475 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 1476 map->value_size, off, size); 1477 return -EACCES; 1478 } 1479 return 0; 1480 } 1481 1482 /* check read/write into a map element with possible variable offset */ 1483 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 1484 int off, int size, bool zero_size_allowed) 1485 { 1486 struct bpf_verifier_state *vstate = env->cur_state; 1487 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 1488 struct bpf_reg_state *reg = &state->regs[regno]; 1489 int err; 1490 1491 /* We may have adjusted the register to this map value, so we 1492 * need to try adding each of min_value and max_value to off 1493 * to make sure our theoretical access will be safe. 1494 */ 1495 if (env->log.level & BPF_LOG_LEVEL) 1496 print_verifier_state(env, state); 1497 1498 /* The minimum value is only important with signed 1499 * comparisons where we can't assume the floor of a 1500 * value is 0. If we are using signed variables for our 1501 * index'es we need to make sure that whatever we use 1502 * will have a set floor within our range. 1503 */ 1504 if (reg->smin_value < 0 && 1505 (reg->smin_value == S64_MIN || 1506 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 1507 reg->smin_value + off < 0)) { 1508 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 1509 regno); 1510 return -EACCES; 1511 } 1512 err = __check_map_access(env, regno, reg->smin_value + off, size, 1513 zero_size_allowed); 1514 if (err) { 1515 verbose(env, "R%d min value is outside of the array range\n", 1516 regno); 1517 return err; 1518 } 1519 1520 /* If we haven't set a max value then we need to bail since we can't be 1521 * sure we won't do bad things. 1522 * If reg->umax_value + off could overflow, treat that as unbounded too. 1523 */ 1524 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 1525 verbose(env, "R%d unbounded memory access, make sure to bounds check any array access into a map\n", 1526 regno); 1527 return -EACCES; 1528 } 1529 err = __check_map_access(env, regno, reg->umax_value + off, size, 1530 zero_size_allowed); 1531 if (err) 1532 verbose(env, "R%d max value is outside of the array range\n", 1533 regno); 1534 1535 if (map_value_has_spin_lock(reg->map_ptr)) { 1536 u32 lock = reg->map_ptr->spin_lock_off; 1537 1538 /* if any part of struct bpf_spin_lock can be touched by 1539 * load/store reject this program. 1540 * To check that [x1, x2) overlaps with [y1, y2) 1541 * it is sufficient to check x1 < y2 && y1 < x2. 1542 */ 1543 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) && 1544 lock < reg->umax_value + off + size) { 1545 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n"); 1546 return -EACCES; 1547 } 1548 } 1549 return err; 1550 } 1551 1552 #define MAX_PACKET_OFF 0xffff 1553 1554 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 1555 const struct bpf_call_arg_meta *meta, 1556 enum bpf_access_type t) 1557 { 1558 switch (env->prog->type) { 1559 /* Program types only with direct read access go here! */ 1560 case BPF_PROG_TYPE_LWT_IN: 1561 case BPF_PROG_TYPE_LWT_OUT: 1562 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 1563 case BPF_PROG_TYPE_SK_REUSEPORT: 1564 case BPF_PROG_TYPE_FLOW_DISSECTOR: 1565 case BPF_PROG_TYPE_CGROUP_SKB: 1566 if (t == BPF_WRITE) 1567 return false; 1568 /* fallthrough */ 1569 1570 /* Program types with direct read + write access go here! */ 1571 case BPF_PROG_TYPE_SCHED_CLS: 1572 case BPF_PROG_TYPE_SCHED_ACT: 1573 case BPF_PROG_TYPE_XDP: 1574 case BPF_PROG_TYPE_LWT_XMIT: 1575 case BPF_PROG_TYPE_SK_SKB: 1576 case BPF_PROG_TYPE_SK_MSG: 1577 if (meta) 1578 return meta->pkt_access; 1579 1580 env->seen_direct_write = true; 1581 return true; 1582 default: 1583 return false; 1584 } 1585 } 1586 1587 static int __check_packet_access(struct bpf_verifier_env *env, u32 regno, 1588 int off, int size, bool zero_size_allowed) 1589 { 1590 struct bpf_reg_state *regs = cur_regs(env); 1591 struct bpf_reg_state *reg = ®s[regno]; 1592 1593 if (off < 0 || size < 0 || (size == 0 && !zero_size_allowed) || 1594 (u64)off + size > reg->range) { 1595 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 1596 off, size, regno, reg->id, reg->off, reg->range); 1597 return -EACCES; 1598 } 1599 return 0; 1600 } 1601 1602 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 1603 int size, bool zero_size_allowed) 1604 { 1605 struct bpf_reg_state *regs = cur_regs(env); 1606 struct bpf_reg_state *reg = ®s[regno]; 1607 int err; 1608 1609 /* We may have added a variable offset to the packet pointer; but any 1610 * reg->range we have comes after that. We are only checking the fixed 1611 * offset. 1612 */ 1613 1614 /* We don't allow negative numbers, because we aren't tracking enough 1615 * detail to prove they're safe. 1616 */ 1617 if (reg->smin_value < 0) { 1618 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 1619 regno); 1620 return -EACCES; 1621 } 1622 err = __check_packet_access(env, regno, off, size, zero_size_allowed); 1623 if (err) { 1624 verbose(env, "R%d offset is outside of the packet\n", regno); 1625 return err; 1626 } 1627 1628 /* __check_packet_access has made sure "off + size - 1" is within u16. 1629 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 1630 * otherwise find_good_pkt_pointers would have refused to set range info 1631 * that __check_packet_access would have rejected this pkt access. 1632 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 1633 */ 1634 env->prog->aux->max_pkt_offset = 1635 max_t(u32, env->prog->aux->max_pkt_offset, 1636 off + reg->umax_value + size - 1); 1637 1638 return err; 1639 } 1640 1641 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 1642 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 1643 enum bpf_access_type t, enum bpf_reg_type *reg_type) 1644 { 1645 struct bpf_insn_access_aux info = { 1646 .reg_type = *reg_type, 1647 }; 1648 1649 if (env->ops->is_valid_access && 1650 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 1651 /* A non zero info.ctx_field_size indicates that this field is a 1652 * candidate for later verifier transformation to load the whole 1653 * field and then apply a mask when accessed with a narrower 1654 * access than actual ctx access size. A zero info.ctx_field_size 1655 * will only allow for whole field access and rejects any other 1656 * type of narrower access. 1657 */ 1658 *reg_type = info.reg_type; 1659 1660 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 1661 /* remember the offset of last byte accessed in ctx */ 1662 if (env->prog->aux->max_ctx_offset < off + size) 1663 env->prog->aux->max_ctx_offset = off + size; 1664 return 0; 1665 } 1666 1667 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 1668 return -EACCES; 1669 } 1670 1671 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 1672 int size) 1673 { 1674 if (size < 0 || off < 0 || 1675 (u64)off + size > sizeof(struct bpf_flow_keys)) { 1676 verbose(env, "invalid access to flow keys off=%d size=%d\n", 1677 off, size); 1678 return -EACCES; 1679 } 1680 return 0; 1681 } 1682 1683 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 1684 u32 regno, int off, int size, 1685 enum bpf_access_type t) 1686 { 1687 struct bpf_reg_state *regs = cur_regs(env); 1688 struct bpf_reg_state *reg = ®s[regno]; 1689 struct bpf_insn_access_aux info = {}; 1690 bool valid; 1691 1692 if (reg->smin_value < 0) { 1693 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 1694 regno); 1695 return -EACCES; 1696 } 1697 1698 switch (reg->type) { 1699 case PTR_TO_SOCK_COMMON: 1700 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 1701 break; 1702 case PTR_TO_SOCKET: 1703 valid = bpf_sock_is_valid_access(off, size, t, &info); 1704 break; 1705 case PTR_TO_TCP_SOCK: 1706 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 1707 break; 1708 default: 1709 valid = false; 1710 } 1711 1712 1713 if (valid) { 1714 env->insn_aux_data[insn_idx].ctx_field_size = 1715 info.ctx_field_size; 1716 return 0; 1717 } 1718 1719 verbose(env, "R%d invalid %s access off=%d size=%d\n", 1720 regno, reg_type_str[reg->type], off, size); 1721 1722 return -EACCES; 1723 } 1724 1725 static bool __is_pointer_value(bool allow_ptr_leaks, 1726 const struct bpf_reg_state *reg) 1727 { 1728 if (allow_ptr_leaks) 1729 return false; 1730 1731 return reg->type != SCALAR_VALUE; 1732 } 1733 1734 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 1735 { 1736 return cur_regs(env) + regno; 1737 } 1738 1739 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 1740 { 1741 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 1742 } 1743 1744 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 1745 { 1746 const struct bpf_reg_state *reg = reg_state(env, regno); 1747 1748 return reg->type == PTR_TO_CTX; 1749 } 1750 1751 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 1752 { 1753 const struct bpf_reg_state *reg = reg_state(env, regno); 1754 1755 return type_is_sk_pointer(reg->type); 1756 } 1757 1758 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 1759 { 1760 const struct bpf_reg_state *reg = reg_state(env, regno); 1761 1762 return type_is_pkt_pointer(reg->type); 1763 } 1764 1765 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 1766 { 1767 const struct bpf_reg_state *reg = reg_state(env, regno); 1768 1769 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 1770 return reg->type == PTR_TO_FLOW_KEYS; 1771 } 1772 1773 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 1774 const struct bpf_reg_state *reg, 1775 int off, int size, bool strict) 1776 { 1777 struct tnum reg_off; 1778 int ip_align; 1779 1780 /* Byte size accesses are always allowed. */ 1781 if (!strict || size == 1) 1782 return 0; 1783 1784 /* For platforms that do not have a Kconfig enabling 1785 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 1786 * NET_IP_ALIGN is universally set to '2'. And on platforms 1787 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 1788 * to this code only in strict mode where we want to emulate 1789 * the NET_IP_ALIGN==2 checking. Therefore use an 1790 * unconditional IP align value of '2'. 1791 */ 1792 ip_align = 2; 1793 1794 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 1795 if (!tnum_is_aligned(reg_off, size)) { 1796 char tn_buf[48]; 1797 1798 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1799 verbose(env, 1800 "misaligned packet access off %d+%s+%d+%d size %d\n", 1801 ip_align, tn_buf, reg->off, off, size); 1802 return -EACCES; 1803 } 1804 1805 return 0; 1806 } 1807 1808 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 1809 const struct bpf_reg_state *reg, 1810 const char *pointer_desc, 1811 int off, int size, bool strict) 1812 { 1813 struct tnum reg_off; 1814 1815 /* Byte size accesses are always allowed. */ 1816 if (!strict || size == 1) 1817 return 0; 1818 1819 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 1820 if (!tnum_is_aligned(reg_off, size)) { 1821 char tn_buf[48]; 1822 1823 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1824 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 1825 pointer_desc, tn_buf, reg->off, off, size); 1826 return -EACCES; 1827 } 1828 1829 return 0; 1830 } 1831 1832 static int check_ptr_alignment(struct bpf_verifier_env *env, 1833 const struct bpf_reg_state *reg, int off, 1834 int size, bool strict_alignment_once) 1835 { 1836 bool strict = env->strict_alignment || strict_alignment_once; 1837 const char *pointer_desc = ""; 1838 1839 switch (reg->type) { 1840 case PTR_TO_PACKET: 1841 case PTR_TO_PACKET_META: 1842 /* Special case, because of NET_IP_ALIGN. Given metadata sits 1843 * right in front, treat it the very same way. 1844 */ 1845 return check_pkt_ptr_alignment(env, reg, off, size, strict); 1846 case PTR_TO_FLOW_KEYS: 1847 pointer_desc = "flow keys "; 1848 break; 1849 case PTR_TO_MAP_VALUE: 1850 pointer_desc = "value "; 1851 break; 1852 case PTR_TO_CTX: 1853 pointer_desc = "context "; 1854 break; 1855 case PTR_TO_STACK: 1856 pointer_desc = "stack "; 1857 /* The stack spill tracking logic in check_stack_write() 1858 * and check_stack_read() relies on stack accesses being 1859 * aligned. 1860 */ 1861 strict = true; 1862 break; 1863 case PTR_TO_SOCKET: 1864 pointer_desc = "sock "; 1865 break; 1866 case PTR_TO_SOCK_COMMON: 1867 pointer_desc = "sock_common "; 1868 break; 1869 case PTR_TO_TCP_SOCK: 1870 pointer_desc = "tcp_sock "; 1871 break; 1872 default: 1873 break; 1874 } 1875 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 1876 strict); 1877 } 1878 1879 static int update_stack_depth(struct bpf_verifier_env *env, 1880 const struct bpf_func_state *func, 1881 int off) 1882 { 1883 u16 stack = env->subprog_info[func->subprogno].stack_depth; 1884 1885 if (stack >= -off) 1886 return 0; 1887 1888 /* update known max for given subprogram */ 1889 env->subprog_info[func->subprogno].stack_depth = -off; 1890 return 0; 1891 } 1892 1893 /* starting from main bpf function walk all instructions of the function 1894 * and recursively walk all callees that given function can call. 1895 * Ignore jump and exit insns. 1896 * Since recursion is prevented by check_cfg() this algorithm 1897 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 1898 */ 1899 static int check_max_stack_depth(struct bpf_verifier_env *env) 1900 { 1901 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 1902 struct bpf_subprog_info *subprog = env->subprog_info; 1903 struct bpf_insn *insn = env->prog->insnsi; 1904 int ret_insn[MAX_CALL_FRAMES]; 1905 int ret_prog[MAX_CALL_FRAMES]; 1906 1907 process_func: 1908 /* round up to 32-bytes, since this is granularity 1909 * of interpreter stack size 1910 */ 1911 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 1912 if (depth > MAX_BPF_STACK) { 1913 verbose(env, "combined stack size of %d calls is %d. Too large\n", 1914 frame + 1, depth); 1915 return -EACCES; 1916 } 1917 continue_func: 1918 subprog_end = subprog[idx + 1].start; 1919 for (; i < subprog_end; i++) { 1920 if (insn[i].code != (BPF_JMP | BPF_CALL)) 1921 continue; 1922 if (insn[i].src_reg != BPF_PSEUDO_CALL) 1923 continue; 1924 /* remember insn and function to return to */ 1925 ret_insn[frame] = i + 1; 1926 ret_prog[frame] = idx; 1927 1928 /* find the callee */ 1929 i = i + insn[i].imm + 1; 1930 idx = find_subprog(env, i); 1931 if (idx < 0) { 1932 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 1933 i); 1934 return -EFAULT; 1935 } 1936 frame++; 1937 if (frame >= MAX_CALL_FRAMES) { 1938 verbose(env, "the call stack of %d frames is too deep !\n", 1939 frame); 1940 return -E2BIG; 1941 } 1942 goto process_func; 1943 } 1944 /* end of for() loop means the last insn of the 'subprog' 1945 * was reached. Doesn't matter whether it was JA or EXIT 1946 */ 1947 if (frame == 0) 1948 return 0; 1949 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 1950 frame--; 1951 i = ret_insn[frame]; 1952 idx = ret_prog[frame]; 1953 goto continue_func; 1954 } 1955 1956 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 1957 static int get_callee_stack_depth(struct bpf_verifier_env *env, 1958 const struct bpf_insn *insn, int idx) 1959 { 1960 int start = idx + insn->imm + 1, subprog; 1961 1962 subprog = find_subprog(env, start); 1963 if (subprog < 0) { 1964 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 1965 start); 1966 return -EFAULT; 1967 } 1968 return env->subprog_info[subprog].stack_depth; 1969 } 1970 #endif 1971 1972 static int check_ctx_reg(struct bpf_verifier_env *env, 1973 const struct bpf_reg_state *reg, int regno) 1974 { 1975 /* Access to ctx or passing it to a helper is only allowed in 1976 * its original, unmodified form. 1977 */ 1978 1979 if (reg->off) { 1980 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n", 1981 regno, reg->off); 1982 return -EACCES; 1983 } 1984 1985 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 1986 char tn_buf[48]; 1987 1988 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 1989 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf); 1990 return -EACCES; 1991 } 1992 1993 return 0; 1994 } 1995 1996 /* truncate register to smaller size (in bytes) 1997 * must be called with size < BPF_REG_SIZE 1998 */ 1999 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 2000 { 2001 u64 mask; 2002 2003 /* clear high bits in bit representation */ 2004 reg->var_off = tnum_cast(reg->var_off, size); 2005 2006 /* fix arithmetic bounds */ 2007 mask = ((u64)1 << (size * 8)) - 1; 2008 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 2009 reg->umin_value &= mask; 2010 reg->umax_value &= mask; 2011 } else { 2012 reg->umin_value = 0; 2013 reg->umax_value = mask; 2014 } 2015 reg->smin_value = reg->umin_value; 2016 reg->smax_value = reg->umax_value; 2017 } 2018 2019 /* check whether memory at (regno + off) is accessible for t = (read | write) 2020 * if t==write, value_regno is a register which value is stored into memory 2021 * if t==read, value_regno is a register which will receive the value from memory 2022 * if t==write && value_regno==-1, some unknown value is stored into memory 2023 * if t==read && value_regno==-1, don't care what we read from memory 2024 */ 2025 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 2026 int off, int bpf_size, enum bpf_access_type t, 2027 int value_regno, bool strict_alignment_once) 2028 { 2029 struct bpf_reg_state *regs = cur_regs(env); 2030 struct bpf_reg_state *reg = regs + regno; 2031 struct bpf_func_state *state; 2032 int size, err = 0; 2033 2034 size = bpf_size_to_bytes(bpf_size); 2035 if (size < 0) 2036 return size; 2037 2038 /* alignment checks will add in reg->off themselves */ 2039 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 2040 if (err) 2041 return err; 2042 2043 /* for access checks, reg->off is just part of off */ 2044 off += reg->off; 2045 2046 if (reg->type == PTR_TO_MAP_VALUE) { 2047 if (t == BPF_WRITE && value_regno >= 0 && 2048 is_pointer_value(env, value_regno)) { 2049 verbose(env, "R%d leaks addr into map\n", value_regno); 2050 return -EACCES; 2051 } 2052 err = check_map_access_type(env, regno, off, size, t); 2053 if (err) 2054 return err; 2055 err = check_map_access(env, regno, off, size, false); 2056 if (!err && t == BPF_READ && value_regno >= 0) 2057 mark_reg_unknown(env, regs, value_regno); 2058 2059 } else if (reg->type == PTR_TO_CTX) { 2060 enum bpf_reg_type reg_type = SCALAR_VALUE; 2061 2062 if (t == BPF_WRITE && value_regno >= 0 && 2063 is_pointer_value(env, value_regno)) { 2064 verbose(env, "R%d leaks addr into ctx\n", value_regno); 2065 return -EACCES; 2066 } 2067 2068 err = check_ctx_reg(env, reg, regno); 2069 if (err < 0) 2070 return err; 2071 2072 err = check_ctx_access(env, insn_idx, off, size, t, ®_type); 2073 if (!err && t == BPF_READ && value_regno >= 0) { 2074 /* ctx access returns either a scalar, or a 2075 * PTR_TO_PACKET[_META,_END]. In the latter 2076 * case, we know the offset is zero. 2077 */ 2078 if (reg_type == SCALAR_VALUE) { 2079 mark_reg_unknown(env, regs, value_regno); 2080 } else { 2081 mark_reg_known_zero(env, regs, 2082 value_regno); 2083 if (reg_type_may_be_null(reg_type)) 2084 regs[value_regno].id = ++env->id_gen; 2085 } 2086 regs[value_regno].type = reg_type; 2087 } 2088 2089 } else if (reg->type == PTR_TO_STACK) { 2090 off += reg->var_off.value; 2091 err = check_stack_access(env, reg, off, size); 2092 if (err) 2093 return err; 2094 2095 state = func(env, reg); 2096 err = update_stack_depth(env, state, off); 2097 if (err) 2098 return err; 2099 2100 if (t == BPF_WRITE) 2101 err = check_stack_write(env, state, off, size, 2102 value_regno, insn_idx); 2103 else 2104 err = check_stack_read(env, state, off, size, 2105 value_regno); 2106 } else if (reg_is_pkt_pointer(reg)) { 2107 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 2108 verbose(env, "cannot write into packet\n"); 2109 return -EACCES; 2110 } 2111 if (t == BPF_WRITE && value_regno >= 0 && 2112 is_pointer_value(env, value_regno)) { 2113 verbose(env, "R%d leaks addr into packet\n", 2114 value_regno); 2115 return -EACCES; 2116 } 2117 err = check_packet_access(env, regno, off, size, false); 2118 if (!err && t == BPF_READ && value_regno >= 0) 2119 mark_reg_unknown(env, regs, value_regno); 2120 } else if (reg->type == PTR_TO_FLOW_KEYS) { 2121 if (t == BPF_WRITE && value_regno >= 0 && 2122 is_pointer_value(env, value_regno)) { 2123 verbose(env, "R%d leaks addr into flow keys\n", 2124 value_regno); 2125 return -EACCES; 2126 } 2127 2128 err = check_flow_keys_access(env, off, size); 2129 if (!err && t == BPF_READ && value_regno >= 0) 2130 mark_reg_unknown(env, regs, value_regno); 2131 } else if (type_is_sk_pointer(reg->type)) { 2132 if (t == BPF_WRITE) { 2133 verbose(env, "R%d cannot write into %s\n", 2134 regno, reg_type_str[reg->type]); 2135 return -EACCES; 2136 } 2137 err = check_sock_access(env, insn_idx, regno, off, size, t); 2138 if (!err && value_regno >= 0) 2139 mark_reg_unknown(env, regs, value_regno); 2140 } else { 2141 verbose(env, "R%d invalid mem access '%s'\n", regno, 2142 reg_type_str[reg->type]); 2143 return -EACCES; 2144 } 2145 2146 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 2147 regs[value_regno].type == SCALAR_VALUE) { 2148 /* b/h/w load zero-extends, mark upper bits as known 0 */ 2149 coerce_reg_to_size(®s[value_regno], size); 2150 } 2151 return err; 2152 } 2153 2154 static int check_xadd(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 2155 { 2156 int err; 2157 2158 if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) || 2159 insn->imm != 0) { 2160 verbose(env, "BPF_XADD uses reserved fields\n"); 2161 return -EINVAL; 2162 } 2163 2164 /* check src1 operand */ 2165 err = check_reg_arg(env, insn->src_reg, SRC_OP); 2166 if (err) 2167 return err; 2168 2169 /* check src2 operand */ 2170 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 2171 if (err) 2172 return err; 2173 2174 if (is_pointer_value(env, insn->src_reg)) { 2175 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 2176 return -EACCES; 2177 } 2178 2179 if (is_ctx_reg(env, insn->dst_reg) || 2180 is_pkt_reg(env, insn->dst_reg) || 2181 is_flow_key_reg(env, insn->dst_reg) || 2182 is_sk_reg(env, insn->dst_reg)) { 2183 verbose(env, "BPF_XADD stores into R%d %s is not allowed\n", 2184 insn->dst_reg, 2185 reg_type_str[reg_state(env, insn->dst_reg)->type]); 2186 return -EACCES; 2187 } 2188 2189 /* check whether atomic_add can read the memory */ 2190 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 2191 BPF_SIZE(insn->code), BPF_READ, -1, true); 2192 if (err) 2193 return err; 2194 2195 /* check whether atomic_add can write into the same memory */ 2196 return check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 2197 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 2198 } 2199 2200 static int __check_stack_boundary(struct bpf_verifier_env *env, u32 regno, 2201 int off, int access_size, 2202 bool zero_size_allowed) 2203 { 2204 struct bpf_reg_state *reg = reg_state(env, regno); 2205 2206 if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || 2207 access_size < 0 || (access_size == 0 && !zero_size_allowed)) { 2208 if (tnum_is_const(reg->var_off)) { 2209 verbose(env, "invalid stack type R%d off=%d access_size=%d\n", 2210 regno, off, access_size); 2211 } else { 2212 char tn_buf[48]; 2213 2214 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2215 verbose(env, "invalid stack type R%d var_off=%s access_size=%d\n", 2216 regno, tn_buf, access_size); 2217 } 2218 return -EACCES; 2219 } 2220 return 0; 2221 } 2222 2223 /* when register 'regno' is passed into function that will read 'access_size' 2224 * bytes from that pointer, make sure that it's within stack boundary 2225 * and all elements of stack are initialized. 2226 * Unlike most pointer bounds-checking functions, this one doesn't take an 2227 * 'off' argument, so it has to add in reg->off itself. 2228 */ 2229 static int check_stack_boundary(struct bpf_verifier_env *env, int regno, 2230 int access_size, bool zero_size_allowed, 2231 struct bpf_call_arg_meta *meta) 2232 { 2233 struct bpf_reg_state *reg = reg_state(env, regno); 2234 struct bpf_func_state *state = func(env, reg); 2235 int err, min_off, max_off, i, slot, spi; 2236 2237 if (reg->type != PTR_TO_STACK) { 2238 /* Allow zero-byte read from NULL, regardless of pointer type */ 2239 if (zero_size_allowed && access_size == 0 && 2240 register_is_null(reg)) 2241 return 0; 2242 2243 verbose(env, "R%d type=%s expected=%s\n", regno, 2244 reg_type_str[reg->type], 2245 reg_type_str[PTR_TO_STACK]); 2246 return -EACCES; 2247 } 2248 2249 if (tnum_is_const(reg->var_off)) { 2250 min_off = max_off = reg->var_off.value + reg->off; 2251 err = __check_stack_boundary(env, regno, min_off, access_size, 2252 zero_size_allowed); 2253 if (err) 2254 return err; 2255 } else { 2256 /* Variable offset is prohibited for unprivileged mode for 2257 * simplicity since it requires corresponding support in 2258 * Spectre masking for stack ALU. 2259 * See also retrieve_ptr_limit(). 2260 */ 2261 if (!env->allow_ptr_leaks) { 2262 char tn_buf[48]; 2263 2264 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2265 verbose(env, "R%d indirect variable offset stack access prohibited for !root, var_off=%s\n", 2266 regno, tn_buf); 2267 return -EACCES; 2268 } 2269 /* Only initialized buffer on stack is allowed to be accessed 2270 * with variable offset. With uninitialized buffer it's hard to 2271 * guarantee that whole memory is marked as initialized on 2272 * helper return since specific bounds are unknown what may 2273 * cause uninitialized stack leaking. 2274 */ 2275 if (meta && meta->raw_mode) 2276 meta = NULL; 2277 2278 if (reg->smax_value >= BPF_MAX_VAR_OFF || 2279 reg->smax_value <= -BPF_MAX_VAR_OFF) { 2280 verbose(env, "R%d unbounded indirect variable offset stack access\n", 2281 regno); 2282 return -EACCES; 2283 } 2284 min_off = reg->smin_value + reg->off; 2285 max_off = reg->smax_value + reg->off; 2286 err = __check_stack_boundary(env, regno, min_off, access_size, 2287 zero_size_allowed); 2288 if (err) { 2289 verbose(env, "R%d min value is outside of stack bound\n", 2290 regno); 2291 return err; 2292 } 2293 err = __check_stack_boundary(env, regno, max_off, access_size, 2294 zero_size_allowed); 2295 if (err) { 2296 verbose(env, "R%d max value is outside of stack bound\n", 2297 regno); 2298 return err; 2299 } 2300 } 2301 2302 if (meta && meta->raw_mode) { 2303 meta->access_size = access_size; 2304 meta->regno = regno; 2305 return 0; 2306 } 2307 2308 for (i = min_off; i < max_off + access_size; i++) { 2309 u8 *stype; 2310 2311 slot = -i - 1; 2312 spi = slot / BPF_REG_SIZE; 2313 if (state->allocated_stack <= slot) 2314 goto err; 2315 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 2316 if (*stype == STACK_MISC) 2317 goto mark; 2318 if (*stype == STACK_ZERO) { 2319 /* helper can write anything into the stack */ 2320 *stype = STACK_MISC; 2321 goto mark; 2322 } 2323 err: 2324 if (tnum_is_const(reg->var_off)) { 2325 verbose(env, "invalid indirect read from stack off %d+%d size %d\n", 2326 min_off, i - min_off, access_size); 2327 } else { 2328 char tn_buf[48]; 2329 2330 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2331 verbose(env, "invalid indirect read from stack var_off %s+%d size %d\n", 2332 tn_buf, i - min_off, access_size); 2333 } 2334 return -EACCES; 2335 mark: 2336 /* reading any byte out of 8-byte 'spill_slot' will cause 2337 * the whole slot to be marked as 'read' 2338 */ 2339 mark_reg_read(env, &state->stack[spi].spilled_ptr, 2340 state->stack[spi].spilled_ptr.parent); 2341 } 2342 return update_stack_depth(env, state, min_off); 2343 } 2344 2345 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 2346 int access_size, bool zero_size_allowed, 2347 struct bpf_call_arg_meta *meta) 2348 { 2349 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 2350 2351 switch (reg->type) { 2352 case PTR_TO_PACKET: 2353 case PTR_TO_PACKET_META: 2354 return check_packet_access(env, regno, reg->off, access_size, 2355 zero_size_allowed); 2356 case PTR_TO_MAP_VALUE: 2357 if (check_map_access_type(env, regno, reg->off, access_size, 2358 meta && meta->raw_mode ? BPF_WRITE : 2359 BPF_READ)) 2360 return -EACCES; 2361 return check_map_access(env, regno, reg->off, access_size, 2362 zero_size_allowed); 2363 default: /* scalar_value|ptr_to_stack or invalid ptr */ 2364 return check_stack_boundary(env, regno, access_size, 2365 zero_size_allowed, meta); 2366 } 2367 } 2368 2369 /* Implementation details: 2370 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL 2371 * Two bpf_map_lookups (even with the same key) will have different reg->id. 2372 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after 2373 * value_or_null->value transition, since the verifier only cares about 2374 * the range of access to valid map value pointer and doesn't care about actual 2375 * address of the map element. 2376 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 2377 * reg->id > 0 after value_or_null->value transition. By doing so 2378 * two bpf_map_lookups will be considered two different pointers that 2379 * point to different bpf_spin_locks. 2380 * The verifier allows taking only one bpf_spin_lock at a time to avoid 2381 * dead-locks. 2382 * Since only one bpf_spin_lock is allowed the checks are simpler than 2383 * reg_is_refcounted() logic. The verifier needs to remember only 2384 * one spin_lock instead of array of acquired_refs. 2385 * cur_state->active_spin_lock remembers which map value element got locked 2386 * and clears it after bpf_spin_unlock. 2387 */ 2388 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 2389 bool is_lock) 2390 { 2391 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 2392 struct bpf_verifier_state *cur = env->cur_state; 2393 bool is_const = tnum_is_const(reg->var_off); 2394 struct bpf_map *map = reg->map_ptr; 2395 u64 val = reg->var_off.value; 2396 2397 if (reg->type != PTR_TO_MAP_VALUE) { 2398 verbose(env, "R%d is not a pointer to map_value\n", regno); 2399 return -EINVAL; 2400 } 2401 if (!is_const) { 2402 verbose(env, 2403 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 2404 regno); 2405 return -EINVAL; 2406 } 2407 if (!map->btf) { 2408 verbose(env, 2409 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 2410 map->name); 2411 return -EINVAL; 2412 } 2413 if (!map_value_has_spin_lock(map)) { 2414 if (map->spin_lock_off == -E2BIG) 2415 verbose(env, 2416 "map '%s' has more than one 'struct bpf_spin_lock'\n", 2417 map->name); 2418 else if (map->spin_lock_off == -ENOENT) 2419 verbose(env, 2420 "map '%s' doesn't have 'struct bpf_spin_lock'\n", 2421 map->name); 2422 else 2423 verbose(env, 2424 "map '%s' is not a struct type or bpf_spin_lock is mangled\n", 2425 map->name); 2426 return -EINVAL; 2427 } 2428 if (map->spin_lock_off != val + reg->off) { 2429 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n", 2430 val + reg->off); 2431 return -EINVAL; 2432 } 2433 if (is_lock) { 2434 if (cur->active_spin_lock) { 2435 verbose(env, 2436 "Locking two bpf_spin_locks are not allowed\n"); 2437 return -EINVAL; 2438 } 2439 cur->active_spin_lock = reg->id; 2440 } else { 2441 if (!cur->active_spin_lock) { 2442 verbose(env, "bpf_spin_unlock without taking a lock\n"); 2443 return -EINVAL; 2444 } 2445 if (cur->active_spin_lock != reg->id) { 2446 verbose(env, "bpf_spin_unlock of different lock\n"); 2447 return -EINVAL; 2448 } 2449 cur->active_spin_lock = 0; 2450 } 2451 return 0; 2452 } 2453 2454 static bool arg_type_is_mem_ptr(enum bpf_arg_type type) 2455 { 2456 return type == ARG_PTR_TO_MEM || 2457 type == ARG_PTR_TO_MEM_OR_NULL || 2458 type == ARG_PTR_TO_UNINIT_MEM; 2459 } 2460 2461 static bool arg_type_is_mem_size(enum bpf_arg_type type) 2462 { 2463 return type == ARG_CONST_SIZE || 2464 type == ARG_CONST_SIZE_OR_ZERO; 2465 } 2466 2467 static bool arg_type_is_int_ptr(enum bpf_arg_type type) 2468 { 2469 return type == ARG_PTR_TO_INT || 2470 type == ARG_PTR_TO_LONG; 2471 } 2472 2473 static int int_ptr_type_to_size(enum bpf_arg_type type) 2474 { 2475 if (type == ARG_PTR_TO_INT) 2476 return sizeof(u32); 2477 else if (type == ARG_PTR_TO_LONG) 2478 return sizeof(u64); 2479 2480 return -EINVAL; 2481 } 2482 2483 static int check_func_arg(struct bpf_verifier_env *env, u32 regno, 2484 enum bpf_arg_type arg_type, 2485 struct bpf_call_arg_meta *meta) 2486 { 2487 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 2488 enum bpf_reg_type expected_type, type = reg->type; 2489 int err = 0; 2490 2491 if (arg_type == ARG_DONTCARE) 2492 return 0; 2493 2494 err = check_reg_arg(env, regno, SRC_OP); 2495 if (err) 2496 return err; 2497 2498 if (arg_type == ARG_ANYTHING) { 2499 if (is_pointer_value(env, regno)) { 2500 verbose(env, "R%d leaks addr into helper function\n", 2501 regno); 2502 return -EACCES; 2503 } 2504 return 0; 2505 } 2506 2507 if (type_is_pkt_pointer(type) && 2508 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 2509 verbose(env, "helper access to the packet is not allowed\n"); 2510 return -EACCES; 2511 } 2512 2513 if (arg_type == ARG_PTR_TO_MAP_KEY || 2514 arg_type == ARG_PTR_TO_MAP_VALUE || 2515 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) { 2516 expected_type = PTR_TO_STACK; 2517 if (!type_is_pkt_pointer(type) && type != PTR_TO_MAP_VALUE && 2518 type != expected_type) 2519 goto err_type; 2520 } else if (arg_type == ARG_CONST_SIZE || 2521 arg_type == ARG_CONST_SIZE_OR_ZERO) { 2522 expected_type = SCALAR_VALUE; 2523 if (type != expected_type) 2524 goto err_type; 2525 } else if (arg_type == ARG_CONST_MAP_PTR) { 2526 expected_type = CONST_PTR_TO_MAP; 2527 if (type != expected_type) 2528 goto err_type; 2529 } else if (arg_type == ARG_PTR_TO_CTX) { 2530 expected_type = PTR_TO_CTX; 2531 if (type != expected_type) 2532 goto err_type; 2533 err = check_ctx_reg(env, reg, regno); 2534 if (err < 0) 2535 return err; 2536 } else if (arg_type == ARG_PTR_TO_SOCK_COMMON) { 2537 expected_type = PTR_TO_SOCK_COMMON; 2538 /* Any sk pointer can be ARG_PTR_TO_SOCK_COMMON */ 2539 if (!type_is_sk_pointer(type)) 2540 goto err_type; 2541 if (reg->ref_obj_id) { 2542 if (meta->ref_obj_id) { 2543 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 2544 regno, reg->ref_obj_id, 2545 meta->ref_obj_id); 2546 return -EFAULT; 2547 } 2548 meta->ref_obj_id = reg->ref_obj_id; 2549 } 2550 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) { 2551 if (meta->func_id == BPF_FUNC_spin_lock) { 2552 if (process_spin_lock(env, regno, true)) 2553 return -EACCES; 2554 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 2555 if (process_spin_lock(env, regno, false)) 2556 return -EACCES; 2557 } else { 2558 verbose(env, "verifier internal error\n"); 2559 return -EFAULT; 2560 } 2561 } else if (arg_type_is_mem_ptr(arg_type)) { 2562 expected_type = PTR_TO_STACK; 2563 /* One exception here. In case function allows for NULL to be 2564 * passed in as argument, it's a SCALAR_VALUE type. Final test 2565 * happens during stack boundary checking. 2566 */ 2567 if (register_is_null(reg) && 2568 arg_type == ARG_PTR_TO_MEM_OR_NULL) 2569 /* final test in check_stack_boundary() */; 2570 else if (!type_is_pkt_pointer(type) && 2571 type != PTR_TO_MAP_VALUE && 2572 type != expected_type) 2573 goto err_type; 2574 meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM; 2575 } else if (arg_type_is_int_ptr(arg_type)) { 2576 expected_type = PTR_TO_STACK; 2577 if (!type_is_pkt_pointer(type) && 2578 type != PTR_TO_MAP_VALUE && 2579 type != expected_type) 2580 goto err_type; 2581 } else { 2582 verbose(env, "unsupported arg_type %d\n", arg_type); 2583 return -EFAULT; 2584 } 2585 2586 if (arg_type == ARG_CONST_MAP_PTR) { 2587 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 2588 meta->map_ptr = reg->map_ptr; 2589 } else if (arg_type == ARG_PTR_TO_MAP_KEY) { 2590 /* bpf_map_xxx(..., map_ptr, ..., key) call: 2591 * check that [key, key + map->key_size) are within 2592 * stack limits and initialized 2593 */ 2594 if (!meta->map_ptr) { 2595 /* in function declaration map_ptr must come before 2596 * map_key, so that it's verified and known before 2597 * we have to check map_key here. Otherwise it means 2598 * that kernel subsystem misconfigured verifier 2599 */ 2600 verbose(env, "invalid map_ptr to access map->key\n"); 2601 return -EACCES; 2602 } 2603 err = check_helper_mem_access(env, regno, 2604 meta->map_ptr->key_size, false, 2605 NULL); 2606 } else if (arg_type == ARG_PTR_TO_MAP_VALUE || 2607 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) { 2608 /* bpf_map_xxx(..., map_ptr, ..., value) call: 2609 * check [value, value + map->value_size) validity 2610 */ 2611 if (!meta->map_ptr) { 2612 /* kernel subsystem misconfigured verifier */ 2613 verbose(env, "invalid map_ptr to access map->value\n"); 2614 return -EACCES; 2615 } 2616 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE); 2617 err = check_helper_mem_access(env, regno, 2618 meta->map_ptr->value_size, false, 2619 meta); 2620 } else if (arg_type_is_mem_size(arg_type)) { 2621 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); 2622 2623 /* remember the mem_size which may be used later 2624 * to refine return values. 2625 */ 2626 meta->msize_smax_value = reg->smax_value; 2627 meta->msize_umax_value = reg->umax_value; 2628 2629 /* The register is SCALAR_VALUE; the access check 2630 * happens using its boundaries. 2631 */ 2632 if (!tnum_is_const(reg->var_off)) 2633 /* For unprivileged variable accesses, disable raw 2634 * mode so that the program is required to 2635 * initialize all the memory that the helper could 2636 * just partially fill up. 2637 */ 2638 meta = NULL; 2639 2640 if (reg->smin_value < 0) { 2641 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 2642 regno); 2643 return -EACCES; 2644 } 2645 2646 if (reg->umin_value == 0) { 2647 err = check_helper_mem_access(env, regno - 1, 0, 2648 zero_size_allowed, 2649 meta); 2650 if (err) 2651 return err; 2652 } 2653 2654 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 2655 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 2656 regno); 2657 return -EACCES; 2658 } 2659 err = check_helper_mem_access(env, regno - 1, 2660 reg->umax_value, 2661 zero_size_allowed, meta); 2662 } else if (arg_type_is_int_ptr(arg_type)) { 2663 int size = int_ptr_type_to_size(arg_type); 2664 2665 err = check_helper_mem_access(env, regno, size, false, meta); 2666 if (err) 2667 return err; 2668 err = check_ptr_alignment(env, reg, 0, size, true); 2669 } 2670 2671 return err; 2672 err_type: 2673 verbose(env, "R%d type=%s expected=%s\n", regno, 2674 reg_type_str[type], reg_type_str[expected_type]); 2675 return -EACCES; 2676 } 2677 2678 static int check_map_func_compatibility(struct bpf_verifier_env *env, 2679 struct bpf_map *map, int func_id) 2680 { 2681 if (!map) 2682 return 0; 2683 2684 /* We need a two way check, first is from map perspective ... */ 2685 switch (map->map_type) { 2686 case BPF_MAP_TYPE_PROG_ARRAY: 2687 if (func_id != BPF_FUNC_tail_call) 2688 goto error; 2689 break; 2690 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 2691 if (func_id != BPF_FUNC_perf_event_read && 2692 func_id != BPF_FUNC_perf_event_output && 2693 func_id != BPF_FUNC_perf_event_read_value) 2694 goto error; 2695 break; 2696 case BPF_MAP_TYPE_STACK_TRACE: 2697 if (func_id != BPF_FUNC_get_stackid) 2698 goto error; 2699 break; 2700 case BPF_MAP_TYPE_CGROUP_ARRAY: 2701 if (func_id != BPF_FUNC_skb_under_cgroup && 2702 func_id != BPF_FUNC_current_task_under_cgroup) 2703 goto error; 2704 break; 2705 case BPF_MAP_TYPE_CGROUP_STORAGE: 2706 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 2707 if (func_id != BPF_FUNC_get_local_storage) 2708 goto error; 2709 break; 2710 /* devmap returns a pointer to a live net_device ifindex that we cannot 2711 * allow to be modified from bpf side. So do not allow lookup elements 2712 * for now. 2713 */ 2714 case BPF_MAP_TYPE_DEVMAP: 2715 if (func_id != BPF_FUNC_redirect_map) 2716 goto error; 2717 break; 2718 /* Restrict bpf side of cpumap and xskmap, open when use-cases 2719 * appear. 2720 */ 2721 case BPF_MAP_TYPE_CPUMAP: 2722 case BPF_MAP_TYPE_XSKMAP: 2723 if (func_id != BPF_FUNC_redirect_map) 2724 goto error; 2725 break; 2726 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 2727 case BPF_MAP_TYPE_HASH_OF_MAPS: 2728 if (func_id != BPF_FUNC_map_lookup_elem) 2729 goto error; 2730 break; 2731 case BPF_MAP_TYPE_SOCKMAP: 2732 if (func_id != BPF_FUNC_sk_redirect_map && 2733 func_id != BPF_FUNC_sock_map_update && 2734 func_id != BPF_FUNC_map_delete_elem && 2735 func_id != BPF_FUNC_msg_redirect_map) 2736 goto error; 2737 break; 2738 case BPF_MAP_TYPE_SOCKHASH: 2739 if (func_id != BPF_FUNC_sk_redirect_hash && 2740 func_id != BPF_FUNC_sock_hash_update && 2741 func_id != BPF_FUNC_map_delete_elem && 2742 func_id != BPF_FUNC_msg_redirect_hash) 2743 goto error; 2744 break; 2745 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 2746 if (func_id != BPF_FUNC_sk_select_reuseport) 2747 goto error; 2748 break; 2749 case BPF_MAP_TYPE_QUEUE: 2750 case BPF_MAP_TYPE_STACK: 2751 if (func_id != BPF_FUNC_map_peek_elem && 2752 func_id != BPF_FUNC_map_pop_elem && 2753 func_id != BPF_FUNC_map_push_elem) 2754 goto error; 2755 break; 2756 default: 2757 break; 2758 } 2759 2760 /* ... and second from the function itself. */ 2761 switch (func_id) { 2762 case BPF_FUNC_tail_call: 2763 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 2764 goto error; 2765 if (env->subprog_cnt > 1) { 2766 verbose(env, "tail_calls are not allowed in programs with bpf-to-bpf calls\n"); 2767 return -EINVAL; 2768 } 2769 break; 2770 case BPF_FUNC_perf_event_read: 2771 case BPF_FUNC_perf_event_output: 2772 case BPF_FUNC_perf_event_read_value: 2773 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 2774 goto error; 2775 break; 2776 case BPF_FUNC_get_stackid: 2777 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 2778 goto error; 2779 break; 2780 case BPF_FUNC_current_task_under_cgroup: 2781 case BPF_FUNC_skb_under_cgroup: 2782 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 2783 goto error; 2784 break; 2785 case BPF_FUNC_redirect_map: 2786 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 2787 map->map_type != BPF_MAP_TYPE_CPUMAP && 2788 map->map_type != BPF_MAP_TYPE_XSKMAP) 2789 goto error; 2790 break; 2791 case BPF_FUNC_sk_redirect_map: 2792 case BPF_FUNC_msg_redirect_map: 2793 case BPF_FUNC_sock_map_update: 2794 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 2795 goto error; 2796 break; 2797 case BPF_FUNC_sk_redirect_hash: 2798 case BPF_FUNC_msg_redirect_hash: 2799 case BPF_FUNC_sock_hash_update: 2800 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 2801 goto error; 2802 break; 2803 case BPF_FUNC_get_local_storage: 2804 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 2805 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 2806 goto error; 2807 break; 2808 case BPF_FUNC_sk_select_reuseport: 2809 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY) 2810 goto error; 2811 break; 2812 case BPF_FUNC_map_peek_elem: 2813 case BPF_FUNC_map_pop_elem: 2814 case BPF_FUNC_map_push_elem: 2815 if (map->map_type != BPF_MAP_TYPE_QUEUE && 2816 map->map_type != BPF_MAP_TYPE_STACK) 2817 goto error; 2818 break; 2819 default: 2820 break; 2821 } 2822 2823 return 0; 2824 error: 2825 verbose(env, "cannot pass map_type %d into func %s#%d\n", 2826 map->map_type, func_id_name(func_id), func_id); 2827 return -EINVAL; 2828 } 2829 2830 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 2831 { 2832 int count = 0; 2833 2834 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 2835 count++; 2836 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 2837 count++; 2838 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 2839 count++; 2840 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 2841 count++; 2842 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 2843 count++; 2844 2845 /* We only support one arg being in raw mode at the moment, 2846 * which is sufficient for the helper functions we have 2847 * right now. 2848 */ 2849 return count <= 1; 2850 } 2851 2852 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr, 2853 enum bpf_arg_type arg_next) 2854 { 2855 return (arg_type_is_mem_ptr(arg_curr) && 2856 !arg_type_is_mem_size(arg_next)) || 2857 (!arg_type_is_mem_ptr(arg_curr) && 2858 arg_type_is_mem_size(arg_next)); 2859 } 2860 2861 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 2862 { 2863 /* bpf_xxx(..., buf, len) call will access 'len' 2864 * bytes from memory 'buf'. Both arg types need 2865 * to be paired, so make sure there's no buggy 2866 * helper function specification. 2867 */ 2868 if (arg_type_is_mem_size(fn->arg1_type) || 2869 arg_type_is_mem_ptr(fn->arg5_type) || 2870 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) || 2871 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) || 2872 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) || 2873 check_args_pair_invalid(fn->arg4_type, fn->arg5_type)) 2874 return false; 2875 2876 return true; 2877 } 2878 2879 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id) 2880 { 2881 int count = 0; 2882 2883 if (arg_type_may_be_refcounted(fn->arg1_type)) 2884 count++; 2885 if (arg_type_may_be_refcounted(fn->arg2_type)) 2886 count++; 2887 if (arg_type_may_be_refcounted(fn->arg3_type)) 2888 count++; 2889 if (arg_type_may_be_refcounted(fn->arg4_type)) 2890 count++; 2891 if (arg_type_may_be_refcounted(fn->arg5_type)) 2892 count++; 2893 2894 /* A reference acquiring function cannot acquire 2895 * another refcounted ptr. 2896 */ 2897 if (is_acquire_function(func_id) && count) 2898 return false; 2899 2900 /* We only support one arg being unreferenced at the moment, 2901 * which is sufficient for the helper functions we have right now. 2902 */ 2903 return count <= 1; 2904 } 2905 2906 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 2907 { 2908 return check_raw_mode_ok(fn) && 2909 check_arg_pair_ok(fn) && 2910 check_refcount_ok(fn, func_id) ? 0 : -EINVAL; 2911 } 2912 2913 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 2914 * are now invalid, so turn them into unknown SCALAR_VALUE. 2915 */ 2916 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env, 2917 struct bpf_func_state *state) 2918 { 2919 struct bpf_reg_state *regs = state->regs, *reg; 2920 int i; 2921 2922 for (i = 0; i < MAX_BPF_REG; i++) 2923 if (reg_is_pkt_pointer_any(®s[i])) 2924 mark_reg_unknown(env, regs, i); 2925 2926 bpf_for_each_spilled_reg(i, state, reg) { 2927 if (!reg) 2928 continue; 2929 if (reg_is_pkt_pointer_any(reg)) 2930 __mark_reg_unknown(reg); 2931 } 2932 } 2933 2934 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 2935 { 2936 struct bpf_verifier_state *vstate = env->cur_state; 2937 int i; 2938 2939 for (i = 0; i <= vstate->curframe; i++) 2940 __clear_all_pkt_pointers(env, vstate->frame[i]); 2941 } 2942 2943 static void release_reg_references(struct bpf_verifier_env *env, 2944 struct bpf_func_state *state, 2945 int ref_obj_id) 2946 { 2947 struct bpf_reg_state *regs = state->regs, *reg; 2948 int i; 2949 2950 for (i = 0; i < MAX_BPF_REG; i++) 2951 if (regs[i].ref_obj_id == ref_obj_id) 2952 mark_reg_unknown(env, regs, i); 2953 2954 bpf_for_each_spilled_reg(i, state, reg) { 2955 if (!reg) 2956 continue; 2957 if (reg->ref_obj_id == ref_obj_id) 2958 __mark_reg_unknown(reg); 2959 } 2960 } 2961 2962 /* The pointer with the specified id has released its reference to kernel 2963 * resources. Identify all copies of the same pointer and clear the reference. 2964 */ 2965 static int release_reference(struct bpf_verifier_env *env, 2966 int ref_obj_id) 2967 { 2968 struct bpf_verifier_state *vstate = env->cur_state; 2969 int err; 2970 int i; 2971 2972 err = release_reference_state(cur_func(env), ref_obj_id); 2973 if (err) 2974 return err; 2975 2976 for (i = 0; i <= vstate->curframe; i++) 2977 release_reg_references(env, vstate->frame[i], ref_obj_id); 2978 2979 return 0; 2980 } 2981 2982 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 2983 int *insn_idx) 2984 { 2985 struct bpf_verifier_state *state = env->cur_state; 2986 struct bpf_func_state *caller, *callee; 2987 int i, err, subprog, target_insn; 2988 2989 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 2990 verbose(env, "the call stack of %d frames is too deep\n", 2991 state->curframe + 2); 2992 return -E2BIG; 2993 } 2994 2995 target_insn = *insn_idx + insn->imm; 2996 subprog = find_subprog(env, target_insn + 1); 2997 if (subprog < 0) { 2998 verbose(env, "verifier bug. No program starts at insn %d\n", 2999 target_insn + 1); 3000 return -EFAULT; 3001 } 3002 3003 caller = state->frame[state->curframe]; 3004 if (state->frame[state->curframe + 1]) { 3005 verbose(env, "verifier bug. Frame %d already allocated\n", 3006 state->curframe + 1); 3007 return -EFAULT; 3008 } 3009 3010 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 3011 if (!callee) 3012 return -ENOMEM; 3013 state->frame[state->curframe + 1] = callee; 3014 3015 /* callee cannot access r0, r6 - r9 for reading and has to write 3016 * into its own stack before reading from it. 3017 * callee can read/write into caller's stack 3018 */ 3019 init_func_state(env, callee, 3020 /* remember the callsite, it will be used by bpf_exit */ 3021 *insn_idx /* callsite */, 3022 state->curframe + 1 /* frameno within this callchain */, 3023 subprog /* subprog number within this prog */); 3024 3025 /* Transfer references to the callee */ 3026 err = transfer_reference_state(callee, caller); 3027 if (err) 3028 return err; 3029 3030 /* copy r1 - r5 args that callee can access. The copy includes parent 3031 * pointers, which connects us up to the liveness chain 3032 */ 3033 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 3034 callee->regs[i] = caller->regs[i]; 3035 3036 /* after the call registers r0 - r5 were scratched */ 3037 for (i = 0; i < CALLER_SAVED_REGS; i++) { 3038 mark_reg_not_init(env, caller->regs, caller_saved[i]); 3039 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 3040 } 3041 3042 /* only increment it after check_reg_arg() finished */ 3043 state->curframe++; 3044 3045 /* and go analyze first insn of the callee */ 3046 *insn_idx = target_insn; 3047 3048 if (env->log.level & BPF_LOG_LEVEL) { 3049 verbose(env, "caller:\n"); 3050 print_verifier_state(env, caller); 3051 verbose(env, "callee:\n"); 3052 print_verifier_state(env, callee); 3053 } 3054 return 0; 3055 } 3056 3057 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 3058 { 3059 struct bpf_verifier_state *state = env->cur_state; 3060 struct bpf_func_state *caller, *callee; 3061 struct bpf_reg_state *r0; 3062 int err; 3063 3064 callee = state->frame[state->curframe]; 3065 r0 = &callee->regs[BPF_REG_0]; 3066 if (r0->type == PTR_TO_STACK) { 3067 /* technically it's ok to return caller's stack pointer 3068 * (or caller's caller's pointer) back to the caller, 3069 * since these pointers are valid. Only current stack 3070 * pointer will be invalid as soon as function exits, 3071 * but let's be conservative 3072 */ 3073 verbose(env, "cannot return stack pointer to the caller\n"); 3074 return -EINVAL; 3075 } 3076 3077 state->curframe--; 3078 caller = state->frame[state->curframe]; 3079 /* return to the caller whatever r0 had in the callee */ 3080 caller->regs[BPF_REG_0] = *r0; 3081 3082 /* Transfer references to the caller */ 3083 err = transfer_reference_state(caller, callee); 3084 if (err) 3085 return err; 3086 3087 *insn_idx = callee->callsite + 1; 3088 if (env->log.level & BPF_LOG_LEVEL) { 3089 verbose(env, "returning from callee:\n"); 3090 print_verifier_state(env, callee); 3091 verbose(env, "to caller at %d:\n", *insn_idx); 3092 print_verifier_state(env, caller); 3093 } 3094 /* clear everything in the callee */ 3095 free_func_state(callee); 3096 state->frame[state->curframe + 1] = NULL; 3097 return 0; 3098 } 3099 3100 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 3101 int func_id, 3102 struct bpf_call_arg_meta *meta) 3103 { 3104 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 3105 3106 if (ret_type != RET_INTEGER || 3107 (func_id != BPF_FUNC_get_stack && 3108 func_id != BPF_FUNC_probe_read_str)) 3109 return; 3110 3111 ret_reg->smax_value = meta->msize_smax_value; 3112 ret_reg->umax_value = meta->msize_umax_value; 3113 __reg_deduce_bounds(ret_reg); 3114 __reg_bound_offset(ret_reg); 3115 } 3116 3117 static int 3118 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 3119 int func_id, int insn_idx) 3120 { 3121 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 3122 struct bpf_map *map = meta->map_ptr; 3123 3124 if (func_id != BPF_FUNC_tail_call && 3125 func_id != BPF_FUNC_map_lookup_elem && 3126 func_id != BPF_FUNC_map_update_elem && 3127 func_id != BPF_FUNC_map_delete_elem && 3128 func_id != BPF_FUNC_map_push_elem && 3129 func_id != BPF_FUNC_map_pop_elem && 3130 func_id != BPF_FUNC_map_peek_elem) 3131 return 0; 3132 3133 if (map == NULL) { 3134 verbose(env, "kernel subsystem misconfigured verifier\n"); 3135 return -EINVAL; 3136 } 3137 3138 /* In case of read-only, some additional restrictions 3139 * need to be applied in order to prevent altering the 3140 * state of the map from program side. 3141 */ 3142 if ((map->map_flags & BPF_F_RDONLY_PROG) && 3143 (func_id == BPF_FUNC_map_delete_elem || 3144 func_id == BPF_FUNC_map_update_elem || 3145 func_id == BPF_FUNC_map_push_elem || 3146 func_id == BPF_FUNC_map_pop_elem)) { 3147 verbose(env, "write into map forbidden\n"); 3148 return -EACCES; 3149 } 3150 3151 if (!BPF_MAP_PTR(aux->map_state)) 3152 bpf_map_ptr_store(aux, meta->map_ptr, 3153 meta->map_ptr->unpriv_array); 3154 else if (BPF_MAP_PTR(aux->map_state) != meta->map_ptr) 3155 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 3156 meta->map_ptr->unpriv_array); 3157 return 0; 3158 } 3159 3160 static int check_reference_leak(struct bpf_verifier_env *env) 3161 { 3162 struct bpf_func_state *state = cur_func(env); 3163 int i; 3164 3165 for (i = 0; i < state->acquired_refs; i++) { 3166 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 3167 state->refs[i].id, state->refs[i].insn_idx); 3168 } 3169 return state->acquired_refs ? -EINVAL : 0; 3170 } 3171 3172 static int check_helper_call(struct bpf_verifier_env *env, int func_id, int insn_idx) 3173 { 3174 const struct bpf_func_proto *fn = NULL; 3175 struct bpf_reg_state *regs; 3176 struct bpf_call_arg_meta meta; 3177 bool changes_data; 3178 int i, err; 3179 3180 /* find function prototype */ 3181 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 3182 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 3183 func_id); 3184 return -EINVAL; 3185 } 3186 3187 if (env->ops->get_func_proto) 3188 fn = env->ops->get_func_proto(func_id, env->prog); 3189 if (!fn) { 3190 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 3191 func_id); 3192 return -EINVAL; 3193 } 3194 3195 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 3196 if (!env->prog->gpl_compatible && fn->gpl_only) { 3197 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 3198 return -EINVAL; 3199 } 3200 3201 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 3202 changes_data = bpf_helper_changes_pkt_data(fn->func); 3203 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 3204 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 3205 func_id_name(func_id), func_id); 3206 return -EINVAL; 3207 } 3208 3209 memset(&meta, 0, sizeof(meta)); 3210 meta.pkt_access = fn->pkt_access; 3211 3212 err = check_func_proto(fn, func_id); 3213 if (err) { 3214 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 3215 func_id_name(func_id), func_id); 3216 return err; 3217 } 3218 3219 meta.func_id = func_id; 3220 /* check args */ 3221 err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); 3222 if (err) 3223 return err; 3224 err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); 3225 if (err) 3226 return err; 3227 err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); 3228 if (err) 3229 return err; 3230 err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); 3231 if (err) 3232 return err; 3233 err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); 3234 if (err) 3235 return err; 3236 3237 err = record_func_map(env, &meta, func_id, insn_idx); 3238 if (err) 3239 return err; 3240 3241 /* Mark slots with STACK_MISC in case of raw mode, stack offset 3242 * is inferred from register state. 3243 */ 3244 for (i = 0; i < meta.access_size; i++) { 3245 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 3246 BPF_WRITE, -1, false); 3247 if (err) 3248 return err; 3249 } 3250 3251 if (func_id == BPF_FUNC_tail_call) { 3252 err = check_reference_leak(env); 3253 if (err) { 3254 verbose(env, "tail_call would lead to reference leak\n"); 3255 return err; 3256 } 3257 } else if (is_release_function(func_id)) { 3258 err = release_reference(env, meta.ref_obj_id); 3259 if (err) { 3260 verbose(env, "func %s#%d reference has not been acquired before\n", 3261 func_id_name(func_id), func_id); 3262 return err; 3263 } 3264 } 3265 3266 regs = cur_regs(env); 3267 3268 /* check that flags argument in get_local_storage(map, flags) is 0, 3269 * this is required because get_local_storage() can't return an error. 3270 */ 3271 if (func_id == BPF_FUNC_get_local_storage && 3272 !register_is_null(®s[BPF_REG_2])) { 3273 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 3274 return -EINVAL; 3275 } 3276 3277 /* reset caller saved regs */ 3278 for (i = 0; i < CALLER_SAVED_REGS; i++) { 3279 mark_reg_not_init(env, regs, caller_saved[i]); 3280 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 3281 } 3282 3283 /* update return register (already marked as written above) */ 3284 if (fn->ret_type == RET_INTEGER) { 3285 /* sets type to SCALAR_VALUE */ 3286 mark_reg_unknown(env, regs, BPF_REG_0); 3287 } else if (fn->ret_type == RET_VOID) { 3288 regs[BPF_REG_0].type = NOT_INIT; 3289 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL || 3290 fn->ret_type == RET_PTR_TO_MAP_VALUE) { 3291 /* There is no offset yet applied, variable or fixed */ 3292 mark_reg_known_zero(env, regs, BPF_REG_0); 3293 /* remember map_ptr, so that check_map_access() 3294 * can check 'value_size' boundary of memory access 3295 * to map element returned from bpf_map_lookup_elem() 3296 */ 3297 if (meta.map_ptr == NULL) { 3298 verbose(env, 3299 "kernel subsystem misconfigured verifier\n"); 3300 return -EINVAL; 3301 } 3302 regs[BPF_REG_0].map_ptr = meta.map_ptr; 3303 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) { 3304 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE; 3305 if (map_value_has_spin_lock(meta.map_ptr)) 3306 regs[BPF_REG_0].id = ++env->id_gen; 3307 } else { 3308 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; 3309 regs[BPF_REG_0].id = ++env->id_gen; 3310 } 3311 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) { 3312 mark_reg_known_zero(env, regs, BPF_REG_0); 3313 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL; 3314 regs[BPF_REG_0].id = ++env->id_gen; 3315 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) { 3316 mark_reg_known_zero(env, regs, BPF_REG_0); 3317 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL; 3318 regs[BPF_REG_0].id = ++env->id_gen; 3319 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) { 3320 mark_reg_known_zero(env, regs, BPF_REG_0); 3321 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL; 3322 regs[BPF_REG_0].id = ++env->id_gen; 3323 } else { 3324 verbose(env, "unknown return type %d of func %s#%d\n", 3325 fn->ret_type, func_id_name(func_id), func_id); 3326 return -EINVAL; 3327 } 3328 3329 if (is_ptr_cast_function(func_id)) { 3330 /* For release_reference() */ 3331 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 3332 } else if (is_acquire_function(func_id)) { 3333 int id = acquire_reference_state(env, insn_idx); 3334 3335 if (id < 0) 3336 return id; 3337 /* For mark_ptr_or_null_reg() */ 3338 regs[BPF_REG_0].id = id; 3339 /* For release_reference() */ 3340 regs[BPF_REG_0].ref_obj_id = id; 3341 } 3342 3343 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 3344 3345 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 3346 if (err) 3347 return err; 3348 3349 if (func_id == BPF_FUNC_get_stack && !env->prog->has_callchain_buf) { 3350 const char *err_str; 3351 3352 #ifdef CONFIG_PERF_EVENTS 3353 err = get_callchain_buffers(sysctl_perf_event_max_stack); 3354 err_str = "cannot get callchain buffer for func %s#%d\n"; 3355 #else 3356 err = -ENOTSUPP; 3357 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 3358 #endif 3359 if (err) { 3360 verbose(env, err_str, func_id_name(func_id), func_id); 3361 return err; 3362 } 3363 3364 env->prog->has_callchain_buf = true; 3365 } 3366 3367 if (changes_data) 3368 clear_all_pkt_pointers(env); 3369 return 0; 3370 } 3371 3372 static bool signed_add_overflows(s64 a, s64 b) 3373 { 3374 /* Do the add in u64, where overflow is well-defined */ 3375 s64 res = (s64)((u64)a + (u64)b); 3376 3377 if (b < 0) 3378 return res > a; 3379 return res < a; 3380 } 3381 3382 static bool signed_sub_overflows(s64 a, s64 b) 3383 { 3384 /* Do the sub in u64, where overflow is well-defined */ 3385 s64 res = (s64)((u64)a - (u64)b); 3386 3387 if (b < 0) 3388 return res < a; 3389 return res > a; 3390 } 3391 3392 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 3393 const struct bpf_reg_state *reg, 3394 enum bpf_reg_type type) 3395 { 3396 bool known = tnum_is_const(reg->var_off); 3397 s64 val = reg->var_off.value; 3398 s64 smin = reg->smin_value; 3399 3400 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 3401 verbose(env, "math between %s pointer and %lld is not allowed\n", 3402 reg_type_str[type], val); 3403 return false; 3404 } 3405 3406 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 3407 verbose(env, "%s pointer offset %d is not allowed\n", 3408 reg_type_str[type], reg->off); 3409 return false; 3410 } 3411 3412 if (smin == S64_MIN) { 3413 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 3414 reg_type_str[type]); 3415 return false; 3416 } 3417 3418 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 3419 verbose(env, "value %lld makes %s pointer be out of bounds\n", 3420 smin, reg_type_str[type]); 3421 return false; 3422 } 3423 3424 return true; 3425 } 3426 3427 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 3428 { 3429 return &env->insn_aux_data[env->insn_idx]; 3430 } 3431 3432 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 3433 u32 *ptr_limit, u8 opcode, bool off_is_neg) 3434 { 3435 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) || 3436 (opcode == BPF_SUB && !off_is_neg); 3437 u32 off; 3438 3439 switch (ptr_reg->type) { 3440 case PTR_TO_STACK: 3441 /* Indirect variable offset stack access is prohibited in 3442 * unprivileged mode so it's not handled here. 3443 */ 3444 off = ptr_reg->off + ptr_reg->var_off.value; 3445 if (mask_to_left) 3446 *ptr_limit = MAX_BPF_STACK + off; 3447 else 3448 *ptr_limit = -off; 3449 return 0; 3450 case PTR_TO_MAP_VALUE: 3451 if (mask_to_left) { 3452 *ptr_limit = ptr_reg->umax_value + ptr_reg->off; 3453 } else { 3454 off = ptr_reg->smin_value + ptr_reg->off; 3455 *ptr_limit = ptr_reg->map_ptr->value_size - off; 3456 } 3457 return 0; 3458 default: 3459 return -EINVAL; 3460 } 3461 } 3462 3463 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 3464 const struct bpf_insn *insn) 3465 { 3466 return env->allow_ptr_leaks || BPF_SRC(insn->code) == BPF_K; 3467 } 3468 3469 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 3470 u32 alu_state, u32 alu_limit) 3471 { 3472 /* If we arrived here from different branches with different 3473 * state or limits to sanitize, then this won't work. 3474 */ 3475 if (aux->alu_state && 3476 (aux->alu_state != alu_state || 3477 aux->alu_limit != alu_limit)) 3478 return -EACCES; 3479 3480 /* Corresponding fixup done in fixup_bpf_calls(). */ 3481 aux->alu_state = alu_state; 3482 aux->alu_limit = alu_limit; 3483 return 0; 3484 } 3485 3486 static int sanitize_val_alu(struct bpf_verifier_env *env, 3487 struct bpf_insn *insn) 3488 { 3489 struct bpf_insn_aux_data *aux = cur_aux(env); 3490 3491 if (can_skip_alu_sanitation(env, insn)) 3492 return 0; 3493 3494 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 3495 } 3496 3497 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 3498 struct bpf_insn *insn, 3499 const struct bpf_reg_state *ptr_reg, 3500 struct bpf_reg_state *dst_reg, 3501 bool off_is_neg) 3502 { 3503 struct bpf_verifier_state *vstate = env->cur_state; 3504 struct bpf_insn_aux_data *aux = cur_aux(env); 3505 bool ptr_is_dst_reg = ptr_reg == dst_reg; 3506 u8 opcode = BPF_OP(insn->code); 3507 u32 alu_state, alu_limit; 3508 struct bpf_reg_state tmp; 3509 bool ret; 3510 3511 if (can_skip_alu_sanitation(env, insn)) 3512 return 0; 3513 3514 /* We already marked aux for masking from non-speculative 3515 * paths, thus we got here in the first place. We only care 3516 * to explore bad access from here. 3517 */ 3518 if (vstate->speculative) 3519 goto do_sim; 3520 3521 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 3522 alu_state |= ptr_is_dst_reg ? 3523 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 3524 3525 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg)) 3526 return 0; 3527 if (update_alu_sanitation_state(aux, alu_state, alu_limit)) 3528 return -EACCES; 3529 do_sim: 3530 /* Simulate and find potential out-of-bounds access under 3531 * speculative execution from truncation as a result of 3532 * masking when off was not within expected range. If off 3533 * sits in dst, then we temporarily need to move ptr there 3534 * to simulate dst (== 0) +/-= ptr. Needed, for example, 3535 * for cases where we use K-based arithmetic in one direction 3536 * and truncated reg-based in the other in order to explore 3537 * bad access. 3538 */ 3539 if (!ptr_is_dst_reg) { 3540 tmp = *dst_reg; 3541 *dst_reg = *ptr_reg; 3542 } 3543 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true); 3544 if (!ptr_is_dst_reg && ret) 3545 *dst_reg = tmp; 3546 return !ret ? -EFAULT : 0; 3547 } 3548 3549 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 3550 * Caller should also handle BPF_MOV case separately. 3551 * If we return -EACCES, caller may want to try again treating pointer as a 3552 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 3553 */ 3554 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 3555 struct bpf_insn *insn, 3556 const struct bpf_reg_state *ptr_reg, 3557 const struct bpf_reg_state *off_reg) 3558 { 3559 struct bpf_verifier_state *vstate = env->cur_state; 3560 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3561 struct bpf_reg_state *regs = state->regs, *dst_reg; 3562 bool known = tnum_is_const(off_reg->var_off); 3563 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 3564 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 3565 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 3566 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 3567 u32 dst = insn->dst_reg, src = insn->src_reg; 3568 u8 opcode = BPF_OP(insn->code); 3569 int ret; 3570 3571 dst_reg = ®s[dst]; 3572 3573 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 3574 smin_val > smax_val || umin_val > umax_val) { 3575 /* Taint dst register if offset had invalid bounds derived from 3576 * e.g. dead branches. 3577 */ 3578 __mark_reg_unknown(dst_reg); 3579 return 0; 3580 } 3581 3582 if (BPF_CLASS(insn->code) != BPF_ALU64) { 3583 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 3584 verbose(env, 3585 "R%d 32-bit pointer arithmetic prohibited\n", 3586 dst); 3587 return -EACCES; 3588 } 3589 3590 switch (ptr_reg->type) { 3591 case PTR_TO_MAP_VALUE_OR_NULL: 3592 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 3593 dst, reg_type_str[ptr_reg->type]); 3594 return -EACCES; 3595 case CONST_PTR_TO_MAP: 3596 case PTR_TO_PACKET_END: 3597 case PTR_TO_SOCKET: 3598 case PTR_TO_SOCKET_OR_NULL: 3599 case PTR_TO_SOCK_COMMON: 3600 case PTR_TO_SOCK_COMMON_OR_NULL: 3601 case PTR_TO_TCP_SOCK: 3602 case PTR_TO_TCP_SOCK_OR_NULL: 3603 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 3604 dst, reg_type_str[ptr_reg->type]); 3605 return -EACCES; 3606 case PTR_TO_MAP_VALUE: 3607 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) { 3608 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n", 3609 off_reg == dst_reg ? dst : src); 3610 return -EACCES; 3611 } 3612 /* fall-through */ 3613 default: 3614 break; 3615 } 3616 3617 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 3618 * The id may be overwritten later if we create a new variable offset. 3619 */ 3620 dst_reg->type = ptr_reg->type; 3621 dst_reg->id = ptr_reg->id; 3622 3623 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 3624 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 3625 return -EINVAL; 3626 3627 switch (opcode) { 3628 case BPF_ADD: 3629 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0); 3630 if (ret < 0) { 3631 verbose(env, "R%d tried to add from different maps or paths\n", dst); 3632 return ret; 3633 } 3634 /* We can take a fixed offset as long as it doesn't overflow 3635 * the s32 'off' field 3636 */ 3637 if (known && (ptr_reg->off + smin_val == 3638 (s64)(s32)(ptr_reg->off + smin_val))) { 3639 /* pointer += K. Accumulate it into fixed offset */ 3640 dst_reg->smin_value = smin_ptr; 3641 dst_reg->smax_value = smax_ptr; 3642 dst_reg->umin_value = umin_ptr; 3643 dst_reg->umax_value = umax_ptr; 3644 dst_reg->var_off = ptr_reg->var_off; 3645 dst_reg->off = ptr_reg->off + smin_val; 3646 dst_reg->raw = ptr_reg->raw; 3647 break; 3648 } 3649 /* A new variable offset is created. Note that off_reg->off 3650 * == 0, since it's a scalar. 3651 * dst_reg gets the pointer type and since some positive 3652 * integer value was added to the pointer, give it a new 'id' 3653 * if it's a PTR_TO_PACKET. 3654 * this creates a new 'base' pointer, off_reg (variable) gets 3655 * added into the variable offset, and we copy the fixed offset 3656 * from ptr_reg. 3657 */ 3658 if (signed_add_overflows(smin_ptr, smin_val) || 3659 signed_add_overflows(smax_ptr, smax_val)) { 3660 dst_reg->smin_value = S64_MIN; 3661 dst_reg->smax_value = S64_MAX; 3662 } else { 3663 dst_reg->smin_value = smin_ptr + smin_val; 3664 dst_reg->smax_value = smax_ptr + smax_val; 3665 } 3666 if (umin_ptr + umin_val < umin_ptr || 3667 umax_ptr + umax_val < umax_ptr) { 3668 dst_reg->umin_value = 0; 3669 dst_reg->umax_value = U64_MAX; 3670 } else { 3671 dst_reg->umin_value = umin_ptr + umin_val; 3672 dst_reg->umax_value = umax_ptr + umax_val; 3673 } 3674 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 3675 dst_reg->off = ptr_reg->off; 3676 dst_reg->raw = ptr_reg->raw; 3677 if (reg_is_pkt_pointer(ptr_reg)) { 3678 dst_reg->id = ++env->id_gen; 3679 /* something was added to pkt_ptr, set range to zero */ 3680 dst_reg->raw = 0; 3681 } 3682 break; 3683 case BPF_SUB: 3684 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0); 3685 if (ret < 0) { 3686 verbose(env, "R%d tried to sub from different maps or paths\n", dst); 3687 return ret; 3688 } 3689 if (dst_reg == off_reg) { 3690 /* scalar -= pointer. Creates an unknown scalar */ 3691 verbose(env, "R%d tried to subtract pointer from scalar\n", 3692 dst); 3693 return -EACCES; 3694 } 3695 /* We don't allow subtraction from FP, because (according to 3696 * test_verifier.c test "invalid fp arithmetic", JITs might not 3697 * be able to deal with it. 3698 */ 3699 if (ptr_reg->type == PTR_TO_STACK) { 3700 verbose(env, "R%d subtraction from stack pointer prohibited\n", 3701 dst); 3702 return -EACCES; 3703 } 3704 if (known && (ptr_reg->off - smin_val == 3705 (s64)(s32)(ptr_reg->off - smin_val))) { 3706 /* pointer -= K. Subtract it from fixed offset */ 3707 dst_reg->smin_value = smin_ptr; 3708 dst_reg->smax_value = smax_ptr; 3709 dst_reg->umin_value = umin_ptr; 3710 dst_reg->umax_value = umax_ptr; 3711 dst_reg->var_off = ptr_reg->var_off; 3712 dst_reg->id = ptr_reg->id; 3713 dst_reg->off = ptr_reg->off - smin_val; 3714 dst_reg->raw = ptr_reg->raw; 3715 break; 3716 } 3717 /* A new variable offset is created. If the subtrahend is known 3718 * nonnegative, then any reg->range we had before is still good. 3719 */ 3720 if (signed_sub_overflows(smin_ptr, smax_val) || 3721 signed_sub_overflows(smax_ptr, smin_val)) { 3722 /* Overflow possible, we know nothing */ 3723 dst_reg->smin_value = S64_MIN; 3724 dst_reg->smax_value = S64_MAX; 3725 } else { 3726 dst_reg->smin_value = smin_ptr - smax_val; 3727 dst_reg->smax_value = smax_ptr - smin_val; 3728 } 3729 if (umin_ptr < umax_val) { 3730 /* Overflow possible, we know nothing */ 3731 dst_reg->umin_value = 0; 3732 dst_reg->umax_value = U64_MAX; 3733 } else { 3734 /* Cannot overflow (as long as bounds are consistent) */ 3735 dst_reg->umin_value = umin_ptr - umax_val; 3736 dst_reg->umax_value = umax_ptr - umin_val; 3737 } 3738 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 3739 dst_reg->off = ptr_reg->off; 3740 dst_reg->raw = ptr_reg->raw; 3741 if (reg_is_pkt_pointer(ptr_reg)) { 3742 dst_reg->id = ++env->id_gen; 3743 /* something was added to pkt_ptr, set range to zero */ 3744 if (smin_val < 0) 3745 dst_reg->raw = 0; 3746 } 3747 break; 3748 case BPF_AND: 3749 case BPF_OR: 3750 case BPF_XOR: 3751 /* bitwise ops on pointers are troublesome, prohibit. */ 3752 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 3753 dst, bpf_alu_string[opcode >> 4]); 3754 return -EACCES; 3755 default: 3756 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 3757 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 3758 dst, bpf_alu_string[opcode >> 4]); 3759 return -EACCES; 3760 } 3761 3762 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 3763 return -EINVAL; 3764 3765 __update_reg_bounds(dst_reg); 3766 __reg_deduce_bounds(dst_reg); 3767 __reg_bound_offset(dst_reg); 3768 3769 /* For unprivileged we require that resulting offset must be in bounds 3770 * in order to be able to sanitize access later on. 3771 */ 3772 if (!env->allow_ptr_leaks) { 3773 if (dst_reg->type == PTR_TO_MAP_VALUE && 3774 check_map_access(env, dst, dst_reg->off, 1, false)) { 3775 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 3776 "prohibited for !root\n", dst); 3777 return -EACCES; 3778 } else if (dst_reg->type == PTR_TO_STACK && 3779 check_stack_access(env, dst_reg, dst_reg->off + 3780 dst_reg->var_off.value, 1)) { 3781 verbose(env, "R%d stack pointer arithmetic goes out of range, " 3782 "prohibited for !root\n", dst); 3783 return -EACCES; 3784 } 3785 } 3786 3787 return 0; 3788 } 3789 3790 /* WARNING: This function does calculations on 64-bit values, but the actual 3791 * execution may occur on 32-bit values. Therefore, things like bitshifts 3792 * need extra checks in the 32-bit case. 3793 */ 3794 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 3795 struct bpf_insn *insn, 3796 struct bpf_reg_state *dst_reg, 3797 struct bpf_reg_state src_reg) 3798 { 3799 struct bpf_reg_state *regs = cur_regs(env); 3800 u8 opcode = BPF_OP(insn->code); 3801 bool src_known, dst_known; 3802 s64 smin_val, smax_val; 3803 u64 umin_val, umax_val; 3804 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 3805 u32 dst = insn->dst_reg; 3806 int ret; 3807 3808 if (insn_bitness == 32) { 3809 /* Relevant for 32-bit RSH: Information can propagate towards 3810 * LSB, so it isn't sufficient to only truncate the output to 3811 * 32 bits. 3812 */ 3813 coerce_reg_to_size(dst_reg, 4); 3814 coerce_reg_to_size(&src_reg, 4); 3815 } 3816 3817 smin_val = src_reg.smin_value; 3818 smax_val = src_reg.smax_value; 3819 umin_val = src_reg.umin_value; 3820 umax_val = src_reg.umax_value; 3821 src_known = tnum_is_const(src_reg.var_off); 3822 dst_known = tnum_is_const(dst_reg->var_off); 3823 3824 if ((src_known && (smin_val != smax_val || umin_val != umax_val)) || 3825 smin_val > smax_val || umin_val > umax_val) { 3826 /* Taint dst register if offset had invalid bounds derived from 3827 * e.g. dead branches. 3828 */ 3829 __mark_reg_unknown(dst_reg); 3830 return 0; 3831 } 3832 3833 if (!src_known && 3834 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 3835 __mark_reg_unknown(dst_reg); 3836 return 0; 3837 } 3838 3839 switch (opcode) { 3840 case BPF_ADD: 3841 ret = sanitize_val_alu(env, insn); 3842 if (ret < 0) { 3843 verbose(env, "R%d tried to add from different pointers or scalars\n", dst); 3844 return ret; 3845 } 3846 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 3847 signed_add_overflows(dst_reg->smax_value, smax_val)) { 3848 dst_reg->smin_value = S64_MIN; 3849 dst_reg->smax_value = S64_MAX; 3850 } else { 3851 dst_reg->smin_value += smin_val; 3852 dst_reg->smax_value += smax_val; 3853 } 3854 if (dst_reg->umin_value + umin_val < umin_val || 3855 dst_reg->umax_value + umax_val < umax_val) { 3856 dst_reg->umin_value = 0; 3857 dst_reg->umax_value = U64_MAX; 3858 } else { 3859 dst_reg->umin_value += umin_val; 3860 dst_reg->umax_value += umax_val; 3861 } 3862 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 3863 break; 3864 case BPF_SUB: 3865 ret = sanitize_val_alu(env, insn); 3866 if (ret < 0) { 3867 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst); 3868 return ret; 3869 } 3870 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 3871 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 3872 /* Overflow possible, we know nothing */ 3873 dst_reg->smin_value = S64_MIN; 3874 dst_reg->smax_value = S64_MAX; 3875 } else { 3876 dst_reg->smin_value -= smax_val; 3877 dst_reg->smax_value -= smin_val; 3878 } 3879 if (dst_reg->umin_value < umax_val) { 3880 /* Overflow possible, we know nothing */ 3881 dst_reg->umin_value = 0; 3882 dst_reg->umax_value = U64_MAX; 3883 } else { 3884 /* Cannot overflow (as long as bounds are consistent) */ 3885 dst_reg->umin_value -= umax_val; 3886 dst_reg->umax_value -= umin_val; 3887 } 3888 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 3889 break; 3890 case BPF_MUL: 3891 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 3892 if (smin_val < 0 || dst_reg->smin_value < 0) { 3893 /* Ain't nobody got time to multiply that sign */ 3894 __mark_reg_unbounded(dst_reg); 3895 __update_reg_bounds(dst_reg); 3896 break; 3897 } 3898 /* Both values are positive, so we can work with unsigned and 3899 * copy the result to signed (unless it exceeds S64_MAX). 3900 */ 3901 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 3902 /* Potential overflow, we know nothing */ 3903 __mark_reg_unbounded(dst_reg); 3904 /* (except what we can learn from the var_off) */ 3905 __update_reg_bounds(dst_reg); 3906 break; 3907 } 3908 dst_reg->umin_value *= umin_val; 3909 dst_reg->umax_value *= umax_val; 3910 if (dst_reg->umax_value > S64_MAX) { 3911 /* Overflow possible, we know nothing */ 3912 dst_reg->smin_value = S64_MIN; 3913 dst_reg->smax_value = S64_MAX; 3914 } else { 3915 dst_reg->smin_value = dst_reg->umin_value; 3916 dst_reg->smax_value = dst_reg->umax_value; 3917 } 3918 break; 3919 case BPF_AND: 3920 if (src_known && dst_known) { 3921 __mark_reg_known(dst_reg, dst_reg->var_off.value & 3922 src_reg.var_off.value); 3923 break; 3924 } 3925 /* We get our minimum from the var_off, since that's inherently 3926 * bitwise. Our maximum is the minimum of the operands' maxima. 3927 */ 3928 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 3929 dst_reg->umin_value = dst_reg->var_off.value; 3930 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 3931 if (dst_reg->smin_value < 0 || smin_val < 0) { 3932 /* Lose signed bounds when ANDing negative numbers, 3933 * ain't nobody got time for that. 3934 */ 3935 dst_reg->smin_value = S64_MIN; 3936 dst_reg->smax_value = S64_MAX; 3937 } else { 3938 /* ANDing two positives gives a positive, so safe to 3939 * cast result into s64. 3940 */ 3941 dst_reg->smin_value = dst_reg->umin_value; 3942 dst_reg->smax_value = dst_reg->umax_value; 3943 } 3944 /* We may learn something more from the var_off */ 3945 __update_reg_bounds(dst_reg); 3946 break; 3947 case BPF_OR: 3948 if (src_known && dst_known) { 3949 __mark_reg_known(dst_reg, dst_reg->var_off.value | 3950 src_reg.var_off.value); 3951 break; 3952 } 3953 /* We get our maximum from the var_off, and our minimum is the 3954 * maximum of the operands' minima 3955 */ 3956 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 3957 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 3958 dst_reg->umax_value = dst_reg->var_off.value | 3959 dst_reg->var_off.mask; 3960 if (dst_reg->smin_value < 0 || smin_val < 0) { 3961 /* Lose signed bounds when ORing negative numbers, 3962 * ain't nobody got time for that. 3963 */ 3964 dst_reg->smin_value = S64_MIN; 3965 dst_reg->smax_value = S64_MAX; 3966 } else { 3967 /* ORing two positives gives a positive, so safe to 3968 * cast result into s64. 3969 */ 3970 dst_reg->smin_value = dst_reg->umin_value; 3971 dst_reg->smax_value = dst_reg->umax_value; 3972 } 3973 /* We may learn something more from the var_off */ 3974 __update_reg_bounds(dst_reg); 3975 break; 3976 case BPF_LSH: 3977 if (umax_val >= insn_bitness) { 3978 /* Shifts greater than 31 or 63 are undefined. 3979 * This includes shifts by a negative number. 3980 */ 3981 mark_reg_unknown(env, regs, insn->dst_reg); 3982 break; 3983 } 3984 /* We lose all sign bit information (except what we can pick 3985 * up from var_off) 3986 */ 3987 dst_reg->smin_value = S64_MIN; 3988 dst_reg->smax_value = S64_MAX; 3989 /* If we might shift our top bit out, then we know nothing */ 3990 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 3991 dst_reg->umin_value = 0; 3992 dst_reg->umax_value = U64_MAX; 3993 } else { 3994 dst_reg->umin_value <<= umin_val; 3995 dst_reg->umax_value <<= umax_val; 3996 } 3997 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 3998 /* We may learn something more from the var_off */ 3999 __update_reg_bounds(dst_reg); 4000 break; 4001 case BPF_RSH: 4002 if (umax_val >= insn_bitness) { 4003 /* Shifts greater than 31 or 63 are undefined. 4004 * This includes shifts by a negative number. 4005 */ 4006 mark_reg_unknown(env, regs, insn->dst_reg); 4007 break; 4008 } 4009 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 4010 * be negative, then either: 4011 * 1) src_reg might be zero, so the sign bit of the result is 4012 * unknown, so we lose our signed bounds 4013 * 2) it's known negative, thus the unsigned bounds capture the 4014 * signed bounds 4015 * 3) the signed bounds cross zero, so they tell us nothing 4016 * about the result 4017 * If the value in dst_reg is known nonnegative, then again the 4018 * unsigned bounts capture the signed bounds. 4019 * Thus, in all cases it suffices to blow away our signed bounds 4020 * and rely on inferring new ones from the unsigned bounds and 4021 * var_off of the result. 4022 */ 4023 dst_reg->smin_value = S64_MIN; 4024 dst_reg->smax_value = S64_MAX; 4025 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 4026 dst_reg->umin_value >>= umax_val; 4027 dst_reg->umax_value >>= umin_val; 4028 /* We may learn something more from the var_off */ 4029 __update_reg_bounds(dst_reg); 4030 break; 4031 case BPF_ARSH: 4032 if (umax_val >= insn_bitness) { 4033 /* Shifts greater than 31 or 63 are undefined. 4034 * This includes shifts by a negative number. 4035 */ 4036 mark_reg_unknown(env, regs, insn->dst_reg); 4037 break; 4038 } 4039 4040 /* Upon reaching here, src_known is true and 4041 * umax_val is equal to umin_val. 4042 */ 4043 dst_reg->smin_value >>= umin_val; 4044 dst_reg->smax_value >>= umin_val; 4045 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val); 4046 4047 /* blow away the dst_reg umin_value/umax_value and rely on 4048 * dst_reg var_off to refine the result. 4049 */ 4050 dst_reg->umin_value = 0; 4051 dst_reg->umax_value = U64_MAX; 4052 __update_reg_bounds(dst_reg); 4053 break; 4054 default: 4055 mark_reg_unknown(env, regs, insn->dst_reg); 4056 break; 4057 } 4058 4059 if (BPF_CLASS(insn->code) != BPF_ALU64) { 4060 /* 32-bit ALU ops are (32,32)->32 */ 4061 coerce_reg_to_size(dst_reg, 4); 4062 } 4063 4064 __reg_deduce_bounds(dst_reg); 4065 __reg_bound_offset(dst_reg); 4066 return 0; 4067 } 4068 4069 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 4070 * and var_off. 4071 */ 4072 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 4073 struct bpf_insn *insn) 4074 { 4075 struct bpf_verifier_state *vstate = env->cur_state; 4076 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4077 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 4078 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 4079 u8 opcode = BPF_OP(insn->code); 4080 4081 dst_reg = ®s[insn->dst_reg]; 4082 src_reg = NULL; 4083 if (dst_reg->type != SCALAR_VALUE) 4084 ptr_reg = dst_reg; 4085 if (BPF_SRC(insn->code) == BPF_X) { 4086 src_reg = ®s[insn->src_reg]; 4087 if (src_reg->type != SCALAR_VALUE) { 4088 if (dst_reg->type != SCALAR_VALUE) { 4089 /* Combining two pointers by any ALU op yields 4090 * an arbitrary scalar. Disallow all math except 4091 * pointer subtraction 4092 */ 4093 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 4094 mark_reg_unknown(env, regs, insn->dst_reg); 4095 return 0; 4096 } 4097 verbose(env, "R%d pointer %s pointer prohibited\n", 4098 insn->dst_reg, 4099 bpf_alu_string[opcode >> 4]); 4100 return -EACCES; 4101 } else { 4102 /* scalar += pointer 4103 * This is legal, but we have to reverse our 4104 * src/dest handling in computing the range 4105 */ 4106 return adjust_ptr_min_max_vals(env, insn, 4107 src_reg, dst_reg); 4108 } 4109 } else if (ptr_reg) { 4110 /* pointer += scalar */ 4111 return adjust_ptr_min_max_vals(env, insn, 4112 dst_reg, src_reg); 4113 } 4114 } else { 4115 /* Pretend the src is a reg with a known value, since we only 4116 * need to be able to read from this state. 4117 */ 4118 off_reg.type = SCALAR_VALUE; 4119 __mark_reg_known(&off_reg, insn->imm); 4120 src_reg = &off_reg; 4121 if (ptr_reg) /* pointer += K */ 4122 return adjust_ptr_min_max_vals(env, insn, 4123 ptr_reg, src_reg); 4124 } 4125 4126 /* Got here implies adding two SCALAR_VALUEs */ 4127 if (WARN_ON_ONCE(ptr_reg)) { 4128 print_verifier_state(env, state); 4129 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 4130 return -EINVAL; 4131 } 4132 if (WARN_ON(!src_reg)) { 4133 print_verifier_state(env, state); 4134 verbose(env, "verifier internal error: no src_reg\n"); 4135 return -EINVAL; 4136 } 4137 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 4138 } 4139 4140 /* check validity of 32-bit and 64-bit arithmetic operations */ 4141 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 4142 { 4143 struct bpf_reg_state *regs = cur_regs(env); 4144 u8 opcode = BPF_OP(insn->code); 4145 int err; 4146 4147 if (opcode == BPF_END || opcode == BPF_NEG) { 4148 if (opcode == BPF_NEG) { 4149 if (BPF_SRC(insn->code) != 0 || 4150 insn->src_reg != BPF_REG_0 || 4151 insn->off != 0 || insn->imm != 0) { 4152 verbose(env, "BPF_NEG uses reserved fields\n"); 4153 return -EINVAL; 4154 } 4155 } else { 4156 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 4157 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 4158 BPF_CLASS(insn->code) == BPF_ALU64) { 4159 verbose(env, "BPF_END uses reserved fields\n"); 4160 return -EINVAL; 4161 } 4162 } 4163 4164 /* check src operand */ 4165 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 4166 if (err) 4167 return err; 4168 4169 if (is_pointer_value(env, insn->dst_reg)) { 4170 verbose(env, "R%d pointer arithmetic prohibited\n", 4171 insn->dst_reg); 4172 return -EACCES; 4173 } 4174 4175 /* check dest operand */ 4176 err = check_reg_arg(env, insn->dst_reg, DST_OP); 4177 if (err) 4178 return err; 4179 4180 } else if (opcode == BPF_MOV) { 4181 4182 if (BPF_SRC(insn->code) == BPF_X) { 4183 if (insn->imm != 0 || insn->off != 0) { 4184 verbose(env, "BPF_MOV uses reserved fields\n"); 4185 return -EINVAL; 4186 } 4187 4188 /* check src operand */ 4189 err = check_reg_arg(env, insn->src_reg, SRC_OP); 4190 if (err) 4191 return err; 4192 } else { 4193 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 4194 verbose(env, "BPF_MOV uses reserved fields\n"); 4195 return -EINVAL; 4196 } 4197 } 4198 4199 /* check dest operand, mark as required later */ 4200 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 4201 if (err) 4202 return err; 4203 4204 if (BPF_SRC(insn->code) == BPF_X) { 4205 struct bpf_reg_state *src_reg = regs + insn->src_reg; 4206 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 4207 4208 if (BPF_CLASS(insn->code) == BPF_ALU64) { 4209 /* case: R1 = R2 4210 * copy register state to dest reg 4211 */ 4212 *dst_reg = *src_reg; 4213 dst_reg->live |= REG_LIVE_WRITTEN; 4214 } else { 4215 /* R1 = (u32) R2 */ 4216 if (is_pointer_value(env, insn->src_reg)) { 4217 verbose(env, 4218 "R%d partial copy of pointer\n", 4219 insn->src_reg); 4220 return -EACCES; 4221 } else if (src_reg->type == SCALAR_VALUE) { 4222 *dst_reg = *src_reg; 4223 dst_reg->live |= REG_LIVE_WRITTEN; 4224 } else { 4225 mark_reg_unknown(env, regs, 4226 insn->dst_reg); 4227 } 4228 coerce_reg_to_size(dst_reg, 4); 4229 } 4230 } else { 4231 /* case: R = imm 4232 * remember the value we stored into this reg 4233 */ 4234 /* clear any state __mark_reg_known doesn't set */ 4235 mark_reg_unknown(env, regs, insn->dst_reg); 4236 regs[insn->dst_reg].type = SCALAR_VALUE; 4237 if (BPF_CLASS(insn->code) == BPF_ALU64) { 4238 __mark_reg_known(regs + insn->dst_reg, 4239 insn->imm); 4240 } else { 4241 __mark_reg_known(regs + insn->dst_reg, 4242 (u32)insn->imm); 4243 } 4244 } 4245 4246 } else if (opcode > BPF_END) { 4247 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 4248 return -EINVAL; 4249 4250 } else { /* all other ALU ops: and, sub, xor, add, ... */ 4251 4252 if (BPF_SRC(insn->code) == BPF_X) { 4253 if (insn->imm != 0 || insn->off != 0) { 4254 verbose(env, "BPF_ALU uses reserved fields\n"); 4255 return -EINVAL; 4256 } 4257 /* check src1 operand */ 4258 err = check_reg_arg(env, insn->src_reg, SRC_OP); 4259 if (err) 4260 return err; 4261 } else { 4262 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 4263 verbose(env, "BPF_ALU uses reserved fields\n"); 4264 return -EINVAL; 4265 } 4266 } 4267 4268 /* check src2 operand */ 4269 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 4270 if (err) 4271 return err; 4272 4273 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 4274 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 4275 verbose(env, "div by zero\n"); 4276 return -EINVAL; 4277 } 4278 4279 if ((opcode == BPF_LSH || opcode == BPF_RSH || 4280 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 4281 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 4282 4283 if (insn->imm < 0 || insn->imm >= size) { 4284 verbose(env, "invalid shift %d\n", insn->imm); 4285 return -EINVAL; 4286 } 4287 } 4288 4289 /* check dest operand */ 4290 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 4291 if (err) 4292 return err; 4293 4294 return adjust_reg_min_max_vals(env, insn); 4295 } 4296 4297 return 0; 4298 } 4299 4300 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 4301 struct bpf_reg_state *dst_reg, 4302 enum bpf_reg_type type, 4303 bool range_right_open) 4304 { 4305 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4306 struct bpf_reg_state *regs = state->regs, *reg; 4307 u16 new_range; 4308 int i, j; 4309 4310 if (dst_reg->off < 0 || 4311 (dst_reg->off == 0 && range_right_open)) 4312 /* This doesn't give us any range */ 4313 return; 4314 4315 if (dst_reg->umax_value > MAX_PACKET_OFF || 4316 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 4317 /* Risk of overflow. For instance, ptr + (1<<63) may be less 4318 * than pkt_end, but that's because it's also less than pkt. 4319 */ 4320 return; 4321 4322 new_range = dst_reg->off; 4323 if (range_right_open) 4324 new_range--; 4325 4326 /* Examples for register markings: 4327 * 4328 * pkt_data in dst register: 4329 * 4330 * r2 = r3; 4331 * r2 += 8; 4332 * if (r2 > pkt_end) goto <handle exception> 4333 * <access okay> 4334 * 4335 * r2 = r3; 4336 * r2 += 8; 4337 * if (r2 < pkt_end) goto <access okay> 4338 * <handle exception> 4339 * 4340 * Where: 4341 * r2 == dst_reg, pkt_end == src_reg 4342 * r2=pkt(id=n,off=8,r=0) 4343 * r3=pkt(id=n,off=0,r=0) 4344 * 4345 * pkt_data in src register: 4346 * 4347 * r2 = r3; 4348 * r2 += 8; 4349 * if (pkt_end >= r2) goto <access okay> 4350 * <handle exception> 4351 * 4352 * r2 = r3; 4353 * r2 += 8; 4354 * if (pkt_end <= r2) goto <handle exception> 4355 * <access okay> 4356 * 4357 * Where: 4358 * pkt_end == dst_reg, r2 == src_reg 4359 * r2=pkt(id=n,off=8,r=0) 4360 * r3=pkt(id=n,off=0,r=0) 4361 * 4362 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 4363 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 4364 * and [r3, r3 + 8-1) respectively is safe to access depending on 4365 * the check. 4366 */ 4367 4368 /* If our ids match, then we must have the same max_value. And we 4369 * don't care about the other reg's fixed offset, since if it's too big 4370 * the range won't allow anything. 4371 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 4372 */ 4373 for (i = 0; i < MAX_BPF_REG; i++) 4374 if (regs[i].type == type && regs[i].id == dst_reg->id) 4375 /* keep the maximum range already checked */ 4376 regs[i].range = max(regs[i].range, new_range); 4377 4378 for (j = 0; j <= vstate->curframe; j++) { 4379 state = vstate->frame[j]; 4380 bpf_for_each_spilled_reg(i, state, reg) { 4381 if (!reg) 4382 continue; 4383 if (reg->type == type && reg->id == dst_reg->id) 4384 reg->range = max(reg->range, new_range); 4385 } 4386 } 4387 } 4388 4389 /* compute branch direction of the expression "if (reg opcode val) goto target;" 4390 * and return: 4391 * 1 - branch will be taken and "goto target" will be executed 4392 * 0 - branch will not be taken and fall-through to next insn 4393 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value range [0,10] 4394 */ 4395 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 4396 bool is_jmp32) 4397 { 4398 struct bpf_reg_state reg_lo; 4399 s64 sval; 4400 4401 if (__is_pointer_value(false, reg)) 4402 return -1; 4403 4404 if (is_jmp32) { 4405 reg_lo = *reg; 4406 reg = ®_lo; 4407 /* For JMP32, only low 32 bits are compared, coerce_reg_to_size 4408 * could truncate high bits and update umin/umax according to 4409 * information of low bits. 4410 */ 4411 coerce_reg_to_size(reg, 4); 4412 /* smin/smax need special handling. For example, after coerce, 4413 * if smin_value is 0x00000000ffffffffLL, the value is -1 when 4414 * used as operand to JMP32. It is a negative number from s32's 4415 * point of view, while it is a positive number when seen as 4416 * s64. The smin/smax are kept as s64, therefore, when used with 4417 * JMP32, they need to be transformed into s32, then sign 4418 * extended back to s64. 4419 * 4420 * Also, smin/smax were copied from umin/umax. If umin/umax has 4421 * different sign bit, then min/max relationship doesn't 4422 * maintain after casting into s32, for this case, set smin/smax 4423 * to safest range. 4424 */ 4425 if ((reg->umax_value ^ reg->umin_value) & 4426 (1ULL << 31)) { 4427 reg->smin_value = S32_MIN; 4428 reg->smax_value = S32_MAX; 4429 } 4430 reg->smin_value = (s64)(s32)reg->smin_value; 4431 reg->smax_value = (s64)(s32)reg->smax_value; 4432 4433 val = (u32)val; 4434 sval = (s64)(s32)val; 4435 } else { 4436 sval = (s64)val; 4437 } 4438 4439 switch (opcode) { 4440 case BPF_JEQ: 4441 if (tnum_is_const(reg->var_off)) 4442 return !!tnum_equals_const(reg->var_off, val); 4443 break; 4444 case BPF_JNE: 4445 if (tnum_is_const(reg->var_off)) 4446 return !tnum_equals_const(reg->var_off, val); 4447 break; 4448 case BPF_JSET: 4449 if ((~reg->var_off.mask & reg->var_off.value) & val) 4450 return 1; 4451 if (!((reg->var_off.mask | reg->var_off.value) & val)) 4452 return 0; 4453 break; 4454 case BPF_JGT: 4455 if (reg->umin_value > val) 4456 return 1; 4457 else if (reg->umax_value <= val) 4458 return 0; 4459 break; 4460 case BPF_JSGT: 4461 if (reg->smin_value > sval) 4462 return 1; 4463 else if (reg->smax_value < sval) 4464 return 0; 4465 break; 4466 case BPF_JLT: 4467 if (reg->umax_value < val) 4468 return 1; 4469 else if (reg->umin_value >= val) 4470 return 0; 4471 break; 4472 case BPF_JSLT: 4473 if (reg->smax_value < sval) 4474 return 1; 4475 else if (reg->smin_value >= sval) 4476 return 0; 4477 break; 4478 case BPF_JGE: 4479 if (reg->umin_value >= val) 4480 return 1; 4481 else if (reg->umax_value < val) 4482 return 0; 4483 break; 4484 case BPF_JSGE: 4485 if (reg->smin_value >= sval) 4486 return 1; 4487 else if (reg->smax_value < sval) 4488 return 0; 4489 break; 4490 case BPF_JLE: 4491 if (reg->umax_value <= val) 4492 return 1; 4493 else if (reg->umin_value > val) 4494 return 0; 4495 break; 4496 case BPF_JSLE: 4497 if (reg->smax_value <= sval) 4498 return 1; 4499 else if (reg->smin_value > sval) 4500 return 0; 4501 break; 4502 } 4503 4504 return -1; 4505 } 4506 4507 /* Generate min value of the high 32-bit from TNUM info. */ 4508 static u64 gen_hi_min(struct tnum var) 4509 { 4510 return var.value & ~0xffffffffULL; 4511 } 4512 4513 /* Generate max value of the high 32-bit from TNUM info. */ 4514 static u64 gen_hi_max(struct tnum var) 4515 { 4516 return (var.value | var.mask) & ~0xffffffffULL; 4517 } 4518 4519 /* Return true if VAL is compared with a s64 sign extended from s32, and they 4520 * are with the same signedness. 4521 */ 4522 static bool cmp_val_with_extended_s64(s64 sval, struct bpf_reg_state *reg) 4523 { 4524 return ((s32)sval >= 0 && 4525 reg->smin_value >= 0 && reg->smax_value <= S32_MAX) || 4526 ((s32)sval < 0 && 4527 reg->smax_value <= 0 && reg->smin_value >= S32_MIN); 4528 } 4529 4530 /* Adjusts the register min/max values in the case that the dst_reg is the 4531 * variable register that we are working on, and src_reg is a constant or we're 4532 * simply doing a BPF_K check. 4533 * In JEQ/JNE cases we also adjust the var_off values. 4534 */ 4535 static void reg_set_min_max(struct bpf_reg_state *true_reg, 4536 struct bpf_reg_state *false_reg, u64 val, 4537 u8 opcode, bool is_jmp32) 4538 { 4539 s64 sval; 4540 4541 /* If the dst_reg is a pointer, we can't learn anything about its 4542 * variable offset from the compare (unless src_reg were a pointer into 4543 * the same object, but we don't bother with that. 4544 * Since false_reg and true_reg have the same type by construction, we 4545 * only need to check one of them for pointerness. 4546 */ 4547 if (__is_pointer_value(false, false_reg)) 4548 return; 4549 4550 val = is_jmp32 ? (u32)val : val; 4551 sval = is_jmp32 ? (s64)(s32)val : (s64)val; 4552 4553 switch (opcode) { 4554 case BPF_JEQ: 4555 case BPF_JNE: 4556 { 4557 struct bpf_reg_state *reg = 4558 opcode == BPF_JEQ ? true_reg : false_reg; 4559 4560 /* For BPF_JEQ, if this is false we know nothing Jon Snow, but 4561 * if it is true we know the value for sure. Likewise for 4562 * BPF_JNE. 4563 */ 4564 if (is_jmp32) { 4565 u64 old_v = reg->var_off.value; 4566 u64 hi_mask = ~0xffffffffULL; 4567 4568 reg->var_off.value = (old_v & hi_mask) | val; 4569 reg->var_off.mask &= hi_mask; 4570 } else { 4571 __mark_reg_known(reg, val); 4572 } 4573 break; 4574 } 4575 case BPF_JSET: 4576 false_reg->var_off = tnum_and(false_reg->var_off, 4577 tnum_const(~val)); 4578 if (is_power_of_2(val)) 4579 true_reg->var_off = tnum_or(true_reg->var_off, 4580 tnum_const(val)); 4581 break; 4582 case BPF_JGE: 4583 case BPF_JGT: 4584 { 4585 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 4586 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 4587 4588 if (is_jmp32) { 4589 false_umax += gen_hi_max(false_reg->var_off); 4590 true_umin += gen_hi_min(true_reg->var_off); 4591 } 4592 false_reg->umax_value = min(false_reg->umax_value, false_umax); 4593 true_reg->umin_value = max(true_reg->umin_value, true_umin); 4594 break; 4595 } 4596 case BPF_JSGE: 4597 case BPF_JSGT: 4598 { 4599 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 4600 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 4601 4602 /* If the full s64 was not sign-extended from s32 then don't 4603 * deduct further info. 4604 */ 4605 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg)) 4606 break; 4607 false_reg->smax_value = min(false_reg->smax_value, false_smax); 4608 true_reg->smin_value = max(true_reg->smin_value, true_smin); 4609 break; 4610 } 4611 case BPF_JLE: 4612 case BPF_JLT: 4613 { 4614 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 4615 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 4616 4617 if (is_jmp32) { 4618 false_umin += gen_hi_min(false_reg->var_off); 4619 true_umax += gen_hi_max(true_reg->var_off); 4620 } 4621 false_reg->umin_value = max(false_reg->umin_value, false_umin); 4622 true_reg->umax_value = min(true_reg->umax_value, true_umax); 4623 break; 4624 } 4625 case BPF_JSLE: 4626 case BPF_JSLT: 4627 { 4628 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 4629 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 4630 4631 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg)) 4632 break; 4633 false_reg->smin_value = max(false_reg->smin_value, false_smin); 4634 true_reg->smax_value = min(true_reg->smax_value, true_smax); 4635 break; 4636 } 4637 default: 4638 break; 4639 } 4640 4641 __reg_deduce_bounds(false_reg); 4642 __reg_deduce_bounds(true_reg); 4643 /* We might have learned some bits from the bounds. */ 4644 __reg_bound_offset(false_reg); 4645 __reg_bound_offset(true_reg); 4646 /* Intersecting with the old var_off might have improved our bounds 4647 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 4648 * then new var_off is (0; 0x7f...fc) which improves our umax. 4649 */ 4650 __update_reg_bounds(false_reg); 4651 __update_reg_bounds(true_reg); 4652 } 4653 4654 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 4655 * the variable reg. 4656 */ 4657 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 4658 struct bpf_reg_state *false_reg, u64 val, 4659 u8 opcode, bool is_jmp32) 4660 { 4661 s64 sval; 4662 4663 if (__is_pointer_value(false, false_reg)) 4664 return; 4665 4666 val = is_jmp32 ? (u32)val : val; 4667 sval = is_jmp32 ? (s64)(s32)val : (s64)val; 4668 4669 switch (opcode) { 4670 case BPF_JEQ: 4671 case BPF_JNE: 4672 { 4673 struct bpf_reg_state *reg = 4674 opcode == BPF_JEQ ? true_reg : false_reg; 4675 4676 if (is_jmp32) { 4677 u64 old_v = reg->var_off.value; 4678 u64 hi_mask = ~0xffffffffULL; 4679 4680 reg->var_off.value = (old_v & hi_mask) | val; 4681 reg->var_off.mask &= hi_mask; 4682 } else { 4683 __mark_reg_known(reg, val); 4684 } 4685 break; 4686 } 4687 case BPF_JSET: 4688 false_reg->var_off = tnum_and(false_reg->var_off, 4689 tnum_const(~val)); 4690 if (is_power_of_2(val)) 4691 true_reg->var_off = tnum_or(true_reg->var_off, 4692 tnum_const(val)); 4693 break; 4694 case BPF_JGE: 4695 case BPF_JGT: 4696 { 4697 u64 false_umin = opcode == BPF_JGT ? val : val + 1; 4698 u64 true_umax = opcode == BPF_JGT ? val - 1 : val; 4699 4700 if (is_jmp32) { 4701 false_umin += gen_hi_min(false_reg->var_off); 4702 true_umax += gen_hi_max(true_reg->var_off); 4703 } 4704 false_reg->umin_value = max(false_reg->umin_value, false_umin); 4705 true_reg->umax_value = min(true_reg->umax_value, true_umax); 4706 break; 4707 } 4708 case BPF_JSGE: 4709 case BPF_JSGT: 4710 { 4711 s64 false_smin = opcode == BPF_JSGT ? sval : sval + 1; 4712 s64 true_smax = opcode == BPF_JSGT ? sval - 1 : sval; 4713 4714 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg)) 4715 break; 4716 false_reg->smin_value = max(false_reg->smin_value, false_smin); 4717 true_reg->smax_value = min(true_reg->smax_value, true_smax); 4718 break; 4719 } 4720 case BPF_JLE: 4721 case BPF_JLT: 4722 { 4723 u64 false_umax = opcode == BPF_JLT ? val : val - 1; 4724 u64 true_umin = opcode == BPF_JLT ? val + 1 : val; 4725 4726 if (is_jmp32) { 4727 false_umax += gen_hi_max(false_reg->var_off); 4728 true_umin += gen_hi_min(true_reg->var_off); 4729 } 4730 false_reg->umax_value = min(false_reg->umax_value, false_umax); 4731 true_reg->umin_value = max(true_reg->umin_value, true_umin); 4732 break; 4733 } 4734 case BPF_JSLE: 4735 case BPF_JSLT: 4736 { 4737 s64 false_smax = opcode == BPF_JSLT ? sval : sval - 1; 4738 s64 true_smin = opcode == BPF_JSLT ? sval + 1 : sval; 4739 4740 if (is_jmp32 && !cmp_val_with_extended_s64(sval, false_reg)) 4741 break; 4742 false_reg->smax_value = min(false_reg->smax_value, false_smax); 4743 true_reg->smin_value = max(true_reg->smin_value, true_smin); 4744 break; 4745 } 4746 default: 4747 break; 4748 } 4749 4750 __reg_deduce_bounds(false_reg); 4751 __reg_deduce_bounds(true_reg); 4752 /* We might have learned some bits from the bounds. */ 4753 __reg_bound_offset(false_reg); 4754 __reg_bound_offset(true_reg); 4755 /* Intersecting with the old var_off might have improved our bounds 4756 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 4757 * then new var_off is (0; 0x7f...fc) which improves our umax. 4758 */ 4759 __update_reg_bounds(false_reg); 4760 __update_reg_bounds(true_reg); 4761 } 4762 4763 /* Regs are known to be equal, so intersect their min/max/var_off */ 4764 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 4765 struct bpf_reg_state *dst_reg) 4766 { 4767 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 4768 dst_reg->umin_value); 4769 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 4770 dst_reg->umax_value); 4771 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 4772 dst_reg->smin_value); 4773 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 4774 dst_reg->smax_value); 4775 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 4776 dst_reg->var_off); 4777 /* We might have learned new bounds from the var_off. */ 4778 __update_reg_bounds(src_reg); 4779 __update_reg_bounds(dst_reg); 4780 /* We might have learned something about the sign bit. */ 4781 __reg_deduce_bounds(src_reg); 4782 __reg_deduce_bounds(dst_reg); 4783 /* We might have learned some bits from the bounds. */ 4784 __reg_bound_offset(src_reg); 4785 __reg_bound_offset(dst_reg); 4786 /* Intersecting with the old var_off might have improved our bounds 4787 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 4788 * then new var_off is (0; 0x7f...fc) which improves our umax. 4789 */ 4790 __update_reg_bounds(src_reg); 4791 __update_reg_bounds(dst_reg); 4792 } 4793 4794 static void reg_combine_min_max(struct bpf_reg_state *true_src, 4795 struct bpf_reg_state *true_dst, 4796 struct bpf_reg_state *false_src, 4797 struct bpf_reg_state *false_dst, 4798 u8 opcode) 4799 { 4800 switch (opcode) { 4801 case BPF_JEQ: 4802 __reg_combine_min_max(true_src, true_dst); 4803 break; 4804 case BPF_JNE: 4805 __reg_combine_min_max(false_src, false_dst); 4806 break; 4807 } 4808 } 4809 4810 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 4811 struct bpf_reg_state *reg, u32 id, 4812 bool is_null) 4813 { 4814 if (reg_type_may_be_null(reg->type) && reg->id == id) { 4815 /* Old offset (both fixed and variable parts) should 4816 * have been known-zero, because we don't allow pointer 4817 * arithmetic on pointers that might be NULL. 4818 */ 4819 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || 4820 !tnum_equals_const(reg->var_off, 0) || 4821 reg->off)) { 4822 __mark_reg_known_zero(reg); 4823 reg->off = 0; 4824 } 4825 if (is_null) { 4826 reg->type = SCALAR_VALUE; 4827 } else if (reg->type == PTR_TO_MAP_VALUE_OR_NULL) { 4828 if (reg->map_ptr->inner_map_meta) { 4829 reg->type = CONST_PTR_TO_MAP; 4830 reg->map_ptr = reg->map_ptr->inner_map_meta; 4831 } else { 4832 reg->type = PTR_TO_MAP_VALUE; 4833 } 4834 } else if (reg->type == PTR_TO_SOCKET_OR_NULL) { 4835 reg->type = PTR_TO_SOCKET; 4836 } else if (reg->type == PTR_TO_SOCK_COMMON_OR_NULL) { 4837 reg->type = PTR_TO_SOCK_COMMON; 4838 } else if (reg->type == PTR_TO_TCP_SOCK_OR_NULL) { 4839 reg->type = PTR_TO_TCP_SOCK; 4840 } 4841 if (is_null) { 4842 /* We don't need id and ref_obj_id from this point 4843 * onwards anymore, thus we should better reset it, 4844 * so that state pruning has chances to take effect. 4845 */ 4846 reg->id = 0; 4847 reg->ref_obj_id = 0; 4848 } else if (!reg_may_point_to_spin_lock(reg)) { 4849 /* For not-NULL ptr, reg->ref_obj_id will be reset 4850 * in release_reg_references(). 4851 * 4852 * reg->id is still used by spin_lock ptr. Other 4853 * than spin_lock ptr type, reg->id can be reset. 4854 */ 4855 reg->id = 0; 4856 } 4857 } 4858 } 4859 4860 /* The logic is similar to find_good_pkt_pointers(), both could eventually 4861 * be folded together at some point. 4862 */ 4863 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 4864 bool is_null) 4865 { 4866 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 4867 struct bpf_reg_state *reg, *regs = state->regs; 4868 u32 ref_obj_id = regs[regno].ref_obj_id; 4869 u32 id = regs[regno].id; 4870 int i, j; 4871 4872 if (ref_obj_id && ref_obj_id == id && is_null) 4873 /* regs[regno] is in the " == NULL" branch. 4874 * No one could have freed the reference state before 4875 * doing the NULL check. 4876 */ 4877 WARN_ON_ONCE(release_reference_state(state, id)); 4878 4879 for (i = 0; i < MAX_BPF_REG; i++) 4880 mark_ptr_or_null_reg(state, ®s[i], id, is_null); 4881 4882 for (j = 0; j <= vstate->curframe; j++) { 4883 state = vstate->frame[j]; 4884 bpf_for_each_spilled_reg(i, state, reg) { 4885 if (!reg) 4886 continue; 4887 mark_ptr_or_null_reg(state, reg, id, is_null); 4888 } 4889 } 4890 } 4891 4892 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 4893 struct bpf_reg_state *dst_reg, 4894 struct bpf_reg_state *src_reg, 4895 struct bpf_verifier_state *this_branch, 4896 struct bpf_verifier_state *other_branch) 4897 { 4898 if (BPF_SRC(insn->code) != BPF_X) 4899 return false; 4900 4901 /* Pointers are always 64-bit. */ 4902 if (BPF_CLASS(insn->code) == BPF_JMP32) 4903 return false; 4904 4905 switch (BPF_OP(insn->code)) { 4906 case BPF_JGT: 4907 if ((dst_reg->type == PTR_TO_PACKET && 4908 src_reg->type == PTR_TO_PACKET_END) || 4909 (dst_reg->type == PTR_TO_PACKET_META && 4910 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 4911 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 4912 find_good_pkt_pointers(this_branch, dst_reg, 4913 dst_reg->type, false); 4914 } else if ((dst_reg->type == PTR_TO_PACKET_END && 4915 src_reg->type == PTR_TO_PACKET) || 4916 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 4917 src_reg->type == PTR_TO_PACKET_META)) { 4918 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 4919 find_good_pkt_pointers(other_branch, src_reg, 4920 src_reg->type, true); 4921 } else { 4922 return false; 4923 } 4924 break; 4925 case BPF_JLT: 4926 if ((dst_reg->type == PTR_TO_PACKET && 4927 src_reg->type == PTR_TO_PACKET_END) || 4928 (dst_reg->type == PTR_TO_PACKET_META && 4929 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 4930 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 4931 find_good_pkt_pointers(other_branch, dst_reg, 4932 dst_reg->type, true); 4933 } else if ((dst_reg->type == PTR_TO_PACKET_END && 4934 src_reg->type == PTR_TO_PACKET) || 4935 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 4936 src_reg->type == PTR_TO_PACKET_META)) { 4937 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 4938 find_good_pkt_pointers(this_branch, src_reg, 4939 src_reg->type, false); 4940 } else { 4941 return false; 4942 } 4943 break; 4944 case BPF_JGE: 4945 if ((dst_reg->type == PTR_TO_PACKET && 4946 src_reg->type == PTR_TO_PACKET_END) || 4947 (dst_reg->type == PTR_TO_PACKET_META && 4948 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 4949 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 4950 find_good_pkt_pointers(this_branch, dst_reg, 4951 dst_reg->type, true); 4952 } else if ((dst_reg->type == PTR_TO_PACKET_END && 4953 src_reg->type == PTR_TO_PACKET) || 4954 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 4955 src_reg->type == PTR_TO_PACKET_META)) { 4956 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 4957 find_good_pkt_pointers(other_branch, src_reg, 4958 src_reg->type, false); 4959 } else { 4960 return false; 4961 } 4962 break; 4963 case BPF_JLE: 4964 if ((dst_reg->type == PTR_TO_PACKET && 4965 src_reg->type == PTR_TO_PACKET_END) || 4966 (dst_reg->type == PTR_TO_PACKET_META && 4967 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 4968 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 4969 find_good_pkt_pointers(other_branch, dst_reg, 4970 dst_reg->type, false); 4971 } else if ((dst_reg->type == PTR_TO_PACKET_END && 4972 src_reg->type == PTR_TO_PACKET) || 4973 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 4974 src_reg->type == PTR_TO_PACKET_META)) { 4975 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 4976 find_good_pkt_pointers(this_branch, src_reg, 4977 src_reg->type, true); 4978 } else { 4979 return false; 4980 } 4981 break; 4982 default: 4983 return false; 4984 } 4985 4986 return true; 4987 } 4988 4989 static int check_cond_jmp_op(struct bpf_verifier_env *env, 4990 struct bpf_insn *insn, int *insn_idx) 4991 { 4992 struct bpf_verifier_state *this_branch = env->cur_state; 4993 struct bpf_verifier_state *other_branch; 4994 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 4995 struct bpf_reg_state *dst_reg, *other_branch_regs; 4996 u8 opcode = BPF_OP(insn->code); 4997 bool is_jmp32; 4998 int err; 4999 5000 /* Only conditional jumps are expected to reach here. */ 5001 if (opcode == BPF_JA || opcode > BPF_JSLE) { 5002 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 5003 return -EINVAL; 5004 } 5005 5006 if (BPF_SRC(insn->code) == BPF_X) { 5007 if (insn->imm != 0) { 5008 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 5009 return -EINVAL; 5010 } 5011 5012 /* check src1 operand */ 5013 err = check_reg_arg(env, insn->src_reg, SRC_OP); 5014 if (err) 5015 return err; 5016 5017 if (is_pointer_value(env, insn->src_reg)) { 5018 verbose(env, "R%d pointer comparison prohibited\n", 5019 insn->src_reg); 5020 return -EACCES; 5021 } 5022 } else { 5023 if (insn->src_reg != BPF_REG_0) { 5024 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 5025 return -EINVAL; 5026 } 5027 } 5028 5029 /* check src2 operand */ 5030 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 5031 if (err) 5032 return err; 5033 5034 dst_reg = ®s[insn->dst_reg]; 5035 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 5036 5037 if (BPF_SRC(insn->code) == BPF_K) { 5038 int pred = is_branch_taken(dst_reg, insn->imm, opcode, 5039 is_jmp32); 5040 5041 if (pred == 1) { 5042 /* only follow the goto, ignore fall-through */ 5043 *insn_idx += insn->off; 5044 return 0; 5045 } else if (pred == 0) { 5046 /* only follow fall-through branch, since 5047 * that's where the program will go 5048 */ 5049 return 0; 5050 } 5051 } 5052 5053 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 5054 false); 5055 if (!other_branch) 5056 return -EFAULT; 5057 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 5058 5059 /* detect if we are comparing against a constant value so we can adjust 5060 * our min/max values for our dst register. 5061 * this is only legit if both are scalars (or pointers to the same 5062 * object, I suppose, but we don't support that right now), because 5063 * otherwise the different base pointers mean the offsets aren't 5064 * comparable. 5065 */ 5066 if (BPF_SRC(insn->code) == BPF_X) { 5067 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 5068 struct bpf_reg_state lo_reg0 = *dst_reg; 5069 struct bpf_reg_state lo_reg1 = *src_reg; 5070 struct bpf_reg_state *src_lo, *dst_lo; 5071 5072 dst_lo = &lo_reg0; 5073 src_lo = &lo_reg1; 5074 coerce_reg_to_size(dst_lo, 4); 5075 coerce_reg_to_size(src_lo, 4); 5076 5077 if (dst_reg->type == SCALAR_VALUE && 5078 src_reg->type == SCALAR_VALUE) { 5079 if (tnum_is_const(src_reg->var_off) || 5080 (is_jmp32 && tnum_is_const(src_lo->var_off))) 5081 reg_set_min_max(&other_branch_regs[insn->dst_reg], 5082 dst_reg, 5083 is_jmp32 5084 ? src_lo->var_off.value 5085 : src_reg->var_off.value, 5086 opcode, is_jmp32); 5087 else if (tnum_is_const(dst_reg->var_off) || 5088 (is_jmp32 && tnum_is_const(dst_lo->var_off))) 5089 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 5090 src_reg, 5091 is_jmp32 5092 ? dst_lo->var_off.value 5093 : dst_reg->var_off.value, 5094 opcode, is_jmp32); 5095 else if (!is_jmp32 && 5096 (opcode == BPF_JEQ || opcode == BPF_JNE)) 5097 /* Comparing for equality, we can combine knowledge */ 5098 reg_combine_min_max(&other_branch_regs[insn->src_reg], 5099 &other_branch_regs[insn->dst_reg], 5100 src_reg, dst_reg, opcode); 5101 } 5102 } else if (dst_reg->type == SCALAR_VALUE) { 5103 reg_set_min_max(&other_branch_regs[insn->dst_reg], 5104 dst_reg, insn->imm, opcode, is_jmp32); 5105 } 5106 5107 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 5108 * NOTE: these optimizations below are related with pointer comparison 5109 * which will never be JMP32. 5110 */ 5111 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 5112 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 5113 reg_type_may_be_null(dst_reg->type)) { 5114 /* Mark all identical registers in each branch as either 5115 * safe or unknown depending R == 0 or R != 0 conditional. 5116 */ 5117 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 5118 opcode == BPF_JNE); 5119 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 5120 opcode == BPF_JEQ); 5121 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 5122 this_branch, other_branch) && 5123 is_pointer_value(env, insn->dst_reg)) { 5124 verbose(env, "R%d pointer comparison prohibited\n", 5125 insn->dst_reg); 5126 return -EACCES; 5127 } 5128 if (env->log.level & BPF_LOG_LEVEL) 5129 print_verifier_state(env, this_branch->frame[this_branch->curframe]); 5130 return 0; 5131 } 5132 5133 /* verify BPF_LD_IMM64 instruction */ 5134 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 5135 { 5136 struct bpf_insn_aux_data *aux = cur_aux(env); 5137 struct bpf_reg_state *regs = cur_regs(env); 5138 struct bpf_map *map; 5139 int err; 5140 5141 if (BPF_SIZE(insn->code) != BPF_DW) { 5142 verbose(env, "invalid BPF_LD_IMM insn\n"); 5143 return -EINVAL; 5144 } 5145 if (insn->off != 0) { 5146 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 5147 return -EINVAL; 5148 } 5149 5150 err = check_reg_arg(env, insn->dst_reg, DST_OP); 5151 if (err) 5152 return err; 5153 5154 if (insn->src_reg == 0) { 5155 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 5156 5157 regs[insn->dst_reg].type = SCALAR_VALUE; 5158 __mark_reg_known(®s[insn->dst_reg], imm); 5159 return 0; 5160 } 5161 5162 map = env->used_maps[aux->map_index]; 5163 mark_reg_known_zero(env, regs, insn->dst_reg); 5164 regs[insn->dst_reg].map_ptr = map; 5165 5166 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) { 5167 regs[insn->dst_reg].type = PTR_TO_MAP_VALUE; 5168 regs[insn->dst_reg].off = aux->map_off; 5169 if (map_value_has_spin_lock(map)) 5170 regs[insn->dst_reg].id = ++env->id_gen; 5171 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) { 5172 regs[insn->dst_reg].type = CONST_PTR_TO_MAP; 5173 } else { 5174 verbose(env, "bpf verifier is misconfigured\n"); 5175 return -EINVAL; 5176 } 5177 5178 return 0; 5179 } 5180 5181 static bool may_access_skb(enum bpf_prog_type type) 5182 { 5183 switch (type) { 5184 case BPF_PROG_TYPE_SOCKET_FILTER: 5185 case BPF_PROG_TYPE_SCHED_CLS: 5186 case BPF_PROG_TYPE_SCHED_ACT: 5187 return true; 5188 default: 5189 return false; 5190 } 5191 } 5192 5193 /* verify safety of LD_ABS|LD_IND instructions: 5194 * - they can only appear in the programs where ctx == skb 5195 * - since they are wrappers of function calls, they scratch R1-R5 registers, 5196 * preserve R6-R9, and store return value into R0 5197 * 5198 * Implicit input: 5199 * ctx == skb == R6 == CTX 5200 * 5201 * Explicit input: 5202 * SRC == any register 5203 * IMM == 32-bit immediate 5204 * 5205 * Output: 5206 * R0 - 8/16/32-bit skb data converted to cpu endianness 5207 */ 5208 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 5209 { 5210 struct bpf_reg_state *regs = cur_regs(env); 5211 u8 mode = BPF_MODE(insn->code); 5212 int i, err; 5213 5214 if (!may_access_skb(env->prog->type)) { 5215 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 5216 return -EINVAL; 5217 } 5218 5219 if (!env->ops->gen_ld_abs) { 5220 verbose(env, "bpf verifier is misconfigured\n"); 5221 return -EINVAL; 5222 } 5223 5224 if (env->subprog_cnt > 1) { 5225 /* when program has LD_ABS insn JITs and interpreter assume 5226 * that r1 == ctx == skb which is not the case for callees 5227 * that can have arbitrary arguments. It's problematic 5228 * for main prog as well since JITs would need to analyze 5229 * all functions in order to make proper register save/restore 5230 * decisions in the main prog. Hence disallow LD_ABS with calls 5231 */ 5232 verbose(env, "BPF_LD_[ABS|IND] instructions cannot be mixed with bpf-to-bpf calls\n"); 5233 return -EINVAL; 5234 } 5235 5236 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 5237 BPF_SIZE(insn->code) == BPF_DW || 5238 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 5239 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 5240 return -EINVAL; 5241 } 5242 5243 /* check whether implicit source operand (register R6) is readable */ 5244 err = check_reg_arg(env, BPF_REG_6, SRC_OP); 5245 if (err) 5246 return err; 5247 5248 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 5249 * gen_ld_abs() may terminate the program at runtime, leading to 5250 * reference leak. 5251 */ 5252 err = check_reference_leak(env); 5253 if (err) { 5254 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 5255 return err; 5256 } 5257 5258 if (env->cur_state->active_spin_lock) { 5259 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 5260 return -EINVAL; 5261 } 5262 5263 if (regs[BPF_REG_6].type != PTR_TO_CTX) { 5264 verbose(env, 5265 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 5266 return -EINVAL; 5267 } 5268 5269 if (mode == BPF_IND) { 5270 /* check explicit source operand */ 5271 err = check_reg_arg(env, insn->src_reg, SRC_OP); 5272 if (err) 5273 return err; 5274 } 5275 5276 /* reset caller saved regs to unreadable */ 5277 for (i = 0; i < CALLER_SAVED_REGS; i++) { 5278 mark_reg_not_init(env, regs, caller_saved[i]); 5279 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 5280 } 5281 5282 /* mark destination R0 register as readable, since it contains 5283 * the value fetched from the packet. 5284 * Already marked as written above. 5285 */ 5286 mark_reg_unknown(env, regs, BPF_REG_0); 5287 return 0; 5288 } 5289 5290 static int check_return_code(struct bpf_verifier_env *env) 5291 { 5292 struct bpf_reg_state *reg; 5293 struct tnum range = tnum_range(0, 1); 5294 5295 switch (env->prog->type) { 5296 case BPF_PROG_TYPE_CGROUP_SKB: 5297 case BPF_PROG_TYPE_CGROUP_SOCK: 5298 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 5299 case BPF_PROG_TYPE_SOCK_OPS: 5300 case BPF_PROG_TYPE_CGROUP_DEVICE: 5301 case BPF_PROG_TYPE_CGROUP_SYSCTL: 5302 break; 5303 default: 5304 return 0; 5305 } 5306 5307 reg = cur_regs(env) + BPF_REG_0; 5308 if (reg->type != SCALAR_VALUE) { 5309 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 5310 reg_type_str[reg->type]); 5311 return -EINVAL; 5312 } 5313 5314 if (!tnum_in(range, reg->var_off)) { 5315 verbose(env, "At program exit the register R0 "); 5316 if (!tnum_is_unknown(reg->var_off)) { 5317 char tn_buf[48]; 5318 5319 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 5320 verbose(env, "has value %s", tn_buf); 5321 } else { 5322 verbose(env, "has unknown scalar value"); 5323 } 5324 verbose(env, " should have been 0 or 1\n"); 5325 return -EINVAL; 5326 } 5327 return 0; 5328 } 5329 5330 /* non-recursive DFS pseudo code 5331 * 1 procedure DFS-iterative(G,v): 5332 * 2 label v as discovered 5333 * 3 let S be a stack 5334 * 4 S.push(v) 5335 * 5 while S is not empty 5336 * 6 t <- S.pop() 5337 * 7 if t is what we're looking for: 5338 * 8 return t 5339 * 9 for all edges e in G.adjacentEdges(t) do 5340 * 10 if edge e is already labelled 5341 * 11 continue with the next edge 5342 * 12 w <- G.adjacentVertex(t,e) 5343 * 13 if vertex w is not discovered and not explored 5344 * 14 label e as tree-edge 5345 * 15 label w as discovered 5346 * 16 S.push(w) 5347 * 17 continue at 5 5348 * 18 else if vertex w is discovered 5349 * 19 label e as back-edge 5350 * 20 else 5351 * 21 // vertex w is explored 5352 * 22 label e as forward- or cross-edge 5353 * 23 label t as explored 5354 * 24 S.pop() 5355 * 5356 * convention: 5357 * 0x10 - discovered 5358 * 0x11 - discovered and fall-through edge labelled 5359 * 0x12 - discovered and fall-through and branch edges labelled 5360 * 0x20 - explored 5361 */ 5362 5363 enum { 5364 DISCOVERED = 0x10, 5365 EXPLORED = 0x20, 5366 FALLTHROUGH = 1, 5367 BRANCH = 2, 5368 }; 5369 5370 #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L) 5371 5372 static int *insn_stack; /* stack of insns to process */ 5373 static int cur_stack; /* current stack index */ 5374 static int *insn_state; 5375 5376 /* t, w, e - match pseudo-code above: 5377 * t - index of current instruction 5378 * w - next instruction 5379 * e - edge 5380 */ 5381 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 5382 { 5383 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 5384 return 0; 5385 5386 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 5387 return 0; 5388 5389 if (w < 0 || w >= env->prog->len) { 5390 verbose_linfo(env, t, "%d: ", t); 5391 verbose(env, "jump out of range from insn %d to %d\n", t, w); 5392 return -EINVAL; 5393 } 5394 5395 if (e == BRANCH) 5396 /* mark branch target for state pruning */ 5397 env->explored_states[w] = STATE_LIST_MARK; 5398 5399 if (insn_state[w] == 0) { 5400 /* tree-edge */ 5401 insn_state[t] = DISCOVERED | e; 5402 insn_state[w] = DISCOVERED; 5403 if (cur_stack >= env->prog->len) 5404 return -E2BIG; 5405 insn_stack[cur_stack++] = w; 5406 return 1; 5407 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 5408 verbose_linfo(env, t, "%d: ", t); 5409 verbose_linfo(env, w, "%d: ", w); 5410 verbose(env, "back-edge from insn %d to %d\n", t, w); 5411 return -EINVAL; 5412 } else if (insn_state[w] == EXPLORED) { 5413 /* forward- or cross-edge */ 5414 insn_state[t] = DISCOVERED | e; 5415 } else { 5416 verbose(env, "insn state internal bug\n"); 5417 return -EFAULT; 5418 } 5419 return 0; 5420 } 5421 5422 /* non-recursive depth-first-search to detect loops in BPF program 5423 * loop == back-edge in directed graph 5424 */ 5425 static int check_cfg(struct bpf_verifier_env *env) 5426 { 5427 struct bpf_insn *insns = env->prog->insnsi; 5428 int insn_cnt = env->prog->len; 5429 int ret = 0; 5430 int i, t; 5431 5432 insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 5433 if (!insn_state) 5434 return -ENOMEM; 5435 5436 insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 5437 if (!insn_stack) { 5438 kvfree(insn_state); 5439 return -ENOMEM; 5440 } 5441 5442 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 5443 insn_stack[0] = 0; /* 0 is the first instruction */ 5444 cur_stack = 1; 5445 5446 peek_stack: 5447 if (cur_stack == 0) 5448 goto check_state; 5449 t = insn_stack[cur_stack - 1]; 5450 5451 if (BPF_CLASS(insns[t].code) == BPF_JMP || 5452 BPF_CLASS(insns[t].code) == BPF_JMP32) { 5453 u8 opcode = BPF_OP(insns[t].code); 5454 5455 if (opcode == BPF_EXIT) { 5456 goto mark_explored; 5457 } else if (opcode == BPF_CALL) { 5458 ret = push_insn(t, t + 1, FALLTHROUGH, env); 5459 if (ret == 1) 5460 goto peek_stack; 5461 else if (ret < 0) 5462 goto err_free; 5463 if (t + 1 < insn_cnt) 5464 env->explored_states[t + 1] = STATE_LIST_MARK; 5465 if (insns[t].src_reg == BPF_PSEUDO_CALL) { 5466 env->explored_states[t] = STATE_LIST_MARK; 5467 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env); 5468 if (ret == 1) 5469 goto peek_stack; 5470 else if (ret < 0) 5471 goto err_free; 5472 } 5473 } else if (opcode == BPF_JA) { 5474 if (BPF_SRC(insns[t].code) != BPF_K) { 5475 ret = -EINVAL; 5476 goto err_free; 5477 } 5478 /* unconditional jump with single edge */ 5479 ret = push_insn(t, t + insns[t].off + 1, 5480 FALLTHROUGH, env); 5481 if (ret == 1) 5482 goto peek_stack; 5483 else if (ret < 0) 5484 goto err_free; 5485 /* tell verifier to check for equivalent states 5486 * after every call and jump 5487 */ 5488 if (t + 1 < insn_cnt) 5489 env->explored_states[t + 1] = STATE_LIST_MARK; 5490 } else { 5491 /* conditional jump with two edges */ 5492 env->explored_states[t] = STATE_LIST_MARK; 5493 ret = push_insn(t, t + 1, FALLTHROUGH, env); 5494 if (ret == 1) 5495 goto peek_stack; 5496 else if (ret < 0) 5497 goto err_free; 5498 5499 ret = push_insn(t, t + insns[t].off + 1, BRANCH, env); 5500 if (ret == 1) 5501 goto peek_stack; 5502 else if (ret < 0) 5503 goto err_free; 5504 } 5505 } else { 5506 /* all other non-branch instructions with single 5507 * fall-through edge 5508 */ 5509 ret = push_insn(t, t + 1, FALLTHROUGH, env); 5510 if (ret == 1) 5511 goto peek_stack; 5512 else if (ret < 0) 5513 goto err_free; 5514 } 5515 5516 mark_explored: 5517 insn_state[t] = EXPLORED; 5518 if (cur_stack-- <= 0) { 5519 verbose(env, "pop stack internal bug\n"); 5520 ret = -EFAULT; 5521 goto err_free; 5522 } 5523 goto peek_stack; 5524 5525 check_state: 5526 for (i = 0; i < insn_cnt; i++) { 5527 if (insn_state[i] != EXPLORED) { 5528 verbose(env, "unreachable insn %d\n", i); 5529 ret = -EINVAL; 5530 goto err_free; 5531 } 5532 } 5533 ret = 0; /* cfg looks good */ 5534 5535 err_free: 5536 kvfree(insn_state); 5537 kvfree(insn_stack); 5538 return ret; 5539 } 5540 5541 /* The minimum supported BTF func info size */ 5542 #define MIN_BPF_FUNCINFO_SIZE 8 5543 #define MAX_FUNCINFO_REC_SIZE 252 5544 5545 static int check_btf_func(struct bpf_verifier_env *env, 5546 const union bpf_attr *attr, 5547 union bpf_attr __user *uattr) 5548 { 5549 u32 i, nfuncs, urec_size, min_size; 5550 u32 krec_size = sizeof(struct bpf_func_info); 5551 struct bpf_func_info *krecord; 5552 const struct btf_type *type; 5553 struct bpf_prog *prog; 5554 const struct btf *btf; 5555 void __user *urecord; 5556 u32 prev_offset = 0; 5557 int ret = 0; 5558 5559 nfuncs = attr->func_info_cnt; 5560 if (!nfuncs) 5561 return 0; 5562 5563 if (nfuncs != env->subprog_cnt) { 5564 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 5565 return -EINVAL; 5566 } 5567 5568 urec_size = attr->func_info_rec_size; 5569 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 5570 urec_size > MAX_FUNCINFO_REC_SIZE || 5571 urec_size % sizeof(u32)) { 5572 verbose(env, "invalid func info rec size %u\n", urec_size); 5573 return -EINVAL; 5574 } 5575 5576 prog = env->prog; 5577 btf = prog->aux->btf; 5578 5579 urecord = u64_to_user_ptr(attr->func_info); 5580 min_size = min_t(u32, krec_size, urec_size); 5581 5582 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 5583 if (!krecord) 5584 return -ENOMEM; 5585 5586 for (i = 0; i < nfuncs; i++) { 5587 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 5588 if (ret) { 5589 if (ret == -E2BIG) { 5590 verbose(env, "nonzero tailing record in func info"); 5591 /* set the size kernel expects so loader can zero 5592 * out the rest of the record. 5593 */ 5594 if (put_user(min_size, &uattr->func_info_rec_size)) 5595 ret = -EFAULT; 5596 } 5597 goto err_free; 5598 } 5599 5600 if (copy_from_user(&krecord[i], urecord, min_size)) { 5601 ret = -EFAULT; 5602 goto err_free; 5603 } 5604 5605 /* check insn_off */ 5606 if (i == 0) { 5607 if (krecord[i].insn_off) { 5608 verbose(env, 5609 "nonzero insn_off %u for the first func info record", 5610 krecord[i].insn_off); 5611 ret = -EINVAL; 5612 goto err_free; 5613 } 5614 } else if (krecord[i].insn_off <= prev_offset) { 5615 verbose(env, 5616 "same or smaller insn offset (%u) than previous func info record (%u)", 5617 krecord[i].insn_off, prev_offset); 5618 ret = -EINVAL; 5619 goto err_free; 5620 } 5621 5622 if (env->subprog_info[i].start != krecord[i].insn_off) { 5623 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 5624 ret = -EINVAL; 5625 goto err_free; 5626 } 5627 5628 /* check type_id */ 5629 type = btf_type_by_id(btf, krecord[i].type_id); 5630 if (!type || BTF_INFO_KIND(type->info) != BTF_KIND_FUNC) { 5631 verbose(env, "invalid type id %d in func info", 5632 krecord[i].type_id); 5633 ret = -EINVAL; 5634 goto err_free; 5635 } 5636 5637 prev_offset = krecord[i].insn_off; 5638 urecord += urec_size; 5639 } 5640 5641 prog->aux->func_info = krecord; 5642 prog->aux->func_info_cnt = nfuncs; 5643 return 0; 5644 5645 err_free: 5646 kvfree(krecord); 5647 return ret; 5648 } 5649 5650 static void adjust_btf_func(struct bpf_verifier_env *env) 5651 { 5652 int i; 5653 5654 if (!env->prog->aux->func_info) 5655 return; 5656 5657 for (i = 0; i < env->subprog_cnt; i++) 5658 env->prog->aux->func_info[i].insn_off = env->subprog_info[i].start; 5659 } 5660 5661 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \ 5662 sizeof(((struct bpf_line_info *)(0))->line_col)) 5663 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 5664 5665 static int check_btf_line(struct bpf_verifier_env *env, 5666 const union bpf_attr *attr, 5667 union bpf_attr __user *uattr) 5668 { 5669 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 5670 struct bpf_subprog_info *sub; 5671 struct bpf_line_info *linfo; 5672 struct bpf_prog *prog; 5673 const struct btf *btf; 5674 void __user *ulinfo; 5675 int err; 5676 5677 nr_linfo = attr->line_info_cnt; 5678 if (!nr_linfo) 5679 return 0; 5680 5681 rec_size = attr->line_info_rec_size; 5682 if (rec_size < MIN_BPF_LINEINFO_SIZE || 5683 rec_size > MAX_LINEINFO_REC_SIZE || 5684 rec_size & (sizeof(u32) - 1)) 5685 return -EINVAL; 5686 5687 /* Need to zero it in case the userspace may 5688 * pass in a smaller bpf_line_info object. 5689 */ 5690 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 5691 GFP_KERNEL | __GFP_NOWARN); 5692 if (!linfo) 5693 return -ENOMEM; 5694 5695 prog = env->prog; 5696 btf = prog->aux->btf; 5697 5698 s = 0; 5699 sub = env->subprog_info; 5700 ulinfo = u64_to_user_ptr(attr->line_info); 5701 expected_size = sizeof(struct bpf_line_info); 5702 ncopy = min_t(u32, expected_size, rec_size); 5703 for (i = 0; i < nr_linfo; i++) { 5704 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 5705 if (err) { 5706 if (err == -E2BIG) { 5707 verbose(env, "nonzero tailing record in line_info"); 5708 if (put_user(expected_size, 5709 &uattr->line_info_rec_size)) 5710 err = -EFAULT; 5711 } 5712 goto err_free; 5713 } 5714 5715 if (copy_from_user(&linfo[i], ulinfo, ncopy)) { 5716 err = -EFAULT; 5717 goto err_free; 5718 } 5719 5720 /* 5721 * Check insn_off to ensure 5722 * 1) strictly increasing AND 5723 * 2) bounded by prog->len 5724 * 5725 * The linfo[0].insn_off == 0 check logically falls into 5726 * the later "missing bpf_line_info for func..." case 5727 * because the first linfo[0].insn_off must be the 5728 * first sub also and the first sub must have 5729 * subprog_info[0].start == 0. 5730 */ 5731 if ((i && linfo[i].insn_off <= prev_offset) || 5732 linfo[i].insn_off >= prog->len) { 5733 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 5734 i, linfo[i].insn_off, prev_offset, 5735 prog->len); 5736 err = -EINVAL; 5737 goto err_free; 5738 } 5739 5740 if (!prog->insnsi[linfo[i].insn_off].code) { 5741 verbose(env, 5742 "Invalid insn code at line_info[%u].insn_off\n", 5743 i); 5744 err = -EINVAL; 5745 goto err_free; 5746 } 5747 5748 if (!btf_name_by_offset(btf, linfo[i].line_off) || 5749 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 5750 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 5751 err = -EINVAL; 5752 goto err_free; 5753 } 5754 5755 if (s != env->subprog_cnt) { 5756 if (linfo[i].insn_off == sub[s].start) { 5757 sub[s].linfo_idx = i; 5758 s++; 5759 } else if (sub[s].start < linfo[i].insn_off) { 5760 verbose(env, "missing bpf_line_info for func#%u\n", s); 5761 err = -EINVAL; 5762 goto err_free; 5763 } 5764 } 5765 5766 prev_offset = linfo[i].insn_off; 5767 ulinfo += rec_size; 5768 } 5769 5770 if (s != env->subprog_cnt) { 5771 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 5772 env->subprog_cnt - s, s); 5773 err = -EINVAL; 5774 goto err_free; 5775 } 5776 5777 prog->aux->linfo = linfo; 5778 prog->aux->nr_linfo = nr_linfo; 5779 5780 return 0; 5781 5782 err_free: 5783 kvfree(linfo); 5784 return err; 5785 } 5786 5787 static int check_btf_info(struct bpf_verifier_env *env, 5788 const union bpf_attr *attr, 5789 union bpf_attr __user *uattr) 5790 { 5791 struct btf *btf; 5792 int err; 5793 5794 if (!attr->func_info_cnt && !attr->line_info_cnt) 5795 return 0; 5796 5797 btf = btf_get_by_fd(attr->prog_btf_fd); 5798 if (IS_ERR(btf)) 5799 return PTR_ERR(btf); 5800 env->prog->aux->btf = btf; 5801 5802 err = check_btf_func(env, attr, uattr); 5803 if (err) 5804 return err; 5805 5806 err = check_btf_line(env, attr, uattr); 5807 if (err) 5808 return err; 5809 5810 return 0; 5811 } 5812 5813 /* check %cur's range satisfies %old's */ 5814 static bool range_within(struct bpf_reg_state *old, 5815 struct bpf_reg_state *cur) 5816 { 5817 return old->umin_value <= cur->umin_value && 5818 old->umax_value >= cur->umax_value && 5819 old->smin_value <= cur->smin_value && 5820 old->smax_value >= cur->smax_value; 5821 } 5822 5823 /* Maximum number of register states that can exist at once */ 5824 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) 5825 struct idpair { 5826 u32 old; 5827 u32 cur; 5828 }; 5829 5830 /* If in the old state two registers had the same id, then they need to have 5831 * the same id in the new state as well. But that id could be different from 5832 * the old state, so we need to track the mapping from old to new ids. 5833 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 5834 * regs with old id 5 must also have new id 9 for the new state to be safe. But 5835 * regs with a different old id could still have new id 9, we don't care about 5836 * that. 5837 * So we look through our idmap to see if this old id has been seen before. If 5838 * so, we require the new id to match; otherwise, we add the id pair to the map. 5839 */ 5840 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) 5841 { 5842 unsigned int i; 5843 5844 for (i = 0; i < ID_MAP_SIZE; i++) { 5845 if (!idmap[i].old) { 5846 /* Reached an empty slot; haven't seen this id before */ 5847 idmap[i].old = old_id; 5848 idmap[i].cur = cur_id; 5849 return true; 5850 } 5851 if (idmap[i].old == old_id) 5852 return idmap[i].cur == cur_id; 5853 } 5854 /* We ran out of idmap slots, which should be impossible */ 5855 WARN_ON_ONCE(1); 5856 return false; 5857 } 5858 5859 static void clean_func_state(struct bpf_verifier_env *env, 5860 struct bpf_func_state *st) 5861 { 5862 enum bpf_reg_liveness live; 5863 int i, j; 5864 5865 for (i = 0; i < BPF_REG_FP; i++) { 5866 live = st->regs[i].live; 5867 /* liveness must not touch this register anymore */ 5868 st->regs[i].live |= REG_LIVE_DONE; 5869 if (!(live & REG_LIVE_READ)) 5870 /* since the register is unused, clear its state 5871 * to make further comparison simpler 5872 */ 5873 __mark_reg_not_init(&st->regs[i]); 5874 } 5875 5876 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 5877 live = st->stack[i].spilled_ptr.live; 5878 /* liveness must not touch this stack slot anymore */ 5879 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 5880 if (!(live & REG_LIVE_READ)) { 5881 __mark_reg_not_init(&st->stack[i].spilled_ptr); 5882 for (j = 0; j < BPF_REG_SIZE; j++) 5883 st->stack[i].slot_type[j] = STACK_INVALID; 5884 } 5885 } 5886 } 5887 5888 static void clean_verifier_state(struct bpf_verifier_env *env, 5889 struct bpf_verifier_state *st) 5890 { 5891 int i; 5892 5893 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 5894 /* all regs in this state in all frames were already marked */ 5895 return; 5896 5897 for (i = 0; i <= st->curframe; i++) 5898 clean_func_state(env, st->frame[i]); 5899 } 5900 5901 /* the parentage chains form a tree. 5902 * the verifier states are added to state lists at given insn and 5903 * pushed into state stack for future exploration. 5904 * when the verifier reaches bpf_exit insn some of the verifer states 5905 * stored in the state lists have their final liveness state already, 5906 * but a lot of states will get revised from liveness point of view when 5907 * the verifier explores other branches. 5908 * Example: 5909 * 1: r0 = 1 5910 * 2: if r1 == 100 goto pc+1 5911 * 3: r0 = 2 5912 * 4: exit 5913 * when the verifier reaches exit insn the register r0 in the state list of 5914 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 5915 * of insn 2 and goes exploring further. At the insn 4 it will walk the 5916 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 5917 * 5918 * Since the verifier pushes the branch states as it sees them while exploring 5919 * the program the condition of walking the branch instruction for the second 5920 * time means that all states below this branch were already explored and 5921 * their final liveness markes are already propagated. 5922 * Hence when the verifier completes the search of state list in is_state_visited() 5923 * we can call this clean_live_states() function to mark all liveness states 5924 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 5925 * will not be used. 5926 * This function also clears the registers and stack for states that !READ 5927 * to simplify state merging. 5928 * 5929 * Important note here that walking the same branch instruction in the callee 5930 * doesn't meant that the states are DONE. The verifier has to compare 5931 * the callsites 5932 */ 5933 static void clean_live_states(struct bpf_verifier_env *env, int insn, 5934 struct bpf_verifier_state *cur) 5935 { 5936 struct bpf_verifier_state_list *sl; 5937 int i; 5938 5939 sl = env->explored_states[insn]; 5940 if (!sl) 5941 return; 5942 5943 while (sl != STATE_LIST_MARK) { 5944 if (sl->state.curframe != cur->curframe) 5945 goto next; 5946 for (i = 0; i <= cur->curframe; i++) 5947 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 5948 goto next; 5949 clean_verifier_state(env, &sl->state); 5950 next: 5951 sl = sl->next; 5952 } 5953 } 5954 5955 /* Returns true if (rold safe implies rcur safe) */ 5956 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 5957 struct idpair *idmap) 5958 { 5959 bool equal; 5960 5961 if (!(rold->live & REG_LIVE_READ)) 5962 /* explored state didn't use this */ 5963 return true; 5964 5965 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0; 5966 5967 if (rold->type == PTR_TO_STACK) 5968 /* two stack pointers are equal only if they're pointing to 5969 * the same stack frame, since fp-8 in foo != fp-8 in bar 5970 */ 5971 return equal && rold->frameno == rcur->frameno; 5972 5973 if (equal) 5974 return true; 5975 5976 if (rold->type == NOT_INIT) 5977 /* explored state can't have used this */ 5978 return true; 5979 if (rcur->type == NOT_INIT) 5980 return false; 5981 switch (rold->type) { 5982 case SCALAR_VALUE: 5983 if (rcur->type == SCALAR_VALUE) { 5984 /* new val must satisfy old val knowledge */ 5985 return range_within(rold, rcur) && 5986 tnum_in(rold->var_off, rcur->var_off); 5987 } else { 5988 /* We're trying to use a pointer in place of a scalar. 5989 * Even if the scalar was unbounded, this could lead to 5990 * pointer leaks because scalars are allowed to leak 5991 * while pointers are not. We could make this safe in 5992 * special cases if root is calling us, but it's 5993 * probably not worth the hassle. 5994 */ 5995 return false; 5996 } 5997 case PTR_TO_MAP_VALUE: 5998 /* If the new min/max/var_off satisfy the old ones and 5999 * everything else matches, we are OK. 6000 * 'id' is not compared, since it's only used for maps with 6001 * bpf_spin_lock inside map element and in such cases if 6002 * the rest of the prog is valid for one map element then 6003 * it's valid for all map elements regardless of the key 6004 * used in bpf_map_lookup() 6005 */ 6006 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 6007 range_within(rold, rcur) && 6008 tnum_in(rold->var_off, rcur->var_off); 6009 case PTR_TO_MAP_VALUE_OR_NULL: 6010 /* a PTR_TO_MAP_VALUE could be safe to use as a 6011 * PTR_TO_MAP_VALUE_OR_NULL into the same map. 6012 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- 6013 * checked, doing so could have affected others with the same 6014 * id, and we can't check for that because we lost the id when 6015 * we converted to a PTR_TO_MAP_VALUE. 6016 */ 6017 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) 6018 return false; 6019 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) 6020 return false; 6021 /* Check our ids match any regs they're supposed to */ 6022 return check_ids(rold->id, rcur->id, idmap); 6023 case PTR_TO_PACKET_META: 6024 case PTR_TO_PACKET: 6025 if (rcur->type != rold->type) 6026 return false; 6027 /* We must have at least as much range as the old ptr 6028 * did, so that any accesses which were safe before are 6029 * still safe. This is true even if old range < old off, 6030 * since someone could have accessed through (ptr - k), or 6031 * even done ptr -= k in a register, to get a safe access. 6032 */ 6033 if (rold->range > rcur->range) 6034 return false; 6035 /* If the offsets don't match, we can't trust our alignment; 6036 * nor can we be sure that we won't fall out of range. 6037 */ 6038 if (rold->off != rcur->off) 6039 return false; 6040 /* id relations must be preserved */ 6041 if (rold->id && !check_ids(rold->id, rcur->id, idmap)) 6042 return false; 6043 /* new val must satisfy old val knowledge */ 6044 return range_within(rold, rcur) && 6045 tnum_in(rold->var_off, rcur->var_off); 6046 case PTR_TO_CTX: 6047 case CONST_PTR_TO_MAP: 6048 case PTR_TO_PACKET_END: 6049 case PTR_TO_FLOW_KEYS: 6050 case PTR_TO_SOCKET: 6051 case PTR_TO_SOCKET_OR_NULL: 6052 case PTR_TO_SOCK_COMMON: 6053 case PTR_TO_SOCK_COMMON_OR_NULL: 6054 case PTR_TO_TCP_SOCK: 6055 case PTR_TO_TCP_SOCK_OR_NULL: 6056 /* Only valid matches are exact, which memcmp() above 6057 * would have accepted 6058 */ 6059 default: 6060 /* Don't know what's going on, just say it's not safe */ 6061 return false; 6062 } 6063 6064 /* Shouldn't get here; if we do, say it's not safe */ 6065 WARN_ON_ONCE(1); 6066 return false; 6067 } 6068 6069 static bool stacksafe(struct bpf_func_state *old, 6070 struct bpf_func_state *cur, 6071 struct idpair *idmap) 6072 { 6073 int i, spi; 6074 6075 /* walk slots of the explored stack and ignore any additional 6076 * slots in the current stack, since explored(safe) state 6077 * didn't use them 6078 */ 6079 for (i = 0; i < old->allocated_stack; i++) { 6080 spi = i / BPF_REG_SIZE; 6081 6082 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 6083 i += BPF_REG_SIZE - 1; 6084 /* explored state didn't use this */ 6085 continue; 6086 } 6087 6088 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 6089 continue; 6090 6091 /* explored stack has more populated slots than current stack 6092 * and these slots were used 6093 */ 6094 if (i >= cur->allocated_stack) 6095 return false; 6096 6097 /* if old state was safe with misc data in the stack 6098 * it will be safe with zero-initialized stack. 6099 * The opposite is not true 6100 */ 6101 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 6102 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 6103 continue; 6104 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 6105 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 6106 /* Ex: old explored (safe) state has STACK_SPILL in 6107 * this stack slot, but current has has STACK_MISC -> 6108 * this verifier states are not equivalent, 6109 * return false to continue verification of this path 6110 */ 6111 return false; 6112 if (i % BPF_REG_SIZE) 6113 continue; 6114 if (old->stack[spi].slot_type[0] != STACK_SPILL) 6115 continue; 6116 if (!regsafe(&old->stack[spi].spilled_ptr, 6117 &cur->stack[spi].spilled_ptr, 6118 idmap)) 6119 /* when explored and current stack slot are both storing 6120 * spilled registers, check that stored pointers types 6121 * are the same as well. 6122 * Ex: explored safe path could have stored 6123 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 6124 * but current path has stored: 6125 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 6126 * such verifier states are not equivalent. 6127 * return false to continue verification of this path 6128 */ 6129 return false; 6130 } 6131 return true; 6132 } 6133 6134 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur) 6135 { 6136 if (old->acquired_refs != cur->acquired_refs) 6137 return false; 6138 return !memcmp(old->refs, cur->refs, 6139 sizeof(*old->refs) * old->acquired_refs); 6140 } 6141 6142 /* compare two verifier states 6143 * 6144 * all states stored in state_list are known to be valid, since 6145 * verifier reached 'bpf_exit' instruction through them 6146 * 6147 * this function is called when verifier exploring different branches of 6148 * execution popped from the state stack. If it sees an old state that has 6149 * more strict register state and more strict stack state then this execution 6150 * branch doesn't need to be explored further, since verifier already 6151 * concluded that more strict state leads to valid finish. 6152 * 6153 * Therefore two states are equivalent if register state is more conservative 6154 * and explored stack state is more conservative than the current one. 6155 * Example: 6156 * explored current 6157 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 6158 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 6159 * 6160 * In other words if current stack state (one being explored) has more 6161 * valid slots than old one that already passed validation, it means 6162 * the verifier can stop exploring and conclude that current state is valid too 6163 * 6164 * Similarly with registers. If explored state has register type as invalid 6165 * whereas register type in current state is meaningful, it means that 6166 * the current state will reach 'bpf_exit' instruction safely 6167 */ 6168 static bool func_states_equal(struct bpf_func_state *old, 6169 struct bpf_func_state *cur) 6170 { 6171 struct idpair *idmap; 6172 bool ret = false; 6173 int i; 6174 6175 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); 6176 /* If we failed to allocate the idmap, just say it's not safe */ 6177 if (!idmap) 6178 return false; 6179 6180 for (i = 0; i < MAX_BPF_REG; i++) { 6181 if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) 6182 goto out_free; 6183 } 6184 6185 if (!stacksafe(old, cur, idmap)) 6186 goto out_free; 6187 6188 if (!refsafe(old, cur)) 6189 goto out_free; 6190 ret = true; 6191 out_free: 6192 kfree(idmap); 6193 return ret; 6194 } 6195 6196 static bool states_equal(struct bpf_verifier_env *env, 6197 struct bpf_verifier_state *old, 6198 struct bpf_verifier_state *cur) 6199 { 6200 int i; 6201 6202 if (old->curframe != cur->curframe) 6203 return false; 6204 6205 /* Verification state from speculative execution simulation 6206 * must never prune a non-speculative execution one. 6207 */ 6208 if (old->speculative && !cur->speculative) 6209 return false; 6210 6211 if (old->active_spin_lock != cur->active_spin_lock) 6212 return false; 6213 6214 /* for states to be equal callsites have to be the same 6215 * and all frame states need to be equivalent 6216 */ 6217 for (i = 0; i <= old->curframe; i++) { 6218 if (old->frame[i]->callsite != cur->frame[i]->callsite) 6219 return false; 6220 if (!func_states_equal(old->frame[i], cur->frame[i])) 6221 return false; 6222 } 6223 return true; 6224 } 6225 6226 static int propagate_liveness_reg(struct bpf_verifier_env *env, 6227 struct bpf_reg_state *reg, 6228 struct bpf_reg_state *parent_reg) 6229 { 6230 int err; 6231 6232 if (parent_reg->live & REG_LIVE_READ || !(reg->live & REG_LIVE_READ)) 6233 return 0; 6234 6235 err = mark_reg_read(env, reg, parent_reg); 6236 if (err) 6237 return err; 6238 6239 return 0; 6240 } 6241 6242 /* A write screens off any subsequent reads; but write marks come from the 6243 * straight-line code between a state and its parent. When we arrive at an 6244 * equivalent state (jump target or such) we didn't arrive by the straight-line 6245 * code, so read marks in the state must propagate to the parent regardless 6246 * of the state's write marks. That's what 'parent == state->parent' comparison 6247 * in mark_reg_read() is for. 6248 */ 6249 static int propagate_liveness(struct bpf_verifier_env *env, 6250 const struct bpf_verifier_state *vstate, 6251 struct bpf_verifier_state *vparent) 6252 { 6253 struct bpf_reg_state *state_reg, *parent_reg; 6254 struct bpf_func_state *state, *parent; 6255 int i, frame, err = 0; 6256 6257 if (vparent->curframe != vstate->curframe) { 6258 WARN(1, "propagate_live: parent frame %d current frame %d\n", 6259 vparent->curframe, vstate->curframe); 6260 return -EFAULT; 6261 } 6262 /* Propagate read liveness of registers... */ 6263 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 6264 for (frame = 0; frame <= vstate->curframe; frame++) { 6265 parent = vparent->frame[frame]; 6266 state = vstate->frame[frame]; 6267 parent_reg = parent->regs; 6268 state_reg = state->regs; 6269 /* We don't need to worry about FP liveness, it's read-only */ 6270 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 6271 err = propagate_liveness_reg(env, &state_reg[i], 6272 &parent_reg[i]); 6273 if (err) 6274 return err; 6275 } 6276 6277 /* Propagate stack slots. */ 6278 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 6279 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 6280 parent_reg = &parent->stack[i].spilled_ptr; 6281 state_reg = &state->stack[i].spilled_ptr; 6282 err = propagate_liveness_reg(env, state_reg, 6283 parent_reg); 6284 if (err) 6285 return err; 6286 } 6287 } 6288 return err; 6289 } 6290 6291 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 6292 { 6293 struct bpf_verifier_state_list *new_sl; 6294 struct bpf_verifier_state_list *sl, **pprev; 6295 struct bpf_verifier_state *cur = env->cur_state, *new; 6296 int i, j, err, states_cnt = 0; 6297 6298 pprev = &env->explored_states[insn_idx]; 6299 sl = *pprev; 6300 6301 if (!sl) 6302 /* this 'insn_idx' instruction wasn't marked, so we will not 6303 * be doing state search here 6304 */ 6305 return 0; 6306 6307 clean_live_states(env, insn_idx, cur); 6308 6309 while (sl != STATE_LIST_MARK) { 6310 if (states_equal(env, &sl->state, cur)) { 6311 sl->hit_cnt++; 6312 /* reached equivalent register/stack state, 6313 * prune the search. 6314 * Registers read by the continuation are read by us. 6315 * If we have any write marks in env->cur_state, they 6316 * will prevent corresponding reads in the continuation 6317 * from reaching our parent (an explored_state). Our 6318 * own state will get the read marks recorded, but 6319 * they'll be immediately forgotten as we're pruning 6320 * this state and will pop a new one. 6321 */ 6322 err = propagate_liveness(env, &sl->state, cur); 6323 if (err) 6324 return err; 6325 return 1; 6326 } 6327 states_cnt++; 6328 sl->miss_cnt++; 6329 /* heuristic to determine whether this state is beneficial 6330 * to keep checking from state equivalence point of view. 6331 * Higher numbers increase max_states_per_insn and verification time, 6332 * but do not meaningfully decrease insn_processed. 6333 */ 6334 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 6335 /* the state is unlikely to be useful. Remove it to 6336 * speed up verification 6337 */ 6338 *pprev = sl->next; 6339 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 6340 free_verifier_state(&sl->state, false); 6341 kfree(sl); 6342 env->peak_states--; 6343 } else { 6344 /* cannot free this state, since parentage chain may 6345 * walk it later. Add it for free_list instead to 6346 * be freed at the end of verification 6347 */ 6348 sl->next = env->free_list; 6349 env->free_list = sl; 6350 } 6351 sl = *pprev; 6352 continue; 6353 } 6354 pprev = &sl->next; 6355 sl = *pprev; 6356 } 6357 6358 if (env->max_states_per_insn < states_cnt) 6359 env->max_states_per_insn = states_cnt; 6360 6361 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 6362 return 0; 6363 6364 /* there were no equivalent states, remember current one. 6365 * technically the current state is not proven to be safe yet, 6366 * but it will either reach outer most bpf_exit (which means it's safe) 6367 * or it will be rejected. Since there are no loops, we won't be 6368 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 6369 * again on the way to bpf_exit 6370 */ 6371 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 6372 if (!new_sl) 6373 return -ENOMEM; 6374 env->total_states++; 6375 env->peak_states++; 6376 6377 /* add new state to the head of linked list */ 6378 new = &new_sl->state; 6379 err = copy_verifier_state(new, cur); 6380 if (err) { 6381 free_verifier_state(new, false); 6382 kfree(new_sl); 6383 return err; 6384 } 6385 new_sl->next = env->explored_states[insn_idx]; 6386 env->explored_states[insn_idx] = new_sl; 6387 /* connect new state to parentage chain. Current frame needs all 6388 * registers connected. Only r6 - r9 of the callers are alive (pushed 6389 * to the stack implicitly by JITs) so in callers' frames connect just 6390 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 6391 * the state of the call instruction (with WRITTEN set), and r0 comes 6392 * from callee with its full parentage chain, anyway. 6393 */ 6394 for (j = 0; j <= cur->curframe; j++) 6395 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 6396 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 6397 /* clear write marks in current state: the writes we did are not writes 6398 * our child did, so they don't screen off its reads from us. 6399 * (There are no read marks in current state, because reads always mark 6400 * their parent and current state never has children yet. Only 6401 * explored_states can get read marks.) 6402 */ 6403 for (i = 0; i < BPF_REG_FP; i++) 6404 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE; 6405 6406 /* all stack frames are accessible from callee, clear them all */ 6407 for (j = 0; j <= cur->curframe; j++) { 6408 struct bpf_func_state *frame = cur->frame[j]; 6409 struct bpf_func_state *newframe = new->frame[j]; 6410 6411 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 6412 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 6413 frame->stack[i].spilled_ptr.parent = 6414 &newframe->stack[i].spilled_ptr; 6415 } 6416 } 6417 return 0; 6418 } 6419 6420 /* Return true if it's OK to have the same insn return a different type. */ 6421 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 6422 { 6423 switch (type) { 6424 case PTR_TO_CTX: 6425 case PTR_TO_SOCKET: 6426 case PTR_TO_SOCKET_OR_NULL: 6427 case PTR_TO_SOCK_COMMON: 6428 case PTR_TO_SOCK_COMMON_OR_NULL: 6429 case PTR_TO_TCP_SOCK: 6430 case PTR_TO_TCP_SOCK_OR_NULL: 6431 return false; 6432 default: 6433 return true; 6434 } 6435 } 6436 6437 /* If an instruction was previously used with particular pointer types, then we 6438 * need to be careful to avoid cases such as the below, where it may be ok 6439 * for one branch accessing the pointer, but not ok for the other branch: 6440 * 6441 * R1 = sock_ptr 6442 * goto X; 6443 * ... 6444 * R1 = some_other_valid_ptr; 6445 * goto X; 6446 * ... 6447 * R2 = *(u32 *)(R1 + 0); 6448 */ 6449 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 6450 { 6451 return src != prev && (!reg_type_mismatch_ok(src) || 6452 !reg_type_mismatch_ok(prev)); 6453 } 6454 6455 static int do_check(struct bpf_verifier_env *env) 6456 { 6457 struct bpf_verifier_state *state; 6458 struct bpf_insn *insns = env->prog->insnsi; 6459 struct bpf_reg_state *regs; 6460 int insn_cnt = env->prog->len; 6461 bool do_print_state = false; 6462 6463 env->prev_linfo = NULL; 6464 6465 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 6466 if (!state) 6467 return -ENOMEM; 6468 state->curframe = 0; 6469 state->speculative = false; 6470 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 6471 if (!state->frame[0]) { 6472 kfree(state); 6473 return -ENOMEM; 6474 } 6475 env->cur_state = state; 6476 init_func_state(env, state->frame[0], 6477 BPF_MAIN_FUNC /* callsite */, 6478 0 /* frameno */, 6479 0 /* subprogno, zero == main subprog */); 6480 6481 for (;;) { 6482 struct bpf_insn *insn; 6483 u8 class; 6484 int err; 6485 6486 if (env->insn_idx >= insn_cnt) { 6487 verbose(env, "invalid insn idx %d insn_cnt %d\n", 6488 env->insn_idx, insn_cnt); 6489 return -EFAULT; 6490 } 6491 6492 insn = &insns[env->insn_idx]; 6493 class = BPF_CLASS(insn->code); 6494 6495 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 6496 verbose(env, 6497 "BPF program is too large. Processed %d insn\n", 6498 env->insn_processed); 6499 return -E2BIG; 6500 } 6501 6502 err = is_state_visited(env, env->insn_idx); 6503 if (err < 0) 6504 return err; 6505 if (err == 1) { 6506 /* found equivalent state, can prune the search */ 6507 if (env->log.level & BPF_LOG_LEVEL) { 6508 if (do_print_state) 6509 verbose(env, "\nfrom %d to %d%s: safe\n", 6510 env->prev_insn_idx, env->insn_idx, 6511 env->cur_state->speculative ? 6512 " (speculative execution)" : ""); 6513 else 6514 verbose(env, "%d: safe\n", env->insn_idx); 6515 } 6516 goto process_bpf_exit; 6517 } 6518 6519 if (signal_pending(current)) 6520 return -EAGAIN; 6521 6522 if (need_resched()) 6523 cond_resched(); 6524 6525 if (env->log.level & BPF_LOG_LEVEL2 || 6526 (env->log.level & BPF_LOG_LEVEL && do_print_state)) { 6527 if (env->log.level & BPF_LOG_LEVEL2) 6528 verbose(env, "%d:", env->insn_idx); 6529 else 6530 verbose(env, "\nfrom %d to %d%s:", 6531 env->prev_insn_idx, env->insn_idx, 6532 env->cur_state->speculative ? 6533 " (speculative execution)" : ""); 6534 print_verifier_state(env, state->frame[state->curframe]); 6535 do_print_state = false; 6536 } 6537 6538 if (env->log.level & BPF_LOG_LEVEL) { 6539 const struct bpf_insn_cbs cbs = { 6540 .cb_print = verbose, 6541 .private_data = env, 6542 }; 6543 6544 verbose_linfo(env, env->insn_idx, "; "); 6545 verbose(env, "%d: ", env->insn_idx); 6546 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 6547 } 6548 6549 if (bpf_prog_is_dev_bound(env->prog->aux)) { 6550 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 6551 env->prev_insn_idx); 6552 if (err) 6553 return err; 6554 } 6555 6556 regs = cur_regs(env); 6557 env->insn_aux_data[env->insn_idx].seen = true; 6558 6559 if (class == BPF_ALU || class == BPF_ALU64) { 6560 err = check_alu_op(env, insn); 6561 if (err) 6562 return err; 6563 6564 } else if (class == BPF_LDX) { 6565 enum bpf_reg_type *prev_src_type, src_reg_type; 6566 6567 /* check for reserved fields is already done */ 6568 6569 /* check src operand */ 6570 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6571 if (err) 6572 return err; 6573 6574 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6575 if (err) 6576 return err; 6577 6578 src_reg_type = regs[insn->src_reg].type; 6579 6580 /* check that memory (src_reg + off) is readable, 6581 * the state of dst_reg will be updated by this func 6582 */ 6583 err = check_mem_access(env, env->insn_idx, insn->src_reg, 6584 insn->off, BPF_SIZE(insn->code), 6585 BPF_READ, insn->dst_reg, false); 6586 if (err) 6587 return err; 6588 6589 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 6590 6591 if (*prev_src_type == NOT_INIT) { 6592 /* saw a valid insn 6593 * dst_reg = *(u32 *)(src_reg + off) 6594 * save type to validate intersecting paths 6595 */ 6596 *prev_src_type = src_reg_type; 6597 6598 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 6599 /* ABuser program is trying to use the same insn 6600 * dst_reg = *(u32*) (src_reg + off) 6601 * with different pointer types: 6602 * src_reg == ctx in one branch and 6603 * src_reg == stack|map in some other branch. 6604 * Reject it. 6605 */ 6606 verbose(env, "same insn cannot be used with different pointers\n"); 6607 return -EINVAL; 6608 } 6609 6610 } else if (class == BPF_STX) { 6611 enum bpf_reg_type *prev_dst_type, dst_reg_type; 6612 6613 if (BPF_MODE(insn->code) == BPF_XADD) { 6614 err = check_xadd(env, env->insn_idx, insn); 6615 if (err) 6616 return err; 6617 env->insn_idx++; 6618 continue; 6619 } 6620 6621 /* check src1 operand */ 6622 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6623 if (err) 6624 return err; 6625 /* check src2 operand */ 6626 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6627 if (err) 6628 return err; 6629 6630 dst_reg_type = regs[insn->dst_reg].type; 6631 6632 /* check that memory (dst_reg + off) is writeable */ 6633 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 6634 insn->off, BPF_SIZE(insn->code), 6635 BPF_WRITE, insn->src_reg, false); 6636 if (err) 6637 return err; 6638 6639 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 6640 6641 if (*prev_dst_type == NOT_INIT) { 6642 *prev_dst_type = dst_reg_type; 6643 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 6644 verbose(env, "same insn cannot be used with different pointers\n"); 6645 return -EINVAL; 6646 } 6647 6648 } else if (class == BPF_ST) { 6649 if (BPF_MODE(insn->code) != BPF_MEM || 6650 insn->src_reg != BPF_REG_0) { 6651 verbose(env, "BPF_ST uses reserved fields\n"); 6652 return -EINVAL; 6653 } 6654 /* check src operand */ 6655 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6656 if (err) 6657 return err; 6658 6659 if (is_ctx_reg(env, insn->dst_reg)) { 6660 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 6661 insn->dst_reg, 6662 reg_type_str[reg_state(env, insn->dst_reg)->type]); 6663 return -EACCES; 6664 } 6665 6666 /* check that memory (dst_reg + off) is writeable */ 6667 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 6668 insn->off, BPF_SIZE(insn->code), 6669 BPF_WRITE, -1, false); 6670 if (err) 6671 return err; 6672 6673 } else if (class == BPF_JMP || class == BPF_JMP32) { 6674 u8 opcode = BPF_OP(insn->code); 6675 6676 if (opcode == BPF_CALL) { 6677 if (BPF_SRC(insn->code) != BPF_K || 6678 insn->off != 0 || 6679 (insn->src_reg != BPF_REG_0 && 6680 insn->src_reg != BPF_PSEUDO_CALL) || 6681 insn->dst_reg != BPF_REG_0 || 6682 class == BPF_JMP32) { 6683 verbose(env, "BPF_CALL uses reserved fields\n"); 6684 return -EINVAL; 6685 } 6686 6687 if (env->cur_state->active_spin_lock && 6688 (insn->src_reg == BPF_PSEUDO_CALL || 6689 insn->imm != BPF_FUNC_spin_unlock)) { 6690 verbose(env, "function calls are not allowed while holding a lock\n"); 6691 return -EINVAL; 6692 } 6693 if (insn->src_reg == BPF_PSEUDO_CALL) 6694 err = check_func_call(env, insn, &env->insn_idx); 6695 else 6696 err = check_helper_call(env, insn->imm, env->insn_idx); 6697 if (err) 6698 return err; 6699 6700 } else if (opcode == BPF_JA) { 6701 if (BPF_SRC(insn->code) != BPF_K || 6702 insn->imm != 0 || 6703 insn->src_reg != BPF_REG_0 || 6704 insn->dst_reg != BPF_REG_0 || 6705 class == BPF_JMP32) { 6706 verbose(env, "BPF_JA uses reserved fields\n"); 6707 return -EINVAL; 6708 } 6709 6710 env->insn_idx += insn->off + 1; 6711 continue; 6712 6713 } else if (opcode == BPF_EXIT) { 6714 if (BPF_SRC(insn->code) != BPF_K || 6715 insn->imm != 0 || 6716 insn->src_reg != BPF_REG_0 || 6717 insn->dst_reg != BPF_REG_0 || 6718 class == BPF_JMP32) { 6719 verbose(env, "BPF_EXIT uses reserved fields\n"); 6720 return -EINVAL; 6721 } 6722 6723 if (env->cur_state->active_spin_lock) { 6724 verbose(env, "bpf_spin_unlock is missing\n"); 6725 return -EINVAL; 6726 } 6727 6728 if (state->curframe) { 6729 /* exit from nested function */ 6730 env->prev_insn_idx = env->insn_idx; 6731 err = prepare_func_exit(env, &env->insn_idx); 6732 if (err) 6733 return err; 6734 do_print_state = true; 6735 continue; 6736 } 6737 6738 err = check_reference_leak(env); 6739 if (err) 6740 return err; 6741 6742 /* eBPF calling convetion is such that R0 is used 6743 * to return the value from eBPF program. 6744 * Make sure that it's readable at this time 6745 * of bpf_exit, which means that program wrote 6746 * something into it earlier 6747 */ 6748 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 6749 if (err) 6750 return err; 6751 6752 if (is_pointer_value(env, BPF_REG_0)) { 6753 verbose(env, "R0 leaks addr as return value\n"); 6754 return -EACCES; 6755 } 6756 6757 err = check_return_code(env); 6758 if (err) 6759 return err; 6760 process_bpf_exit: 6761 err = pop_stack(env, &env->prev_insn_idx, 6762 &env->insn_idx); 6763 if (err < 0) { 6764 if (err != -ENOENT) 6765 return err; 6766 break; 6767 } else { 6768 do_print_state = true; 6769 continue; 6770 } 6771 } else { 6772 err = check_cond_jmp_op(env, insn, &env->insn_idx); 6773 if (err) 6774 return err; 6775 } 6776 } else if (class == BPF_LD) { 6777 u8 mode = BPF_MODE(insn->code); 6778 6779 if (mode == BPF_ABS || mode == BPF_IND) { 6780 err = check_ld_abs(env, insn); 6781 if (err) 6782 return err; 6783 6784 } else if (mode == BPF_IMM) { 6785 err = check_ld_imm(env, insn); 6786 if (err) 6787 return err; 6788 6789 env->insn_idx++; 6790 env->insn_aux_data[env->insn_idx].seen = true; 6791 } else { 6792 verbose(env, "invalid BPF_LD mode\n"); 6793 return -EINVAL; 6794 } 6795 } else { 6796 verbose(env, "unknown insn class %d\n", class); 6797 return -EINVAL; 6798 } 6799 6800 env->insn_idx++; 6801 } 6802 6803 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 6804 return 0; 6805 } 6806 6807 static int check_map_prealloc(struct bpf_map *map) 6808 { 6809 return (map->map_type != BPF_MAP_TYPE_HASH && 6810 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 6811 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || 6812 !(map->map_flags & BPF_F_NO_PREALLOC); 6813 } 6814 6815 static bool is_tracing_prog_type(enum bpf_prog_type type) 6816 { 6817 switch (type) { 6818 case BPF_PROG_TYPE_KPROBE: 6819 case BPF_PROG_TYPE_TRACEPOINT: 6820 case BPF_PROG_TYPE_PERF_EVENT: 6821 case BPF_PROG_TYPE_RAW_TRACEPOINT: 6822 return true; 6823 default: 6824 return false; 6825 } 6826 } 6827 6828 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 6829 struct bpf_map *map, 6830 struct bpf_prog *prog) 6831 6832 { 6833 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use 6834 * preallocated hash maps, since doing memory allocation 6835 * in overflow_handler can crash depending on where nmi got 6836 * triggered. 6837 */ 6838 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) { 6839 if (!check_map_prealloc(map)) { 6840 verbose(env, "perf_event programs can only use preallocated hash map\n"); 6841 return -EINVAL; 6842 } 6843 if (map->inner_map_meta && 6844 !check_map_prealloc(map->inner_map_meta)) { 6845 verbose(env, "perf_event programs can only use preallocated inner hash map\n"); 6846 return -EINVAL; 6847 } 6848 } 6849 6850 if ((is_tracing_prog_type(prog->type) || 6851 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) && 6852 map_value_has_spin_lock(map)) { 6853 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 6854 return -EINVAL; 6855 } 6856 6857 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) && 6858 !bpf_offload_prog_map_match(prog, map)) { 6859 verbose(env, "offload device mismatch between prog and map\n"); 6860 return -EINVAL; 6861 } 6862 6863 return 0; 6864 } 6865 6866 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 6867 { 6868 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 6869 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 6870 } 6871 6872 /* look for pseudo eBPF instructions that access map FDs and 6873 * replace them with actual map pointers 6874 */ 6875 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) 6876 { 6877 struct bpf_insn *insn = env->prog->insnsi; 6878 int insn_cnt = env->prog->len; 6879 int i, j, err; 6880 6881 err = bpf_prog_calc_tag(env->prog); 6882 if (err) 6883 return err; 6884 6885 for (i = 0; i < insn_cnt; i++, insn++) { 6886 if (BPF_CLASS(insn->code) == BPF_LDX && 6887 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 6888 verbose(env, "BPF_LDX uses reserved fields\n"); 6889 return -EINVAL; 6890 } 6891 6892 if (BPF_CLASS(insn->code) == BPF_STX && 6893 ((BPF_MODE(insn->code) != BPF_MEM && 6894 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { 6895 verbose(env, "BPF_STX uses reserved fields\n"); 6896 return -EINVAL; 6897 } 6898 6899 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 6900 struct bpf_insn_aux_data *aux; 6901 struct bpf_map *map; 6902 struct fd f; 6903 u64 addr; 6904 6905 if (i == insn_cnt - 1 || insn[1].code != 0 || 6906 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 6907 insn[1].off != 0) { 6908 verbose(env, "invalid bpf_ld_imm64 insn\n"); 6909 return -EINVAL; 6910 } 6911 6912 if (insn[0].src_reg == 0) 6913 /* valid generic load 64-bit imm */ 6914 goto next_insn; 6915 6916 /* In final convert_pseudo_ld_imm64() step, this is 6917 * converted into regular 64-bit imm load insn. 6918 */ 6919 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD && 6920 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) || 6921 (insn[0].src_reg == BPF_PSEUDO_MAP_FD && 6922 insn[1].imm != 0)) { 6923 verbose(env, 6924 "unrecognized bpf_ld_imm64 insn\n"); 6925 return -EINVAL; 6926 } 6927 6928 f = fdget(insn[0].imm); 6929 map = __bpf_map_get(f); 6930 if (IS_ERR(map)) { 6931 verbose(env, "fd %d is not pointing to valid bpf_map\n", 6932 insn[0].imm); 6933 return PTR_ERR(map); 6934 } 6935 6936 err = check_map_prog_compatibility(env, map, env->prog); 6937 if (err) { 6938 fdput(f); 6939 return err; 6940 } 6941 6942 aux = &env->insn_aux_data[i]; 6943 if (insn->src_reg == BPF_PSEUDO_MAP_FD) { 6944 addr = (unsigned long)map; 6945 } else { 6946 u32 off = insn[1].imm; 6947 6948 if (off >= BPF_MAX_VAR_OFF) { 6949 verbose(env, "direct value offset of %u is not allowed\n", off); 6950 fdput(f); 6951 return -EINVAL; 6952 } 6953 6954 if (!map->ops->map_direct_value_addr) { 6955 verbose(env, "no direct value access support for this map type\n"); 6956 fdput(f); 6957 return -EINVAL; 6958 } 6959 6960 err = map->ops->map_direct_value_addr(map, &addr, off); 6961 if (err) { 6962 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 6963 map->value_size, off); 6964 fdput(f); 6965 return err; 6966 } 6967 6968 aux->map_off = off; 6969 addr += off; 6970 } 6971 6972 insn[0].imm = (u32)addr; 6973 insn[1].imm = addr >> 32; 6974 6975 /* check whether we recorded this map already */ 6976 for (j = 0; j < env->used_map_cnt; j++) { 6977 if (env->used_maps[j] == map) { 6978 aux->map_index = j; 6979 fdput(f); 6980 goto next_insn; 6981 } 6982 } 6983 6984 if (env->used_map_cnt >= MAX_USED_MAPS) { 6985 fdput(f); 6986 return -E2BIG; 6987 } 6988 6989 /* hold the map. If the program is rejected by verifier, 6990 * the map will be released by release_maps() or it 6991 * will be used by the valid program until it's unloaded 6992 * and all maps are released in free_used_maps() 6993 */ 6994 map = bpf_map_inc(map, false); 6995 if (IS_ERR(map)) { 6996 fdput(f); 6997 return PTR_ERR(map); 6998 } 6999 7000 aux->map_index = env->used_map_cnt; 7001 env->used_maps[env->used_map_cnt++] = map; 7002 7003 if (bpf_map_is_cgroup_storage(map) && 7004 bpf_cgroup_storage_assign(env->prog, map)) { 7005 verbose(env, "only one cgroup storage of each type is allowed\n"); 7006 fdput(f); 7007 return -EBUSY; 7008 } 7009 7010 fdput(f); 7011 next_insn: 7012 insn++; 7013 i++; 7014 continue; 7015 } 7016 7017 /* Basic sanity check before we invest more work here. */ 7018 if (!bpf_opcode_in_insntable(insn->code)) { 7019 verbose(env, "unknown opcode %02x\n", insn->code); 7020 return -EINVAL; 7021 } 7022 } 7023 7024 /* now all pseudo BPF_LD_IMM64 instructions load valid 7025 * 'struct bpf_map *' into a register instead of user map_fd. 7026 * These pointers will be used later by verifier to validate map access. 7027 */ 7028 return 0; 7029 } 7030 7031 /* drop refcnt of maps used by the rejected program */ 7032 static void release_maps(struct bpf_verifier_env *env) 7033 { 7034 enum bpf_cgroup_storage_type stype; 7035 int i; 7036 7037 for_each_cgroup_storage_type(stype) { 7038 if (!env->prog->aux->cgroup_storage[stype]) 7039 continue; 7040 bpf_cgroup_storage_release(env->prog, 7041 env->prog->aux->cgroup_storage[stype]); 7042 } 7043 7044 for (i = 0; i < env->used_map_cnt; i++) 7045 bpf_map_put(env->used_maps[i]); 7046 } 7047 7048 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 7049 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 7050 { 7051 struct bpf_insn *insn = env->prog->insnsi; 7052 int insn_cnt = env->prog->len; 7053 int i; 7054 7055 for (i = 0; i < insn_cnt; i++, insn++) 7056 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW)) 7057 insn->src_reg = 0; 7058 } 7059 7060 /* single env->prog->insni[off] instruction was replaced with the range 7061 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 7062 * [0, off) and [off, end) to new locations, so the patched range stays zero 7063 */ 7064 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, 7065 u32 off, u32 cnt) 7066 { 7067 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; 7068 int i; 7069 7070 if (cnt == 1) 7071 return 0; 7072 new_data = vzalloc(array_size(prog_len, 7073 sizeof(struct bpf_insn_aux_data))); 7074 if (!new_data) 7075 return -ENOMEM; 7076 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 7077 memcpy(new_data + off + cnt - 1, old_data + off, 7078 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 7079 for (i = off; i < off + cnt - 1; i++) 7080 new_data[i].seen = true; 7081 env->insn_aux_data = new_data; 7082 vfree(old_data); 7083 return 0; 7084 } 7085 7086 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 7087 { 7088 int i; 7089 7090 if (len == 1) 7091 return; 7092 /* NOTE: fake 'exit' subprog should be updated as well. */ 7093 for (i = 0; i <= env->subprog_cnt; i++) { 7094 if (env->subprog_info[i].start <= off) 7095 continue; 7096 env->subprog_info[i].start += len - 1; 7097 } 7098 } 7099 7100 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 7101 const struct bpf_insn *patch, u32 len) 7102 { 7103 struct bpf_prog *new_prog; 7104 7105 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 7106 if (IS_ERR(new_prog)) { 7107 if (PTR_ERR(new_prog) == -ERANGE) 7108 verbose(env, 7109 "insn %d cannot be patched due to 16-bit range\n", 7110 env->insn_aux_data[off].orig_idx); 7111 return NULL; 7112 } 7113 if (adjust_insn_aux_data(env, new_prog->len, off, len)) 7114 return NULL; 7115 adjust_subprog_starts(env, off, len); 7116 return new_prog; 7117 } 7118 7119 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 7120 u32 off, u32 cnt) 7121 { 7122 int i, j; 7123 7124 /* find first prog starting at or after off (first to remove) */ 7125 for (i = 0; i < env->subprog_cnt; i++) 7126 if (env->subprog_info[i].start >= off) 7127 break; 7128 /* find first prog starting at or after off + cnt (first to stay) */ 7129 for (j = i; j < env->subprog_cnt; j++) 7130 if (env->subprog_info[j].start >= off + cnt) 7131 break; 7132 /* if j doesn't start exactly at off + cnt, we are just removing 7133 * the front of previous prog 7134 */ 7135 if (env->subprog_info[j].start != off + cnt) 7136 j--; 7137 7138 if (j > i) { 7139 struct bpf_prog_aux *aux = env->prog->aux; 7140 int move; 7141 7142 /* move fake 'exit' subprog as well */ 7143 move = env->subprog_cnt + 1 - j; 7144 7145 memmove(env->subprog_info + i, 7146 env->subprog_info + j, 7147 sizeof(*env->subprog_info) * move); 7148 env->subprog_cnt -= j - i; 7149 7150 /* remove func_info */ 7151 if (aux->func_info) { 7152 move = aux->func_info_cnt - j; 7153 7154 memmove(aux->func_info + i, 7155 aux->func_info + j, 7156 sizeof(*aux->func_info) * move); 7157 aux->func_info_cnt -= j - i; 7158 /* func_info->insn_off is set after all code rewrites, 7159 * in adjust_btf_func() - no need to adjust 7160 */ 7161 } 7162 } else { 7163 /* convert i from "first prog to remove" to "first to adjust" */ 7164 if (env->subprog_info[i].start == off) 7165 i++; 7166 } 7167 7168 /* update fake 'exit' subprog as well */ 7169 for (; i <= env->subprog_cnt; i++) 7170 env->subprog_info[i].start -= cnt; 7171 7172 return 0; 7173 } 7174 7175 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 7176 u32 cnt) 7177 { 7178 struct bpf_prog *prog = env->prog; 7179 u32 i, l_off, l_cnt, nr_linfo; 7180 struct bpf_line_info *linfo; 7181 7182 nr_linfo = prog->aux->nr_linfo; 7183 if (!nr_linfo) 7184 return 0; 7185 7186 linfo = prog->aux->linfo; 7187 7188 /* find first line info to remove, count lines to be removed */ 7189 for (i = 0; i < nr_linfo; i++) 7190 if (linfo[i].insn_off >= off) 7191 break; 7192 7193 l_off = i; 7194 l_cnt = 0; 7195 for (; i < nr_linfo; i++) 7196 if (linfo[i].insn_off < off + cnt) 7197 l_cnt++; 7198 else 7199 break; 7200 7201 /* First live insn doesn't match first live linfo, it needs to "inherit" 7202 * last removed linfo. prog is already modified, so prog->len == off 7203 * means no live instructions after (tail of the program was removed). 7204 */ 7205 if (prog->len != off && l_cnt && 7206 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 7207 l_cnt--; 7208 linfo[--i].insn_off = off + cnt; 7209 } 7210 7211 /* remove the line info which refer to the removed instructions */ 7212 if (l_cnt) { 7213 memmove(linfo + l_off, linfo + i, 7214 sizeof(*linfo) * (nr_linfo - i)); 7215 7216 prog->aux->nr_linfo -= l_cnt; 7217 nr_linfo = prog->aux->nr_linfo; 7218 } 7219 7220 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 7221 for (i = l_off; i < nr_linfo; i++) 7222 linfo[i].insn_off -= cnt; 7223 7224 /* fix up all subprogs (incl. 'exit') which start >= off */ 7225 for (i = 0; i <= env->subprog_cnt; i++) 7226 if (env->subprog_info[i].linfo_idx > l_off) { 7227 /* program may have started in the removed region but 7228 * may not be fully removed 7229 */ 7230 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 7231 env->subprog_info[i].linfo_idx -= l_cnt; 7232 else 7233 env->subprog_info[i].linfo_idx = l_off; 7234 } 7235 7236 return 0; 7237 } 7238 7239 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 7240 { 7241 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 7242 unsigned int orig_prog_len = env->prog->len; 7243 int err; 7244 7245 if (bpf_prog_is_dev_bound(env->prog->aux)) 7246 bpf_prog_offload_remove_insns(env, off, cnt); 7247 7248 err = bpf_remove_insns(env->prog, off, cnt); 7249 if (err) 7250 return err; 7251 7252 err = adjust_subprog_starts_after_remove(env, off, cnt); 7253 if (err) 7254 return err; 7255 7256 err = bpf_adj_linfo_after_remove(env, off, cnt); 7257 if (err) 7258 return err; 7259 7260 memmove(aux_data + off, aux_data + off + cnt, 7261 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 7262 7263 return 0; 7264 } 7265 7266 /* The verifier does more data flow analysis than llvm and will not 7267 * explore branches that are dead at run time. Malicious programs can 7268 * have dead code too. Therefore replace all dead at-run-time code 7269 * with 'ja -1'. 7270 * 7271 * Just nops are not optimal, e.g. if they would sit at the end of the 7272 * program and through another bug we would manage to jump there, then 7273 * we'd execute beyond program memory otherwise. Returning exception 7274 * code also wouldn't work since we can have subprogs where the dead 7275 * code could be located. 7276 */ 7277 static void sanitize_dead_code(struct bpf_verifier_env *env) 7278 { 7279 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 7280 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 7281 struct bpf_insn *insn = env->prog->insnsi; 7282 const int insn_cnt = env->prog->len; 7283 int i; 7284 7285 for (i = 0; i < insn_cnt; i++) { 7286 if (aux_data[i].seen) 7287 continue; 7288 memcpy(insn + i, &trap, sizeof(trap)); 7289 } 7290 } 7291 7292 static bool insn_is_cond_jump(u8 code) 7293 { 7294 u8 op; 7295 7296 if (BPF_CLASS(code) == BPF_JMP32) 7297 return true; 7298 7299 if (BPF_CLASS(code) != BPF_JMP) 7300 return false; 7301 7302 op = BPF_OP(code); 7303 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 7304 } 7305 7306 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 7307 { 7308 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 7309 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 7310 struct bpf_insn *insn = env->prog->insnsi; 7311 const int insn_cnt = env->prog->len; 7312 int i; 7313 7314 for (i = 0; i < insn_cnt; i++, insn++) { 7315 if (!insn_is_cond_jump(insn->code)) 7316 continue; 7317 7318 if (!aux_data[i + 1].seen) 7319 ja.off = insn->off; 7320 else if (!aux_data[i + 1 + insn->off].seen) 7321 ja.off = 0; 7322 else 7323 continue; 7324 7325 if (bpf_prog_is_dev_bound(env->prog->aux)) 7326 bpf_prog_offload_replace_insn(env, i, &ja); 7327 7328 memcpy(insn, &ja, sizeof(ja)); 7329 } 7330 } 7331 7332 static int opt_remove_dead_code(struct bpf_verifier_env *env) 7333 { 7334 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 7335 int insn_cnt = env->prog->len; 7336 int i, err; 7337 7338 for (i = 0; i < insn_cnt; i++) { 7339 int j; 7340 7341 j = 0; 7342 while (i + j < insn_cnt && !aux_data[i + j].seen) 7343 j++; 7344 if (!j) 7345 continue; 7346 7347 err = verifier_remove_insns(env, i, j); 7348 if (err) 7349 return err; 7350 insn_cnt = env->prog->len; 7351 } 7352 7353 return 0; 7354 } 7355 7356 static int opt_remove_nops(struct bpf_verifier_env *env) 7357 { 7358 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 7359 struct bpf_insn *insn = env->prog->insnsi; 7360 int insn_cnt = env->prog->len; 7361 int i, err; 7362 7363 for (i = 0; i < insn_cnt; i++) { 7364 if (memcmp(&insn[i], &ja, sizeof(ja))) 7365 continue; 7366 7367 err = verifier_remove_insns(env, i, 1); 7368 if (err) 7369 return err; 7370 insn_cnt--; 7371 i--; 7372 } 7373 7374 return 0; 7375 } 7376 7377 /* convert load instructions that access fields of a context type into a 7378 * sequence of instructions that access fields of the underlying structure: 7379 * struct __sk_buff -> struct sk_buff 7380 * struct bpf_sock_ops -> struct sock 7381 */ 7382 static int convert_ctx_accesses(struct bpf_verifier_env *env) 7383 { 7384 const struct bpf_verifier_ops *ops = env->ops; 7385 int i, cnt, size, ctx_field_size, delta = 0; 7386 const int insn_cnt = env->prog->len; 7387 struct bpf_insn insn_buf[16], *insn; 7388 u32 target_size, size_default, off; 7389 struct bpf_prog *new_prog; 7390 enum bpf_access_type type; 7391 bool is_narrower_load; 7392 7393 if (ops->gen_prologue || env->seen_direct_write) { 7394 if (!ops->gen_prologue) { 7395 verbose(env, "bpf verifier is misconfigured\n"); 7396 return -EINVAL; 7397 } 7398 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 7399 env->prog); 7400 if (cnt >= ARRAY_SIZE(insn_buf)) { 7401 verbose(env, "bpf verifier is misconfigured\n"); 7402 return -EINVAL; 7403 } else if (cnt) { 7404 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 7405 if (!new_prog) 7406 return -ENOMEM; 7407 7408 env->prog = new_prog; 7409 delta += cnt - 1; 7410 } 7411 } 7412 7413 if (bpf_prog_is_dev_bound(env->prog->aux)) 7414 return 0; 7415 7416 insn = env->prog->insnsi + delta; 7417 7418 for (i = 0; i < insn_cnt; i++, insn++) { 7419 bpf_convert_ctx_access_t convert_ctx_access; 7420 7421 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 7422 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 7423 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 7424 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) 7425 type = BPF_READ; 7426 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 7427 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 7428 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 7429 insn->code == (BPF_STX | BPF_MEM | BPF_DW)) 7430 type = BPF_WRITE; 7431 else 7432 continue; 7433 7434 if (type == BPF_WRITE && 7435 env->insn_aux_data[i + delta].sanitize_stack_off) { 7436 struct bpf_insn patch[] = { 7437 /* Sanitize suspicious stack slot with zero. 7438 * There are no memory dependencies for this store, 7439 * since it's only using frame pointer and immediate 7440 * constant of zero 7441 */ 7442 BPF_ST_MEM(BPF_DW, BPF_REG_FP, 7443 env->insn_aux_data[i + delta].sanitize_stack_off, 7444 0), 7445 /* the original STX instruction will immediately 7446 * overwrite the same stack slot with appropriate value 7447 */ 7448 *insn, 7449 }; 7450 7451 cnt = ARRAY_SIZE(patch); 7452 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 7453 if (!new_prog) 7454 return -ENOMEM; 7455 7456 delta += cnt - 1; 7457 env->prog = new_prog; 7458 insn = new_prog->insnsi + i + delta; 7459 continue; 7460 } 7461 7462 switch (env->insn_aux_data[i + delta].ptr_type) { 7463 case PTR_TO_CTX: 7464 if (!ops->convert_ctx_access) 7465 continue; 7466 convert_ctx_access = ops->convert_ctx_access; 7467 break; 7468 case PTR_TO_SOCKET: 7469 case PTR_TO_SOCK_COMMON: 7470 convert_ctx_access = bpf_sock_convert_ctx_access; 7471 break; 7472 case PTR_TO_TCP_SOCK: 7473 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 7474 break; 7475 default: 7476 continue; 7477 } 7478 7479 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 7480 size = BPF_LDST_BYTES(insn); 7481 7482 /* If the read access is a narrower load of the field, 7483 * convert to a 4/8-byte load, to minimum program type specific 7484 * convert_ctx_access changes. If conversion is successful, 7485 * we will apply proper mask to the result. 7486 */ 7487 is_narrower_load = size < ctx_field_size; 7488 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 7489 off = insn->off; 7490 if (is_narrower_load) { 7491 u8 size_code; 7492 7493 if (type == BPF_WRITE) { 7494 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 7495 return -EINVAL; 7496 } 7497 7498 size_code = BPF_H; 7499 if (ctx_field_size == 4) 7500 size_code = BPF_W; 7501 else if (ctx_field_size == 8) 7502 size_code = BPF_DW; 7503 7504 insn->off = off & ~(size_default - 1); 7505 insn->code = BPF_LDX | BPF_MEM | size_code; 7506 } 7507 7508 target_size = 0; 7509 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 7510 &target_size); 7511 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 7512 (ctx_field_size && !target_size)) { 7513 verbose(env, "bpf verifier is misconfigured\n"); 7514 return -EINVAL; 7515 } 7516 7517 if (is_narrower_load && size < target_size) { 7518 u8 shift = (off & (size_default - 1)) * 8; 7519 7520 if (ctx_field_size <= 4) { 7521 if (shift) 7522 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 7523 insn->dst_reg, 7524 shift); 7525 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 7526 (1 << size * 8) - 1); 7527 } else { 7528 if (shift) 7529 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 7530 insn->dst_reg, 7531 shift); 7532 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 7533 (1 << size * 8) - 1); 7534 } 7535 } 7536 7537 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 7538 if (!new_prog) 7539 return -ENOMEM; 7540 7541 delta += cnt - 1; 7542 7543 /* keep walking new program and skip insns we just inserted */ 7544 env->prog = new_prog; 7545 insn = new_prog->insnsi + i + delta; 7546 } 7547 7548 return 0; 7549 } 7550 7551 static int jit_subprogs(struct bpf_verifier_env *env) 7552 { 7553 struct bpf_prog *prog = env->prog, **func, *tmp; 7554 int i, j, subprog_start, subprog_end = 0, len, subprog; 7555 struct bpf_insn *insn; 7556 void *old_bpf_func; 7557 int err; 7558 7559 if (env->subprog_cnt <= 1) 7560 return 0; 7561 7562 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 7563 if (insn->code != (BPF_JMP | BPF_CALL) || 7564 insn->src_reg != BPF_PSEUDO_CALL) 7565 continue; 7566 /* Upon error here we cannot fall back to interpreter but 7567 * need a hard reject of the program. Thus -EFAULT is 7568 * propagated in any case. 7569 */ 7570 subprog = find_subprog(env, i + insn->imm + 1); 7571 if (subprog < 0) { 7572 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 7573 i + insn->imm + 1); 7574 return -EFAULT; 7575 } 7576 /* temporarily remember subprog id inside insn instead of 7577 * aux_data, since next loop will split up all insns into funcs 7578 */ 7579 insn->off = subprog; 7580 /* remember original imm in case JIT fails and fallback 7581 * to interpreter will be needed 7582 */ 7583 env->insn_aux_data[i].call_imm = insn->imm; 7584 /* point imm to __bpf_call_base+1 from JITs point of view */ 7585 insn->imm = 1; 7586 } 7587 7588 err = bpf_prog_alloc_jited_linfo(prog); 7589 if (err) 7590 goto out_undo_insn; 7591 7592 err = -ENOMEM; 7593 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 7594 if (!func) 7595 goto out_undo_insn; 7596 7597 for (i = 0; i < env->subprog_cnt; i++) { 7598 subprog_start = subprog_end; 7599 subprog_end = env->subprog_info[i + 1].start; 7600 7601 len = subprog_end - subprog_start; 7602 /* BPF_PROG_RUN doesn't call subprogs directly, 7603 * hence main prog stats include the runtime of subprogs. 7604 * subprogs don't have IDs and not reachable via prog_get_next_id 7605 * func[i]->aux->stats will never be accessed and stays NULL 7606 */ 7607 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 7608 if (!func[i]) 7609 goto out_free; 7610 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 7611 len * sizeof(struct bpf_insn)); 7612 func[i]->type = prog->type; 7613 func[i]->len = len; 7614 if (bpf_prog_calc_tag(func[i])) 7615 goto out_free; 7616 func[i]->is_func = 1; 7617 func[i]->aux->func_idx = i; 7618 /* the btf and func_info will be freed only at prog->aux */ 7619 func[i]->aux->btf = prog->aux->btf; 7620 func[i]->aux->func_info = prog->aux->func_info; 7621 7622 /* Use bpf_prog_F_tag to indicate functions in stack traces. 7623 * Long term would need debug info to populate names 7624 */ 7625 func[i]->aux->name[0] = 'F'; 7626 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 7627 func[i]->jit_requested = 1; 7628 func[i]->aux->linfo = prog->aux->linfo; 7629 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 7630 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 7631 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 7632 func[i] = bpf_int_jit_compile(func[i]); 7633 if (!func[i]->jited) { 7634 err = -ENOTSUPP; 7635 goto out_free; 7636 } 7637 cond_resched(); 7638 } 7639 /* at this point all bpf functions were successfully JITed 7640 * now populate all bpf_calls with correct addresses and 7641 * run last pass of JIT 7642 */ 7643 for (i = 0; i < env->subprog_cnt; i++) { 7644 insn = func[i]->insnsi; 7645 for (j = 0; j < func[i]->len; j++, insn++) { 7646 if (insn->code != (BPF_JMP | BPF_CALL) || 7647 insn->src_reg != BPF_PSEUDO_CALL) 7648 continue; 7649 subprog = insn->off; 7650 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) - 7651 __bpf_call_base; 7652 } 7653 7654 /* we use the aux data to keep a list of the start addresses 7655 * of the JITed images for each function in the program 7656 * 7657 * for some architectures, such as powerpc64, the imm field 7658 * might not be large enough to hold the offset of the start 7659 * address of the callee's JITed image from __bpf_call_base 7660 * 7661 * in such cases, we can lookup the start address of a callee 7662 * by using its subprog id, available from the off field of 7663 * the call instruction, as an index for this list 7664 */ 7665 func[i]->aux->func = func; 7666 func[i]->aux->func_cnt = env->subprog_cnt; 7667 } 7668 for (i = 0; i < env->subprog_cnt; i++) { 7669 old_bpf_func = func[i]->bpf_func; 7670 tmp = bpf_int_jit_compile(func[i]); 7671 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 7672 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 7673 err = -ENOTSUPP; 7674 goto out_free; 7675 } 7676 cond_resched(); 7677 } 7678 7679 /* finally lock prog and jit images for all functions and 7680 * populate kallsysm 7681 */ 7682 for (i = 0; i < env->subprog_cnt; i++) { 7683 bpf_prog_lock_ro(func[i]); 7684 bpf_prog_kallsyms_add(func[i]); 7685 } 7686 7687 /* Last step: make now unused interpreter insns from main 7688 * prog consistent for later dump requests, so they can 7689 * later look the same as if they were interpreted only. 7690 */ 7691 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 7692 if (insn->code != (BPF_JMP | BPF_CALL) || 7693 insn->src_reg != BPF_PSEUDO_CALL) 7694 continue; 7695 insn->off = env->insn_aux_data[i].call_imm; 7696 subprog = find_subprog(env, i + insn->off + 1); 7697 insn->imm = subprog; 7698 } 7699 7700 prog->jited = 1; 7701 prog->bpf_func = func[0]->bpf_func; 7702 prog->aux->func = func; 7703 prog->aux->func_cnt = env->subprog_cnt; 7704 bpf_prog_free_unused_jited_linfo(prog); 7705 return 0; 7706 out_free: 7707 for (i = 0; i < env->subprog_cnt; i++) 7708 if (func[i]) 7709 bpf_jit_free(func[i]); 7710 kfree(func); 7711 out_undo_insn: 7712 /* cleanup main prog to be interpreted */ 7713 prog->jit_requested = 0; 7714 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 7715 if (insn->code != (BPF_JMP | BPF_CALL) || 7716 insn->src_reg != BPF_PSEUDO_CALL) 7717 continue; 7718 insn->off = 0; 7719 insn->imm = env->insn_aux_data[i].call_imm; 7720 } 7721 bpf_prog_free_jited_linfo(prog); 7722 return err; 7723 } 7724 7725 static int fixup_call_args(struct bpf_verifier_env *env) 7726 { 7727 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 7728 struct bpf_prog *prog = env->prog; 7729 struct bpf_insn *insn = prog->insnsi; 7730 int i, depth; 7731 #endif 7732 int err = 0; 7733 7734 if (env->prog->jit_requested && 7735 !bpf_prog_is_dev_bound(env->prog->aux)) { 7736 err = jit_subprogs(env); 7737 if (err == 0) 7738 return 0; 7739 if (err == -EFAULT) 7740 return err; 7741 } 7742 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 7743 for (i = 0; i < prog->len; i++, insn++) { 7744 if (insn->code != (BPF_JMP | BPF_CALL) || 7745 insn->src_reg != BPF_PSEUDO_CALL) 7746 continue; 7747 depth = get_callee_stack_depth(env, insn, i); 7748 if (depth < 0) 7749 return depth; 7750 bpf_patch_call_args(insn, depth); 7751 } 7752 err = 0; 7753 #endif 7754 return err; 7755 } 7756 7757 /* fixup insn->imm field of bpf_call instructions 7758 * and inline eligible helpers as explicit sequence of BPF instructions 7759 * 7760 * this function is called after eBPF program passed verification 7761 */ 7762 static int fixup_bpf_calls(struct bpf_verifier_env *env) 7763 { 7764 struct bpf_prog *prog = env->prog; 7765 struct bpf_insn *insn = prog->insnsi; 7766 const struct bpf_func_proto *fn; 7767 const int insn_cnt = prog->len; 7768 const struct bpf_map_ops *ops; 7769 struct bpf_insn_aux_data *aux; 7770 struct bpf_insn insn_buf[16]; 7771 struct bpf_prog *new_prog; 7772 struct bpf_map *map_ptr; 7773 int i, cnt, delta = 0; 7774 7775 for (i = 0; i < insn_cnt; i++, insn++) { 7776 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 7777 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 7778 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 7779 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 7780 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 7781 struct bpf_insn mask_and_div[] = { 7782 BPF_MOV32_REG(insn->src_reg, insn->src_reg), 7783 /* Rx div 0 -> 0 */ 7784 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2), 7785 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 7786 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 7787 *insn, 7788 }; 7789 struct bpf_insn mask_and_mod[] = { 7790 BPF_MOV32_REG(insn->src_reg, insn->src_reg), 7791 /* Rx mod 0 -> Rx */ 7792 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1), 7793 *insn, 7794 }; 7795 struct bpf_insn *patchlet; 7796 7797 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 7798 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 7799 patchlet = mask_and_div + (is64 ? 1 : 0); 7800 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0); 7801 } else { 7802 patchlet = mask_and_mod + (is64 ? 1 : 0); 7803 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0); 7804 } 7805 7806 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 7807 if (!new_prog) 7808 return -ENOMEM; 7809 7810 delta += cnt - 1; 7811 env->prog = prog = new_prog; 7812 insn = new_prog->insnsi + i + delta; 7813 continue; 7814 } 7815 7816 if (BPF_CLASS(insn->code) == BPF_LD && 7817 (BPF_MODE(insn->code) == BPF_ABS || 7818 BPF_MODE(insn->code) == BPF_IND)) { 7819 cnt = env->ops->gen_ld_abs(insn, insn_buf); 7820 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 7821 verbose(env, "bpf verifier is misconfigured\n"); 7822 return -EINVAL; 7823 } 7824 7825 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 7826 if (!new_prog) 7827 return -ENOMEM; 7828 7829 delta += cnt - 1; 7830 env->prog = prog = new_prog; 7831 insn = new_prog->insnsi + i + delta; 7832 continue; 7833 } 7834 7835 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 7836 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 7837 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 7838 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 7839 struct bpf_insn insn_buf[16]; 7840 struct bpf_insn *patch = &insn_buf[0]; 7841 bool issrc, isneg; 7842 u32 off_reg; 7843 7844 aux = &env->insn_aux_data[i + delta]; 7845 if (!aux->alu_state || 7846 aux->alu_state == BPF_ALU_NON_POINTER) 7847 continue; 7848 7849 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 7850 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 7851 BPF_ALU_SANITIZE_SRC; 7852 7853 off_reg = issrc ? insn->src_reg : insn->dst_reg; 7854 if (isneg) 7855 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 7856 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1); 7857 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 7858 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 7859 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 7860 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 7861 if (issrc) { 7862 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, 7863 off_reg); 7864 insn->src_reg = BPF_REG_AX; 7865 } else { 7866 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg, 7867 BPF_REG_AX); 7868 } 7869 if (isneg) 7870 insn->code = insn->code == code_add ? 7871 code_sub : code_add; 7872 *patch++ = *insn; 7873 if (issrc && isneg) 7874 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 7875 cnt = patch - insn_buf; 7876 7877 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 7878 if (!new_prog) 7879 return -ENOMEM; 7880 7881 delta += cnt - 1; 7882 env->prog = prog = new_prog; 7883 insn = new_prog->insnsi + i + delta; 7884 continue; 7885 } 7886 7887 if (insn->code != (BPF_JMP | BPF_CALL)) 7888 continue; 7889 if (insn->src_reg == BPF_PSEUDO_CALL) 7890 continue; 7891 7892 if (insn->imm == BPF_FUNC_get_route_realm) 7893 prog->dst_needed = 1; 7894 if (insn->imm == BPF_FUNC_get_prandom_u32) 7895 bpf_user_rnd_init_once(); 7896 if (insn->imm == BPF_FUNC_override_return) 7897 prog->kprobe_override = 1; 7898 if (insn->imm == BPF_FUNC_tail_call) { 7899 /* If we tail call into other programs, we 7900 * cannot make any assumptions since they can 7901 * be replaced dynamically during runtime in 7902 * the program array. 7903 */ 7904 prog->cb_access = 1; 7905 env->prog->aux->stack_depth = MAX_BPF_STACK; 7906 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF; 7907 7908 /* mark bpf_tail_call as different opcode to avoid 7909 * conditional branch in the interpeter for every normal 7910 * call and to prevent accidental JITing by JIT compiler 7911 * that doesn't support bpf_tail_call yet 7912 */ 7913 insn->imm = 0; 7914 insn->code = BPF_JMP | BPF_TAIL_CALL; 7915 7916 aux = &env->insn_aux_data[i + delta]; 7917 if (!bpf_map_ptr_unpriv(aux)) 7918 continue; 7919 7920 /* instead of changing every JIT dealing with tail_call 7921 * emit two extra insns: 7922 * if (index >= max_entries) goto out; 7923 * index &= array->index_mask; 7924 * to avoid out-of-bounds cpu speculation 7925 */ 7926 if (bpf_map_ptr_poisoned(aux)) { 7927 verbose(env, "tail_call abusing map_ptr\n"); 7928 return -EINVAL; 7929 } 7930 7931 map_ptr = BPF_MAP_PTR(aux->map_state); 7932 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 7933 map_ptr->max_entries, 2); 7934 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 7935 container_of(map_ptr, 7936 struct bpf_array, 7937 map)->index_mask); 7938 insn_buf[2] = *insn; 7939 cnt = 3; 7940 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 7941 if (!new_prog) 7942 return -ENOMEM; 7943 7944 delta += cnt - 1; 7945 env->prog = prog = new_prog; 7946 insn = new_prog->insnsi + i + delta; 7947 continue; 7948 } 7949 7950 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 7951 * and other inlining handlers are currently limited to 64 bit 7952 * only. 7953 */ 7954 if (prog->jit_requested && BITS_PER_LONG == 64 && 7955 (insn->imm == BPF_FUNC_map_lookup_elem || 7956 insn->imm == BPF_FUNC_map_update_elem || 7957 insn->imm == BPF_FUNC_map_delete_elem || 7958 insn->imm == BPF_FUNC_map_push_elem || 7959 insn->imm == BPF_FUNC_map_pop_elem || 7960 insn->imm == BPF_FUNC_map_peek_elem)) { 7961 aux = &env->insn_aux_data[i + delta]; 7962 if (bpf_map_ptr_poisoned(aux)) 7963 goto patch_call_imm; 7964 7965 map_ptr = BPF_MAP_PTR(aux->map_state); 7966 ops = map_ptr->ops; 7967 if (insn->imm == BPF_FUNC_map_lookup_elem && 7968 ops->map_gen_lookup) { 7969 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 7970 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 7971 verbose(env, "bpf verifier is misconfigured\n"); 7972 return -EINVAL; 7973 } 7974 7975 new_prog = bpf_patch_insn_data(env, i + delta, 7976 insn_buf, cnt); 7977 if (!new_prog) 7978 return -ENOMEM; 7979 7980 delta += cnt - 1; 7981 env->prog = prog = new_prog; 7982 insn = new_prog->insnsi + i + delta; 7983 continue; 7984 } 7985 7986 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 7987 (void *(*)(struct bpf_map *map, void *key))NULL)); 7988 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 7989 (int (*)(struct bpf_map *map, void *key))NULL)); 7990 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 7991 (int (*)(struct bpf_map *map, void *key, void *value, 7992 u64 flags))NULL)); 7993 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 7994 (int (*)(struct bpf_map *map, void *value, 7995 u64 flags))NULL)); 7996 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 7997 (int (*)(struct bpf_map *map, void *value))NULL)); 7998 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 7999 (int (*)(struct bpf_map *map, void *value))NULL)); 8000 8001 switch (insn->imm) { 8002 case BPF_FUNC_map_lookup_elem: 8003 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - 8004 __bpf_call_base; 8005 continue; 8006 case BPF_FUNC_map_update_elem: 8007 insn->imm = BPF_CAST_CALL(ops->map_update_elem) - 8008 __bpf_call_base; 8009 continue; 8010 case BPF_FUNC_map_delete_elem: 8011 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - 8012 __bpf_call_base; 8013 continue; 8014 case BPF_FUNC_map_push_elem: 8015 insn->imm = BPF_CAST_CALL(ops->map_push_elem) - 8016 __bpf_call_base; 8017 continue; 8018 case BPF_FUNC_map_pop_elem: 8019 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) - 8020 __bpf_call_base; 8021 continue; 8022 case BPF_FUNC_map_peek_elem: 8023 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) - 8024 __bpf_call_base; 8025 continue; 8026 } 8027 8028 goto patch_call_imm; 8029 } 8030 8031 patch_call_imm: 8032 fn = env->ops->get_func_proto(insn->imm, env->prog); 8033 /* all functions that have prototype and verifier allowed 8034 * programs to call them, must be real in-kernel functions 8035 */ 8036 if (!fn->func) { 8037 verbose(env, 8038 "kernel subsystem misconfigured func %s#%d\n", 8039 func_id_name(insn->imm), insn->imm); 8040 return -EFAULT; 8041 } 8042 insn->imm = fn->func - __bpf_call_base; 8043 } 8044 8045 return 0; 8046 } 8047 8048 static void free_states(struct bpf_verifier_env *env) 8049 { 8050 struct bpf_verifier_state_list *sl, *sln; 8051 int i; 8052 8053 sl = env->free_list; 8054 while (sl) { 8055 sln = sl->next; 8056 free_verifier_state(&sl->state, false); 8057 kfree(sl); 8058 sl = sln; 8059 } 8060 8061 if (!env->explored_states) 8062 return; 8063 8064 for (i = 0; i < env->prog->len; i++) { 8065 sl = env->explored_states[i]; 8066 8067 if (sl) 8068 while (sl != STATE_LIST_MARK) { 8069 sln = sl->next; 8070 free_verifier_state(&sl->state, false); 8071 kfree(sl); 8072 sl = sln; 8073 } 8074 } 8075 8076 kvfree(env->explored_states); 8077 } 8078 8079 static void print_verification_stats(struct bpf_verifier_env *env) 8080 { 8081 int i; 8082 8083 if (env->log.level & BPF_LOG_STATS) { 8084 verbose(env, "verification time %lld usec\n", 8085 div_u64(env->verification_time, 1000)); 8086 verbose(env, "stack depth "); 8087 for (i = 0; i < env->subprog_cnt; i++) { 8088 u32 depth = env->subprog_info[i].stack_depth; 8089 8090 verbose(env, "%d", depth); 8091 if (i + 1 < env->subprog_cnt) 8092 verbose(env, "+"); 8093 } 8094 verbose(env, "\n"); 8095 } 8096 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 8097 "total_states %d peak_states %d mark_read %d\n", 8098 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 8099 env->max_states_per_insn, env->total_states, 8100 env->peak_states, env->longest_mark_read_walk); 8101 } 8102 8103 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, 8104 union bpf_attr __user *uattr) 8105 { 8106 u64 start_time = ktime_get_ns(); 8107 struct bpf_verifier_env *env; 8108 struct bpf_verifier_log *log; 8109 int i, len, ret = -EINVAL; 8110 bool is_priv; 8111 8112 /* no program is valid */ 8113 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 8114 return -EINVAL; 8115 8116 /* 'struct bpf_verifier_env' can be global, but since it's not small, 8117 * allocate/free it every time bpf_check() is called 8118 */ 8119 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 8120 if (!env) 8121 return -ENOMEM; 8122 log = &env->log; 8123 8124 len = (*prog)->len; 8125 env->insn_aux_data = 8126 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 8127 ret = -ENOMEM; 8128 if (!env->insn_aux_data) 8129 goto err_free_env; 8130 for (i = 0; i < len; i++) 8131 env->insn_aux_data[i].orig_idx = i; 8132 env->prog = *prog; 8133 env->ops = bpf_verifier_ops[env->prog->type]; 8134 8135 /* grab the mutex to protect few globals used by verifier */ 8136 mutex_lock(&bpf_verifier_lock); 8137 8138 if (attr->log_level || attr->log_buf || attr->log_size) { 8139 /* user requested verbose verifier output 8140 * and supplied buffer to store the verification trace 8141 */ 8142 log->level = attr->log_level; 8143 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 8144 log->len_total = attr->log_size; 8145 8146 ret = -EINVAL; 8147 /* log attributes have to be sane */ 8148 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 || 8149 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK) 8150 goto err_unlock; 8151 } 8152 8153 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 8154 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 8155 env->strict_alignment = true; 8156 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 8157 env->strict_alignment = false; 8158 8159 is_priv = capable(CAP_SYS_ADMIN); 8160 env->allow_ptr_leaks = is_priv; 8161 8162 ret = replace_map_fd_with_map_ptr(env); 8163 if (ret < 0) 8164 goto skip_full_check; 8165 8166 if (bpf_prog_is_dev_bound(env->prog->aux)) { 8167 ret = bpf_prog_offload_verifier_prep(env->prog); 8168 if (ret) 8169 goto skip_full_check; 8170 } 8171 8172 env->explored_states = kvcalloc(env->prog->len, 8173 sizeof(struct bpf_verifier_state_list *), 8174 GFP_USER); 8175 ret = -ENOMEM; 8176 if (!env->explored_states) 8177 goto skip_full_check; 8178 8179 ret = check_subprogs(env); 8180 if (ret < 0) 8181 goto skip_full_check; 8182 8183 ret = check_btf_info(env, attr, uattr); 8184 if (ret < 0) 8185 goto skip_full_check; 8186 8187 ret = check_cfg(env); 8188 if (ret < 0) 8189 goto skip_full_check; 8190 8191 ret = do_check(env); 8192 if (env->cur_state) { 8193 free_verifier_state(env->cur_state, true); 8194 env->cur_state = NULL; 8195 } 8196 8197 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux)) 8198 ret = bpf_prog_offload_finalize(env); 8199 8200 skip_full_check: 8201 while (!pop_stack(env, NULL, NULL)); 8202 free_states(env); 8203 8204 if (ret == 0) 8205 ret = check_max_stack_depth(env); 8206 8207 /* instruction rewrites happen after this point */ 8208 if (is_priv) { 8209 if (ret == 0) 8210 opt_hard_wire_dead_code_branches(env); 8211 if (ret == 0) 8212 ret = opt_remove_dead_code(env); 8213 if (ret == 0) 8214 ret = opt_remove_nops(env); 8215 } else { 8216 if (ret == 0) 8217 sanitize_dead_code(env); 8218 } 8219 8220 if (ret == 0) 8221 /* program is valid, convert *(u32*)(ctx + off) accesses */ 8222 ret = convert_ctx_accesses(env); 8223 8224 if (ret == 0) 8225 ret = fixup_bpf_calls(env); 8226 8227 if (ret == 0) 8228 ret = fixup_call_args(env); 8229 8230 env->verification_time = ktime_get_ns() - start_time; 8231 print_verification_stats(env); 8232 8233 if (log->level && bpf_verifier_log_full(log)) 8234 ret = -ENOSPC; 8235 if (log->level && !log->ubuf) { 8236 ret = -EFAULT; 8237 goto err_release_maps; 8238 } 8239 8240 if (ret == 0 && env->used_map_cnt) { 8241 /* if program passed verifier, update used_maps in bpf_prog_info */ 8242 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 8243 sizeof(env->used_maps[0]), 8244 GFP_KERNEL); 8245 8246 if (!env->prog->aux->used_maps) { 8247 ret = -ENOMEM; 8248 goto err_release_maps; 8249 } 8250 8251 memcpy(env->prog->aux->used_maps, env->used_maps, 8252 sizeof(env->used_maps[0]) * env->used_map_cnt); 8253 env->prog->aux->used_map_cnt = env->used_map_cnt; 8254 8255 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 8256 * bpf_ld_imm64 instructions 8257 */ 8258 convert_pseudo_ld_imm64(env); 8259 } 8260 8261 if (ret == 0) 8262 adjust_btf_func(env); 8263 8264 err_release_maps: 8265 if (!env->prog->aux->used_maps) 8266 /* if we didn't copy map pointers into bpf_prog_info, release 8267 * them now. Otherwise free_used_maps() will release them. 8268 */ 8269 release_maps(env); 8270 *prog = env->prog; 8271 err_unlock: 8272 mutex_unlock(&bpf_verifier_lock); 8273 vfree(env->insn_aux_data); 8274 err_free_env: 8275 kfree(env); 8276 return ret; 8277 } 8278