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 /* t, w, e - match pseudo-code above: 5373 * t - index of current instruction 5374 * w - next instruction 5375 * e - edge 5376 */ 5377 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) 5378 { 5379 int *insn_stack = env->cfg.insn_stack; 5380 int *insn_state = env->cfg.insn_state; 5381 5382 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 5383 return 0; 5384 5385 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 5386 return 0; 5387 5388 if (w < 0 || w >= env->prog->len) { 5389 verbose_linfo(env, t, "%d: ", t); 5390 verbose(env, "jump out of range from insn %d to %d\n", t, w); 5391 return -EINVAL; 5392 } 5393 5394 if (e == BRANCH) 5395 /* mark branch target for state pruning */ 5396 env->explored_states[w] = STATE_LIST_MARK; 5397 5398 if (insn_state[w] == 0) { 5399 /* tree-edge */ 5400 insn_state[t] = DISCOVERED | e; 5401 insn_state[w] = DISCOVERED; 5402 if (env->cfg.cur_stack >= env->prog->len) 5403 return -E2BIG; 5404 insn_stack[env->cfg.cur_stack++] = w; 5405 return 1; 5406 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 5407 verbose_linfo(env, t, "%d: ", t); 5408 verbose_linfo(env, w, "%d: ", w); 5409 verbose(env, "back-edge from insn %d to %d\n", t, w); 5410 return -EINVAL; 5411 } else if (insn_state[w] == EXPLORED) { 5412 /* forward- or cross-edge */ 5413 insn_state[t] = DISCOVERED | e; 5414 } else { 5415 verbose(env, "insn state internal bug\n"); 5416 return -EFAULT; 5417 } 5418 return 0; 5419 } 5420 5421 /* non-recursive depth-first-search to detect loops in BPF program 5422 * loop == back-edge in directed graph 5423 */ 5424 static int check_cfg(struct bpf_verifier_env *env) 5425 { 5426 struct bpf_insn *insns = env->prog->insnsi; 5427 int insn_cnt = env->prog->len; 5428 int *insn_stack, *insn_state; 5429 int ret = 0; 5430 int i, t; 5431 5432 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 5433 if (!insn_state) 5434 return -ENOMEM; 5435 5436 insn_stack = env->cfg.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 env->cfg.cur_stack = 1; 5445 5446 peek_stack: 5447 if (env->cfg.cur_stack == 0) 5448 goto check_state; 5449 t = insn_stack[env->cfg.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 (env->cfg.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 env->cfg.insn_state = env->cfg.insn_stack = NULL; 5539 return ret; 5540 } 5541 5542 /* The minimum supported BTF func info size */ 5543 #define MIN_BPF_FUNCINFO_SIZE 8 5544 #define MAX_FUNCINFO_REC_SIZE 252 5545 5546 static int check_btf_func(struct bpf_verifier_env *env, 5547 const union bpf_attr *attr, 5548 union bpf_attr __user *uattr) 5549 { 5550 u32 i, nfuncs, urec_size, min_size; 5551 u32 krec_size = sizeof(struct bpf_func_info); 5552 struct bpf_func_info *krecord; 5553 const struct btf_type *type; 5554 struct bpf_prog *prog; 5555 const struct btf *btf; 5556 void __user *urecord; 5557 u32 prev_offset = 0; 5558 int ret = 0; 5559 5560 nfuncs = attr->func_info_cnt; 5561 if (!nfuncs) 5562 return 0; 5563 5564 if (nfuncs != env->subprog_cnt) { 5565 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 5566 return -EINVAL; 5567 } 5568 5569 urec_size = attr->func_info_rec_size; 5570 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 5571 urec_size > MAX_FUNCINFO_REC_SIZE || 5572 urec_size % sizeof(u32)) { 5573 verbose(env, "invalid func info rec size %u\n", urec_size); 5574 return -EINVAL; 5575 } 5576 5577 prog = env->prog; 5578 btf = prog->aux->btf; 5579 5580 urecord = u64_to_user_ptr(attr->func_info); 5581 min_size = min_t(u32, krec_size, urec_size); 5582 5583 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 5584 if (!krecord) 5585 return -ENOMEM; 5586 5587 for (i = 0; i < nfuncs; i++) { 5588 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 5589 if (ret) { 5590 if (ret == -E2BIG) { 5591 verbose(env, "nonzero tailing record in func info"); 5592 /* set the size kernel expects so loader can zero 5593 * out the rest of the record. 5594 */ 5595 if (put_user(min_size, &uattr->func_info_rec_size)) 5596 ret = -EFAULT; 5597 } 5598 goto err_free; 5599 } 5600 5601 if (copy_from_user(&krecord[i], urecord, min_size)) { 5602 ret = -EFAULT; 5603 goto err_free; 5604 } 5605 5606 /* check insn_off */ 5607 if (i == 0) { 5608 if (krecord[i].insn_off) { 5609 verbose(env, 5610 "nonzero insn_off %u for the first func info record", 5611 krecord[i].insn_off); 5612 ret = -EINVAL; 5613 goto err_free; 5614 } 5615 } else if (krecord[i].insn_off <= prev_offset) { 5616 verbose(env, 5617 "same or smaller insn offset (%u) than previous func info record (%u)", 5618 krecord[i].insn_off, prev_offset); 5619 ret = -EINVAL; 5620 goto err_free; 5621 } 5622 5623 if (env->subprog_info[i].start != krecord[i].insn_off) { 5624 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 5625 ret = -EINVAL; 5626 goto err_free; 5627 } 5628 5629 /* check type_id */ 5630 type = btf_type_by_id(btf, krecord[i].type_id); 5631 if (!type || BTF_INFO_KIND(type->info) != BTF_KIND_FUNC) { 5632 verbose(env, "invalid type id %d in func info", 5633 krecord[i].type_id); 5634 ret = -EINVAL; 5635 goto err_free; 5636 } 5637 5638 prev_offset = krecord[i].insn_off; 5639 urecord += urec_size; 5640 } 5641 5642 prog->aux->func_info = krecord; 5643 prog->aux->func_info_cnt = nfuncs; 5644 return 0; 5645 5646 err_free: 5647 kvfree(krecord); 5648 return ret; 5649 } 5650 5651 static void adjust_btf_func(struct bpf_verifier_env *env) 5652 { 5653 int i; 5654 5655 if (!env->prog->aux->func_info) 5656 return; 5657 5658 for (i = 0; i < env->subprog_cnt; i++) 5659 env->prog->aux->func_info[i].insn_off = env->subprog_info[i].start; 5660 } 5661 5662 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \ 5663 sizeof(((struct bpf_line_info *)(0))->line_col)) 5664 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 5665 5666 static int check_btf_line(struct bpf_verifier_env *env, 5667 const union bpf_attr *attr, 5668 union bpf_attr __user *uattr) 5669 { 5670 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 5671 struct bpf_subprog_info *sub; 5672 struct bpf_line_info *linfo; 5673 struct bpf_prog *prog; 5674 const struct btf *btf; 5675 void __user *ulinfo; 5676 int err; 5677 5678 nr_linfo = attr->line_info_cnt; 5679 if (!nr_linfo) 5680 return 0; 5681 5682 rec_size = attr->line_info_rec_size; 5683 if (rec_size < MIN_BPF_LINEINFO_SIZE || 5684 rec_size > MAX_LINEINFO_REC_SIZE || 5685 rec_size & (sizeof(u32) - 1)) 5686 return -EINVAL; 5687 5688 /* Need to zero it in case the userspace may 5689 * pass in a smaller bpf_line_info object. 5690 */ 5691 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 5692 GFP_KERNEL | __GFP_NOWARN); 5693 if (!linfo) 5694 return -ENOMEM; 5695 5696 prog = env->prog; 5697 btf = prog->aux->btf; 5698 5699 s = 0; 5700 sub = env->subprog_info; 5701 ulinfo = u64_to_user_ptr(attr->line_info); 5702 expected_size = sizeof(struct bpf_line_info); 5703 ncopy = min_t(u32, expected_size, rec_size); 5704 for (i = 0; i < nr_linfo; i++) { 5705 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 5706 if (err) { 5707 if (err == -E2BIG) { 5708 verbose(env, "nonzero tailing record in line_info"); 5709 if (put_user(expected_size, 5710 &uattr->line_info_rec_size)) 5711 err = -EFAULT; 5712 } 5713 goto err_free; 5714 } 5715 5716 if (copy_from_user(&linfo[i], ulinfo, ncopy)) { 5717 err = -EFAULT; 5718 goto err_free; 5719 } 5720 5721 /* 5722 * Check insn_off to ensure 5723 * 1) strictly increasing AND 5724 * 2) bounded by prog->len 5725 * 5726 * The linfo[0].insn_off == 0 check logically falls into 5727 * the later "missing bpf_line_info for func..." case 5728 * because the first linfo[0].insn_off must be the 5729 * first sub also and the first sub must have 5730 * subprog_info[0].start == 0. 5731 */ 5732 if ((i && linfo[i].insn_off <= prev_offset) || 5733 linfo[i].insn_off >= prog->len) { 5734 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 5735 i, linfo[i].insn_off, prev_offset, 5736 prog->len); 5737 err = -EINVAL; 5738 goto err_free; 5739 } 5740 5741 if (!prog->insnsi[linfo[i].insn_off].code) { 5742 verbose(env, 5743 "Invalid insn code at line_info[%u].insn_off\n", 5744 i); 5745 err = -EINVAL; 5746 goto err_free; 5747 } 5748 5749 if (!btf_name_by_offset(btf, linfo[i].line_off) || 5750 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 5751 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 5752 err = -EINVAL; 5753 goto err_free; 5754 } 5755 5756 if (s != env->subprog_cnt) { 5757 if (linfo[i].insn_off == sub[s].start) { 5758 sub[s].linfo_idx = i; 5759 s++; 5760 } else if (sub[s].start < linfo[i].insn_off) { 5761 verbose(env, "missing bpf_line_info for func#%u\n", s); 5762 err = -EINVAL; 5763 goto err_free; 5764 } 5765 } 5766 5767 prev_offset = linfo[i].insn_off; 5768 ulinfo += rec_size; 5769 } 5770 5771 if (s != env->subprog_cnt) { 5772 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 5773 env->subprog_cnt - s, s); 5774 err = -EINVAL; 5775 goto err_free; 5776 } 5777 5778 prog->aux->linfo = linfo; 5779 prog->aux->nr_linfo = nr_linfo; 5780 5781 return 0; 5782 5783 err_free: 5784 kvfree(linfo); 5785 return err; 5786 } 5787 5788 static int check_btf_info(struct bpf_verifier_env *env, 5789 const union bpf_attr *attr, 5790 union bpf_attr __user *uattr) 5791 { 5792 struct btf *btf; 5793 int err; 5794 5795 if (!attr->func_info_cnt && !attr->line_info_cnt) 5796 return 0; 5797 5798 btf = btf_get_by_fd(attr->prog_btf_fd); 5799 if (IS_ERR(btf)) 5800 return PTR_ERR(btf); 5801 env->prog->aux->btf = btf; 5802 5803 err = check_btf_func(env, attr, uattr); 5804 if (err) 5805 return err; 5806 5807 err = check_btf_line(env, attr, uattr); 5808 if (err) 5809 return err; 5810 5811 return 0; 5812 } 5813 5814 /* check %cur's range satisfies %old's */ 5815 static bool range_within(struct bpf_reg_state *old, 5816 struct bpf_reg_state *cur) 5817 { 5818 return old->umin_value <= cur->umin_value && 5819 old->umax_value >= cur->umax_value && 5820 old->smin_value <= cur->smin_value && 5821 old->smax_value >= cur->smax_value; 5822 } 5823 5824 /* Maximum number of register states that can exist at once */ 5825 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) 5826 struct idpair { 5827 u32 old; 5828 u32 cur; 5829 }; 5830 5831 /* If in the old state two registers had the same id, then they need to have 5832 * the same id in the new state as well. But that id could be different from 5833 * the old state, so we need to track the mapping from old to new ids. 5834 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 5835 * regs with old id 5 must also have new id 9 for the new state to be safe. But 5836 * regs with a different old id could still have new id 9, we don't care about 5837 * that. 5838 * So we look through our idmap to see if this old id has been seen before. If 5839 * so, we require the new id to match; otherwise, we add the id pair to the map. 5840 */ 5841 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) 5842 { 5843 unsigned int i; 5844 5845 for (i = 0; i < ID_MAP_SIZE; i++) { 5846 if (!idmap[i].old) { 5847 /* Reached an empty slot; haven't seen this id before */ 5848 idmap[i].old = old_id; 5849 idmap[i].cur = cur_id; 5850 return true; 5851 } 5852 if (idmap[i].old == old_id) 5853 return idmap[i].cur == cur_id; 5854 } 5855 /* We ran out of idmap slots, which should be impossible */ 5856 WARN_ON_ONCE(1); 5857 return false; 5858 } 5859 5860 static void clean_func_state(struct bpf_verifier_env *env, 5861 struct bpf_func_state *st) 5862 { 5863 enum bpf_reg_liveness live; 5864 int i, j; 5865 5866 for (i = 0; i < BPF_REG_FP; i++) { 5867 live = st->regs[i].live; 5868 /* liveness must not touch this register anymore */ 5869 st->regs[i].live |= REG_LIVE_DONE; 5870 if (!(live & REG_LIVE_READ)) 5871 /* since the register is unused, clear its state 5872 * to make further comparison simpler 5873 */ 5874 __mark_reg_not_init(&st->regs[i]); 5875 } 5876 5877 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 5878 live = st->stack[i].spilled_ptr.live; 5879 /* liveness must not touch this stack slot anymore */ 5880 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 5881 if (!(live & REG_LIVE_READ)) { 5882 __mark_reg_not_init(&st->stack[i].spilled_ptr); 5883 for (j = 0; j < BPF_REG_SIZE; j++) 5884 st->stack[i].slot_type[j] = STACK_INVALID; 5885 } 5886 } 5887 } 5888 5889 static void clean_verifier_state(struct bpf_verifier_env *env, 5890 struct bpf_verifier_state *st) 5891 { 5892 int i; 5893 5894 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 5895 /* all regs in this state in all frames were already marked */ 5896 return; 5897 5898 for (i = 0; i <= st->curframe; i++) 5899 clean_func_state(env, st->frame[i]); 5900 } 5901 5902 /* the parentage chains form a tree. 5903 * the verifier states are added to state lists at given insn and 5904 * pushed into state stack for future exploration. 5905 * when the verifier reaches bpf_exit insn some of the verifer states 5906 * stored in the state lists have their final liveness state already, 5907 * but a lot of states will get revised from liveness point of view when 5908 * the verifier explores other branches. 5909 * Example: 5910 * 1: r0 = 1 5911 * 2: if r1 == 100 goto pc+1 5912 * 3: r0 = 2 5913 * 4: exit 5914 * when the verifier reaches exit insn the register r0 in the state list of 5915 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 5916 * of insn 2 and goes exploring further. At the insn 4 it will walk the 5917 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 5918 * 5919 * Since the verifier pushes the branch states as it sees them while exploring 5920 * the program the condition of walking the branch instruction for the second 5921 * time means that all states below this branch were already explored and 5922 * their final liveness markes are already propagated. 5923 * Hence when the verifier completes the search of state list in is_state_visited() 5924 * we can call this clean_live_states() function to mark all liveness states 5925 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 5926 * will not be used. 5927 * This function also clears the registers and stack for states that !READ 5928 * to simplify state merging. 5929 * 5930 * Important note here that walking the same branch instruction in the callee 5931 * doesn't meant that the states are DONE. The verifier has to compare 5932 * the callsites 5933 */ 5934 static void clean_live_states(struct bpf_verifier_env *env, int insn, 5935 struct bpf_verifier_state *cur) 5936 { 5937 struct bpf_verifier_state_list *sl; 5938 int i; 5939 5940 sl = env->explored_states[insn]; 5941 if (!sl) 5942 return; 5943 5944 while (sl != STATE_LIST_MARK) { 5945 if (sl->state.curframe != cur->curframe) 5946 goto next; 5947 for (i = 0; i <= cur->curframe; i++) 5948 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 5949 goto next; 5950 clean_verifier_state(env, &sl->state); 5951 next: 5952 sl = sl->next; 5953 } 5954 } 5955 5956 /* Returns true if (rold safe implies rcur safe) */ 5957 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 5958 struct idpair *idmap) 5959 { 5960 bool equal; 5961 5962 if (!(rold->live & REG_LIVE_READ)) 5963 /* explored state didn't use this */ 5964 return true; 5965 5966 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0; 5967 5968 if (rold->type == PTR_TO_STACK) 5969 /* two stack pointers are equal only if they're pointing to 5970 * the same stack frame, since fp-8 in foo != fp-8 in bar 5971 */ 5972 return equal && rold->frameno == rcur->frameno; 5973 5974 if (equal) 5975 return true; 5976 5977 if (rold->type == NOT_INIT) 5978 /* explored state can't have used this */ 5979 return true; 5980 if (rcur->type == NOT_INIT) 5981 return false; 5982 switch (rold->type) { 5983 case SCALAR_VALUE: 5984 if (rcur->type == SCALAR_VALUE) { 5985 /* new val must satisfy old val knowledge */ 5986 return range_within(rold, rcur) && 5987 tnum_in(rold->var_off, rcur->var_off); 5988 } else { 5989 /* We're trying to use a pointer in place of a scalar. 5990 * Even if the scalar was unbounded, this could lead to 5991 * pointer leaks because scalars are allowed to leak 5992 * while pointers are not. We could make this safe in 5993 * special cases if root is calling us, but it's 5994 * probably not worth the hassle. 5995 */ 5996 return false; 5997 } 5998 case PTR_TO_MAP_VALUE: 5999 /* If the new min/max/var_off satisfy the old ones and 6000 * everything else matches, we are OK. 6001 * 'id' is not compared, since it's only used for maps with 6002 * bpf_spin_lock inside map element and in such cases if 6003 * the rest of the prog is valid for one map element then 6004 * it's valid for all map elements regardless of the key 6005 * used in bpf_map_lookup() 6006 */ 6007 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 6008 range_within(rold, rcur) && 6009 tnum_in(rold->var_off, rcur->var_off); 6010 case PTR_TO_MAP_VALUE_OR_NULL: 6011 /* a PTR_TO_MAP_VALUE could be safe to use as a 6012 * PTR_TO_MAP_VALUE_OR_NULL into the same map. 6013 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- 6014 * checked, doing so could have affected others with the same 6015 * id, and we can't check for that because we lost the id when 6016 * we converted to a PTR_TO_MAP_VALUE. 6017 */ 6018 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) 6019 return false; 6020 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) 6021 return false; 6022 /* Check our ids match any regs they're supposed to */ 6023 return check_ids(rold->id, rcur->id, idmap); 6024 case PTR_TO_PACKET_META: 6025 case PTR_TO_PACKET: 6026 if (rcur->type != rold->type) 6027 return false; 6028 /* We must have at least as much range as the old ptr 6029 * did, so that any accesses which were safe before are 6030 * still safe. This is true even if old range < old off, 6031 * since someone could have accessed through (ptr - k), or 6032 * even done ptr -= k in a register, to get a safe access. 6033 */ 6034 if (rold->range > rcur->range) 6035 return false; 6036 /* If the offsets don't match, we can't trust our alignment; 6037 * nor can we be sure that we won't fall out of range. 6038 */ 6039 if (rold->off != rcur->off) 6040 return false; 6041 /* id relations must be preserved */ 6042 if (rold->id && !check_ids(rold->id, rcur->id, idmap)) 6043 return false; 6044 /* new val must satisfy old val knowledge */ 6045 return range_within(rold, rcur) && 6046 tnum_in(rold->var_off, rcur->var_off); 6047 case PTR_TO_CTX: 6048 case CONST_PTR_TO_MAP: 6049 case PTR_TO_PACKET_END: 6050 case PTR_TO_FLOW_KEYS: 6051 case PTR_TO_SOCKET: 6052 case PTR_TO_SOCKET_OR_NULL: 6053 case PTR_TO_SOCK_COMMON: 6054 case PTR_TO_SOCK_COMMON_OR_NULL: 6055 case PTR_TO_TCP_SOCK: 6056 case PTR_TO_TCP_SOCK_OR_NULL: 6057 /* Only valid matches are exact, which memcmp() above 6058 * would have accepted 6059 */ 6060 default: 6061 /* Don't know what's going on, just say it's not safe */ 6062 return false; 6063 } 6064 6065 /* Shouldn't get here; if we do, say it's not safe */ 6066 WARN_ON_ONCE(1); 6067 return false; 6068 } 6069 6070 static bool stacksafe(struct bpf_func_state *old, 6071 struct bpf_func_state *cur, 6072 struct idpair *idmap) 6073 { 6074 int i, spi; 6075 6076 /* walk slots of the explored stack and ignore any additional 6077 * slots in the current stack, since explored(safe) state 6078 * didn't use them 6079 */ 6080 for (i = 0; i < old->allocated_stack; i++) { 6081 spi = i / BPF_REG_SIZE; 6082 6083 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 6084 i += BPF_REG_SIZE - 1; 6085 /* explored state didn't use this */ 6086 continue; 6087 } 6088 6089 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 6090 continue; 6091 6092 /* explored stack has more populated slots than current stack 6093 * and these slots were used 6094 */ 6095 if (i >= cur->allocated_stack) 6096 return false; 6097 6098 /* if old state was safe with misc data in the stack 6099 * it will be safe with zero-initialized stack. 6100 * The opposite is not true 6101 */ 6102 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 6103 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 6104 continue; 6105 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 6106 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 6107 /* Ex: old explored (safe) state has STACK_SPILL in 6108 * this stack slot, but current has has STACK_MISC -> 6109 * this verifier states are not equivalent, 6110 * return false to continue verification of this path 6111 */ 6112 return false; 6113 if (i % BPF_REG_SIZE) 6114 continue; 6115 if (old->stack[spi].slot_type[0] != STACK_SPILL) 6116 continue; 6117 if (!regsafe(&old->stack[spi].spilled_ptr, 6118 &cur->stack[spi].spilled_ptr, 6119 idmap)) 6120 /* when explored and current stack slot are both storing 6121 * spilled registers, check that stored pointers types 6122 * are the same as well. 6123 * Ex: explored safe path could have stored 6124 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 6125 * but current path has stored: 6126 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 6127 * such verifier states are not equivalent. 6128 * return false to continue verification of this path 6129 */ 6130 return false; 6131 } 6132 return true; 6133 } 6134 6135 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur) 6136 { 6137 if (old->acquired_refs != cur->acquired_refs) 6138 return false; 6139 return !memcmp(old->refs, cur->refs, 6140 sizeof(*old->refs) * old->acquired_refs); 6141 } 6142 6143 /* compare two verifier states 6144 * 6145 * all states stored in state_list are known to be valid, since 6146 * verifier reached 'bpf_exit' instruction through them 6147 * 6148 * this function is called when verifier exploring different branches of 6149 * execution popped from the state stack. If it sees an old state that has 6150 * more strict register state and more strict stack state then this execution 6151 * branch doesn't need to be explored further, since verifier already 6152 * concluded that more strict state leads to valid finish. 6153 * 6154 * Therefore two states are equivalent if register state is more conservative 6155 * and explored stack state is more conservative than the current one. 6156 * Example: 6157 * explored current 6158 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 6159 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 6160 * 6161 * In other words if current stack state (one being explored) has more 6162 * valid slots than old one that already passed validation, it means 6163 * the verifier can stop exploring and conclude that current state is valid too 6164 * 6165 * Similarly with registers. If explored state has register type as invalid 6166 * whereas register type in current state is meaningful, it means that 6167 * the current state will reach 'bpf_exit' instruction safely 6168 */ 6169 static bool func_states_equal(struct bpf_func_state *old, 6170 struct bpf_func_state *cur) 6171 { 6172 struct idpair *idmap; 6173 bool ret = false; 6174 int i; 6175 6176 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); 6177 /* If we failed to allocate the idmap, just say it's not safe */ 6178 if (!idmap) 6179 return false; 6180 6181 for (i = 0; i < MAX_BPF_REG; i++) { 6182 if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) 6183 goto out_free; 6184 } 6185 6186 if (!stacksafe(old, cur, idmap)) 6187 goto out_free; 6188 6189 if (!refsafe(old, cur)) 6190 goto out_free; 6191 ret = true; 6192 out_free: 6193 kfree(idmap); 6194 return ret; 6195 } 6196 6197 static bool states_equal(struct bpf_verifier_env *env, 6198 struct bpf_verifier_state *old, 6199 struct bpf_verifier_state *cur) 6200 { 6201 int i; 6202 6203 if (old->curframe != cur->curframe) 6204 return false; 6205 6206 /* Verification state from speculative execution simulation 6207 * must never prune a non-speculative execution one. 6208 */ 6209 if (old->speculative && !cur->speculative) 6210 return false; 6211 6212 if (old->active_spin_lock != cur->active_spin_lock) 6213 return false; 6214 6215 /* for states to be equal callsites have to be the same 6216 * and all frame states need to be equivalent 6217 */ 6218 for (i = 0; i <= old->curframe; i++) { 6219 if (old->frame[i]->callsite != cur->frame[i]->callsite) 6220 return false; 6221 if (!func_states_equal(old->frame[i], cur->frame[i])) 6222 return false; 6223 } 6224 return true; 6225 } 6226 6227 static int propagate_liveness_reg(struct bpf_verifier_env *env, 6228 struct bpf_reg_state *reg, 6229 struct bpf_reg_state *parent_reg) 6230 { 6231 int err; 6232 6233 if (parent_reg->live & REG_LIVE_READ || !(reg->live & REG_LIVE_READ)) 6234 return 0; 6235 6236 err = mark_reg_read(env, reg, parent_reg); 6237 if (err) 6238 return err; 6239 6240 return 0; 6241 } 6242 6243 /* A write screens off any subsequent reads; but write marks come from the 6244 * straight-line code between a state and its parent. When we arrive at an 6245 * equivalent state (jump target or such) we didn't arrive by the straight-line 6246 * code, so read marks in the state must propagate to the parent regardless 6247 * of the state's write marks. That's what 'parent == state->parent' comparison 6248 * in mark_reg_read() is for. 6249 */ 6250 static int propagate_liveness(struct bpf_verifier_env *env, 6251 const struct bpf_verifier_state *vstate, 6252 struct bpf_verifier_state *vparent) 6253 { 6254 struct bpf_reg_state *state_reg, *parent_reg; 6255 struct bpf_func_state *state, *parent; 6256 int i, frame, err = 0; 6257 6258 if (vparent->curframe != vstate->curframe) { 6259 WARN(1, "propagate_live: parent frame %d current frame %d\n", 6260 vparent->curframe, vstate->curframe); 6261 return -EFAULT; 6262 } 6263 /* Propagate read liveness of registers... */ 6264 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 6265 for (frame = 0; frame <= vstate->curframe; frame++) { 6266 parent = vparent->frame[frame]; 6267 state = vstate->frame[frame]; 6268 parent_reg = parent->regs; 6269 state_reg = state->regs; 6270 /* We don't need to worry about FP liveness, it's read-only */ 6271 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 6272 err = propagate_liveness_reg(env, &state_reg[i], 6273 &parent_reg[i]); 6274 if (err) 6275 return err; 6276 } 6277 6278 /* Propagate stack slots. */ 6279 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 6280 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 6281 parent_reg = &parent->stack[i].spilled_ptr; 6282 state_reg = &state->stack[i].spilled_ptr; 6283 err = propagate_liveness_reg(env, state_reg, 6284 parent_reg); 6285 if (err) 6286 return err; 6287 } 6288 } 6289 return err; 6290 } 6291 6292 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 6293 { 6294 struct bpf_verifier_state_list *new_sl; 6295 struct bpf_verifier_state_list *sl, **pprev; 6296 struct bpf_verifier_state *cur = env->cur_state, *new; 6297 int i, j, err, states_cnt = 0; 6298 6299 pprev = &env->explored_states[insn_idx]; 6300 sl = *pprev; 6301 6302 if (!sl) 6303 /* this 'insn_idx' instruction wasn't marked, so we will not 6304 * be doing state search here 6305 */ 6306 return 0; 6307 6308 clean_live_states(env, insn_idx, cur); 6309 6310 while (sl != STATE_LIST_MARK) { 6311 if (states_equal(env, &sl->state, cur)) { 6312 sl->hit_cnt++; 6313 /* reached equivalent register/stack state, 6314 * prune the search. 6315 * Registers read by the continuation are read by us. 6316 * If we have any write marks in env->cur_state, they 6317 * will prevent corresponding reads in the continuation 6318 * from reaching our parent (an explored_state). Our 6319 * own state will get the read marks recorded, but 6320 * they'll be immediately forgotten as we're pruning 6321 * this state and will pop a new one. 6322 */ 6323 err = propagate_liveness(env, &sl->state, cur); 6324 if (err) 6325 return err; 6326 return 1; 6327 } 6328 states_cnt++; 6329 sl->miss_cnt++; 6330 /* heuristic to determine whether this state is beneficial 6331 * to keep checking from state equivalence point of view. 6332 * Higher numbers increase max_states_per_insn and verification time, 6333 * but do not meaningfully decrease insn_processed. 6334 */ 6335 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 6336 /* the state is unlikely to be useful. Remove it to 6337 * speed up verification 6338 */ 6339 *pprev = sl->next; 6340 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 6341 free_verifier_state(&sl->state, false); 6342 kfree(sl); 6343 env->peak_states--; 6344 } else { 6345 /* cannot free this state, since parentage chain may 6346 * walk it later. Add it for free_list instead to 6347 * be freed at the end of verification 6348 */ 6349 sl->next = env->free_list; 6350 env->free_list = sl; 6351 } 6352 sl = *pprev; 6353 continue; 6354 } 6355 pprev = &sl->next; 6356 sl = *pprev; 6357 } 6358 6359 if (env->max_states_per_insn < states_cnt) 6360 env->max_states_per_insn = states_cnt; 6361 6362 if (!env->allow_ptr_leaks && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 6363 return 0; 6364 6365 /* there were no equivalent states, remember current one. 6366 * technically the current state is not proven to be safe yet, 6367 * but it will either reach outer most bpf_exit (which means it's safe) 6368 * or it will be rejected. Since there are no loops, we won't be 6369 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 6370 * again on the way to bpf_exit 6371 */ 6372 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 6373 if (!new_sl) 6374 return -ENOMEM; 6375 env->total_states++; 6376 env->peak_states++; 6377 6378 /* add new state to the head of linked list */ 6379 new = &new_sl->state; 6380 err = copy_verifier_state(new, cur); 6381 if (err) { 6382 free_verifier_state(new, false); 6383 kfree(new_sl); 6384 return err; 6385 } 6386 new_sl->next = env->explored_states[insn_idx]; 6387 env->explored_states[insn_idx] = new_sl; 6388 /* connect new state to parentage chain. Current frame needs all 6389 * registers connected. Only r6 - r9 of the callers are alive (pushed 6390 * to the stack implicitly by JITs) so in callers' frames connect just 6391 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 6392 * the state of the call instruction (with WRITTEN set), and r0 comes 6393 * from callee with its full parentage chain, anyway. 6394 */ 6395 for (j = 0; j <= cur->curframe; j++) 6396 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 6397 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 6398 /* clear write marks in current state: the writes we did are not writes 6399 * our child did, so they don't screen off its reads from us. 6400 * (There are no read marks in current state, because reads always mark 6401 * their parent and current state never has children yet. Only 6402 * explored_states can get read marks.) 6403 */ 6404 for (i = 0; i < BPF_REG_FP; i++) 6405 cur->frame[cur->curframe]->regs[i].live = REG_LIVE_NONE; 6406 6407 /* all stack frames are accessible from callee, clear them all */ 6408 for (j = 0; j <= cur->curframe; j++) { 6409 struct bpf_func_state *frame = cur->frame[j]; 6410 struct bpf_func_state *newframe = new->frame[j]; 6411 6412 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 6413 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 6414 frame->stack[i].spilled_ptr.parent = 6415 &newframe->stack[i].spilled_ptr; 6416 } 6417 } 6418 return 0; 6419 } 6420 6421 /* Return true if it's OK to have the same insn return a different type. */ 6422 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 6423 { 6424 switch (type) { 6425 case PTR_TO_CTX: 6426 case PTR_TO_SOCKET: 6427 case PTR_TO_SOCKET_OR_NULL: 6428 case PTR_TO_SOCK_COMMON: 6429 case PTR_TO_SOCK_COMMON_OR_NULL: 6430 case PTR_TO_TCP_SOCK: 6431 case PTR_TO_TCP_SOCK_OR_NULL: 6432 return false; 6433 default: 6434 return true; 6435 } 6436 } 6437 6438 /* If an instruction was previously used with particular pointer types, then we 6439 * need to be careful to avoid cases such as the below, where it may be ok 6440 * for one branch accessing the pointer, but not ok for the other branch: 6441 * 6442 * R1 = sock_ptr 6443 * goto X; 6444 * ... 6445 * R1 = some_other_valid_ptr; 6446 * goto X; 6447 * ... 6448 * R2 = *(u32 *)(R1 + 0); 6449 */ 6450 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 6451 { 6452 return src != prev && (!reg_type_mismatch_ok(src) || 6453 !reg_type_mismatch_ok(prev)); 6454 } 6455 6456 static int do_check(struct bpf_verifier_env *env) 6457 { 6458 struct bpf_verifier_state *state; 6459 struct bpf_insn *insns = env->prog->insnsi; 6460 struct bpf_reg_state *regs; 6461 int insn_cnt = env->prog->len; 6462 bool do_print_state = false; 6463 6464 env->prev_linfo = NULL; 6465 6466 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 6467 if (!state) 6468 return -ENOMEM; 6469 state->curframe = 0; 6470 state->speculative = false; 6471 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 6472 if (!state->frame[0]) { 6473 kfree(state); 6474 return -ENOMEM; 6475 } 6476 env->cur_state = state; 6477 init_func_state(env, state->frame[0], 6478 BPF_MAIN_FUNC /* callsite */, 6479 0 /* frameno */, 6480 0 /* subprogno, zero == main subprog */); 6481 6482 for (;;) { 6483 struct bpf_insn *insn; 6484 u8 class; 6485 int err; 6486 6487 if (env->insn_idx >= insn_cnt) { 6488 verbose(env, "invalid insn idx %d insn_cnt %d\n", 6489 env->insn_idx, insn_cnt); 6490 return -EFAULT; 6491 } 6492 6493 insn = &insns[env->insn_idx]; 6494 class = BPF_CLASS(insn->code); 6495 6496 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 6497 verbose(env, 6498 "BPF program is too large. Processed %d insn\n", 6499 env->insn_processed); 6500 return -E2BIG; 6501 } 6502 6503 err = is_state_visited(env, env->insn_idx); 6504 if (err < 0) 6505 return err; 6506 if (err == 1) { 6507 /* found equivalent state, can prune the search */ 6508 if (env->log.level & BPF_LOG_LEVEL) { 6509 if (do_print_state) 6510 verbose(env, "\nfrom %d to %d%s: safe\n", 6511 env->prev_insn_idx, env->insn_idx, 6512 env->cur_state->speculative ? 6513 " (speculative execution)" : ""); 6514 else 6515 verbose(env, "%d: safe\n", env->insn_idx); 6516 } 6517 goto process_bpf_exit; 6518 } 6519 6520 if (signal_pending(current)) 6521 return -EAGAIN; 6522 6523 if (need_resched()) 6524 cond_resched(); 6525 6526 if (env->log.level & BPF_LOG_LEVEL2 || 6527 (env->log.level & BPF_LOG_LEVEL && do_print_state)) { 6528 if (env->log.level & BPF_LOG_LEVEL2) 6529 verbose(env, "%d:", env->insn_idx); 6530 else 6531 verbose(env, "\nfrom %d to %d%s:", 6532 env->prev_insn_idx, env->insn_idx, 6533 env->cur_state->speculative ? 6534 " (speculative execution)" : ""); 6535 print_verifier_state(env, state->frame[state->curframe]); 6536 do_print_state = false; 6537 } 6538 6539 if (env->log.level & BPF_LOG_LEVEL) { 6540 const struct bpf_insn_cbs cbs = { 6541 .cb_print = verbose, 6542 .private_data = env, 6543 }; 6544 6545 verbose_linfo(env, env->insn_idx, "; "); 6546 verbose(env, "%d: ", env->insn_idx); 6547 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 6548 } 6549 6550 if (bpf_prog_is_dev_bound(env->prog->aux)) { 6551 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 6552 env->prev_insn_idx); 6553 if (err) 6554 return err; 6555 } 6556 6557 regs = cur_regs(env); 6558 env->insn_aux_data[env->insn_idx].seen = true; 6559 6560 if (class == BPF_ALU || class == BPF_ALU64) { 6561 err = check_alu_op(env, insn); 6562 if (err) 6563 return err; 6564 6565 } else if (class == BPF_LDX) { 6566 enum bpf_reg_type *prev_src_type, src_reg_type; 6567 6568 /* check for reserved fields is already done */ 6569 6570 /* check src operand */ 6571 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6572 if (err) 6573 return err; 6574 6575 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 6576 if (err) 6577 return err; 6578 6579 src_reg_type = regs[insn->src_reg].type; 6580 6581 /* check that memory (src_reg + off) is readable, 6582 * the state of dst_reg will be updated by this func 6583 */ 6584 err = check_mem_access(env, env->insn_idx, insn->src_reg, 6585 insn->off, BPF_SIZE(insn->code), 6586 BPF_READ, insn->dst_reg, false); 6587 if (err) 6588 return err; 6589 6590 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 6591 6592 if (*prev_src_type == NOT_INIT) { 6593 /* saw a valid insn 6594 * dst_reg = *(u32 *)(src_reg + off) 6595 * save type to validate intersecting paths 6596 */ 6597 *prev_src_type = src_reg_type; 6598 6599 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 6600 /* ABuser program is trying to use the same insn 6601 * dst_reg = *(u32*) (src_reg + off) 6602 * with different pointer types: 6603 * src_reg == ctx in one branch and 6604 * src_reg == stack|map in some other branch. 6605 * Reject it. 6606 */ 6607 verbose(env, "same insn cannot be used with different pointers\n"); 6608 return -EINVAL; 6609 } 6610 6611 } else if (class == BPF_STX) { 6612 enum bpf_reg_type *prev_dst_type, dst_reg_type; 6613 6614 if (BPF_MODE(insn->code) == BPF_XADD) { 6615 err = check_xadd(env, env->insn_idx, insn); 6616 if (err) 6617 return err; 6618 env->insn_idx++; 6619 continue; 6620 } 6621 6622 /* check src1 operand */ 6623 err = check_reg_arg(env, insn->src_reg, SRC_OP); 6624 if (err) 6625 return err; 6626 /* check src2 operand */ 6627 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6628 if (err) 6629 return err; 6630 6631 dst_reg_type = regs[insn->dst_reg].type; 6632 6633 /* check that memory (dst_reg + off) is writeable */ 6634 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 6635 insn->off, BPF_SIZE(insn->code), 6636 BPF_WRITE, insn->src_reg, false); 6637 if (err) 6638 return err; 6639 6640 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 6641 6642 if (*prev_dst_type == NOT_INIT) { 6643 *prev_dst_type = dst_reg_type; 6644 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 6645 verbose(env, "same insn cannot be used with different pointers\n"); 6646 return -EINVAL; 6647 } 6648 6649 } else if (class == BPF_ST) { 6650 if (BPF_MODE(insn->code) != BPF_MEM || 6651 insn->src_reg != BPF_REG_0) { 6652 verbose(env, "BPF_ST uses reserved fields\n"); 6653 return -EINVAL; 6654 } 6655 /* check src operand */ 6656 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 6657 if (err) 6658 return err; 6659 6660 if (is_ctx_reg(env, insn->dst_reg)) { 6661 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 6662 insn->dst_reg, 6663 reg_type_str[reg_state(env, insn->dst_reg)->type]); 6664 return -EACCES; 6665 } 6666 6667 /* check that memory (dst_reg + off) is writeable */ 6668 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 6669 insn->off, BPF_SIZE(insn->code), 6670 BPF_WRITE, -1, false); 6671 if (err) 6672 return err; 6673 6674 } else if (class == BPF_JMP || class == BPF_JMP32) { 6675 u8 opcode = BPF_OP(insn->code); 6676 6677 if (opcode == BPF_CALL) { 6678 if (BPF_SRC(insn->code) != BPF_K || 6679 insn->off != 0 || 6680 (insn->src_reg != BPF_REG_0 && 6681 insn->src_reg != BPF_PSEUDO_CALL) || 6682 insn->dst_reg != BPF_REG_0 || 6683 class == BPF_JMP32) { 6684 verbose(env, "BPF_CALL uses reserved fields\n"); 6685 return -EINVAL; 6686 } 6687 6688 if (env->cur_state->active_spin_lock && 6689 (insn->src_reg == BPF_PSEUDO_CALL || 6690 insn->imm != BPF_FUNC_spin_unlock)) { 6691 verbose(env, "function calls are not allowed while holding a lock\n"); 6692 return -EINVAL; 6693 } 6694 if (insn->src_reg == BPF_PSEUDO_CALL) 6695 err = check_func_call(env, insn, &env->insn_idx); 6696 else 6697 err = check_helper_call(env, insn->imm, env->insn_idx); 6698 if (err) 6699 return err; 6700 6701 } else if (opcode == BPF_JA) { 6702 if (BPF_SRC(insn->code) != BPF_K || 6703 insn->imm != 0 || 6704 insn->src_reg != BPF_REG_0 || 6705 insn->dst_reg != BPF_REG_0 || 6706 class == BPF_JMP32) { 6707 verbose(env, "BPF_JA uses reserved fields\n"); 6708 return -EINVAL; 6709 } 6710 6711 env->insn_idx += insn->off + 1; 6712 continue; 6713 6714 } else if (opcode == BPF_EXIT) { 6715 if (BPF_SRC(insn->code) != BPF_K || 6716 insn->imm != 0 || 6717 insn->src_reg != BPF_REG_0 || 6718 insn->dst_reg != BPF_REG_0 || 6719 class == BPF_JMP32) { 6720 verbose(env, "BPF_EXIT uses reserved fields\n"); 6721 return -EINVAL; 6722 } 6723 6724 if (env->cur_state->active_spin_lock) { 6725 verbose(env, "bpf_spin_unlock is missing\n"); 6726 return -EINVAL; 6727 } 6728 6729 if (state->curframe) { 6730 /* exit from nested function */ 6731 env->prev_insn_idx = env->insn_idx; 6732 err = prepare_func_exit(env, &env->insn_idx); 6733 if (err) 6734 return err; 6735 do_print_state = true; 6736 continue; 6737 } 6738 6739 err = check_reference_leak(env); 6740 if (err) 6741 return err; 6742 6743 /* eBPF calling convetion is such that R0 is used 6744 * to return the value from eBPF program. 6745 * Make sure that it's readable at this time 6746 * of bpf_exit, which means that program wrote 6747 * something into it earlier 6748 */ 6749 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 6750 if (err) 6751 return err; 6752 6753 if (is_pointer_value(env, BPF_REG_0)) { 6754 verbose(env, "R0 leaks addr as return value\n"); 6755 return -EACCES; 6756 } 6757 6758 err = check_return_code(env); 6759 if (err) 6760 return err; 6761 process_bpf_exit: 6762 err = pop_stack(env, &env->prev_insn_idx, 6763 &env->insn_idx); 6764 if (err < 0) { 6765 if (err != -ENOENT) 6766 return err; 6767 break; 6768 } else { 6769 do_print_state = true; 6770 continue; 6771 } 6772 } else { 6773 err = check_cond_jmp_op(env, insn, &env->insn_idx); 6774 if (err) 6775 return err; 6776 } 6777 } else if (class == BPF_LD) { 6778 u8 mode = BPF_MODE(insn->code); 6779 6780 if (mode == BPF_ABS || mode == BPF_IND) { 6781 err = check_ld_abs(env, insn); 6782 if (err) 6783 return err; 6784 6785 } else if (mode == BPF_IMM) { 6786 err = check_ld_imm(env, insn); 6787 if (err) 6788 return err; 6789 6790 env->insn_idx++; 6791 env->insn_aux_data[env->insn_idx].seen = true; 6792 } else { 6793 verbose(env, "invalid BPF_LD mode\n"); 6794 return -EINVAL; 6795 } 6796 } else { 6797 verbose(env, "unknown insn class %d\n", class); 6798 return -EINVAL; 6799 } 6800 6801 env->insn_idx++; 6802 } 6803 6804 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 6805 return 0; 6806 } 6807 6808 static int check_map_prealloc(struct bpf_map *map) 6809 { 6810 return (map->map_type != BPF_MAP_TYPE_HASH && 6811 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 6812 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || 6813 !(map->map_flags & BPF_F_NO_PREALLOC); 6814 } 6815 6816 static bool is_tracing_prog_type(enum bpf_prog_type type) 6817 { 6818 switch (type) { 6819 case BPF_PROG_TYPE_KPROBE: 6820 case BPF_PROG_TYPE_TRACEPOINT: 6821 case BPF_PROG_TYPE_PERF_EVENT: 6822 case BPF_PROG_TYPE_RAW_TRACEPOINT: 6823 return true; 6824 default: 6825 return false; 6826 } 6827 } 6828 6829 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 6830 struct bpf_map *map, 6831 struct bpf_prog *prog) 6832 6833 { 6834 /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use 6835 * preallocated hash maps, since doing memory allocation 6836 * in overflow_handler can crash depending on where nmi got 6837 * triggered. 6838 */ 6839 if (prog->type == BPF_PROG_TYPE_PERF_EVENT) { 6840 if (!check_map_prealloc(map)) { 6841 verbose(env, "perf_event programs can only use preallocated hash map\n"); 6842 return -EINVAL; 6843 } 6844 if (map->inner_map_meta && 6845 !check_map_prealloc(map->inner_map_meta)) { 6846 verbose(env, "perf_event programs can only use preallocated inner hash map\n"); 6847 return -EINVAL; 6848 } 6849 } 6850 6851 if ((is_tracing_prog_type(prog->type) || 6852 prog->type == BPF_PROG_TYPE_SOCKET_FILTER) && 6853 map_value_has_spin_lock(map)) { 6854 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 6855 return -EINVAL; 6856 } 6857 6858 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) && 6859 !bpf_offload_prog_map_match(prog, map)) { 6860 verbose(env, "offload device mismatch between prog and map\n"); 6861 return -EINVAL; 6862 } 6863 6864 return 0; 6865 } 6866 6867 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 6868 { 6869 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 6870 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 6871 } 6872 6873 /* look for pseudo eBPF instructions that access map FDs and 6874 * replace them with actual map pointers 6875 */ 6876 static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) 6877 { 6878 struct bpf_insn *insn = env->prog->insnsi; 6879 int insn_cnt = env->prog->len; 6880 int i, j, err; 6881 6882 err = bpf_prog_calc_tag(env->prog); 6883 if (err) 6884 return err; 6885 6886 for (i = 0; i < insn_cnt; i++, insn++) { 6887 if (BPF_CLASS(insn->code) == BPF_LDX && 6888 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 6889 verbose(env, "BPF_LDX uses reserved fields\n"); 6890 return -EINVAL; 6891 } 6892 6893 if (BPF_CLASS(insn->code) == BPF_STX && 6894 ((BPF_MODE(insn->code) != BPF_MEM && 6895 BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { 6896 verbose(env, "BPF_STX uses reserved fields\n"); 6897 return -EINVAL; 6898 } 6899 6900 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 6901 struct bpf_insn_aux_data *aux; 6902 struct bpf_map *map; 6903 struct fd f; 6904 u64 addr; 6905 6906 if (i == insn_cnt - 1 || insn[1].code != 0 || 6907 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 6908 insn[1].off != 0) { 6909 verbose(env, "invalid bpf_ld_imm64 insn\n"); 6910 return -EINVAL; 6911 } 6912 6913 if (insn[0].src_reg == 0) 6914 /* valid generic load 64-bit imm */ 6915 goto next_insn; 6916 6917 /* In final convert_pseudo_ld_imm64() step, this is 6918 * converted into regular 64-bit imm load insn. 6919 */ 6920 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD && 6921 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) || 6922 (insn[0].src_reg == BPF_PSEUDO_MAP_FD && 6923 insn[1].imm != 0)) { 6924 verbose(env, 6925 "unrecognized bpf_ld_imm64 insn\n"); 6926 return -EINVAL; 6927 } 6928 6929 f = fdget(insn[0].imm); 6930 map = __bpf_map_get(f); 6931 if (IS_ERR(map)) { 6932 verbose(env, "fd %d is not pointing to valid bpf_map\n", 6933 insn[0].imm); 6934 return PTR_ERR(map); 6935 } 6936 6937 err = check_map_prog_compatibility(env, map, env->prog); 6938 if (err) { 6939 fdput(f); 6940 return err; 6941 } 6942 6943 aux = &env->insn_aux_data[i]; 6944 if (insn->src_reg == BPF_PSEUDO_MAP_FD) { 6945 addr = (unsigned long)map; 6946 } else { 6947 u32 off = insn[1].imm; 6948 6949 if (off >= BPF_MAX_VAR_OFF) { 6950 verbose(env, "direct value offset of %u is not allowed\n", off); 6951 fdput(f); 6952 return -EINVAL; 6953 } 6954 6955 if (!map->ops->map_direct_value_addr) { 6956 verbose(env, "no direct value access support for this map type\n"); 6957 fdput(f); 6958 return -EINVAL; 6959 } 6960 6961 err = map->ops->map_direct_value_addr(map, &addr, off); 6962 if (err) { 6963 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 6964 map->value_size, off); 6965 fdput(f); 6966 return err; 6967 } 6968 6969 aux->map_off = off; 6970 addr += off; 6971 } 6972 6973 insn[0].imm = (u32)addr; 6974 insn[1].imm = addr >> 32; 6975 6976 /* check whether we recorded this map already */ 6977 for (j = 0; j < env->used_map_cnt; j++) { 6978 if (env->used_maps[j] == map) { 6979 aux->map_index = j; 6980 fdput(f); 6981 goto next_insn; 6982 } 6983 } 6984 6985 if (env->used_map_cnt >= MAX_USED_MAPS) { 6986 fdput(f); 6987 return -E2BIG; 6988 } 6989 6990 /* hold the map. If the program is rejected by verifier, 6991 * the map will be released by release_maps() or it 6992 * will be used by the valid program until it's unloaded 6993 * and all maps are released in free_used_maps() 6994 */ 6995 map = bpf_map_inc(map, false); 6996 if (IS_ERR(map)) { 6997 fdput(f); 6998 return PTR_ERR(map); 6999 } 7000 7001 aux->map_index = env->used_map_cnt; 7002 env->used_maps[env->used_map_cnt++] = map; 7003 7004 if (bpf_map_is_cgroup_storage(map) && 7005 bpf_cgroup_storage_assign(env->prog, map)) { 7006 verbose(env, "only one cgroup storage of each type is allowed\n"); 7007 fdput(f); 7008 return -EBUSY; 7009 } 7010 7011 fdput(f); 7012 next_insn: 7013 insn++; 7014 i++; 7015 continue; 7016 } 7017 7018 /* Basic sanity check before we invest more work here. */ 7019 if (!bpf_opcode_in_insntable(insn->code)) { 7020 verbose(env, "unknown opcode %02x\n", insn->code); 7021 return -EINVAL; 7022 } 7023 } 7024 7025 /* now all pseudo BPF_LD_IMM64 instructions load valid 7026 * 'struct bpf_map *' into a register instead of user map_fd. 7027 * These pointers will be used later by verifier to validate map access. 7028 */ 7029 return 0; 7030 } 7031 7032 /* drop refcnt of maps used by the rejected program */ 7033 static void release_maps(struct bpf_verifier_env *env) 7034 { 7035 enum bpf_cgroup_storage_type stype; 7036 int i; 7037 7038 for_each_cgroup_storage_type(stype) { 7039 if (!env->prog->aux->cgroup_storage[stype]) 7040 continue; 7041 bpf_cgroup_storage_release(env->prog, 7042 env->prog->aux->cgroup_storage[stype]); 7043 } 7044 7045 for (i = 0; i < env->used_map_cnt; i++) 7046 bpf_map_put(env->used_maps[i]); 7047 } 7048 7049 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 7050 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 7051 { 7052 struct bpf_insn *insn = env->prog->insnsi; 7053 int insn_cnt = env->prog->len; 7054 int i; 7055 7056 for (i = 0; i < insn_cnt; i++, insn++) 7057 if (insn->code == (BPF_LD | BPF_IMM | BPF_DW)) 7058 insn->src_reg = 0; 7059 } 7060 7061 /* single env->prog->insni[off] instruction was replaced with the range 7062 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 7063 * [0, off) and [off, end) to new locations, so the patched range stays zero 7064 */ 7065 static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, 7066 u32 off, u32 cnt) 7067 { 7068 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; 7069 int i; 7070 7071 if (cnt == 1) 7072 return 0; 7073 new_data = vzalloc(array_size(prog_len, 7074 sizeof(struct bpf_insn_aux_data))); 7075 if (!new_data) 7076 return -ENOMEM; 7077 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 7078 memcpy(new_data + off + cnt - 1, old_data + off, 7079 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 7080 for (i = off; i < off + cnt - 1; i++) 7081 new_data[i].seen = true; 7082 env->insn_aux_data = new_data; 7083 vfree(old_data); 7084 return 0; 7085 } 7086 7087 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 7088 { 7089 int i; 7090 7091 if (len == 1) 7092 return; 7093 /* NOTE: fake 'exit' subprog should be updated as well. */ 7094 for (i = 0; i <= env->subprog_cnt; i++) { 7095 if (env->subprog_info[i].start <= off) 7096 continue; 7097 env->subprog_info[i].start += len - 1; 7098 } 7099 } 7100 7101 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 7102 const struct bpf_insn *patch, u32 len) 7103 { 7104 struct bpf_prog *new_prog; 7105 7106 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 7107 if (IS_ERR(new_prog)) { 7108 if (PTR_ERR(new_prog) == -ERANGE) 7109 verbose(env, 7110 "insn %d cannot be patched due to 16-bit range\n", 7111 env->insn_aux_data[off].orig_idx); 7112 return NULL; 7113 } 7114 if (adjust_insn_aux_data(env, new_prog->len, off, len)) 7115 return NULL; 7116 adjust_subprog_starts(env, off, len); 7117 return new_prog; 7118 } 7119 7120 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 7121 u32 off, u32 cnt) 7122 { 7123 int i, j; 7124 7125 /* find first prog starting at or after off (first to remove) */ 7126 for (i = 0; i < env->subprog_cnt; i++) 7127 if (env->subprog_info[i].start >= off) 7128 break; 7129 /* find first prog starting at or after off + cnt (first to stay) */ 7130 for (j = i; j < env->subprog_cnt; j++) 7131 if (env->subprog_info[j].start >= off + cnt) 7132 break; 7133 /* if j doesn't start exactly at off + cnt, we are just removing 7134 * the front of previous prog 7135 */ 7136 if (env->subprog_info[j].start != off + cnt) 7137 j--; 7138 7139 if (j > i) { 7140 struct bpf_prog_aux *aux = env->prog->aux; 7141 int move; 7142 7143 /* move fake 'exit' subprog as well */ 7144 move = env->subprog_cnt + 1 - j; 7145 7146 memmove(env->subprog_info + i, 7147 env->subprog_info + j, 7148 sizeof(*env->subprog_info) * move); 7149 env->subprog_cnt -= j - i; 7150 7151 /* remove func_info */ 7152 if (aux->func_info) { 7153 move = aux->func_info_cnt - j; 7154 7155 memmove(aux->func_info + i, 7156 aux->func_info + j, 7157 sizeof(*aux->func_info) * move); 7158 aux->func_info_cnt -= j - i; 7159 /* func_info->insn_off is set after all code rewrites, 7160 * in adjust_btf_func() - no need to adjust 7161 */ 7162 } 7163 } else { 7164 /* convert i from "first prog to remove" to "first to adjust" */ 7165 if (env->subprog_info[i].start == off) 7166 i++; 7167 } 7168 7169 /* update fake 'exit' subprog as well */ 7170 for (; i <= env->subprog_cnt; i++) 7171 env->subprog_info[i].start -= cnt; 7172 7173 return 0; 7174 } 7175 7176 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 7177 u32 cnt) 7178 { 7179 struct bpf_prog *prog = env->prog; 7180 u32 i, l_off, l_cnt, nr_linfo; 7181 struct bpf_line_info *linfo; 7182 7183 nr_linfo = prog->aux->nr_linfo; 7184 if (!nr_linfo) 7185 return 0; 7186 7187 linfo = prog->aux->linfo; 7188 7189 /* find first line info to remove, count lines to be removed */ 7190 for (i = 0; i < nr_linfo; i++) 7191 if (linfo[i].insn_off >= off) 7192 break; 7193 7194 l_off = i; 7195 l_cnt = 0; 7196 for (; i < nr_linfo; i++) 7197 if (linfo[i].insn_off < off + cnt) 7198 l_cnt++; 7199 else 7200 break; 7201 7202 /* First live insn doesn't match first live linfo, it needs to "inherit" 7203 * last removed linfo. prog is already modified, so prog->len == off 7204 * means no live instructions after (tail of the program was removed). 7205 */ 7206 if (prog->len != off && l_cnt && 7207 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 7208 l_cnt--; 7209 linfo[--i].insn_off = off + cnt; 7210 } 7211 7212 /* remove the line info which refer to the removed instructions */ 7213 if (l_cnt) { 7214 memmove(linfo + l_off, linfo + i, 7215 sizeof(*linfo) * (nr_linfo - i)); 7216 7217 prog->aux->nr_linfo -= l_cnt; 7218 nr_linfo = prog->aux->nr_linfo; 7219 } 7220 7221 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 7222 for (i = l_off; i < nr_linfo; i++) 7223 linfo[i].insn_off -= cnt; 7224 7225 /* fix up all subprogs (incl. 'exit') which start >= off */ 7226 for (i = 0; i <= env->subprog_cnt; i++) 7227 if (env->subprog_info[i].linfo_idx > l_off) { 7228 /* program may have started in the removed region but 7229 * may not be fully removed 7230 */ 7231 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 7232 env->subprog_info[i].linfo_idx -= l_cnt; 7233 else 7234 env->subprog_info[i].linfo_idx = l_off; 7235 } 7236 7237 return 0; 7238 } 7239 7240 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 7241 { 7242 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 7243 unsigned int orig_prog_len = env->prog->len; 7244 int err; 7245 7246 if (bpf_prog_is_dev_bound(env->prog->aux)) 7247 bpf_prog_offload_remove_insns(env, off, cnt); 7248 7249 err = bpf_remove_insns(env->prog, off, cnt); 7250 if (err) 7251 return err; 7252 7253 err = adjust_subprog_starts_after_remove(env, off, cnt); 7254 if (err) 7255 return err; 7256 7257 err = bpf_adj_linfo_after_remove(env, off, cnt); 7258 if (err) 7259 return err; 7260 7261 memmove(aux_data + off, aux_data + off + cnt, 7262 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 7263 7264 return 0; 7265 } 7266 7267 /* The verifier does more data flow analysis than llvm and will not 7268 * explore branches that are dead at run time. Malicious programs can 7269 * have dead code too. Therefore replace all dead at-run-time code 7270 * with 'ja -1'. 7271 * 7272 * Just nops are not optimal, e.g. if they would sit at the end of the 7273 * program and through another bug we would manage to jump there, then 7274 * we'd execute beyond program memory otherwise. Returning exception 7275 * code also wouldn't work since we can have subprogs where the dead 7276 * code could be located. 7277 */ 7278 static void sanitize_dead_code(struct bpf_verifier_env *env) 7279 { 7280 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 7281 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 7282 struct bpf_insn *insn = env->prog->insnsi; 7283 const int insn_cnt = env->prog->len; 7284 int i; 7285 7286 for (i = 0; i < insn_cnt; i++) { 7287 if (aux_data[i].seen) 7288 continue; 7289 memcpy(insn + i, &trap, sizeof(trap)); 7290 } 7291 } 7292 7293 static bool insn_is_cond_jump(u8 code) 7294 { 7295 u8 op; 7296 7297 if (BPF_CLASS(code) == BPF_JMP32) 7298 return true; 7299 7300 if (BPF_CLASS(code) != BPF_JMP) 7301 return false; 7302 7303 op = BPF_OP(code); 7304 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 7305 } 7306 7307 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 7308 { 7309 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 7310 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 7311 struct bpf_insn *insn = env->prog->insnsi; 7312 const int insn_cnt = env->prog->len; 7313 int i; 7314 7315 for (i = 0; i < insn_cnt; i++, insn++) { 7316 if (!insn_is_cond_jump(insn->code)) 7317 continue; 7318 7319 if (!aux_data[i + 1].seen) 7320 ja.off = insn->off; 7321 else if (!aux_data[i + 1 + insn->off].seen) 7322 ja.off = 0; 7323 else 7324 continue; 7325 7326 if (bpf_prog_is_dev_bound(env->prog->aux)) 7327 bpf_prog_offload_replace_insn(env, i, &ja); 7328 7329 memcpy(insn, &ja, sizeof(ja)); 7330 } 7331 } 7332 7333 static int opt_remove_dead_code(struct bpf_verifier_env *env) 7334 { 7335 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 7336 int insn_cnt = env->prog->len; 7337 int i, err; 7338 7339 for (i = 0; i < insn_cnt; i++) { 7340 int j; 7341 7342 j = 0; 7343 while (i + j < insn_cnt && !aux_data[i + j].seen) 7344 j++; 7345 if (!j) 7346 continue; 7347 7348 err = verifier_remove_insns(env, i, j); 7349 if (err) 7350 return err; 7351 insn_cnt = env->prog->len; 7352 } 7353 7354 return 0; 7355 } 7356 7357 static int opt_remove_nops(struct bpf_verifier_env *env) 7358 { 7359 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 7360 struct bpf_insn *insn = env->prog->insnsi; 7361 int insn_cnt = env->prog->len; 7362 int i, err; 7363 7364 for (i = 0; i < insn_cnt; i++) { 7365 if (memcmp(&insn[i], &ja, sizeof(ja))) 7366 continue; 7367 7368 err = verifier_remove_insns(env, i, 1); 7369 if (err) 7370 return err; 7371 insn_cnt--; 7372 i--; 7373 } 7374 7375 return 0; 7376 } 7377 7378 /* convert load instructions that access fields of a context type into a 7379 * sequence of instructions that access fields of the underlying structure: 7380 * struct __sk_buff -> struct sk_buff 7381 * struct bpf_sock_ops -> struct sock 7382 */ 7383 static int convert_ctx_accesses(struct bpf_verifier_env *env) 7384 { 7385 const struct bpf_verifier_ops *ops = env->ops; 7386 int i, cnt, size, ctx_field_size, delta = 0; 7387 const int insn_cnt = env->prog->len; 7388 struct bpf_insn insn_buf[16], *insn; 7389 u32 target_size, size_default, off; 7390 struct bpf_prog *new_prog; 7391 enum bpf_access_type type; 7392 bool is_narrower_load; 7393 7394 if (ops->gen_prologue || env->seen_direct_write) { 7395 if (!ops->gen_prologue) { 7396 verbose(env, "bpf verifier is misconfigured\n"); 7397 return -EINVAL; 7398 } 7399 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 7400 env->prog); 7401 if (cnt >= ARRAY_SIZE(insn_buf)) { 7402 verbose(env, "bpf verifier is misconfigured\n"); 7403 return -EINVAL; 7404 } else if (cnt) { 7405 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 7406 if (!new_prog) 7407 return -ENOMEM; 7408 7409 env->prog = new_prog; 7410 delta += cnt - 1; 7411 } 7412 } 7413 7414 if (bpf_prog_is_dev_bound(env->prog->aux)) 7415 return 0; 7416 7417 insn = env->prog->insnsi + delta; 7418 7419 for (i = 0; i < insn_cnt; i++, insn++) { 7420 bpf_convert_ctx_access_t convert_ctx_access; 7421 7422 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 7423 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 7424 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 7425 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) 7426 type = BPF_READ; 7427 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 7428 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 7429 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 7430 insn->code == (BPF_STX | BPF_MEM | BPF_DW)) 7431 type = BPF_WRITE; 7432 else 7433 continue; 7434 7435 if (type == BPF_WRITE && 7436 env->insn_aux_data[i + delta].sanitize_stack_off) { 7437 struct bpf_insn patch[] = { 7438 /* Sanitize suspicious stack slot with zero. 7439 * There are no memory dependencies for this store, 7440 * since it's only using frame pointer and immediate 7441 * constant of zero 7442 */ 7443 BPF_ST_MEM(BPF_DW, BPF_REG_FP, 7444 env->insn_aux_data[i + delta].sanitize_stack_off, 7445 0), 7446 /* the original STX instruction will immediately 7447 * overwrite the same stack slot with appropriate value 7448 */ 7449 *insn, 7450 }; 7451 7452 cnt = ARRAY_SIZE(patch); 7453 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 7454 if (!new_prog) 7455 return -ENOMEM; 7456 7457 delta += cnt - 1; 7458 env->prog = new_prog; 7459 insn = new_prog->insnsi + i + delta; 7460 continue; 7461 } 7462 7463 switch (env->insn_aux_data[i + delta].ptr_type) { 7464 case PTR_TO_CTX: 7465 if (!ops->convert_ctx_access) 7466 continue; 7467 convert_ctx_access = ops->convert_ctx_access; 7468 break; 7469 case PTR_TO_SOCKET: 7470 case PTR_TO_SOCK_COMMON: 7471 convert_ctx_access = bpf_sock_convert_ctx_access; 7472 break; 7473 case PTR_TO_TCP_SOCK: 7474 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 7475 break; 7476 default: 7477 continue; 7478 } 7479 7480 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 7481 size = BPF_LDST_BYTES(insn); 7482 7483 /* If the read access is a narrower load of the field, 7484 * convert to a 4/8-byte load, to minimum program type specific 7485 * convert_ctx_access changes. If conversion is successful, 7486 * we will apply proper mask to the result. 7487 */ 7488 is_narrower_load = size < ctx_field_size; 7489 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 7490 off = insn->off; 7491 if (is_narrower_load) { 7492 u8 size_code; 7493 7494 if (type == BPF_WRITE) { 7495 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 7496 return -EINVAL; 7497 } 7498 7499 size_code = BPF_H; 7500 if (ctx_field_size == 4) 7501 size_code = BPF_W; 7502 else if (ctx_field_size == 8) 7503 size_code = BPF_DW; 7504 7505 insn->off = off & ~(size_default - 1); 7506 insn->code = BPF_LDX | BPF_MEM | size_code; 7507 } 7508 7509 target_size = 0; 7510 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 7511 &target_size); 7512 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 7513 (ctx_field_size && !target_size)) { 7514 verbose(env, "bpf verifier is misconfigured\n"); 7515 return -EINVAL; 7516 } 7517 7518 if (is_narrower_load && size < target_size) { 7519 u8 shift = (off & (size_default - 1)) * 8; 7520 7521 if (ctx_field_size <= 4) { 7522 if (shift) 7523 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 7524 insn->dst_reg, 7525 shift); 7526 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 7527 (1 << size * 8) - 1); 7528 } else { 7529 if (shift) 7530 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 7531 insn->dst_reg, 7532 shift); 7533 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 7534 (1 << size * 8) - 1); 7535 } 7536 } 7537 7538 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 7539 if (!new_prog) 7540 return -ENOMEM; 7541 7542 delta += cnt - 1; 7543 7544 /* keep walking new program and skip insns we just inserted */ 7545 env->prog = new_prog; 7546 insn = new_prog->insnsi + i + delta; 7547 } 7548 7549 return 0; 7550 } 7551 7552 static int jit_subprogs(struct bpf_verifier_env *env) 7553 { 7554 struct bpf_prog *prog = env->prog, **func, *tmp; 7555 int i, j, subprog_start, subprog_end = 0, len, subprog; 7556 struct bpf_insn *insn; 7557 void *old_bpf_func; 7558 int err; 7559 7560 if (env->subprog_cnt <= 1) 7561 return 0; 7562 7563 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 7564 if (insn->code != (BPF_JMP | BPF_CALL) || 7565 insn->src_reg != BPF_PSEUDO_CALL) 7566 continue; 7567 /* Upon error here we cannot fall back to interpreter but 7568 * need a hard reject of the program. Thus -EFAULT is 7569 * propagated in any case. 7570 */ 7571 subprog = find_subprog(env, i + insn->imm + 1); 7572 if (subprog < 0) { 7573 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 7574 i + insn->imm + 1); 7575 return -EFAULT; 7576 } 7577 /* temporarily remember subprog id inside insn instead of 7578 * aux_data, since next loop will split up all insns into funcs 7579 */ 7580 insn->off = subprog; 7581 /* remember original imm in case JIT fails and fallback 7582 * to interpreter will be needed 7583 */ 7584 env->insn_aux_data[i].call_imm = insn->imm; 7585 /* point imm to __bpf_call_base+1 from JITs point of view */ 7586 insn->imm = 1; 7587 } 7588 7589 err = bpf_prog_alloc_jited_linfo(prog); 7590 if (err) 7591 goto out_undo_insn; 7592 7593 err = -ENOMEM; 7594 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 7595 if (!func) 7596 goto out_undo_insn; 7597 7598 for (i = 0; i < env->subprog_cnt; i++) { 7599 subprog_start = subprog_end; 7600 subprog_end = env->subprog_info[i + 1].start; 7601 7602 len = subprog_end - subprog_start; 7603 /* BPF_PROG_RUN doesn't call subprogs directly, 7604 * hence main prog stats include the runtime of subprogs. 7605 * subprogs don't have IDs and not reachable via prog_get_next_id 7606 * func[i]->aux->stats will never be accessed and stays NULL 7607 */ 7608 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 7609 if (!func[i]) 7610 goto out_free; 7611 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 7612 len * sizeof(struct bpf_insn)); 7613 func[i]->type = prog->type; 7614 func[i]->len = len; 7615 if (bpf_prog_calc_tag(func[i])) 7616 goto out_free; 7617 func[i]->is_func = 1; 7618 func[i]->aux->func_idx = i; 7619 /* the btf and func_info will be freed only at prog->aux */ 7620 func[i]->aux->btf = prog->aux->btf; 7621 func[i]->aux->func_info = prog->aux->func_info; 7622 7623 /* Use bpf_prog_F_tag to indicate functions in stack traces. 7624 * Long term would need debug info to populate names 7625 */ 7626 func[i]->aux->name[0] = 'F'; 7627 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 7628 func[i]->jit_requested = 1; 7629 func[i]->aux->linfo = prog->aux->linfo; 7630 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 7631 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 7632 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 7633 func[i] = bpf_int_jit_compile(func[i]); 7634 if (!func[i]->jited) { 7635 err = -ENOTSUPP; 7636 goto out_free; 7637 } 7638 cond_resched(); 7639 } 7640 /* at this point all bpf functions were successfully JITed 7641 * now populate all bpf_calls with correct addresses and 7642 * run last pass of JIT 7643 */ 7644 for (i = 0; i < env->subprog_cnt; i++) { 7645 insn = func[i]->insnsi; 7646 for (j = 0; j < func[i]->len; j++, insn++) { 7647 if (insn->code != (BPF_JMP | BPF_CALL) || 7648 insn->src_reg != BPF_PSEUDO_CALL) 7649 continue; 7650 subprog = insn->off; 7651 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) - 7652 __bpf_call_base; 7653 } 7654 7655 /* we use the aux data to keep a list of the start addresses 7656 * of the JITed images for each function in the program 7657 * 7658 * for some architectures, such as powerpc64, the imm field 7659 * might not be large enough to hold the offset of the start 7660 * address of the callee's JITed image from __bpf_call_base 7661 * 7662 * in such cases, we can lookup the start address of a callee 7663 * by using its subprog id, available from the off field of 7664 * the call instruction, as an index for this list 7665 */ 7666 func[i]->aux->func = func; 7667 func[i]->aux->func_cnt = env->subprog_cnt; 7668 } 7669 for (i = 0; i < env->subprog_cnt; i++) { 7670 old_bpf_func = func[i]->bpf_func; 7671 tmp = bpf_int_jit_compile(func[i]); 7672 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 7673 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 7674 err = -ENOTSUPP; 7675 goto out_free; 7676 } 7677 cond_resched(); 7678 } 7679 7680 /* finally lock prog and jit images for all functions and 7681 * populate kallsysm 7682 */ 7683 for (i = 0; i < env->subprog_cnt; i++) { 7684 bpf_prog_lock_ro(func[i]); 7685 bpf_prog_kallsyms_add(func[i]); 7686 } 7687 7688 /* Last step: make now unused interpreter insns from main 7689 * prog consistent for later dump requests, so they can 7690 * later look the same as if they were interpreted only. 7691 */ 7692 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 7693 if (insn->code != (BPF_JMP | BPF_CALL) || 7694 insn->src_reg != BPF_PSEUDO_CALL) 7695 continue; 7696 insn->off = env->insn_aux_data[i].call_imm; 7697 subprog = find_subprog(env, i + insn->off + 1); 7698 insn->imm = subprog; 7699 } 7700 7701 prog->jited = 1; 7702 prog->bpf_func = func[0]->bpf_func; 7703 prog->aux->func = func; 7704 prog->aux->func_cnt = env->subprog_cnt; 7705 bpf_prog_free_unused_jited_linfo(prog); 7706 return 0; 7707 out_free: 7708 for (i = 0; i < env->subprog_cnt; i++) 7709 if (func[i]) 7710 bpf_jit_free(func[i]); 7711 kfree(func); 7712 out_undo_insn: 7713 /* cleanup main prog to be interpreted */ 7714 prog->jit_requested = 0; 7715 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 7716 if (insn->code != (BPF_JMP | BPF_CALL) || 7717 insn->src_reg != BPF_PSEUDO_CALL) 7718 continue; 7719 insn->off = 0; 7720 insn->imm = env->insn_aux_data[i].call_imm; 7721 } 7722 bpf_prog_free_jited_linfo(prog); 7723 return err; 7724 } 7725 7726 static int fixup_call_args(struct bpf_verifier_env *env) 7727 { 7728 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 7729 struct bpf_prog *prog = env->prog; 7730 struct bpf_insn *insn = prog->insnsi; 7731 int i, depth; 7732 #endif 7733 int err = 0; 7734 7735 if (env->prog->jit_requested && 7736 !bpf_prog_is_dev_bound(env->prog->aux)) { 7737 err = jit_subprogs(env); 7738 if (err == 0) 7739 return 0; 7740 if (err == -EFAULT) 7741 return err; 7742 } 7743 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 7744 for (i = 0; i < prog->len; i++, insn++) { 7745 if (insn->code != (BPF_JMP | BPF_CALL) || 7746 insn->src_reg != BPF_PSEUDO_CALL) 7747 continue; 7748 depth = get_callee_stack_depth(env, insn, i); 7749 if (depth < 0) 7750 return depth; 7751 bpf_patch_call_args(insn, depth); 7752 } 7753 err = 0; 7754 #endif 7755 return err; 7756 } 7757 7758 /* fixup insn->imm field of bpf_call instructions 7759 * and inline eligible helpers as explicit sequence of BPF instructions 7760 * 7761 * this function is called after eBPF program passed verification 7762 */ 7763 static int fixup_bpf_calls(struct bpf_verifier_env *env) 7764 { 7765 struct bpf_prog *prog = env->prog; 7766 struct bpf_insn *insn = prog->insnsi; 7767 const struct bpf_func_proto *fn; 7768 const int insn_cnt = prog->len; 7769 const struct bpf_map_ops *ops; 7770 struct bpf_insn_aux_data *aux; 7771 struct bpf_insn insn_buf[16]; 7772 struct bpf_prog *new_prog; 7773 struct bpf_map *map_ptr; 7774 int i, cnt, delta = 0; 7775 7776 for (i = 0; i < insn_cnt; i++, insn++) { 7777 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 7778 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 7779 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 7780 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 7781 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 7782 struct bpf_insn mask_and_div[] = { 7783 BPF_MOV32_REG(insn->src_reg, insn->src_reg), 7784 /* Rx div 0 -> 0 */ 7785 BPF_JMP_IMM(BPF_JNE, insn->src_reg, 0, 2), 7786 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 7787 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 7788 *insn, 7789 }; 7790 struct bpf_insn mask_and_mod[] = { 7791 BPF_MOV32_REG(insn->src_reg, insn->src_reg), 7792 /* Rx mod 0 -> Rx */ 7793 BPF_JMP_IMM(BPF_JEQ, insn->src_reg, 0, 1), 7794 *insn, 7795 }; 7796 struct bpf_insn *patchlet; 7797 7798 if (insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 7799 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 7800 patchlet = mask_and_div + (is64 ? 1 : 0); 7801 cnt = ARRAY_SIZE(mask_and_div) - (is64 ? 1 : 0); 7802 } else { 7803 patchlet = mask_and_mod + (is64 ? 1 : 0); 7804 cnt = ARRAY_SIZE(mask_and_mod) - (is64 ? 1 : 0); 7805 } 7806 7807 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 7808 if (!new_prog) 7809 return -ENOMEM; 7810 7811 delta += cnt - 1; 7812 env->prog = prog = new_prog; 7813 insn = new_prog->insnsi + i + delta; 7814 continue; 7815 } 7816 7817 if (BPF_CLASS(insn->code) == BPF_LD && 7818 (BPF_MODE(insn->code) == BPF_ABS || 7819 BPF_MODE(insn->code) == BPF_IND)) { 7820 cnt = env->ops->gen_ld_abs(insn, insn_buf); 7821 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 7822 verbose(env, "bpf verifier is misconfigured\n"); 7823 return -EINVAL; 7824 } 7825 7826 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 7827 if (!new_prog) 7828 return -ENOMEM; 7829 7830 delta += cnt - 1; 7831 env->prog = prog = new_prog; 7832 insn = new_prog->insnsi + i + delta; 7833 continue; 7834 } 7835 7836 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 7837 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 7838 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 7839 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 7840 struct bpf_insn insn_buf[16]; 7841 struct bpf_insn *patch = &insn_buf[0]; 7842 bool issrc, isneg; 7843 u32 off_reg; 7844 7845 aux = &env->insn_aux_data[i + delta]; 7846 if (!aux->alu_state || 7847 aux->alu_state == BPF_ALU_NON_POINTER) 7848 continue; 7849 7850 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 7851 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 7852 BPF_ALU_SANITIZE_SRC; 7853 7854 off_reg = issrc ? insn->src_reg : insn->dst_reg; 7855 if (isneg) 7856 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 7857 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1); 7858 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 7859 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 7860 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 7861 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 7862 if (issrc) { 7863 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, 7864 off_reg); 7865 insn->src_reg = BPF_REG_AX; 7866 } else { 7867 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg, 7868 BPF_REG_AX); 7869 } 7870 if (isneg) 7871 insn->code = insn->code == code_add ? 7872 code_sub : code_add; 7873 *patch++ = *insn; 7874 if (issrc && isneg) 7875 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 7876 cnt = patch - insn_buf; 7877 7878 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 7879 if (!new_prog) 7880 return -ENOMEM; 7881 7882 delta += cnt - 1; 7883 env->prog = prog = new_prog; 7884 insn = new_prog->insnsi + i + delta; 7885 continue; 7886 } 7887 7888 if (insn->code != (BPF_JMP | BPF_CALL)) 7889 continue; 7890 if (insn->src_reg == BPF_PSEUDO_CALL) 7891 continue; 7892 7893 if (insn->imm == BPF_FUNC_get_route_realm) 7894 prog->dst_needed = 1; 7895 if (insn->imm == BPF_FUNC_get_prandom_u32) 7896 bpf_user_rnd_init_once(); 7897 if (insn->imm == BPF_FUNC_override_return) 7898 prog->kprobe_override = 1; 7899 if (insn->imm == BPF_FUNC_tail_call) { 7900 /* If we tail call into other programs, we 7901 * cannot make any assumptions since they can 7902 * be replaced dynamically during runtime in 7903 * the program array. 7904 */ 7905 prog->cb_access = 1; 7906 env->prog->aux->stack_depth = MAX_BPF_STACK; 7907 env->prog->aux->max_pkt_offset = MAX_PACKET_OFF; 7908 7909 /* mark bpf_tail_call as different opcode to avoid 7910 * conditional branch in the interpeter for every normal 7911 * call and to prevent accidental JITing by JIT compiler 7912 * that doesn't support bpf_tail_call yet 7913 */ 7914 insn->imm = 0; 7915 insn->code = BPF_JMP | BPF_TAIL_CALL; 7916 7917 aux = &env->insn_aux_data[i + delta]; 7918 if (!bpf_map_ptr_unpriv(aux)) 7919 continue; 7920 7921 /* instead of changing every JIT dealing with tail_call 7922 * emit two extra insns: 7923 * if (index >= max_entries) goto out; 7924 * index &= array->index_mask; 7925 * to avoid out-of-bounds cpu speculation 7926 */ 7927 if (bpf_map_ptr_poisoned(aux)) { 7928 verbose(env, "tail_call abusing map_ptr\n"); 7929 return -EINVAL; 7930 } 7931 7932 map_ptr = BPF_MAP_PTR(aux->map_state); 7933 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 7934 map_ptr->max_entries, 2); 7935 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 7936 container_of(map_ptr, 7937 struct bpf_array, 7938 map)->index_mask); 7939 insn_buf[2] = *insn; 7940 cnt = 3; 7941 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 7942 if (!new_prog) 7943 return -ENOMEM; 7944 7945 delta += cnt - 1; 7946 env->prog = prog = new_prog; 7947 insn = new_prog->insnsi + i + delta; 7948 continue; 7949 } 7950 7951 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 7952 * and other inlining handlers are currently limited to 64 bit 7953 * only. 7954 */ 7955 if (prog->jit_requested && BITS_PER_LONG == 64 && 7956 (insn->imm == BPF_FUNC_map_lookup_elem || 7957 insn->imm == BPF_FUNC_map_update_elem || 7958 insn->imm == BPF_FUNC_map_delete_elem || 7959 insn->imm == BPF_FUNC_map_push_elem || 7960 insn->imm == BPF_FUNC_map_pop_elem || 7961 insn->imm == BPF_FUNC_map_peek_elem)) { 7962 aux = &env->insn_aux_data[i + delta]; 7963 if (bpf_map_ptr_poisoned(aux)) 7964 goto patch_call_imm; 7965 7966 map_ptr = BPF_MAP_PTR(aux->map_state); 7967 ops = map_ptr->ops; 7968 if (insn->imm == BPF_FUNC_map_lookup_elem && 7969 ops->map_gen_lookup) { 7970 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 7971 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 7972 verbose(env, "bpf verifier is misconfigured\n"); 7973 return -EINVAL; 7974 } 7975 7976 new_prog = bpf_patch_insn_data(env, i + delta, 7977 insn_buf, cnt); 7978 if (!new_prog) 7979 return -ENOMEM; 7980 7981 delta += cnt - 1; 7982 env->prog = prog = new_prog; 7983 insn = new_prog->insnsi + i + delta; 7984 continue; 7985 } 7986 7987 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 7988 (void *(*)(struct bpf_map *map, void *key))NULL)); 7989 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 7990 (int (*)(struct bpf_map *map, void *key))NULL)); 7991 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 7992 (int (*)(struct bpf_map *map, void *key, void *value, 7993 u64 flags))NULL)); 7994 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 7995 (int (*)(struct bpf_map *map, void *value, 7996 u64 flags))NULL)); 7997 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 7998 (int (*)(struct bpf_map *map, void *value))NULL)); 7999 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 8000 (int (*)(struct bpf_map *map, void *value))NULL)); 8001 8002 switch (insn->imm) { 8003 case BPF_FUNC_map_lookup_elem: 8004 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - 8005 __bpf_call_base; 8006 continue; 8007 case BPF_FUNC_map_update_elem: 8008 insn->imm = BPF_CAST_CALL(ops->map_update_elem) - 8009 __bpf_call_base; 8010 continue; 8011 case BPF_FUNC_map_delete_elem: 8012 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - 8013 __bpf_call_base; 8014 continue; 8015 case BPF_FUNC_map_push_elem: 8016 insn->imm = BPF_CAST_CALL(ops->map_push_elem) - 8017 __bpf_call_base; 8018 continue; 8019 case BPF_FUNC_map_pop_elem: 8020 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) - 8021 __bpf_call_base; 8022 continue; 8023 case BPF_FUNC_map_peek_elem: 8024 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) - 8025 __bpf_call_base; 8026 continue; 8027 } 8028 8029 goto patch_call_imm; 8030 } 8031 8032 patch_call_imm: 8033 fn = env->ops->get_func_proto(insn->imm, env->prog); 8034 /* all functions that have prototype and verifier allowed 8035 * programs to call them, must be real in-kernel functions 8036 */ 8037 if (!fn->func) { 8038 verbose(env, 8039 "kernel subsystem misconfigured func %s#%d\n", 8040 func_id_name(insn->imm), insn->imm); 8041 return -EFAULT; 8042 } 8043 insn->imm = fn->func - __bpf_call_base; 8044 } 8045 8046 return 0; 8047 } 8048 8049 static void free_states(struct bpf_verifier_env *env) 8050 { 8051 struct bpf_verifier_state_list *sl, *sln; 8052 int i; 8053 8054 sl = env->free_list; 8055 while (sl) { 8056 sln = sl->next; 8057 free_verifier_state(&sl->state, false); 8058 kfree(sl); 8059 sl = sln; 8060 } 8061 8062 if (!env->explored_states) 8063 return; 8064 8065 for (i = 0; i < env->prog->len; i++) { 8066 sl = env->explored_states[i]; 8067 8068 if (sl) 8069 while (sl != STATE_LIST_MARK) { 8070 sln = sl->next; 8071 free_verifier_state(&sl->state, false); 8072 kfree(sl); 8073 sl = sln; 8074 } 8075 } 8076 8077 kvfree(env->explored_states); 8078 } 8079 8080 static void print_verification_stats(struct bpf_verifier_env *env) 8081 { 8082 int i; 8083 8084 if (env->log.level & BPF_LOG_STATS) { 8085 verbose(env, "verification time %lld usec\n", 8086 div_u64(env->verification_time, 1000)); 8087 verbose(env, "stack depth "); 8088 for (i = 0; i < env->subprog_cnt; i++) { 8089 u32 depth = env->subprog_info[i].stack_depth; 8090 8091 verbose(env, "%d", depth); 8092 if (i + 1 < env->subprog_cnt) 8093 verbose(env, "+"); 8094 } 8095 verbose(env, "\n"); 8096 } 8097 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 8098 "total_states %d peak_states %d mark_read %d\n", 8099 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 8100 env->max_states_per_insn, env->total_states, 8101 env->peak_states, env->longest_mark_read_walk); 8102 } 8103 8104 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, 8105 union bpf_attr __user *uattr) 8106 { 8107 u64 start_time = ktime_get_ns(); 8108 struct bpf_verifier_env *env; 8109 struct bpf_verifier_log *log; 8110 int i, len, ret = -EINVAL; 8111 bool is_priv; 8112 8113 /* no program is valid */ 8114 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 8115 return -EINVAL; 8116 8117 /* 'struct bpf_verifier_env' can be global, but since it's not small, 8118 * allocate/free it every time bpf_check() is called 8119 */ 8120 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 8121 if (!env) 8122 return -ENOMEM; 8123 log = &env->log; 8124 8125 len = (*prog)->len; 8126 env->insn_aux_data = 8127 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 8128 ret = -ENOMEM; 8129 if (!env->insn_aux_data) 8130 goto err_free_env; 8131 for (i = 0; i < len; i++) 8132 env->insn_aux_data[i].orig_idx = i; 8133 env->prog = *prog; 8134 env->ops = bpf_verifier_ops[env->prog->type]; 8135 is_priv = capable(CAP_SYS_ADMIN); 8136 8137 /* grab the mutex to protect few globals used by verifier */ 8138 if (!is_priv) 8139 mutex_lock(&bpf_verifier_lock); 8140 8141 if (attr->log_level || attr->log_buf || attr->log_size) { 8142 /* user requested verbose verifier output 8143 * and supplied buffer to store the verification trace 8144 */ 8145 log->level = attr->log_level; 8146 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 8147 log->len_total = attr->log_size; 8148 8149 ret = -EINVAL; 8150 /* log attributes have to be sane */ 8151 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 || 8152 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK) 8153 goto err_unlock; 8154 } 8155 8156 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 8157 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 8158 env->strict_alignment = true; 8159 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 8160 env->strict_alignment = false; 8161 8162 env->allow_ptr_leaks = is_priv; 8163 8164 ret = replace_map_fd_with_map_ptr(env); 8165 if (ret < 0) 8166 goto skip_full_check; 8167 8168 if (bpf_prog_is_dev_bound(env->prog->aux)) { 8169 ret = bpf_prog_offload_verifier_prep(env->prog); 8170 if (ret) 8171 goto skip_full_check; 8172 } 8173 8174 env->explored_states = kvcalloc(env->prog->len, 8175 sizeof(struct bpf_verifier_state_list *), 8176 GFP_USER); 8177 ret = -ENOMEM; 8178 if (!env->explored_states) 8179 goto skip_full_check; 8180 8181 ret = check_subprogs(env); 8182 if (ret < 0) 8183 goto skip_full_check; 8184 8185 ret = check_btf_info(env, attr, uattr); 8186 if (ret < 0) 8187 goto skip_full_check; 8188 8189 ret = check_cfg(env); 8190 if (ret < 0) 8191 goto skip_full_check; 8192 8193 ret = do_check(env); 8194 if (env->cur_state) { 8195 free_verifier_state(env->cur_state, true); 8196 env->cur_state = NULL; 8197 } 8198 8199 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux)) 8200 ret = bpf_prog_offload_finalize(env); 8201 8202 skip_full_check: 8203 while (!pop_stack(env, NULL, NULL)); 8204 free_states(env); 8205 8206 if (ret == 0) 8207 ret = check_max_stack_depth(env); 8208 8209 /* instruction rewrites happen after this point */ 8210 if (is_priv) { 8211 if (ret == 0) 8212 opt_hard_wire_dead_code_branches(env); 8213 if (ret == 0) 8214 ret = opt_remove_dead_code(env); 8215 if (ret == 0) 8216 ret = opt_remove_nops(env); 8217 } else { 8218 if (ret == 0) 8219 sanitize_dead_code(env); 8220 } 8221 8222 if (ret == 0) 8223 /* program is valid, convert *(u32*)(ctx + off) accesses */ 8224 ret = convert_ctx_accesses(env); 8225 8226 if (ret == 0) 8227 ret = fixup_bpf_calls(env); 8228 8229 if (ret == 0) 8230 ret = fixup_call_args(env); 8231 8232 env->verification_time = ktime_get_ns() - start_time; 8233 print_verification_stats(env); 8234 8235 if (log->level && bpf_verifier_log_full(log)) 8236 ret = -ENOSPC; 8237 if (log->level && !log->ubuf) { 8238 ret = -EFAULT; 8239 goto err_release_maps; 8240 } 8241 8242 if (ret == 0 && env->used_map_cnt) { 8243 /* if program passed verifier, update used_maps in bpf_prog_info */ 8244 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 8245 sizeof(env->used_maps[0]), 8246 GFP_KERNEL); 8247 8248 if (!env->prog->aux->used_maps) { 8249 ret = -ENOMEM; 8250 goto err_release_maps; 8251 } 8252 8253 memcpy(env->prog->aux->used_maps, env->used_maps, 8254 sizeof(env->used_maps[0]) * env->used_map_cnt); 8255 env->prog->aux->used_map_cnt = env->used_map_cnt; 8256 8257 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 8258 * bpf_ld_imm64 instructions 8259 */ 8260 convert_pseudo_ld_imm64(env); 8261 } 8262 8263 if (ret == 0) 8264 adjust_btf_func(env); 8265 8266 err_release_maps: 8267 if (!env->prog->aux->used_maps) 8268 /* if we didn't copy map pointers into bpf_prog_info, release 8269 * them now. Otherwise free_used_maps() will release them. 8270 */ 8271 release_maps(env); 8272 *prog = env->prog; 8273 err_unlock: 8274 if (!is_priv) 8275 mutex_unlock(&bpf_verifier_lock); 8276 vfree(env->insn_aux_data); 8277 err_free_env: 8278 kfree(env); 8279 return ret; 8280 } 8281