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