1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com 3 * Copyright (c) 2016 Facebook 4 * Copyright (c) 2018 Covalent IO, Inc. http://covalent.io 5 */ 6 #include <uapi/linux/btf.h> 7 #include <linux/kernel.h> 8 #include <linux/types.h> 9 #include <linux/slab.h> 10 #include <linux/bpf.h> 11 #include <linux/btf.h> 12 #include <linux/bpf_verifier.h> 13 #include <linux/filter.h> 14 #include <net/netlink.h> 15 #include <linux/file.h> 16 #include <linux/vmalloc.h> 17 #include <linux/stringify.h> 18 #include <linux/bsearch.h> 19 #include <linux/sort.h> 20 #include <linux/perf_event.h> 21 #include <linux/ctype.h> 22 #include <linux/error-injection.h> 23 #include <linux/bpf_lsm.h> 24 #include <linux/btf_ids.h> 25 26 #include "disasm.h" 27 28 static const struct bpf_verifier_ops * const bpf_verifier_ops[] = { 29 #define BPF_PROG_TYPE(_id, _name, prog_ctx_type, kern_ctx_type) \ 30 [_id] = & _name ## _verifier_ops, 31 #define BPF_MAP_TYPE(_id, _ops) 32 #define BPF_LINK_TYPE(_id, _name) 33 #include <linux/bpf_types.h> 34 #undef BPF_PROG_TYPE 35 #undef BPF_MAP_TYPE 36 #undef BPF_LINK_TYPE 37 }; 38 39 /* bpf_check() is a static code analyzer that walks eBPF program 40 * instruction by instruction and updates register/stack state. 41 * All paths of conditional branches are analyzed until 'bpf_exit' insn. 42 * 43 * The first pass is depth-first-search to check that the program is a DAG. 44 * It rejects the following programs: 45 * - larger than BPF_MAXINSNS insns 46 * - if loop is present (detected via back-edge) 47 * - unreachable insns exist (shouldn't be a forest. program = one function) 48 * - out of bounds or malformed jumps 49 * The second pass is all possible path descent from the 1st insn. 50 * Since it's analyzing all pathes through the program, the length of the 51 * analysis is limited to 64k insn, which may be hit even if total number of 52 * insn is less then 4K, but there are too many branches that change stack/regs. 53 * Number of 'branches to be analyzed' is limited to 1k 54 * 55 * On entry to each instruction, each register has a type, and the instruction 56 * changes the types of the registers depending on instruction semantics. 57 * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is 58 * copied to R1. 59 * 60 * All registers are 64-bit. 61 * R0 - return register 62 * R1-R5 argument passing registers 63 * R6-R9 callee saved registers 64 * R10 - frame pointer read-only 65 * 66 * At the start of BPF program the register R1 contains a pointer to bpf_context 67 * and has type PTR_TO_CTX. 68 * 69 * Verifier tracks arithmetic operations on pointers in case: 70 * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), 71 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), 72 * 1st insn copies R10 (which has FRAME_PTR) type into R1 73 * and 2nd arithmetic instruction is pattern matched to recognize 74 * that it wants to construct a pointer to some element within stack. 75 * So after 2nd insn, the register R1 has type PTR_TO_STACK 76 * (and -20 constant is saved for further stack bounds checking). 77 * Meaning that this reg is a pointer to stack plus known immediate constant. 78 * 79 * Most of the time the registers have SCALAR_VALUE type, which 80 * means the register has some value, but it's not a valid pointer. 81 * (like pointer plus pointer becomes SCALAR_VALUE type) 82 * 83 * When verifier sees load or store instructions the type of base register 84 * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, PTR_TO_STACK, PTR_TO_SOCKET. These are 85 * four pointer types recognized by check_mem_access() function. 86 * 87 * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' 88 * and the range of [ptr, ptr + map's value_size) is accessible. 89 * 90 * registers used to pass values to function calls are checked against 91 * function argument constraints. 92 * 93 * ARG_PTR_TO_MAP_KEY is one of such argument constraints. 94 * It means that the register type passed to this function must be 95 * PTR_TO_STACK and it will be used inside the function as 96 * 'pointer to map element key' 97 * 98 * For example the argument constraints for bpf_map_lookup_elem(): 99 * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, 100 * .arg1_type = ARG_CONST_MAP_PTR, 101 * .arg2_type = ARG_PTR_TO_MAP_KEY, 102 * 103 * ret_type says that this function returns 'pointer to map elem value or null' 104 * function expects 1st argument to be a const pointer to 'struct bpf_map' and 105 * 2nd argument should be a pointer to stack, which will be used inside 106 * the helper function as a pointer to map element key. 107 * 108 * On the kernel side the helper function looks like: 109 * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) 110 * { 111 * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; 112 * void *key = (void *) (unsigned long) r2; 113 * void *value; 114 * 115 * here kernel can access 'key' and 'map' pointers safely, knowing that 116 * [key, key + map->key_size) bytes are valid and were initialized on 117 * the stack of eBPF program. 118 * } 119 * 120 * Corresponding eBPF program may look like: 121 * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR 122 * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK 123 * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP 124 * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), 125 * here verifier looks at prototype of map_lookup_elem() and sees: 126 * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, 127 * Now verifier knows that this map has key of R1->map_ptr->key_size bytes 128 * 129 * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, 130 * Now verifier checks that [R2, R2 + map's key_size) are within stack limits 131 * and were initialized prior to this call. 132 * If it's ok, then verifier allows this BPF_CALL insn and looks at 133 * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets 134 * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function 135 * returns ether pointer to map value or NULL. 136 * 137 * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' 138 * insn, the register holding that pointer in the true branch changes state to 139 * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false 140 * branch. See check_cond_jmp_op(). 141 * 142 * After the call R0 is set to return type of the function and registers R1-R5 143 * are set to NOT_INIT to indicate that they are no longer readable. 144 * 145 * The following reference types represent a potential reference to a kernel 146 * resource which, after first being allocated, must be checked and freed by 147 * the BPF program: 148 * - PTR_TO_SOCKET_OR_NULL, PTR_TO_SOCKET 149 * 150 * When the verifier sees a helper call return a reference type, it allocates a 151 * pointer id for the reference and stores it in the current function state. 152 * Similar to the way that PTR_TO_MAP_VALUE_OR_NULL is converted into 153 * PTR_TO_MAP_VALUE, PTR_TO_SOCKET_OR_NULL becomes PTR_TO_SOCKET when the type 154 * passes through a NULL-check conditional. For the branch wherein the state is 155 * changed to CONST_IMM, the verifier releases the reference. 156 * 157 * For each helper function that allocates a reference, such as 158 * bpf_sk_lookup_tcp(), there is a corresponding release function, such as 159 * bpf_sk_release(). When a reference type passes into the release function, 160 * the verifier also releases the reference. If any unchecked or unreleased 161 * reference remains at the end of the program, the verifier rejects it. 162 */ 163 164 /* verifier_state + insn_idx are pushed to stack when branch is encountered */ 165 struct bpf_verifier_stack_elem { 166 /* verifer state is 'st' 167 * before processing instruction 'insn_idx' 168 * and after processing instruction 'prev_insn_idx' 169 */ 170 struct bpf_verifier_state st; 171 int insn_idx; 172 int prev_insn_idx; 173 struct bpf_verifier_stack_elem *next; 174 /* length of verifier log at the time this state was pushed on stack */ 175 u32 log_pos; 176 }; 177 178 #define BPF_COMPLEXITY_LIMIT_JMP_SEQ 8192 179 #define BPF_COMPLEXITY_LIMIT_STATES 64 180 181 #define BPF_MAP_KEY_POISON (1ULL << 63) 182 #define BPF_MAP_KEY_SEEN (1ULL << 62) 183 184 #define BPF_MAP_PTR_UNPRIV 1UL 185 #define BPF_MAP_PTR_POISON ((void *)((0xeB9FUL << 1) + \ 186 POISON_POINTER_DELTA)) 187 #define BPF_MAP_PTR(X) ((struct bpf_map *)((X) & ~BPF_MAP_PTR_UNPRIV)) 188 189 static bool bpf_map_ptr_poisoned(const struct bpf_insn_aux_data *aux) 190 { 191 return BPF_MAP_PTR(aux->map_ptr_state) == BPF_MAP_PTR_POISON; 192 } 193 194 static bool bpf_map_ptr_unpriv(const struct bpf_insn_aux_data *aux) 195 { 196 return aux->map_ptr_state & BPF_MAP_PTR_UNPRIV; 197 } 198 199 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux, 200 const struct bpf_map *map, bool unpriv) 201 { 202 BUILD_BUG_ON((unsigned long)BPF_MAP_PTR_POISON & BPF_MAP_PTR_UNPRIV); 203 unpriv |= bpf_map_ptr_unpriv(aux); 204 aux->map_ptr_state = (unsigned long)map | 205 (unpriv ? BPF_MAP_PTR_UNPRIV : 0UL); 206 } 207 208 static bool bpf_map_key_poisoned(const struct bpf_insn_aux_data *aux) 209 { 210 return aux->map_key_state & BPF_MAP_KEY_POISON; 211 } 212 213 static bool bpf_map_key_unseen(const struct bpf_insn_aux_data *aux) 214 { 215 return !(aux->map_key_state & BPF_MAP_KEY_SEEN); 216 } 217 218 static u64 bpf_map_key_immediate(const struct bpf_insn_aux_data *aux) 219 { 220 return aux->map_key_state & ~(BPF_MAP_KEY_SEEN | BPF_MAP_KEY_POISON); 221 } 222 223 static void bpf_map_key_store(struct bpf_insn_aux_data *aux, u64 state) 224 { 225 bool poisoned = bpf_map_key_poisoned(aux); 226 227 aux->map_key_state = state | BPF_MAP_KEY_SEEN | 228 (poisoned ? BPF_MAP_KEY_POISON : 0ULL); 229 } 230 231 static bool bpf_pseudo_call(const struct bpf_insn *insn) 232 { 233 return insn->code == (BPF_JMP | BPF_CALL) && 234 insn->src_reg == BPF_PSEUDO_CALL; 235 } 236 237 static bool bpf_pseudo_func(const struct bpf_insn *insn) 238 { 239 return insn->code == (BPF_LD | BPF_IMM | BPF_DW) && 240 insn->src_reg == BPF_PSEUDO_FUNC; 241 } 242 243 struct bpf_call_arg_meta { 244 struct bpf_map *map_ptr; 245 bool raw_mode; 246 bool pkt_access; 247 int regno; 248 int access_size; 249 int mem_size; 250 u64 msize_max_value; 251 int ref_obj_id; 252 int func_id; 253 struct btf *btf; 254 u32 btf_id; 255 struct btf *ret_btf; 256 u32 ret_btf_id; 257 u32 subprogno; 258 }; 259 260 struct btf *btf_vmlinux; 261 262 static DEFINE_MUTEX(bpf_verifier_lock); 263 264 static const struct bpf_line_info * 265 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 266 { 267 const struct bpf_line_info *linfo; 268 const struct bpf_prog *prog; 269 u32 i, nr_linfo; 270 271 prog = env->prog; 272 nr_linfo = prog->aux->nr_linfo; 273 274 if (!nr_linfo || insn_off >= prog->len) 275 return NULL; 276 277 linfo = prog->aux->linfo; 278 for (i = 1; i < nr_linfo; i++) 279 if (insn_off < linfo[i].insn_off) 280 break; 281 282 return &linfo[i - 1]; 283 } 284 285 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, 286 va_list args) 287 { 288 unsigned int n; 289 290 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); 291 292 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, 293 "verifier log line truncated - local buffer too short\n"); 294 295 n = min(log->len_total - log->len_used - 1, n); 296 log->kbuf[n] = '\0'; 297 298 if (log->level == BPF_LOG_KERNEL) { 299 pr_err("BPF:%s\n", log->kbuf); 300 return; 301 } 302 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) 303 log->len_used += n; 304 else 305 log->ubuf = NULL; 306 } 307 308 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos) 309 { 310 char zero = 0; 311 312 if (!bpf_verifier_log_needed(log)) 313 return; 314 315 log->len_used = new_pos; 316 if (put_user(zero, log->ubuf + new_pos)) 317 log->ubuf = NULL; 318 } 319 320 /* log_level controls verbosity level of eBPF verifier. 321 * bpf_verifier_log_write() is used to dump the verification trace to the log, 322 * so the user can figure out what's wrong with the program 323 */ 324 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 325 const char *fmt, ...) 326 { 327 va_list args; 328 329 if (!bpf_verifier_log_needed(&env->log)) 330 return; 331 332 va_start(args, fmt); 333 bpf_verifier_vlog(&env->log, fmt, args); 334 va_end(args); 335 } 336 EXPORT_SYMBOL_GPL(bpf_verifier_log_write); 337 338 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 339 { 340 struct bpf_verifier_env *env = private_data; 341 va_list args; 342 343 if (!bpf_verifier_log_needed(&env->log)) 344 return; 345 346 va_start(args, fmt); 347 bpf_verifier_vlog(&env->log, fmt, args); 348 va_end(args); 349 } 350 351 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log, 352 const char *fmt, ...) 353 { 354 va_list args; 355 356 if (!bpf_verifier_log_needed(log)) 357 return; 358 359 va_start(args, fmt); 360 bpf_verifier_vlog(log, fmt, args); 361 va_end(args); 362 } 363 364 static const char *ltrim(const char *s) 365 { 366 while (isspace(*s)) 367 s++; 368 369 return s; 370 } 371 372 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 373 u32 insn_off, 374 const char *prefix_fmt, ...) 375 { 376 const struct bpf_line_info *linfo; 377 378 if (!bpf_verifier_log_needed(&env->log)) 379 return; 380 381 linfo = find_linfo(env, insn_off); 382 if (!linfo || linfo == env->prev_linfo) 383 return; 384 385 if (prefix_fmt) { 386 va_list args; 387 388 va_start(args, prefix_fmt); 389 bpf_verifier_vlog(&env->log, prefix_fmt, args); 390 va_end(args); 391 } 392 393 verbose(env, "%s\n", 394 ltrim(btf_name_by_offset(env->prog->aux->btf, 395 linfo->line_off))); 396 397 env->prev_linfo = linfo; 398 } 399 400 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 401 struct bpf_reg_state *reg, 402 struct tnum *range, const char *ctx, 403 const char *reg_name) 404 { 405 char tn_buf[48]; 406 407 verbose(env, "At %s the register %s ", ctx, reg_name); 408 if (!tnum_is_unknown(reg->var_off)) { 409 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 410 verbose(env, "has value %s", tn_buf); 411 } else { 412 verbose(env, "has unknown scalar value"); 413 } 414 tnum_strn(tn_buf, sizeof(tn_buf), *range); 415 verbose(env, " should have been in %s\n", tn_buf); 416 } 417 418 static bool type_is_pkt_pointer(enum bpf_reg_type type) 419 { 420 return type == PTR_TO_PACKET || 421 type == PTR_TO_PACKET_META; 422 } 423 424 static bool type_is_sk_pointer(enum bpf_reg_type type) 425 { 426 return type == PTR_TO_SOCKET || 427 type == PTR_TO_SOCK_COMMON || 428 type == PTR_TO_TCP_SOCK || 429 type == PTR_TO_XDP_SOCK; 430 } 431 432 static bool reg_type_not_null(enum bpf_reg_type type) 433 { 434 return type == PTR_TO_SOCKET || 435 type == PTR_TO_TCP_SOCK || 436 type == PTR_TO_MAP_VALUE || 437 type == PTR_TO_MAP_KEY || 438 type == PTR_TO_SOCK_COMMON; 439 } 440 441 static bool reg_type_may_be_null(enum bpf_reg_type type) 442 { 443 return type == PTR_TO_MAP_VALUE_OR_NULL || 444 type == PTR_TO_SOCKET_OR_NULL || 445 type == PTR_TO_SOCK_COMMON_OR_NULL || 446 type == PTR_TO_TCP_SOCK_OR_NULL || 447 type == PTR_TO_BTF_ID_OR_NULL || 448 type == PTR_TO_MEM_OR_NULL || 449 type == PTR_TO_RDONLY_BUF_OR_NULL || 450 type == PTR_TO_RDWR_BUF_OR_NULL; 451 } 452 453 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 454 { 455 return reg->type == PTR_TO_MAP_VALUE && 456 map_value_has_spin_lock(reg->map_ptr); 457 } 458 459 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type) 460 { 461 return type == PTR_TO_SOCKET || 462 type == PTR_TO_SOCKET_OR_NULL || 463 type == PTR_TO_TCP_SOCK || 464 type == PTR_TO_TCP_SOCK_OR_NULL || 465 type == PTR_TO_MEM || 466 type == PTR_TO_MEM_OR_NULL; 467 } 468 469 static bool arg_type_may_be_refcounted(enum bpf_arg_type type) 470 { 471 return type == ARG_PTR_TO_SOCK_COMMON; 472 } 473 474 static bool arg_type_may_be_null(enum bpf_arg_type type) 475 { 476 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL || 477 type == ARG_PTR_TO_MEM_OR_NULL || 478 type == ARG_PTR_TO_CTX_OR_NULL || 479 type == ARG_PTR_TO_SOCKET_OR_NULL || 480 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL || 481 type == ARG_PTR_TO_STACK_OR_NULL; 482 } 483 484 /* Determine whether the function releases some resources allocated by another 485 * function call. The first reference type argument will be assumed to be 486 * released by release_reference(). 487 */ 488 static bool is_release_function(enum bpf_func_id func_id) 489 { 490 return func_id == BPF_FUNC_sk_release || 491 func_id == BPF_FUNC_ringbuf_submit || 492 func_id == BPF_FUNC_ringbuf_discard; 493 } 494 495 static bool may_be_acquire_function(enum bpf_func_id func_id) 496 { 497 return func_id == BPF_FUNC_sk_lookup_tcp || 498 func_id == BPF_FUNC_sk_lookup_udp || 499 func_id == BPF_FUNC_skc_lookup_tcp || 500 func_id == BPF_FUNC_map_lookup_elem || 501 func_id == BPF_FUNC_ringbuf_reserve; 502 } 503 504 static bool is_acquire_function(enum bpf_func_id func_id, 505 const struct bpf_map *map) 506 { 507 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 508 509 if (func_id == BPF_FUNC_sk_lookup_tcp || 510 func_id == BPF_FUNC_sk_lookup_udp || 511 func_id == BPF_FUNC_skc_lookup_tcp || 512 func_id == BPF_FUNC_ringbuf_reserve) 513 return true; 514 515 if (func_id == BPF_FUNC_map_lookup_elem && 516 (map_type == BPF_MAP_TYPE_SOCKMAP || 517 map_type == BPF_MAP_TYPE_SOCKHASH)) 518 return true; 519 520 return false; 521 } 522 523 static bool is_ptr_cast_function(enum bpf_func_id func_id) 524 { 525 return func_id == BPF_FUNC_tcp_sock || 526 func_id == BPF_FUNC_sk_fullsock || 527 func_id == BPF_FUNC_skc_to_tcp_sock || 528 func_id == BPF_FUNC_skc_to_tcp6_sock || 529 func_id == BPF_FUNC_skc_to_udp6_sock || 530 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 531 func_id == BPF_FUNC_skc_to_tcp_request_sock; 532 } 533 534 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 535 { 536 return BPF_CLASS(insn->code) == BPF_STX && 537 BPF_MODE(insn->code) == BPF_ATOMIC && 538 insn->imm == BPF_CMPXCHG; 539 } 540 541 /* string representation of 'enum bpf_reg_type' */ 542 static const char * const reg_type_str[] = { 543 [NOT_INIT] = "?", 544 [SCALAR_VALUE] = "inv", 545 [PTR_TO_CTX] = "ctx", 546 [CONST_PTR_TO_MAP] = "map_ptr", 547 [PTR_TO_MAP_VALUE] = "map_value", 548 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", 549 [PTR_TO_STACK] = "fp", 550 [PTR_TO_PACKET] = "pkt", 551 [PTR_TO_PACKET_META] = "pkt_meta", 552 [PTR_TO_PACKET_END] = "pkt_end", 553 [PTR_TO_FLOW_KEYS] = "flow_keys", 554 [PTR_TO_SOCKET] = "sock", 555 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null", 556 [PTR_TO_SOCK_COMMON] = "sock_common", 557 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null", 558 [PTR_TO_TCP_SOCK] = "tcp_sock", 559 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null", 560 [PTR_TO_TP_BUFFER] = "tp_buffer", 561 [PTR_TO_XDP_SOCK] = "xdp_sock", 562 [PTR_TO_BTF_ID] = "ptr_", 563 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_", 564 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_", 565 [PTR_TO_MEM] = "mem", 566 [PTR_TO_MEM_OR_NULL] = "mem_or_null", 567 [PTR_TO_RDONLY_BUF] = "rdonly_buf", 568 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null", 569 [PTR_TO_RDWR_BUF] = "rdwr_buf", 570 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null", 571 [PTR_TO_FUNC] = "func", 572 [PTR_TO_MAP_KEY] = "map_key", 573 }; 574 575 static char slot_type_char[] = { 576 [STACK_INVALID] = '?', 577 [STACK_SPILL] = 'r', 578 [STACK_MISC] = 'm', 579 [STACK_ZERO] = '0', 580 }; 581 582 static void print_liveness(struct bpf_verifier_env *env, 583 enum bpf_reg_liveness live) 584 { 585 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 586 verbose(env, "_"); 587 if (live & REG_LIVE_READ) 588 verbose(env, "r"); 589 if (live & REG_LIVE_WRITTEN) 590 verbose(env, "w"); 591 if (live & REG_LIVE_DONE) 592 verbose(env, "D"); 593 } 594 595 static struct bpf_func_state *func(struct bpf_verifier_env *env, 596 const struct bpf_reg_state *reg) 597 { 598 struct bpf_verifier_state *cur = env->cur_state; 599 600 return cur->frame[reg->frameno]; 601 } 602 603 static const char *kernel_type_name(const struct btf* btf, u32 id) 604 { 605 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 606 } 607 608 static void print_verifier_state(struct bpf_verifier_env *env, 609 const struct bpf_func_state *state) 610 { 611 const struct bpf_reg_state *reg; 612 enum bpf_reg_type t; 613 int i; 614 615 if (state->frameno) 616 verbose(env, " frame%d:", state->frameno); 617 for (i = 0; i < MAX_BPF_REG; i++) { 618 reg = &state->regs[i]; 619 t = reg->type; 620 if (t == NOT_INIT) 621 continue; 622 verbose(env, " R%d", i); 623 print_liveness(env, reg->live); 624 verbose(env, "=%s", reg_type_str[t]); 625 if (t == SCALAR_VALUE && reg->precise) 626 verbose(env, "P"); 627 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 628 tnum_is_const(reg->var_off)) { 629 /* reg->off should be 0 for SCALAR_VALUE */ 630 verbose(env, "%lld", reg->var_off.value + reg->off); 631 } else { 632 if (t == PTR_TO_BTF_ID || 633 t == PTR_TO_BTF_ID_OR_NULL || 634 t == PTR_TO_PERCPU_BTF_ID) 635 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id)); 636 verbose(env, "(id=%d", reg->id); 637 if (reg_type_may_be_refcounted_or_null(t)) 638 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id); 639 if (t != SCALAR_VALUE) 640 verbose(env, ",off=%d", reg->off); 641 if (type_is_pkt_pointer(t)) 642 verbose(env, ",r=%d", reg->range); 643 else if (t == CONST_PTR_TO_MAP || 644 t == PTR_TO_MAP_KEY || 645 t == PTR_TO_MAP_VALUE || 646 t == PTR_TO_MAP_VALUE_OR_NULL) 647 verbose(env, ",ks=%d,vs=%d", 648 reg->map_ptr->key_size, 649 reg->map_ptr->value_size); 650 if (tnum_is_const(reg->var_off)) { 651 /* Typically an immediate SCALAR_VALUE, but 652 * could be a pointer whose offset is too big 653 * for reg->off 654 */ 655 verbose(env, ",imm=%llx", reg->var_off.value); 656 } else { 657 if (reg->smin_value != reg->umin_value && 658 reg->smin_value != S64_MIN) 659 verbose(env, ",smin_value=%lld", 660 (long long)reg->smin_value); 661 if (reg->smax_value != reg->umax_value && 662 reg->smax_value != S64_MAX) 663 verbose(env, ",smax_value=%lld", 664 (long long)reg->smax_value); 665 if (reg->umin_value != 0) 666 verbose(env, ",umin_value=%llu", 667 (unsigned long long)reg->umin_value); 668 if (reg->umax_value != U64_MAX) 669 verbose(env, ",umax_value=%llu", 670 (unsigned long long)reg->umax_value); 671 if (!tnum_is_unknown(reg->var_off)) { 672 char tn_buf[48]; 673 674 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 675 verbose(env, ",var_off=%s", tn_buf); 676 } 677 if (reg->s32_min_value != reg->smin_value && 678 reg->s32_min_value != S32_MIN) 679 verbose(env, ",s32_min_value=%d", 680 (int)(reg->s32_min_value)); 681 if (reg->s32_max_value != reg->smax_value && 682 reg->s32_max_value != S32_MAX) 683 verbose(env, ",s32_max_value=%d", 684 (int)(reg->s32_max_value)); 685 if (reg->u32_min_value != reg->umin_value && 686 reg->u32_min_value != U32_MIN) 687 verbose(env, ",u32_min_value=%d", 688 (int)(reg->u32_min_value)); 689 if (reg->u32_max_value != reg->umax_value && 690 reg->u32_max_value != U32_MAX) 691 verbose(env, ",u32_max_value=%d", 692 (int)(reg->u32_max_value)); 693 } 694 verbose(env, ")"); 695 } 696 } 697 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 698 char types_buf[BPF_REG_SIZE + 1]; 699 bool valid = false; 700 int j; 701 702 for (j = 0; j < BPF_REG_SIZE; j++) { 703 if (state->stack[i].slot_type[j] != STACK_INVALID) 704 valid = true; 705 types_buf[j] = slot_type_char[ 706 state->stack[i].slot_type[j]]; 707 } 708 types_buf[BPF_REG_SIZE] = 0; 709 if (!valid) 710 continue; 711 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 712 print_liveness(env, state->stack[i].spilled_ptr.live); 713 if (state->stack[i].slot_type[0] == STACK_SPILL) { 714 reg = &state->stack[i].spilled_ptr; 715 t = reg->type; 716 verbose(env, "=%s", reg_type_str[t]); 717 if (t == SCALAR_VALUE && reg->precise) 718 verbose(env, "P"); 719 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 720 verbose(env, "%lld", reg->var_off.value + reg->off); 721 } else { 722 verbose(env, "=%s", types_buf); 723 } 724 } 725 if (state->acquired_refs && state->refs[0].id) { 726 verbose(env, " refs=%d", state->refs[0].id); 727 for (i = 1; i < state->acquired_refs; i++) 728 if (state->refs[i].id) 729 verbose(env, ",%d", state->refs[i].id); 730 } 731 verbose(env, "\n"); 732 } 733 734 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \ 735 static int copy_##NAME##_state(struct bpf_func_state *dst, \ 736 const struct bpf_func_state *src) \ 737 { \ 738 if (!src->FIELD) \ 739 return 0; \ 740 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \ 741 /* internal bug, make state invalid to reject the program */ \ 742 memset(dst, 0, sizeof(*dst)); \ 743 return -EFAULT; \ 744 } \ 745 memcpy(dst->FIELD, src->FIELD, \ 746 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \ 747 return 0; \ 748 } 749 /* copy_reference_state() */ 750 COPY_STATE_FN(reference, acquired_refs, refs, 1) 751 /* copy_stack_state() */ 752 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE) 753 #undef COPY_STATE_FN 754 755 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \ 756 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \ 757 bool copy_old) \ 758 { \ 759 u32 old_size = state->COUNT; \ 760 struct bpf_##NAME##_state *new_##FIELD; \ 761 int slot = size / SIZE; \ 762 \ 763 if (size <= old_size || !size) { \ 764 if (copy_old) \ 765 return 0; \ 766 state->COUNT = slot * SIZE; \ 767 if (!size && old_size) { \ 768 kfree(state->FIELD); \ 769 state->FIELD = NULL; \ 770 } \ 771 return 0; \ 772 } \ 773 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \ 774 GFP_KERNEL); \ 775 if (!new_##FIELD) \ 776 return -ENOMEM; \ 777 if (copy_old) { \ 778 if (state->FIELD) \ 779 memcpy(new_##FIELD, state->FIELD, \ 780 sizeof(*new_##FIELD) * (old_size / SIZE)); \ 781 memset(new_##FIELD + old_size / SIZE, 0, \ 782 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \ 783 } \ 784 state->COUNT = slot * SIZE; \ 785 kfree(state->FIELD); \ 786 state->FIELD = new_##FIELD; \ 787 return 0; \ 788 } 789 /* realloc_reference_state() */ 790 REALLOC_STATE_FN(reference, acquired_refs, refs, 1) 791 /* realloc_stack_state() */ 792 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE) 793 #undef REALLOC_STATE_FN 794 795 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to 796 * make it consume minimal amount of memory. check_stack_write() access from 797 * the program calls into realloc_func_state() to grow the stack size. 798 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state 799 * which realloc_stack_state() copies over. It points to previous 800 * bpf_verifier_state which is never reallocated. 801 */ 802 static int realloc_func_state(struct bpf_func_state *state, int stack_size, 803 int refs_size, bool copy_old) 804 { 805 int err = realloc_reference_state(state, refs_size, copy_old); 806 if (err) 807 return err; 808 return realloc_stack_state(state, stack_size, copy_old); 809 } 810 811 /* Acquire a pointer id from the env and update the state->refs to include 812 * this new pointer reference. 813 * On success, returns a valid pointer id to associate with the register 814 * On failure, returns a negative errno. 815 */ 816 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 817 { 818 struct bpf_func_state *state = cur_func(env); 819 int new_ofs = state->acquired_refs; 820 int id, err; 821 822 err = realloc_reference_state(state, state->acquired_refs + 1, true); 823 if (err) 824 return err; 825 id = ++env->id_gen; 826 state->refs[new_ofs].id = id; 827 state->refs[new_ofs].insn_idx = insn_idx; 828 829 return id; 830 } 831 832 /* release function corresponding to acquire_reference_state(). Idempotent. */ 833 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 834 { 835 int i, last_idx; 836 837 last_idx = state->acquired_refs - 1; 838 for (i = 0; i < state->acquired_refs; i++) { 839 if (state->refs[i].id == ptr_id) { 840 if (last_idx && i != last_idx) 841 memcpy(&state->refs[i], &state->refs[last_idx], 842 sizeof(*state->refs)); 843 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 844 state->acquired_refs--; 845 return 0; 846 } 847 } 848 return -EINVAL; 849 } 850 851 static int transfer_reference_state(struct bpf_func_state *dst, 852 struct bpf_func_state *src) 853 { 854 int err = realloc_reference_state(dst, src->acquired_refs, false); 855 if (err) 856 return err; 857 err = copy_reference_state(dst, src); 858 if (err) 859 return err; 860 return 0; 861 } 862 863 static void free_func_state(struct bpf_func_state *state) 864 { 865 if (!state) 866 return; 867 kfree(state->refs); 868 kfree(state->stack); 869 kfree(state); 870 } 871 872 static void clear_jmp_history(struct bpf_verifier_state *state) 873 { 874 kfree(state->jmp_history); 875 state->jmp_history = NULL; 876 state->jmp_history_cnt = 0; 877 } 878 879 static void free_verifier_state(struct bpf_verifier_state *state, 880 bool free_self) 881 { 882 int i; 883 884 for (i = 0; i <= state->curframe; i++) { 885 free_func_state(state->frame[i]); 886 state->frame[i] = NULL; 887 } 888 clear_jmp_history(state); 889 if (free_self) 890 kfree(state); 891 } 892 893 /* copy verifier state from src to dst growing dst stack space 894 * when necessary to accommodate larger src stack 895 */ 896 static int copy_func_state(struct bpf_func_state *dst, 897 const struct bpf_func_state *src) 898 { 899 int err; 900 901 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs, 902 false); 903 if (err) 904 return err; 905 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 906 err = copy_reference_state(dst, src); 907 if (err) 908 return err; 909 return copy_stack_state(dst, src); 910 } 911 912 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 913 const struct bpf_verifier_state *src) 914 { 915 struct bpf_func_state *dst; 916 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt; 917 int i, err; 918 919 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) { 920 kfree(dst_state->jmp_history); 921 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER); 922 if (!dst_state->jmp_history) 923 return -ENOMEM; 924 } 925 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz); 926 dst_state->jmp_history_cnt = src->jmp_history_cnt; 927 928 /* if dst has more stack frames then src frame, free them */ 929 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 930 free_func_state(dst_state->frame[i]); 931 dst_state->frame[i] = NULL; 932 } 933 dst_state->speculative = src->speculative; 934 dst_state->curframe = src->curframe; 935 dst_state->active_spin_lock = src->active_spin_lock; 936 dst_state->branches = src->branches; 937 dst_state->parent = src->parent; 938 dst_state->first_insn_idx = src->first_insn_idx; 939 dst_state->last_insn_idx = src->last_insn_idx; 940 for (i = 0; i <= src->curframe; i++) { 941 dst = dst_state->frame[i]; 942 if (!dst) { 943 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 944 if (!dst) 945 return -ENOMEM; 946 dst_state->frame[i] = dst; 947 } 948 err = copy_func_state(dst, src->frame[i]); 949 if (err) 950 return err; 951 } 952 return 0; 953 } 954 955 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 956 { 957 while (st) { 958 u32 br = --st->branches; 959 960 /* WARN_ON(br > 1) technically makes sense here, 961 * but see comment in push_stack(), hence: 962 */ 963 WARN_ONCE((int)br < 0, 964 "BUG update_branch_counts:branches_to_explore=%d\n", 965 br); 966 if (br) 967 break; 968 st = st->parent; 969 } 970 } 971 972 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 973 int *insn_idx, bool pop_log) 974 { 975 struct bpf_verifier_state *cur = env->cur_state; 976 struct bpf_verifier_stack_elem *elem, *head = env->head; 977 int err; 978 979 if (env->head == NULL) 980 return -ENOENT; 981 982 if (cur) { 983 err = copy_verifier_state(cur, &head->st); 984 if (err) 985 return err; 986 } 987 if (pop_log) 988 bpf_vlog_reset(&env->log, head->log_pos); 989 if (insn_idx) 990 *insn_idx = head->insn_idx; 991 if (prev_insn_idx) 992 *prev_insn_idx = head->prev_insn_idx; 993 elem = head->next; 994 free_verifier_state(&head->st, false); 995 kfree(head); 996 env->head = elem; 997 env->stack_size--; 998 return 0; 999 } 1000 1001 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1002 int insn_idx, int prev_insn_idx, 1003 bool speculative) 1004 { 1005 struct bpf_verifier_state *cur = env->cur_state; 1006 struct bpf_verifier_stack_elem *elem; 1007 int err; 1008 1009 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1010 if (!elem) 1011 goto err; 1012 1013 elem->insn_idx = insn_idx; 1014 elem->prev_insn_idx = prev_insn_idx; 1015 elem->next = env->head; 1016 elem->log_pos = env->log.len_used; 1017 env->head = elem; 1018 env->stack_size++; 1019 err = copy_verifier_state(&elem->st, cur); 1020 if (err) 1021 goto err; 1022 elem->st.speculative |= speculative; 1023 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1024 verbose(env, "The sequence of %d jumps is too complex.\n", 1025 env->stack_size); 1026 goto err; 1027 } 1028 if (elem->st.parent) { 1029 ++elem->st.parent->branches; 1030 /* WARN_ON(branches > 2) technically makes sense here, 1031 * but 1032 * 1. speculative states will bump 'branches' for non-branch 1033 * instructions 1034 * 2. is_state_visited() heuristics may decide not to create 1035 * a new state for a sequence of branches and all such current 1036 * and cloned states will be pointing to a single parent state 1037 * which might have large 'branches' count. 1038 */ 1039 } 1040 return &elem->st; 1041 err: 1042 free_verifier_state(env->cur_state, true); 1043 env->cur_state = NULL; 1044 /* pop all elements and return */ 1045 while (!pop_stack(env, NULL, NULL, false)); 1046 return NULL; 1047 } 1048 1049 #define CALLER_SAVED_REGS 6 1050 static const int caller_saved[CALLER_SAVED_REGS] = { 1051 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1052 }; 1053 1054 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1055 struct bpf_reg_state *reg); 1056 1057 /* This helper doesn't clear reg->id */ 1058 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1059 { 1060 reg->var_off = tnum_const(imm); 1061 reg->smin_value = (s64)imm; 1062 reg->smax_value = (s64)imm; 1063 reg->umin_value = imm; 1064 reg->umax_value = imm; 1065 1066 reg->s32_min_value = (s32)imm; 1067 reg->s32_max_value = (s32)imm; 1068 reg->u32_min_value = (u32)imm; 1069 reg->u32_max_value = (u32)imm; 1070 } 1071 1072 /* Mark the unknown part of a register (variable offset or scalar value) as 1073 * known to have the value @imm. 1074 */ 1075 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1076 { 1077 /* Clear id, off, and union(map_ptr, range) */ 1078 memset(((u8 *)reg) + sizeof(reg->type), 0, 1079 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1080 ___mark_reg_known(reg, imm); 1081 } 1082 1083 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1084 { 1085 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1086 reg->s32_min_value = (s32)imm; 1087 reg->s32_max_value = (s32)imm; 1088 reg->u32_min_value = (u32)imm; 1089 reg->u32_max_value = (u32)imm; 1090 } 1091 1092 /* Mark the 'variable offset' part of a register as zero. This should be 1093 * used only on registers holding a pointer type. 1094 */ 1095 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1096 { 1097 __mark_reg_known(reg, 0); 1098 } 1099 1100 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1101 { 1102 __mark_reg_known(reg, 0); 1103 reg->type = SCALAR_VALUE; 1104 } 1105 1106 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1107 struct bpf_reg_state *regs, u32 regno) 1108 { 1109 if (WARN_ON(regno >= MAX_BPF_REG)) { 1110 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1111 /* Something bad happened, let's kill all regs */ 1112 for (regno = 0; regno < MAX_BPF_REG; regno++) 1113 __mark_reg_not_init(env, regs + regno); 1114 return; 1115 } 1116 __mark_reg_known_zero(regs + regno); 1117 } 1118 1119 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1120 { 1121 switch (reg->type) { 1122 case PTR_TO_MAP_VALUE_OR_NULL: { 1123 const struct bpf_map *map = reg->map_ptr; 1124 1125 if (map->inner_map_meta) { 1126 reg->type = CONST_PTR_TO_MAP; 1127 reg->map_ptr = map->inner_map_meta; 1128 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1129 reg->type = PTR_TO_XDP_SOCK; 1130 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1131 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1132 reg->type = PTR_TO_SOCKET; 1133 } else { 1134 reg->type = PTR_TO_MAP_VALUE; 1135 } 1136 break; 1137 } 1138 case PTR_TO_SOCKET_OR_NULL: 1139 reg->type = PTR_TO_SOCKET; 1140 break; 1141 case PTR_TO_SOCK_COMMON_OR_NULL: 1142 reg->type = PTR_TO_SOCK_COMMON; 1143 break; 1144 case PTR_TO_TCP_SOCK_OR_NULL: 1145 reg->type = PTR_TO_TCP_SOCK; 1146 break; 1147 case PTR_TO_BTF_ID_OR_NULL: 1148 reg->type = PTR_TO_BTF_ID; 1149 break; 1150 case PTR_TO_MEM_OR_NULL: 1151 reg->type = PTR_TO_MEM; 1152 break; 1153 case PTR_TO_RDONLY_BUF_OR_NULL: 1154 reg->type = PTR_TO_RDONLY_BUF; 1155 break; 1156 case PTR_TO_RDWR_BUF_OR_NULL: 1157 reg->type = PTR_TO_RDWR_BUF; 1158 break; 1159 default: 1160 WARN_ONCE(1, "unknown nullable register type"); 1161 } 1162 } 1163 1164 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1165 { 1166 return type_is_pkt_pointer(reg->type); 1167 } 1168 1169 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1170 { 1171 return reg_is_pkt_pointer(reg) || 1172 reg->type == PTR_TO_PACKET_END; 1173 } 1174 1175 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1176 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1177 enum bpf_reg_type which) 1178 { 1179 /* The register can already have a range from prior markings. 1180 * This is fine as long as it hasn't been advanced from its 1181 * origin. 1182 */ 1183 return reg->type == which && 1184 reg->id == 0 && 1185 reg->off == 0 && 1186 tnum_equals_const(reg->var_off, 0); 1187 } 1188 1189 /* Reset the min/max bounds of a register */ 1190 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1191 { 1192 reg->smin_value = S64_MIN; 1193 reg->smax_value = S64_MAX; 1194 reg->umin_value = 0; 1195 reg->umax_value = U64_MAX; 1196 1197 reg->s32_min_value = S32_MIN; 1198 reg->s32_max_value = S32_MAX; 1199 reg->u32_min_value = 0; 1200 reg->u32_max_value = U32_MAX; 1201 } 1202 1203 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1204 { 1205 reg->smin_value = S64_MIN; 1206 reg->smax_value = S64_MAX; 1207 reg->umin_value = 0; 1208 reg->umax_value = U64_MAX; 1209 } 1210 1211 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1212 { 1213 reg->s32_min_value = S32_MIN; 1214 reg->s32_max_value = S32_MAX; 1215 reg->u32_min_value = 0; 1216 reg->u32_max_value = U32_MAX; 1217 } 1218 1219 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1220 { 1221 struct tnum var32_off = tnum_subreg(reg->var_off); 1222 1223 /* min signed is max(sign bit) | min(other bits) */ 1224 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1225 var32_off.value | (var32_off.mask & S32_MIN)); 1226 /* max signed is min(sign bit) | max(other bits) */ 1227 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1228 var32_off.value | (var32_off.mask & S32_MAX)); 1229 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1230 reg->u32_max_value = min(reg->u32_max_value, 1231 (u32)(var32_off.value | var32_off.mask)); 1232 } 1233 1234 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1235 { 1236 /* min signed is max(sign bit) | min(other bits) */ 1237 reg->smin_value = max_t(s64, reg->smin_value, 1238 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1239 /* max signed is min(sign bit) | max(other bits) */ 1240 reg->smax_value = min_t(s64, reg->smax_value, 1241 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1242 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1243 reg->umax_value = min(reg->umax_value, 1244 reg->var_off.value | reg->var_off.mask); 1245 } 1246 1247 static void __update_reg_bounds(struct bpf_reg_state *reg) 1248 { 1249 __update_reg32_bounds(reg); 1250 __update_reg64_bounds(reg); 1251 } 1252 1253 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1254 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1255 { 1256 /* Learn sign from signed bounds. 1257 * If we cannot cross the sign boundary, then signed and unsigned bounds 1258 * are the same, so combine. This works even in the negative case, e.g. 1259 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1260 */ 1261 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 1262 reg->s32_min_value = reg->u32_min_value = 1263 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1264 reg->s32_max_value = reg->u32_max_value = 1265 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1266 return; 1267 } 1268 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1269 * boundary, so we must be careful. 1270 */ 1271 if ((s32)reg->u32_max_value >= 0) { 1272 /* Positive. We can't learn anything from the smin, but smax 1273 * is positive, hence safe. 1274 */ 1275 reg->s32_min_value = reg->u32_min_value; 1276 reg->s32_max_value = reg->u32_max_value = 1277 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1278 } else if ((s32)reg->u32_min_value < 0) { 1279 /* Negative. We can't learn anything from the smax, but smin 1280 * is negative, hence safe. 1281 */ 1282 reg->s32_min_value = reg->u32_min_value = 1283 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1284 reg->s32_max_value = reg->u32_max_value; 1285 } 1286 } 1287 1288 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 1289 { 1290 /* Learn sign from signed bounds. 1291 * If we cannot cross the sign boundary, then signed and unsigned bounds 1292 * are the same, so combine. This works even in the negative case, e.g. 1293 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1294 */ 1295 if (reg->smin_value >= 0 || reg->smax_value < 0) { 1296 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1297 reg->umin_value); 1298 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1299 reg->umax_value); 1300 return; 1301 } 1302 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1303 * boundary, so we must be careful. 1304 */ 1305 if ((s64)reg->umax_value >= 0) { 1306 /* Positive. We can't learn anything from the smin, but smax 1307 * is positive, hence safe. 1308 */ 1309 reg->smin_value = reg->umin_value; 1310 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1311 reg->umax_value); 1312 } else if ((s64)reg->umin_value < 0) { 1313 /* Negative. We can't learn anything from the smax, but smin 1314 * is negative, hence safe. 1315 */ 1316 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1317 reg->umin_value); 1318 reg->smax_value = reg->umax_value; 1319 } 1320 } 1321 1322 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 1323 { 1324 __reg32_deduce_bounds(reg); 1325 __reg64_deduce_bounds(reg); 1326 } 1327 1328 /* Attempts to improve var_off based on unsigned min/max information */ 1329 static void __reg_bound_offset(struct bpf_reg_state *reg) 1330 { 1331 struct tnum var64_off = tnum_intersect(reg->var_off, 1332 tnum_range(reg->umin_value, 1333 reg->umax_value)); 1334 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off), 1335 tnum_range(reg->u32_min_value, 1336 reg->u32_max_value)); 1337 1338 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 1339 } 1340 1341 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 1342 { 1343 reg->umin_value = reg->u32_min_value; 1344 reg->umax_value = reg->u32_max_value; 1345 /* Attempt to pull 32-bit signed bounds into 64-bit bounds 1346 * but must be positive otherwise set to worse case bounds 1347 * and refine later from tnum. 1348 */ 1349 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0) 1350 reg->smax_value = reg->s32_max_value; 1351 else 1352 reg->smax_value = U32_MAX; 1353 if (reg->s32_min_value >= 0) 1354 reg->smin_value = reg->s32_min_value; 1355 else 1356 reg->smin_value = 0; 1357 } 1358 1359 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 1360 { 1361 /* special case when 64-bit register has upper 32-bit register 1362 * zeroed. Typically happens after zext or <<32, >>32 sequence 1363 * allowing us to use 32-bit bounds directly, 1364 */ 1365 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 1366 __reg_assign_32_into_64(reg); 1367 } else { 1368 /* Otherwise the best we can do is push lower 32bit known and 1369 * unknown bits into register (var_off set from jmp logic) 1370 * then learn as much as possible from the 64-bit tnum 1371 * known and unknown bits. The previous smin/smax bounds are 1372 * invalid here because of jmp32 compare so mark them unknown 1373 * so they do not impact tnum bounds calculation. 1374 */ 1375 __mark_reg64_unbounded(reg); 1376 __update_reg_bounds(reg); 1377 } 1378 1379 /* Intersecting with the old var_off might have improved our bounds 1380 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1381 * then new var_off is (0; 0x7f...fc) which improves our umax. 1382 */ 1383 __reg_deduce_bounds(reg); 1384 __reg_bound_offset(reg); 1385 __update_reg_bounds(reg); 1386 } 1387 1388 static bool __reg64_bound_s32(s64 a) 1389 { 1390 return a > S32_MIN && a < S32_MAX; 1391 } 1392 1393 static bool __reg64_bound_u32(u64 a) 1394 { 1395 if (a > U32_MIN && a < U32_MAX) 1396 return true; 1397 return false; 1398 } 1399 1400 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 1401 { 1402 __mark_reg32_unbounded(reg); 1403 1404 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 1405 reg->s32_min_value = (s32)reg->smin_value; 1406 reg->s32_max_value = (s32)reg->smax_value; 1407 } 1408 if (__reg64_bound_u32(reg->umin_value)) 1409 reg->u32_min_value = (u32)reg->umin_value; 1410 if (__reg64_bound_u32(reg->umax_value)) 1411 reg->u32_max_value = (u32)reg->umax_value; 1412 1413 /* Intersecting with the old var_off might have improved our bounds 1414 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1415 * then new var_off is (0; 0x7f...fc) which improves our umax. 1416 */ 1417 __reg_deduce_bounds(reg); 1418 __reg_bound_offset(reg); 1419 __update_reg_bounds(reg); 1420 } 1421 1422 /* Mark a register as having a completely unknown (scalar) value. */ 1423 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1424 struct bpf_reg_state *reg) 1425 { 1426 /* 1427 * Clear type, id, off, and union(map_ptr, range) and 1428 * padding between 'type' and union 1429 */ 1430 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 1431 reg->type = SCALAR_VALUE; 1432 reg->var_off = tnum_unknown; 1433 reg->frameno = 0; 1434 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable; 1435 __mark_reg_unbounded(reg); 1436 } 1437 1438 static void mark_reg_unknown(struct bpf_verifier_env *env, 1439 struct bpf_reg_state *regs, u32 regno) 1440 { 1441 if (WARN_ON(regno >= MAX_BPF_REG)) { 1442 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 1443 /* Something bad happened, let's kill all regs except FP */ 1444 for (regno = 0; regno < BPF_REG_FP; regno++) 1445 __mark_reg_not_init(env, regs + regno); 1446 return; 1447 } 1448 __mark_reg_unknown(env, regs + regno); 1449 } 1450 1451 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1452 struct bpf_reg_state *reg) 1453 { 1454 __mark_reg_unknown(env, reg); 1455 reg->type = NOT_INIT; 1456 } 1457 1458 static void mark_reg_not_init(struct bpf_verifier_env *env, 1459 struct bpf_reg_state *regs, u32 regno) 1460 { 1461 if (WARN_ON(regno >= MAX_BPF_REG)) { 1462 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 1463 /* Something bad happened, let's kill all regs except FP */ 1464 for (regno = 0; regno < BPF_REG_FP; regno++) 1465 __mark_reg_not_init(env, regs + regno); 1466 return; 1467 } 1468 __mark_reg_not_init(env, regs + regno); 1469 } 1470 1471 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 1472 struct bpf_reg_state *regs, u32 regno, 1473 enum bpf_reg_type reg_type, 1474 struct btf *btf, u32 btf_id) 1475 { 1476 if (reg_type == SCALAR_VALUE) { 1477 mark_reg_unknown(env, regs, regno); 1478 return; 1479 } 1480 mark_reg_known_zero(env, regs, regno); 1481 regs[regno].type = PTR_TO_BTF_ID; 1482 regs[regno].btf = btf; 1483 regs[regno].btf_id = btf_id; 1484 } 1485 1486 #define DEF_NOT_SUBREG (0) 1487 static void init_reg_state(struct bpf_verifier_env *env, 1488 struct bpf_func_state *state) 1489 { 1490 struct bpf_reg_state *regs = state->regs; 1491 int i; 1492 1493 for (i = 0; i < MAX_BPF_REG; i++) { 1494 mark_reg_not_init(env, regs, i); 1495 regs[i].live = REG_LIVE_NONE; 1496 regs[i].parent = NULL; 1497 regs[i].subreg_def = DEF_NOT_SUBREG; 1498 } 1499 1500 /* frame pointer */ 1501 regs[BPF_REG_FP].type = PTR_TO_STACK; 1502 mark_reg_known_zero(env, regs, BPF_REG_FP); 1503 regs[BPF_REG_FP].frameno = state->frameno; 1504 } 1505 1506 #define BPF_MAIN_FUNC (-1) 1507 static void init_func_state(struct bpf_verifier_env *env, 1508 struct bpf_func_state *state, 1509 int callsite, int frameno, int subprogno) 1510 { 1511 state->callsite = callsite; 1512 state->frameno = frameno; 1513 state->subprogno = subprogno; 1514 init_reg_state(env, state); 1515 } 1516 1517 enum reg_arg_type { 1518 SRC_OP, /* register is used as source operand */ 1519 DST_OP, /* register is used as destination operand */ 1520 DST_OP_NO_MARK /* same as above, check only, don't mark */ 1521 }; 1522 1523 static int cmp_subprogs(const void *a, const void *b) 1524 { 1525 return ((struct bpf_subprog_info *)a)->start - 1526 ((struct bpf_subprog_info *)b)->start; 1527 } 1528 1529 static int find_subprog(struct bpf_verifier_env *env, int off) 1530 { 1531 struct bpf_subprog_info *p; 1532 1533 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 1534 sizeof(env->subprog_info[0]), cmp_subprogs); 1535 if (!p) 1536 return -ENOENT; 1537 return p - env->subprog_info; 1538 1539 } 1540 1541 static int add_subprog(struct bpf_verifier_env *env, int off) 1542 { 1543 int insn_cnt = env->prog->len; 1544 int ret; 1545 1546 if (off >= insn_cnt || off < 0) { 1547 verbose(env, "call to invalid destination\n"); 1548 return -EINVAL; 1549 } 1550 ret = find_subprog(env, off); 1551 if (ret >= 0) 1552 return ret; 1553 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 1554 verbose(env, "too many subprograms\n"); 1555 return -E2BIG; 1556 } 1557 env->subprog_info[env->subprog_cnt++].start = off; 1558 sort(env->subprog_info, env->subprog_cnt, 1559 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 1560 return env->subprog_cnt - 1; 1561 } 1562 1563 static int check_subprogs(struct bpf_verifier_env *env) 1564 { 1565 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0; 1566 struct bpf_subprog_info *subprog = env->subprog_info; 1567 struct bpf_insn *insn = env->prog->insnsi; 1568 int insn_cnt = env->prog->len; 1569 1570 /* Add entry function. */ 1571 ret = add_subprog(env, 0); 1572 if (ret < 0) 1573 return ret; 1574 1575 /* determine subprog starts. The end is one before the next starts */ 1576 for (i = 0; i < insn_cnt; i++) { 1577 if (bpf_pseudo_func(insn + i)) { 1578 if (!env->bpf_capable) { 1579 verbose(env, 1580 "function pointers are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 1581 return -EPERM; 1582 } 1583 ret = add_subprog(env, i + insn[i].imm + 1); 1584 if (ret < 0) 1585 return ret; 1586 /* remember subprog */ 1587 insn[i + 1].imm = ret; 1588 continue; 1589 } 1590 if (!bpf_pseudo_call(insn + i)) 1591 continue; 1592 if (!env->bpf_capable) { 1593 verbose(env, 1594 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 1595 return -EPERM; 1596 } 1597 ret = add_subprog(env, i + insn[i].imm + 1); 1598 if (ret < 0) 1599 return ret; 1600 } 1601 1602 /* Add a fake 'exit' subprog which could simplify subprog iteration 1603 * logic. 'subprog_cnt' should not be increased. 1604 */ 1605 subprog[env->subprog_cnt].start = insn_cnt; 1606 1607 if (env->log.level & BPF_LOG_LEVEL2) 1608 for (i = 0; i < env->subprog_cnt; i++) 1609 verbose(env, "func#%d @%d\n", i, subprog[i].start); 1610 1611 /* now check that all jumps are within the same subprog */ 1612 subprog_start = subprog[cur_subprog].start; 1613 subprog_end = subprog[cur_subprog + 1].start; 1614 for (i = 0; i < insn_cnt; i++) { 1615 u8 code = insn[i].code; 1616 1617 if (code == (BPF_JMP | BPF_CALL) && 1618 insn[i].imm == BPF_FUNC_tail_call && 1619 insn[i].src_reg != BPF_PSEUDO_CALL) 1620 subprog[cur_subprog].has_tail_call = true; 1621 if (BPF_CLASS(code) == BPF_LD && 1622 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 1623 subprog[cur_subprog].has_ld_abs = true; 1624 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 1625 goto next; 1626 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 1627 goto next; 1628 off = i + insn[i].off + 1; 1629 if (off < subprog_start || off >= subprog_end) { 1630 verbose(env, "jump out of range from insn %d to %d\n", i, off); 1631 return -EINVAL; 1632 } 1633 next: 1634 if (i == subprog_end - 1) { 1635 /* to avoid fall-through from one subprog into another 1636 * the last insn of the subprog should be either exit 1637 * or unconditional jump back 1638 */ 1639 if (code != (BPF_JMP | BPF_EXIT) && 1640 code != (BPF_JMP | BPF_JA)) { 1641 verbose(env, "last insn is not an exit or jmp\n"); 1642 return -EINVAL; 1643 } 1644 subprog_start = subprog_end; 1645 cur_subprog++; 1646 if (cur_subprog < env->subprog_cnt) 1647 subprog_end = subprog[cur_subprog + 1].start; 1648 } 1649 } 1650 return 0; 1651 } 1652 1653 /* Parentage chain of this register (or stack slot) should take care of all 1654 * issues like callee-saved registers, stack slot allocation time, etc. 1655 */ 1656 static int mark_reg_read(struct bpf_verifier_env *env, 1657 const struct bpf_reg_state *state, 1658 struct bpf_reg_state *parent, u8 flag) 1659 { 1660 bool writes = parent == state->parent; /* Observe write marks */ 1661 int cnt = 0; 1662 1663 while (parent) { 1664 /* if read wasn't screened by an earlier write ... */ 1665 if (writes && state->live & REG_LIVE_WRITTEN) 1666 break; 1667 if (parent->live & REG_LIVE_DONE) { 1668 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 1669 reg_type_str[parent->type], 1670 parent->var_off.value, parent->off); 1671 return -EFAULT; 1672 } 1673 /* The first condition is more likely to be true than the 1674 * second, checked it first. 1675 */ 1676 if ((parent->live & REG_LIVE_READ) == flag || 1677 parent->live & REG_LIVE_READ64) 1678 /* The parentage chain never changes and 1679 * this parent was already marked as LIVE_READ. 1680 * There is no need to keep walking the chain again and 1681 * keep re-marking all parents as LIVE_READ. 1682 * This case happens when the same register is read 1683 * multiple times without writes into it in-between. 1684 * Also, if parent has the stronger REG_LIVE_READ64 set, 1685 * then no need to set the weak REG_LIVE_READ32. 1686 */ 1687 break; 1688 /* ... then we depend on parent's value */ 1689 parent->live |= flag; 1690 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 1691 if (flag == REG_LIVE_READ64) 1692 parent->live &= ~REG_LIVE_READ32; 1693 state = parent; 1694 parent = state->parent; 1695 writes = true; 1696 cnt++; 1697 } 1698 1699 if (env->longest_mark_read_walk < cnt) 1700 env->longest_mark_read_walk = cnt; 1701 return 0; 1702 } 1703 1704 /* This function is supposed to be used by the following 32-bit optimization 1705 * code only. It returns TRUE if the source or destination register operates 1706 * on 64-bit, otherwise return FALSE. 1707 */ 1708 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 1709 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 1710 { 1711 u8 code, class, op; 1712 1713 code = insn->code; 1714 class = BPF_CLASS(code); 1715 op = BPF_OP(code); 1716 if (class == BPF_JMP) { 1717 /* BPF_EXIT for "main" will reach here. Return TRUE 1718 * conservatively. 1719 */ 1720 if (op == BPF_EXIT) 1721 return true; 1722 if (op == BPF_CALL) { 1723 /* BPF to BPF call will reach here because of marking 1724 * caller saved clobber with DST_OP_NO_MARK for which we 1725 * don't care the register def because they are anyway 1726 * marked as NOT_INIT already. 1727 */ 1728 if (insn->src_reg == BPF_PSEUDO_CALL) 1729 return false; 1730 /* Helper call will reach here because of arg type 1731 * check, conservatively return TRUE. 1732 */ 1733 if (t == SRC_OP) 1734 return true; 1735 1736 return false; 1737 } 1738 } 1739 1740 if (class == BPF_ALU64 || class == BPF_JMP || 1741 /* BPF_END always use BPF_ALU class. */ 1742 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 1743 return true; 1744 1745 if (class == BPF_ALU || class == BPF_JMP32) 1746 return false; 1747 1748 if (class == BPF_LDX) { 1749 if (t != SRC_OP) 1750 return BPF_SIZE(code) == BPF_DW; 1751 /* LDX source must be ptr. */ 1752 return true; 1753 } 1754 1755 if (class == BPF_STX) { 1756 /* BPF_STX (including atomic variants) has multiple source 1757 * operands, one of which is a ptr. Check whether the caller is 1758 * asking about it. 1759 */ 1760 if (t == SRC_OP && reg->type != SCALAR_VALUE) 1761 return true; 1762 return BPF_SIZE(code) == BPF_DW; 1763 } 1764 1765 if (class == BPF_LD) { 1766 u8 mode = BPF_MODE(code); 1767 1768 /* LD_IMM64 */ 1769 if (mode == BPF_IMM) 1770 return true; 1771 1772 /* Both LD_IND and LD_ABS return 32-bit data. */ 1773 if (t != SRC_OP) 1774 return false; 1775 1776 /* Implicit ctx ptr. */ 1777 if (regno == BPF_REG_6) 1778 return true; 1779 1780 /* Explicit source could be any width. */ 1781 return true; 1782 } 1783 1784 if (class == BPF_ST) 1785 /* The only source register for BPF_ST is a ptr. */ 1786 return true; 1787 1788 /* Conservatively return true at default. */ 1789 return true; 1790 } 1791 1792 /* Return the regno defined by the insn, or -1. */ 1793 static int insn_def_regno(const struct bpf_insn *insn) 1794 { 1795 switch (BPF_CLASS(insn->code)) { 1796 case BPF_JMP: 1797 case BPF_JMP32: 1798 case BPF_ST: 1799 return -1; 1800 case BPF_STX: 1801 if (BPF_MODE(insn->code) == BPF_ATOMIC && 1802 (insn->imm & BPF_FETCH)) { 1803 if (insn->imm == BPF_CMPXCHG) 1804 return BPF_REG_0; 1805 else 1806 return insn->src_reg; 1807 } else { 1808 return -1; 1809 } 1810 default: 1811 return insn->dst_reg; 1812 } 1813 } 1814 1815 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 1816 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 1817 { 1818 int dst_reg = insn_def_regno(insn); 1819 1820 if (dst_reg == -1) 1821 return false; 1822 1823 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 1824 } 1825 1826 static void mark_insn_zext(struct bpf_verifier_env *env, 1827 struct bpf_reg_state *reg) 1828 { 1829 s32 def_idx = reg->subreg_def; 1830 1831 if (def_idx == DEF_NOT_SUBREG) 1832 return; 1833 1834 env->insn_aux_data[def_idx - 1].zext_dst = true; 1835 /* The dst will be zero extended, so won't be sub-register anymore. */ 1836 reg->subreg_def = DEF_NOT_SUBREG; 1837 } 1838 1839 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 1840 enum reg_arg_type t) 1841 { 1842 struct bpf_verifier_state *vstate = env->cur_state; 1843 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 1844 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 1845 struct bpf_reg_state *reg, *regs = state->regs; 1846 bool rw64; 1847 1848 if (regno >= MAX_BPF_REG) { 1849 verbose(env, "R%d is invalid\n", regno); 1850 return -EINVAL; 1851 } 1852 1853 reg = ®s[regno]; 1854 rw64 = is_reg64(env, insn, regno, reg, t); 1855 if (t == SRC_OP) { 1856 /* check whether register used as source operand can be read */ 1857 if (reg->type == NOT_INIT) { 1858 verbose(env, "R%d !read_ok\n", regno); 1859 return -EACCES; 1860 } 1861 /* We don't need to worry about FP liveness because it's read-only */ 1862 if (regno == BPF_REG_FP) 1863 return 0; 1864 1865 if (rw64) 1866 mark_insn_zext(env, reg); 1867 1868 return mark_reg_read(env, reg, reg->parent, 1869 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 1870 } else { 1871 /* check whether register used as dest operand can be written to */ 1872 if (regno == BPF_REG_FP) { 1873 verbose(env, "frame pointer is read only\n"); 1874 return -EACCES; 1875 } 1876 reg->live |= REG_LIVE_WRITTEN; 1877 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 1878 if (t == DST_OP) 1879 mark_reg_unknown(env, regs, regno); 1880 } 1881 return 0; 1882 } 1883 1884 /* for any branch, call, exit record the history of jmps in the given state */ 1885 static int push_jmp_history(struct bpf_verifier_env *env, 1886 struct bpf_verifier_state *cur) 1887 { 1888 u32 cnt = cur->jmp_history_cnt; 1889 struct bpf_idx_pair *p; 1890 1891 cnt++; 1892 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER); 1893 if (!p) 1894 return -ENOMEM; 1895 p[cnt - 1].idx = env->insn_idx; 1896 p[cnt - 1].prev_idx = env->prev_insn_idx; 1897 cur->jmp_history = p; 1898 cur->jmp_history_cnt = cnt; 1899 return 0; 1900 } 1901 1902 /* Backtrack one insn at a time. If idx is not at the top of recorded 1903 * history then previous instruction came from straight line execution. 1904 */ 1905 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 1906 u32 *history) 1907 { 1908 u32 cnt = *history; 1909 1910 if (cnt && st->jmp_history[cnt - 1].idx == i) { 1911 i = st->jmp_history[cnt - 1].prev_idx; 1912 (*history)--; 1913 } else { 1914 i--; 1915 } 1916 return i; 1917 } 1918 1919 /* For given verifier state backtrack_insn() is called from the last insn to 1920 * the first insn. Its purpose is to compute a bitmask of registers and 1921 * stack slots that needs precision in the parent verifier state. 1922 */ 1923 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 1924 u32 *reg_mask, u64 *stack_mask) 1925 { 1926 const struct bpf_insn_cbs cbs = { 1927 .cb_print = verbose, 1928 .private_data = env, 1929 }; 1930 struct bpf_insn *insn = env->prog->insnsi + idx; 1931 u8 class = BPF_CLASS(insn->code); 1932 u8 opcode = BPF_OP(insn->code); 1933 u8 mode = BPF_MODE(insn->code); 1934 u32 dreg = 1u << insn->dst_reg; 1935 u32 sreg = 1u << insn->src_reg; 1936 u32 spi; 1937 1938 if (insn->code == 0) 1939 return 0; 1940 if (env->log.level & BPF_LOG_LEVEL) { 1941 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask); 1942 verbose(env, "%d: ", idx); 1943 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 1944 } 1945 1946 if (class == BPF_ALU || class == BPF_ALU64) { 1947 if (!(*reg_mask & dreg)) 1948 return 0; 1949 if (opcode == BPF_MOV) { 1950 if (BPF_SRC(insn->code) == BPF_X) { 1951 /* dreg = sreg 1952 * dreg needs precision after this insn 1953 * sreg needs precision before this insn 1954 */ 1955 *reg_mask &= ~dreg; 1956 *reg_mask |= sreg; 1957 } else { 1958 /* dreg = K 1959 * dreg needs precision after this insn. 1960 * Corresponding register is already marked 1961 * as precise=true in this verifier state. 1962 * No further markings in parent are necessary 1963 */ 1964 *reg_mask &= ~dreg; 1965 } 1966 } else { 1967 if (BPF_SRC(insn->code) == BPF_X) { 1968 /* dreg += sreg 1969 * both dreg and sreg need precision 1970 * before this insn 1971 */ 1972 *reg_mask |= sreg; 1973 } /* else dreg += K 1974 * dreg still needs precision before this insn 1975 */ 1976 } 1977 } else if (class == BPF_LDX) { 1978 if (!(*reg_mask & dreg)) 1979 return 0; 1980 *reg_mask &= ~dreg; 1981 1982 /* scalars can only be spilled into stack w/o losing precision. 1983 * Load from any other memory can be zero extended. 1984 * The desire to keep that precision is already indicated 1985 * by 'precise' mark in corresponding register of this state. 1986 * No further tracking necessary. 1987 */ 1988 if (insn->src_reg != BPF_REG_FP) 1989 return 0; 1990 if (BPF_SIZE(insn->code) != BPF_DW) 1991 return 0; 1992 1993 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 1994 * that [fp - off] slot contains scalar that needs to be 1995 * tracked with precision 1996 */ 1997 spi = (-insn->off - 1) / BPF_REG_SIZE; 1998 if (spi >= 64) { 1999 verbose(env, "BUG spi %d\n", spi); 2000 WARN_ONCE(1, "verifier backtracking bug"); 2001 return -EFAULT; 2002 } 2003 *stack_mask |= 1ull << spi; 2004 } else if (class == BPF_STX || class == BPF_ST) { 2005 if (*reg_mask & dreg) 2006 /* stx & st shouldn't be using _scalar_ dst_reg 2007 * to access memory. It means backtracking 2008 * encountered a case of pointer subtraction. 2009 */ 2010 return -ENOTSUPP; 2011 /* scalars can only be spilled into stack */ 2012 if (insn->dst_reg != BPF_REG_FP) 2013 return 0; 2014 if (BPF_SIZE(insn->code) != BPF_DW) 2015 return 0; 2016 spi = (-insn->off - 1) / BPF_REG_SIZE; 2017 if (spi >= 64) { 2018 verbose(env, "BUG spi %d\n", spi); 2019 WARN_ONCE(1, "verifier backtracking bug"); 2020 return -EFAULT; 2021 } 2022 if (!(*stack_mask & (1ull << spi))) 2023 return 0; 2024 *stack_mask &= ~(1ull << spi); 2025 if (class == BPF_STX) 2026 *reg_mask |= sreg; 2027 } else if (class == BPF_JMP || class == BPF_JMP32) { 2028 if (opcode == BPF_CALL) { 2029 if (insn->src_reg == BPF_PSEUDO_CALL) 2030 return -ENOTSUPP; 2031 /* regular helper call sets R0 */ 2032 *reg_mask &= ~1; 2033 if (*reg_mask & 0x3f) { 2034 /* if backtracing was looking for registers R1-R5 2035 * they should have been found already. 2036 */ 2037 verbose(env, "BUG regs %x\n", *reg_mask); 2038 WARN_ONCE(1, "verifier backtracking bug"); 2039 return -EFAULT; 2040 } 2041 } else if (opcode == BPF_EXIT) { 2042 return -ENOTSUPP; 2043 } 2044 } else if (class == BPF_LD) { 2045 if (!(*reg_mask & dreg)) 2046 return 0; 2047 *reg_mask &= ~dreg; 2048 /* It's ld_imm64 or ld_abs or ld_ind. 2049 * For ld_imm64 no further tracking of precision 2050 * into parent is necessary 2051 */ 2052 if (mode == BPF_IND || mode == BPF_ABS) 2053 /* to be analyzed */ 2054 return -ENOTSUPP; 2055 } 2056 return 0; 2057 } 2058 2059 /* the scalar precision tracking algorithm: 2060 * . at the start all registers have precise=false. 2061 * . scalar ranges are tracked as normal through alu and jmp insns. 2062 * . once precise value of the scalar register is used in: 2063 * . ptr + scalar alu 2064 * . if (scalar cond K|scalar) 2065 * . helper_call(.., scalar, ...) where ARG_CONST is expected 2066 * backtrack through the verifier states and mark all registers and 2067 * stack slots with spilled constants that these scalar regisers 2068 * should be precise. 2069 * . during state pruning two registers (or spilled stack slots) 2070 * are equivalent if both are not precise. 2071 * 2072 * Note the verifier cannot simply walk register parentage chain, 2073 * since many different registers and stack slots could have been 2074 * used to compute single precise scalar. 2075 * 2076 * The approach of starting with precise=true for all registers and then 2077 * backtrack to mark a register as not precise when the verifier detects 2078 * that program doesn't care about specific value (e.g., when helper 2079 * takes register as ARG_ANYTHING parameter) is not safe. 2080 * 2081 * It's ok to walk single parentage chain of the verifier states. 2082 * It's possible that this backtracking will go all the way till 1st insn. 2083 * All other branches will be explored for needing precision later. 2084 * 2085 * The backtracking needs to deal with cases like: 2086 * R8=map_value(id=0,off=0,ks=4,vs=1952,imm=0) R9_w=map_value(id=0,off=40,ks=4,vs=1952,imm=0) 2087 * r9 -= r8 2088 * r5 = r9 2089 * if r5 > 0x79f goto pc+7 2090 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 2091 * r5 += 1 2092 * ... 2093 * call bpf_perf_event_output#25 2094 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 2095 * 2096 * and this case: 2097 * r6 = 1 2098 * call foo // uses callee's r6 inside to compute r0 2099 * r0 += r6 2100 * if r0 == 0 goto 2101 * 2102 * to track above reg_mask/stack_mask needs to be independent for each frame. 2103 * 2104 * Also if parent's curframe > frame where backtracking started, 2105 * the verifier need to mark registers in both frames, otherwise callees 2106 * may incorrectly prune callers. This is similar to 2107 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 2108 * 2109 * For now backtracking falls back into conservative marking. 2110 */ 2111 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 2112 struct bpf_verifier_state *st) 2113 { 2114 struct bpf_func_state *func; 2115 struct bpf_reg_state *reg; 2116 int i, j; 2117 2118 /* big hammer: mark all scalars precise in this path. 2119 * pop_stack may still get !precise scalars. 2120 */ 2121 for (; st; st = st->parent) 2122 for (i = 0; i <= st->curframe; i++) { 2123 func = st->frame[i]; 2124 for (j = 0; j < BPF_REG_FP; j++) { 2125 reg = &func->regs[j]; 2126 if (reg->type != SCALAR_VALUE) 2127 continue; 2128 reg->precise = true; 2129 } 2130 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 2131 if (func->stack[j].slot_type[0] != STACK_SPILL) 2132 continue; 2133 reg = &func->stack[j].spilled_ptr; 2134 if (reg->type != SCALAR_VALUE) 2135 continue; 2136 reg->precise = true; 2137 } 2138 } 2139 } 2140 2141 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno, 2142 int spi) 2143 { 2144 struct bpf_verifier_state *st = env->cur_state; 2145 int first_idx = st->first_insn_idx; 2146 int last_idx = env->insn_idx; 2147 struct bpf_func_state *func; 2148 struct bpf_reg_state *reg; 2149 u32 reg_mask = regno >= 0 ? 1u << regno : 0; 2150 u64 stack_mask = spi >= 0 ? 1ull << spi : 0; 2151 bool skip_first = true; 2152 bool new_marks = false; 2153 int i, err; 2154 2155 if (!env->bpf_capable) 2156 return 0; 2157 2158 func = st->frame[st->curframe]; 2159 if (regno >= 0) { 2160 reg = &func->regs[regno]; 2161 if (reg->type != SCALAR_VALUE) { 2162 WARN_ONCE(1, "backtracing misuse"); 2163 return -EFAULT; 2164 } 2165 if (!reg->precise) 2166 new_marks = true; 2167 else 2168 reg_mask = 0; 2169 reg->precise = true; 2170 } 2171 2172 while (spi >= 0) { 2173 if (func->stack[spi].slot_type[0] != STACK_SPILL) { 2174 stack_mask = 0; 2175 break; 2176 } 2177 reg = &func->stack[spi].spilled_ptr; 2178 if (reg->type != SCALAR_VALUE) { 2179 stack_mask = 0; 2180 break; 2181 } 2182 if (!reg->precise) 2183 new_marks = true; 2184 else 2185 stack_mask = 0; 2186 reg->precise = true; 2187 break; 2188 } 2189 2190 if (!new_marks) 2191 return 0; 2192 if (!reg_mask && !stack_mask) 2193 return 0; 2194 for (;;) { 2195 DECLARE_BITMAP(mask, 64); 2196 u32 history = st->jmp_history_cnt; 2197 2198 if (env->log.level & BPF_LOG_LEVEL) 2199 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx); 2200 for (i = last_idx;;) { 2201 if (skip_first) { 2202 err = 0; 2203 skip_first = false; 2204 } else { 2205 err = backtrack_insn(env, i, ®_mask, &stack_mask); 2206 } 2207 if (err == -ENOTSUPP) { 2208 mark_all_scalars_precise(env, st); 2209 return 0; 2210 } else if (err) { 2211 return err; 2212 } 2213 if (!reg_mask && !stack_mask) 2214 /* Found assignment(s) into tracked register in this state. 2215 * Since this state is already marked, just return. 2216 * Nothing to be tracked further in the parent state. 2217 */ 2218 return 0; 2219 if (i == first_idx) 2220 break; 2221 i = get_prev_insn_idx(st, i, &history); 2222 if (i >= env->prog->len) { 2223 /* This can happen if backtracking reached insn 0 2224 * and there are still reg_mask or stack_mask 2225 * to backtrack. 2226 * It means the backtracking missed the spot where 2227 * particular register was initialized with a constant. 2228 */ 2229 verbose(env, "BUG backtracking idx %d\n", i); 2230 WARN_ONCE(1, "verifier backtracking bug"); 2231 return -EFAULT; 2232 } 2233 } 2234 st = st->parent; 2235 if (!st) 2236 break; 2237 2238 new_marks = false; 2239 func = st->frame[st->curframe]; 2240 bitmap_from_u64(mask, reg_mask); 2241 for_each_set_bit(i, mask, 32) { 2242 reg = &func->regs[i]; 2243 if (reg->type != SCALAR_VALUE) { 2244 reg_mask &= ~(1u << i); 2245 continue; 2246 } 2247 if (!reg->precise) 2248 new_marks = true; 2249 reg->precise = true; 2250 } 2251 2252 bitmap_from_u64(mask, stack_mask); 2253 for_each_set_bit(i, mask, 64) { 2254 if (i >= func->allocated_stack / BPF_REG_SIZE) { 2255 /* the sequence of instructions: 2256 * 2: (bf) r3 = r10 2257 * 3: (7b) *(u64 *)(r3 -8) = r0 2258 * 4: (79) r4 = *(u64 *)(r10 -8) 2259 * doesn't contain jmps. It's backtracked 2260 * as a single block. 2261 * During backtracking insn 3 is not recognized as 2262 * stack access, so at the end of backtracking 2263 * stack slot fp-8 is still marked in stack_mask. 2264 * However the parent state may not have accessed 2265 * fp-8 and it's "unallocated" stack space. 2266 * In such case fallback to conservative. 2267 */ 2268 mark_all_scalars_precise(env, st); 2269 return 0; 2270 } 2271 2272 if (func->stack[i].slot_type[0] != STACK_SPILL) { 2273 stack_mask &= ~(1ull << i); 2274 continue; 2275 } 2276 reg = &func->stack[i].spilled_ptr; 2277 if (reg->type != SCALAR_VALUE) { 2278 stack_mask &= ~(1ull << i); 2279 continue; 2280 } 2281 if (!reg->precise) 2282 new_marks = true; 2283 reg->precise = true; 2284 } 2285 if (env->log.level & BPF_LOG_LEVEL) { 2286 print_verifier_state(env, func); 2287 verbose(env, "parent %s regs=%x stack=%llx marks\n", 2288 new_marks ? "didn't have" : "already had", 2289 reg_mask, stack_mask); 2290 } 2291 2292 if (!reg_mask && !stack_mask) 2293 break; 2294 if (!new_marks) 2295 break; 2296 2297 last_idx = st->last_insn_idx; 2298 first_idx = st->first_insn_idx; 2299 } 2300 return 0; 2301 } 2302 2303 static int mark_chain_precision(struct bpf_verifier_env *env, int regno) 2304 { 2305 return __mark_chain_precision(env, regno, -1); 2306 } 2307 2308 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi) 2309 { 2310 return __mark_chain_precision(env, -1, spi); 2311 } 2312 2313 static bool is_spillable_regtype(enum bpf_reg_type type) 2314 { 2315 switch (type) { 2316 case PTR_TO_MAP_VALUE: 2317 case PTR_TO_MAP_VALUE_OR_NULL: 2318 case PTR_TO_STACK: 2319 case PTR_TO_CTX: 2320 case PTR_TO_PACKET: 2321 case PTR_TO_PACKET_META: 2322 case PTR_TO_PACKET_END: 2323 case PTR_TO_FLOW_KEYS: 2324 case CONST_PTR_TO_MAP: 2325 case PTR_TO_SOCKET: 2326 case PTR_TO_SOCKET_OR_NULL: 2327 case PTR_TO_SOCK_COMMON: 2328 case PTR_TO_SOCK_COMMON_OR_NULL: 2329 case PTR_TO_TCP_SOCK: 2330 case PTR_TO_TCP_SOCK_OR_NULL: 2331 case PTR_TO_XDP_SOCK: 2332 case PTR_TO_BTF_ID: 2333 case PTR_TO_BTF_ID_OR_NULL: 2334 case PTR_TO_RDONLY_BUF: 2335 case PTR_TO_RDONLY_BUF_OR_NULL: 2336 case PTR_TO_RDWR_BUF: 2337 case PTR_TO_RDWR_BUF_OR_NULL: 2338 case PTR_TO_PERCPU_BTF_ID: 2339 case PTR_TO_MEM: 2340 case PTR_TO_MEM_OR_NULL: 2341 case PTR_TO_FUNC: 2342 case PTR_TO_MAP_KEY: 2343 return true; 2344 default: 2345 return false; 2346 } 2347 } 2348 2349 /* Does this register contain a constant zero? */ 2350 static bool register_is_null(struct bpf_reg_state *reg) 2351 { 2352 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 2353 } 2354 2355 static bool register_is_const(struct bpf_reg_state *reg) 2356 { 2357 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 2358 } 2359 2360 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 2361 { 2362 return tnum_is_unknown(reg->var_off) && 2363 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 2364 reg->umin_value == 0 && reg->umax_value == U64_MAX && 2365 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 2366 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 2367 } 2368 2369 static bool register_is_bounded(struct bpf_reg_state *reg) 2370 { 2371 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 2372 } 2373 2374 static bool __is_pointer_value(bool allow_ptr_leaks, 2375 const struct bpf_reg_state *reg) 2376 { 2377 if (allow_ptr_leaks) 2378 return false; 2379 2380 return reg->type != SCALAR_VALUE; 2381 } 2382 2383 static void save_register_state(struct bpf_func_state *state, 2384 int spi, struct bpf_reg_state *reg) 2385 { 2386 int i; 2387 2388 state->stack[spi].spilled_ptr = *reg; 2389 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2390 2391 for (i = 0; i < BPF_REG_SIZE; i++) 2392 state->stack[spi].slot_type[i] = STACK_SPILL; 2393 } 2394 2395 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 2396 * stack boundary and alignment are checked in check_mem_access() 2397 */ 2398 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 2399 /* stack frame we're writing to */ 2400 struct bpf_func_state *state, 2401 int off, int size, int value_regno, 2402 int insn_idx) 2403 { 2404 struct bpf_func_state *cur; /* state of the current function */ 2405 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 2406 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg; 2407 struct bpf_reg_state *reg = NULL; 2408 2409 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE), 2410 state->acquired_refs, true); 2411 if (err) 2412 return err; 2413 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 2414 * so it's aligned access and [off, off + size) are within stack limits 2415 */ 2416 if (!env->allow_ptr_leaks && 2417 state->stack[spi].slot_type[0] == STACK_SPILL && 2418 size != BPF_REG_SIZE) { 2419 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 2420 return -EACCES; 2421 } 2422 2423 cur = env->cur_state->frame[env->cur_state->curframe]; 2424 if (value_regno >= 0) 2425 reg = &cur->regs[value_regno]; 2426 2427 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) && 2428 !register_is_null(reg) && env->bpf_capable) { 2429 if (dst_reg != BPF_REG_FP) { 2430 /* The backtracking logic can only recognize explicit 2431 * stack slot address like [fp - 8]. Other spill of 2432 * scalar via different register has to be conervative. 2433 * Backtrack from here and mark all registers as precise 2434 * that contributed into 'reg' being a constant. 2435 */ 2436 err = mark_chain_precision(env, value_regno); 2437 if (err) 2438 return err; 2439 } 2440 save_register_state(state, spi, reg); 2441 } else if (reg && is_spillable_regtype(reg->type)) { 2442 /* register containing pointer is being spilled into stack */ 2443 if (size != BPF_REG_SIZE) { 2444 verbose_linfo(env, insn_idx, "; "); 2445 verbose(env, "invalid size of register spill\n"); 2446 return -EACCES; 2447 } 2448 2449 if (state != cur && reg->type == PTR_TO_STACK) { 2450 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 2451 return -EINVAL; 2452 } 2453 2454 if (!env->bypass_spec_v4) { 2455 bool sanitize = false; 2456 2457 if (state->stack[spi].slot_type[0] == STACK_SPILL && 2458 register_is_const(&state->stack[spi].spilled_ptr)) 2459 sanitize = true; 2460 for (i = 0; i < BPF_REG_SIZE; i++) 2461 if (state->stack[spi].slot_type[i] == STACK_MISC) { 2462 sanitize = true; 2463 break; 2464 } 2465 if (sanitize) { 2466 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off; 2467 int soff = (-spi - 1) * BPF_REG_SIZE; 2468 2469 /* detected reuse of integer stack slot with a pointer 2470 * which means either llvm is reusing stack slot or 2471 * an attacker is trying to exploit CVE-2018-3639 2472 * (speculative store bypass) 2473 * Have to sanitize that slot with preemptive 2474 * store of zero. 2475 */ 2476 if (*poff && *poff != soff) { 2477 /* disallow programs where single insn stores 2478 * into two different stack slots, since verifier 2479 * cannot sanitize them 2480 */ 2481 verbose(env, 2482 "insn %d cannot access two stack slots fp%d and fp%d", 2483 insn_idx, *poff, soff); 2484 return -EINVAL; 2485 } 2486 *poff = soff; 2487 } 2488 } 2489 save_register_state(state, spi, reg); 2490 } else { 2491 u8 type = STACK_MISC; 2492 2493 /* regular write of data into stack destroys any spilled ptr */ 2494 state->stack[spi].spilled_ptr.type = NOT_INIT; 2495 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */ 2496 if (state->stack[spi].slot_type[0] == STACK_SPILL) 2497 for (i = 0; i < BPF_REG_SIZE; i++) 2498 state->stack[spi].slot_type[i] = STACK_MISC; 2499 2500 /* only mark the slot as written if all 8 bytes were written 2501 * otherwise read propagation may incorrectly stop too soon 2502 * when stack slots are partially written. 2503 * This heuristic means that read propagation will be 2504 * conservative, since it will add reg_live_read marks 2505 * to stack slots all the way to first state when programs 2506 * writes+reads less than 8 bytes 2507 */ 2508 if (size == BPF_REG_SIZE) 2509 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2510 2511 /* when we zero initialize stack slots mark them as such */ 2512 if (reg && register_is_null(reg)) { 2513 /* backtracking doesn't work for STACK_ZERO yet. */ 2514 err = mark_chain_precision(env, value_regno); 2515 if (err) 2516 return err; 2517 type = STACK_ZERO; 2518 } 2519 2520 /* Mark slots affected by this stack write. */ 2521 for (i = 0; i < size; i++) 2522 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 2523 type; 2524 } 2525 return 0; 2526 } 2527 2528 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 2529 * known to contain a variable offset. 2530 * This function checks whether the write is permitted and conservatively 2531 * tracks the effects of the write, considering that each stack slot in the 2532 * dynamic range is potentially written to. 2533 * 2534 * 'off' includes 'regno->off'. 2535 * 'value_regno' can be -1, meaning that an unknown value is being written to 2536 * the stack. 2537 * 2538 * Spilled pointers in range are not marked as written because we don't know 2539 * what's going to be actually written. This means that read propagation for 2540 * future reads cannot be terminated by this write. 2541 * 2542 * For privileged programs, uninitialized stack slots are considered 2543 * initialized by this write (even though we don't know exactly what offsets 2544 * are going to be written to). The idea is that we don't want the verifier to 2545 * reject future reads that access slots written to through variable offsets. 2546 */ 2547 static int check_stack_write_var_off(struct bpf_verifier_env *env, 2548 /* func where register points to */ 2549 struct bpf_func_state *state, 2550 int ptr_regno, int off, int size, 2551 int value_regno, int insn_idx) 2552 { 2553 struct bpf_func_state *cur; /* state of the current function */ 2554 int min_off, max_off; 2555 int i, err; 2556 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 2557 bool writing_zero = false; 2558 /* set if the fact that we're writing a zero is used to let any 2559 * stack slots remain STACK_ZERO 2560 */ 2561 bool zero_used = false; 2562 2563 cur = env->cur_state->frame[env->cur_state->curframe]; 2564 ptr_reg = &cur->regs[ptr_regno]; 2565 min_off = ptr_reg->smin_value + off; 2566 max_off = ptr_reg->smax_value + off + size; 2567 if (value_regno >= 0) 2568 value_reg = &cur->regs[value_regno]; 2569 if (value_reg && register_is_null(value_reg)) 2570 writing_zero = true; 2571 2572 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE), 2573 state->acquired_refs, true); 2574 if (err) 2575 return err; 2576 2577 2578 /* Variable offset writes destroy any spilled pointers in range. */ 2579 for (i = min_off; i < max_off; i++) { 2580 u8 new_type, *stype; 2581 int slot, spi; 2582 2583 slot = -i - 1; 2584 spi = slot / BPF_REG_SIZE; 2585 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 2586 2587 if (!env->allow_ptr_leaks 2588 && *stype != NOT_INIT 2589 && *stype != SCALAR_VALUE) { 2590 /* Reject the write if there's are spilled pointers in 2591 * range. If we didn't reject here, the ptr status 2592 * would be erased below (even though not all slots are 2593 * actually overwritten), possibly opening the door to 2594 * leaks. 2595 */ 2596 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 2597 insn_idx, i); 2598 return -EINVAL; 2599 } 2600 2601 /* Erase all spilled pointers. */ 2602 state->stack[spi].spilled_ptr.type = NOT_INIT; 2603 2604 /* Update the slot type. */ 2605 new_type = STACK_MISC; 2606 if (writing_zero && *stype == STACK_ZERO) { 2607 new_type = STACK_ZERO; 2608 zero_used = true; 2609 } 2610 /* If the slot is STACK_INVALID, we check whether it's OK to 2611 * pretend that it will be initialized by this write. The slot 2612 * might not actually be written to, and so if we mark it as 2613 * initialized future reads might leak uninitialized memory. 2614 * For privileged programs, we will accept such reads to slots 2615 * that may or may not be written because, if we're reject 2616 * them, the error would be too confusing. 2617 */ 2618 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 2619 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 2620 insn_idx, i); 2621 return -EINVAL; 2622 } 2623 *stype = new_type; 2624 } 2625 if (zero_used) { 2626 /* backtracking doesn't work for STACK_ZERO yet. */ 2627 err = mark_chain_precision(env, value_regno); 2628 if (err) 2629 return err; 2630 } 2631 return 0; 2632 } 2633 2634 /* When register 'dst_regno' is assigned some values from stack[min_off, 2635 * max_off), we set the register's type according to the types of the 2636 * respective stack slots. If all the stack values are known to be zeros, then 2637 * so is the destination reg. Otherwise, the register is considered to be 2638 * SCALAR. This function does not deal with register filling; the caller must 2639 * ensure that all spilled registers in the stack range have been marked as 2640 * read. 2641 */ 2642 static void mark_reg_stack_read(struct bpf_verifier_env *env, 2643 /* func where src register points to */ 2644 struct bpf_func_state *ptr_state, 2645 int min_off, int max_off, int dst_regno) 2646 { 2647 struct bpf_verifier_state *vstate = env->cur_state; 2648 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2649 int i, slot, spi; 2650 u8 *stype; 2651 int zeros = 0; 2652 2653 for (i = min_off; i < max_off; i++) { 2654 slot = -i - 1; 2655 spi = slot / BPF_REG_SIZE; 2656 stype = ptr_state->stack[spi].slot_type; 2657 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 2658 break; 2659 zeros++; 2660 } 2661 if (zeros == max_off - min_off) { 2662 /* any access_size read into register is zero extended, 2663 * so the whole register == const_zero 2664 */ 2665 __mark_reg_const_zero(&state->regs[dst_regno]); 2666 /* backtracking doesn't support STACK_ZERO yet, 2667 * so mark it precise here, so that later 2668 * backtracking can stop here. 2669 * Backtracking may not need this if this register 2670 * doesn't participate in pointer adjustment. 2671 * Forward propagation of precise flag is not 2672 * necessary either. This mark is only to stop 2673 * backtracking. Any register that contributed 2674 * to const 0 was marked precise before spill. 2675 */ 2676 state->regs[dst_regno].precise = true; 2677 } else { 2678 /* have read misc data from the stack */ 2679 mark_reg_unknown(env, state->regs, dst_regno); 2680 } 2681 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 2682 } 2683 2684 /* Read the stack at 'off' and put the results into the register indicated by 2685 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 2686 * spilled reg. 2687 * 2688 * 'dst_regno' can be -1, meaning that the read value is not going to a 2689 * register. 2690 * 2691 * The access is assumed to be within the current stack bounds. 2692 */ 2693 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 2694 /* func where src register points to */ 2695 struct bpf_func_state *reg_state, 2696 int off, int size, int dst_regno) 2697 { 2698 struct bpf_verifier_state *vstate = env->cur_state; 2699 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2700 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 2701 struct bpf_reg_state *reg; 2702 u8 *stype; 2703 2704 stype = reg_state->stack[spi].slot_type; 2705 reg = ®_state->stack[spi].spilled_ptr; 2706 2707 if (stype[0] == STACK_SPILL) { 2708 if (size != BPF_REG_SIZE) { 2709 if (reg->type != SCALAR_VALUE) { 2710 verbose_linfo(env, env->insn_idx, "; "); 2711 verbose(env, "invalid size of register fill\n"); 2712 return -EACCES; 2713 } 2714 if (dst_regno >= 0) { 2715 mark_reg_unknown(env, state->regs, dst_regno); 2716 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 2717 } 2718 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2719 return 0; 2720 } 2721 for (i = 1; i < BPF_REG_SIZE; i++) { 2722 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { 2723 verbose(env, "corrupted spill memory\n"); 2724 return -EACCES; 2725 } 2726 } 2727 2728 if (dst_regno >= 0) { 2729 /* restore register state from stack */ 2730 state->regs[dst_regno] = *reg; 2731 /* mark reg as written since spilled pointer state likely 2732 * has its liveness marks cleared by is_state_visited() 2733 * which resets stack/reg liveness for state transitions 2734 */ 2735 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 2736 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 2737 /* If dst_regno==-1, the caller is asking us whether 2738 * it is acceptable to use this value as a SCALAR_VALUE 2739 * (e.g. for XADD). 2740 * We must not allow unprivileged callers to do that 2741 * with spilled pointers. 2742 */ 2743 verbose(env, "leaking pointer from stack off %d\n", 2744 off); 2745 return -EACCES; 2746 } 2747 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2748 } else { 2749 u8 type; 2750 2751 for (i = 0; i < size; i++) { 2752 type = stype[(slot - i) % BPF_REG_SIZE]; 2753 if (type == STACK_MISC) 2754 continue; 2755 if (type == STACK_ZERO) 2756 continue; 2757 verbose(env, "invalid read from stack off %d+%d size %d\n", 2758 off, i, size); 2759 return -EACCES; 2760 } 2761 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2762 if (dst_regno >= 0) 2763 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 2764 } 2765 return 0; 2766 } 2767 2768 enum stack_access_src { 2769 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 2770 ACCESS_HELPER = 2, /* the access is performed by a helper */ 2771 }; 2772 2773 static int check_stack_range_initialized(struct bpf_verifier_env *env, 2774 int regno, int off, int access_size, 2775 bool zero_size_allowed, 2776 enum stack_access_src type, 2777 struct bpf_call_arg_meta *meta); 2778 2779 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 2780 { 2781 return cur_regs(env) + regno; 2782 } 2783 2784 /* Read the stack at 'ptr_regno + off' and put the result into the register 2785 * 'dst_regno'. 2786 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 2787 * but not its variable offset. 2788 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 2789 * 2790 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 2791 * filling registers (i.e. reads of spilled register cannot be detected when 2792 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 2793 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 2794 * offset; for a fixed offset check_stack_read_fixed_off should be used 2795 * instead. 2796 */ 2797 static int check_stack_read_var_off(struct bpf_verifier_env *env, 2798 int ptr_regno, int off, int size, int dst_regno) 2799 { 2800 /* The state of the source register. */ 2801 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 2802 struct bpf_func_state *ptr_state = func(env, reg); 2803 int err; 2804 int min_off, max_off; 2805 2806 /* Note that we pass a NULL meta, so raw access will not be permitted. 2807 */ 2808 err = check_stack_range_initialized(env, ptr_regno, off, size, 2809 false, ACCESS_DIRECT, NULL); 2810 if (err) 2811 return err; 2812 2813 min_off = reg->smin_value + off; 2814 max_off = reg->smax_value + off; 2815 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 2816 return 0; 2817 } 2818 2819 /* check_stack_read dispatches to check_stack_read_fixed_off or 2820 * check_stack_read_var_off. 2821 * 2822 * The caller must ensure that the offset falls within the allocated stack 2823 * bounds. 2824 * 2825 * 'dst_regno' is a register which will receive the value from the stack. It 2826 * can be -1, meaning that the read value is not going to a register. 2827 */ 2828 static int check_stack_read(struct bpf_verifier_env *env, 2829 int ptr_regno, int off, int size, 2830 int dst_regno) 2831 { 2832 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 2833 struct bpf_func_state *state = func(env, reg); 2834 int err; 2835 /* Some accesses are only permitted with a static offset. */ 2836 bool var_off = !tnum_is_const(reg->var_off); 2837 2838 /* The offset is required to be static when reads don't go to a 2839 * register, in order to not leak pointers (see 2840 * check_stack_read_fixed_off). 2841 */ 2842 if (dst_regno < 0 && var_off) { 2843 char tn_buf[48]; 2844 2845 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2846 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 2847 tn_buf, off, size); 2848 return -EACCES; 2849 } 2850 /* Variable offset is prohibited for unprivileged mode for simplicity 2851 * since it requires corresponding support in Spectre masking for stack 2852 * ALU. See also retrieve_ptr_limit(). 2853 */ 2854 if (!env->bypass_spec_v1 && var_off) { 2855 char tn_buf[48]; 2856 2857 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2858 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 2859 ptr_regno, tn_buf); 2860 return -EACCES; 2861 } 2862 2863 if (!var_off) { 2864 off += reg->var_off.value; 2865 err = check_stack_read_fixed_off(env, state, off, size, 2866 dst_regno); 2867 } else { 2868 /* Variable offset stack reads need more conservative handling 2869 * than fixed offset ones. Note that dst_regno >= 0 on this 2870 * branch. 2871 */ 2872 err = check_stack_read_var_off(env, ptr_regno, off, size, 2873 dst_regno); 2874 } 2875 return err; 2876 } 2877 2878 2879 /* check_stack_write dispatches to check_stack_write_fixed_off or 2880 * check_stack_write_var_off. 2881 * 2882 * 'ptr_regno' is the register used as a pointer into the stack. 2883 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 2884 * 'value_regno' is the register whose value we're writing to the stack. It can 2885 * be -1, meaning that we're not writing from a register. 2886 * 2887 * The caller must ensure that the offset falls within the maximum stack size. 2888 */ 2889 static int check_stack_write(struct bpf_verifier_env *env, 2890 int ptr_regno, int off, int size, 2891 int value_regno, int insn_idx) 2892 { 2893 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 2894 struct bpf_func_state *state = func(env, reg); 2895 int err; 2896 2897 if (tnum_is_const(reg->var_off)) { 2898 off += reg->var_off.value; 2899 err = check_stack_write_fixed_off(env, state, off, size, 2900 value_regno, insn_idx); 2901 } else { 2902 /* Variable offset stack reads need more conservative handling 2903 * than fixed offset ones. 2904 */ 2905 err = check_stack_write_var_off(env, state, 2906 ptr_regno, off, size, 2907 value_regno, insn_idx); 2908 } 2909 return err; 2910 } 2911 2912 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 2913 int off, int size, enum bpf_access_type type) 2914 { 2915 struct bpf_reg_state *regs = cur_regs(env); 2916 struct bpf_map *map = regs[regno].map_ptr; 2917 u32 cap = bpf_map_flags_to_cap(map); 2918 2919 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 2920 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 2921 map->value_size, off, size); 2922 return -EACCES; 2923 } 2924 2925 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 2926 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 2927 map->value_size, off, size); 2928 return -EACCES; 2929 } 2930 2931 return 0; 2932 } 2933 2934 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 2935 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 2936 int off, int size, u32 mem_size, 2937 bool zero_size_allowed) 2938 { 2939 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 2940 struct bpf_reg_state *reg; 2941 2942 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 2943 return 0; 2944 2945 reg = &cur_regs(env)[regno]; 2946 switch (reg->type) { 2947 case PTR_TO_MAP_KEY: 2948 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 2949 mem_size, off, size); 2950 break; 2951 case PTR_TO_MAP_VALUE: 2952 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 2953 mem_size, off, size); 2954 break; 2955 case PTR_TO_PACKET: 2956 case PTR_TO_PACKET_META: 2957 case PTR_TO_PACKET_END: 2958 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 2959 off, size, regno, reg->id, off, mem_size); 2960 break; 2961 case PTR_TO_MEM: 2962 default: 2963 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 2964 mem_size, off, size); 2965 } 2966 2967 return -EACCES; 2968 } 2969 2970 /* check read/write into a memory region with possible variable offset */ 2971 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 2972 int off, int size, u32 mem_size, 2973 bool zero_size_allowed) 2974 { 2975 struct bpf_verifier_state *vstate = env->cur_state; 2976 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2977 struct bpf_reg_state *reg = &state->regs[regno]; 2978 int err; 2979 2980 /* We may have adjusted the register pointing to memory region, so we 2981 * need to try adding each of min_value and max_value to off 2982 * to make sure our theoretical access will be safe. 2983 */ 2984 if (env->log.level & BPF_LOG_LEVEL) 2985 print_verifier_state(env, state); 2986 2987 /* The minimum value is only important with signed 2988 * comparisons where we can't assume the floor of a 2989 * value is 0. If we are using signed variables for our 2990 * index'es we need to make sure that whatever we use 2991 * will have a set floor within our range. 2992 */ 2993 if (reg->smin_value < 0 && 2994 (reg->smin_value == S64_MIN || 2995 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 2996 reg->smin_value + off < 0)) { 2997 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 2998 regno); 2999 return -EACCES; 3000 } 3001 err = __check_mem_access(env, regno, reg->smin_value + off, size, 3002 mem_size, zero_size_allowed); 3003 if (err) { 3004 verbose(env, "R%d min value is outside of the allowed memory range\n", 3005 regno); 3006 return err; 3007 } 3008 3009 /* If we haven't set a max value then we need to bail since we can't be 3010 * sure we won't do bad things. 3011 * If reg->umax_value + off could overflow, treat that as unbounded too. 3012 */ 3013 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 3014 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 3015 regno); 3016 return -EACCES; 3017 } 3018 err = __check_mem_access(env, regno, reg->umax_value + off, size, 3019 mem_size, zero_size_allowed); 3020 if (err) { 3021 verbose(env, "R%d max value is outside of the allowed memory range\n", 3022 regno); 3023 return err; 3024 } 3025 3026 return 0; 3027 } 3028 3029 /* check read/write into a map element with possible variable offset */ 3030 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 3031 int off, int size, bool zero_size_allowed) 3032 { 3033 struct bpf_verifier_state *vstate = env->cur_state; 3034 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3035 struct bpf_reg_state *reg = &state->regs[regno]; 3036 struct bpf_map *map = reg->map_ptr; 3037 int err; 3038 3039 err = check_mem_region_access(env, regno, off, size, map->value_size, 3040 zero_size_allowed); 3041 if (err) 3042 return err; 3043 3044 if (map_value_has_spin_lock(map)) { 3045 u32 lock = map->spin_lock_off; 3046 3047 /* if any part of struct bpf_spin_lock can be touched by 3048 * load/store reject this program. 3049 * To check that [x1, x2) overlaps with [y1, y2) 3050 * it is sufficient to check x1 < y2 && y1 < x2. 3051 */ 3052 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) && 3053 lock < reg->umax_value + off + size) { 3054 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n"); 3055 return -EACCES; 3056 } 3057 } 3058 return err; 3059 } 3060 3061 #define MAX_PACKET_OFF 0xffff 3062 3063 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog) 3064 { 3065 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type; 3066 } 3067 3068 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 3069 const struct bpf_call_arg_meta *meta, 3070 enum bpf_access_type t) 3071 { 3072 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 3073 3074 switch (prog_type) { 3075 /* Program types only with direct read access go here! */ 3076 case BPF_PROG_TYPE_LWT_IN: 3077 case BPF_PROG_TYPE_LWT_OUT: 3078 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 3079 case BPF_PROG_TYPE_SK_REUSEPORT: 3080 case BPF_PROG_TYPE_FLOW_DISSECTOR: 3081 case BPF_PROG_TYPE_CGROUP_SKB: 3082 if (t == BPF_WRITE) 3083 return false; 3084 fallthrough; 3085 3086 /* Program types with direct read + write access go here! */ 3087 case BPF_PROG_TYPE_SCHED_CLS: 3088 case BPF_PROG_TYPE_SCHED_ACT: 3089 case BPF_PROG_TYPE_XDP: 3090 case BPF_PROG_TYPE_LWT_XMIT: 3091 case BPF_PROG_TYPE_SK_SKB: 3092 case BPF_PROG_TYPE_SK_MSG: 3093 if (meta) 3094 return meta->pkt_access; 3095 3096 env->seen_direct_write = true; 3097 return true; 3098 3099 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 3100 if (t == BPF_WRITE) 3101 env->seen_direct_write = true; 3102 3103 return true; 3104 3105 default: 3106 return false; 3107 } 3108 } 3109 3110 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 3111 int size, bool zero_size_allowed) 3112 { 3113 struct bpf_reg_state *regs = cur_regs(env); 3114 struct bpf_reg_state *reg = ®s[regno]; 3115 int err; 3116 3117 /* We may have added a variable offset to the packet pointer; but any 3118 * reg->range we have comes after that. We are only checking the fixed 3119 * offset. 3120 */ 3121 3122 /* We don't allow negative numbers, because we aren't tracking enough 3123 * detail to prove they're safe. 3124 */ 3125 if (reg->smin_value < 0) { 3126 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3127 regno); 3128 return -EACCES; 3129 } 3130 3131 err = reg->range < 0 ? -EINVAL : 3132 __check_mem_access(env, regno, off, size, reg->range, 3133 zero_size_allowed); 3134 if (err) { 3135 verbose(env, "R%d offset is outside of the packet\n", regno); 3136 return err; 3137 } 3138 3139 /* __check_mem_access has made sure "off + size - 1" is within u16. 3140 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 3141 * otherwise find_good_pkt_pointers would have refused to set range info 3142 * that __check_mem_access would have rejected this pkt access. 3143 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 3144 */ 3145 env->prog->aux->max_pkt_offset = 3146 max_t(u32, env->prog->aux->max_pkt_offset, 3147 off + reg->umax_value + size - 1); 3148 3149 return err; 3150 } 3151 3152 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 3153 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 3154 enum bpf_access_type t, enum bpf_reg_type *reg_type, 3155 struct btf **btf, u32 *btf_id) 3156 { 3157 struct bpf_insn_access_aux info = { 3158 .reg_type = *reg_type, 3159 .log = &env->log, 3160 }; 3161 3162 if (env->ops->is_valid_access && 3163 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 3164 /* A non zero info.ctx_field_size indicates that this field is a 3165 * candidate for later verifier transformation to load the whole 3166 * field and then apply a mask when accessed with a narrower 3167 * access than actual ctx access size. A zero info.ctx_field_size 3168 * will only allow for whole field access and rejects any other 3169 * type of narrower access. 3170 */ 3171 *reg_type = info.reg_type; 3172 3173 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) { 3174 *btf = info.btf; 3175 *btf_id = info.btf_id; 3176 } else { 3177 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 3178 } 3179 /* remember the offset of last byte accessed in ctx */ 3180 if (env->prog->aux->max_ctx_offset < off + size) 3181 env->prog->aux->max_ctx_offset = off + size; 3182 return 0; 3183 } 3184 3185 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 3186 return -EACCES; 3187 } 3188 3189 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 3190 int size) 3191 { 3192 if (size < 0 || off < 0 || 3193 (u64)off + size > sizeof(struct bpf_flow_keys)) { 3194 verbose(env, "invalid access to flow keys off=%d size=%d\n", 3195 off, size); 3196 return -EACCES; 3197 } 3198 return 0; 3199 } 3200 3201 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 3202 u32 regno, int off, int size, 3203 enum bpf_access_type t) 3204 { 3205 struct bpf_reg_state *regs = cur_regs(env); 3206 struct bpf_reg_state *reg = ®s[regno]; 3207 struct bpf_insn_access_aux info = {}; 3208 bool valid; 3209 3210 if (reg->smin_value < 0) { 3211 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3212 regno); 3213 return -EACCES; 3214 } 3215 3216 switch (reg->type) { 3217 case PTR_TO_SOCK_COMMON: 3218 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 3219 break; 3220 case PTR_TO_SOCKET: 3221 valid = bpf_sock_is_valid_access(off, size, t, &info); 3222 break; 3223 case PTR_TO_TCP_SOCK: 3224 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 3225 break; 3226 case PTR_TO_XDP_SOCK: 3227 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 3228 break; 3229 default: 3230 valid = false; 3231 } 3232 3233 3234 if (valid) { 3235 env->insn_aux_data[insn_idx].ctx_field_size = 3236 info.ctx_field_size; 3237 return 0; 3238 } 3239 3240 verbose(env, "R%d invalid %s access off=%d size=%d\n", 3241 regno, reg_type_str[reg->type], off, size); 3242 3243 return -EACCES; 3244 } 3245 3246 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 3247 { 3248 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 3249 } 3250 3251 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 3252 { 3253 const struct bpf_reg_state *reg = reg_state(env, regno); 3254 3255 return reg->type == PTR_TO_CTX; 3256 } 3257 3258 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 3259 { 3260 const struct bpf_reg_state *reg = reg_state(env, regno); 3261 3262 return type_is_sk_pointer(reg->type); 3263 } 3264 3265 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 3266 { 3267 const struct bpf_reg_state *reg = reg_state(env, regno); 3268 3269 return type_is_pkt_pointer(reg->type); 3270 } 3271 3272 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 3273 { 3274 const struct bpf_reg_state *reg = reg_state(env, regno); 3275 3276 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 3277 return reg->type == PTR_TO_FLOW_KEYS; 3278 } 3279 3280 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 3281 const struct bpf_reg_state *reg, 3282 int off, int size, bool strict) 3283 { 3284 struct tnum reg_off; 3285 int ip_align; 3286 3287 /* Byte size accesses are always allowed. */ 3288 if (!strict || size == 1) 3289 return 0; 3290 3291 /* For platforms that do not have a Kconfig enabling 3292 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 3293 * NET_IP_ALIGN is universally set to '2'. And on platforms 3294 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 3295 * to this code only in strict mode where we want to emulate 3296 * the NET_IP_ALIGN==2 checking. Therefore use an 3297 * unconditional IP align value of '2'. 3298 */ 3299 ip_align = 2; 3300 3301 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 3302 if (!tnum_is_aligned(reg_off, size)) { 3303 char tn_buf[48]; 3304 3305 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3306 verbose(env, 3307 "misaligned packet access off %d+%s+%d+%d size %d\n", 3308 ip_align, tn_buf, reg->off, off, size); 3309 return -EACCES; 3310 } 3311 3312 return 0; 3313 } 3314 3315 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 3316 const struct bpf_reg_state *reg, 3317 const char *pointer_desc, 3318 int off, int size, bool strict) 3319 { 3320 struct tnum reg_off; 3321 3322 /* Byte size accesses are always allowed. */ 3323 if (!strict || size == 1) 3324 return 0; 3325 3326 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 3327 if (!tnum_is_aligned(reg_off, size)) { 3328 char tn_buf[48]; 3329 3330 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3331 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 3332 pointer_desc, tn_buf, reg->off, off, size); 3333 return -EACCES; 3334 } 3335 3336 return 0; 3337 } 3338 3339 static int check_ptr_alignment(struct bpf_verifier_env *env, 3340 const struct bpf_reg_state *reg, int off, 3341 int size, bool strict_alignment_once) 3342 { 3343 bool strict = env->strict_alignment || strict_alignment_once; 3344 const char *pointer_desc = ""; 3345 3346 switch (reg->type) { 3347 case PTR_TO_PACKET: 3348 case PTR_TO_PACKET_META: 3349 /* Special case, because of NET_IP_ALIGN. Given metadata sits 3350 * right in front, treat it the very same way. 3351 */ 3352 return check_pkt_ptr_alignment(env, reg, off, size, strict); 3353 case PTR_TO_FLOW_KEYS: 3354 pointer_desc = "flow keys "; 3355 break; 3356 case PTR_TO_MAP_KEY: 3357 pointer_desc = "key "; 3358 break; 3359 case PTR_TO_MAP_VALUE: 3360 pointer_desc = "value "; 3361 break; 3362 case PTR_TO_CTX: 3363 pointer_desc = "context "; 3364 break; 3365 case PTR_TO_STACK: 3366 pointer_desc = "stack "; 3367 /* The stack spill tracking logic in check_stack_write_fixed_off() 3368 * and check_stack_read_fixed_off() relies on stack accesses being 3369 * aligned. 3370 */ 3371 strict = true; 3372 break; 3373 case PTR_TO_SOCKET: 3374 pointer_desc = "sock "; 3375 break; 3376 case PTR_TO_SOCK_COMMON: 3377 pointer_desc = "sock_common "; 3378 break; 3379 case PTR_TO_TCP_SOCK: 3380 pointer_desc = "tcp_sock "; 3381 break; 3382 case PTR_TO_XDP_SOCK: 3383 pointer_desc = "xdp_sock "; 3384 break; 3385 default: 3386 break; 3387 } 3388 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 3389 strict); 3390 } 3391 3392 static int update_stack_depth(struct bpf_verifier_env *env, 3393 const struct bpf_func_state *func, 3394 int off) 3395 { 3396 u16 stack = env->subprog_info[func->subprogno].stack_depth; 3397 3398 if (stack >= -off) 3399 return 0; 3400 3401 /* update known max for given subprogram */ 3402 env->subprog_info[func->subprogno].stack_depth = -off; 3403 return 0; 3404 } 3405 3406 /* starting from main bpf function walk all instructions of the function 3407 * and recursively walk all callees that given function can call. 3408 * Ignore jump and exit insns. 3409 * Since recursion is prevented by check_cfg() this algorithm 3410 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 3411 */ 3412 static int check_max_stack_depth(struct bpf_verifier_env *env) 3413 { 3414 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 3415 struct bpf_subprog_info *subprog = env->subprog_info; 3416 struct bpf_insn *insn = env->prog->insnsi; 3417 bool tail_call_reachable = false; 3418 int ret_insn[MAX_CALL_FRAMES]; 3419 int ret_prog[MAX_CALL_FRAMES]; 3420 int j; 3421 3422 process_func: 3423 /* protect against potential stack overflow that might happen when 3424 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 3425 * depth for such case down to 256 so that the worst case scenario 3426 * would result in 8k stack size (32 which is tailcall limit * 256 = 3427 * 8k). 3428 * 3429 * To get the idea what might happen, see an example: 3430 * func1 -> sub rsp, 128 3431 * subfunc1 -> sub rsp, 256 3432 * tailcall1 -> add rsp, 256 3433 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 3434 * subfunc2 -> sub rsp, 64 3435 * subfunc22 -> sub rsp, 128 3436 * tailcall2 -> add rsp, 128 3437 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 3438 * 3439 * tailcall will unwind the current stack frame but it will not get rid 3440 * of caller's stack as shown on the example above. 3441 */ 3442 if (idx && subprog[idx].has_tail_call && depth >= 256) { 3443 verbose(env, 3444 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 3445 depth); 3446 return -EACCES; 3447 } 3448 /* round up to 32-bytes, since this is granularity 3449 * of interpreter stack size 3450 */ 3451 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 3452 if (depth > MAX_BPF_STACK) { 3453 verbose(env, "combined stack size of %d calls is %d. Too large\n", 3454 frame + 1, depth); 3455 return -EACCES; 3456 } 3457 continue_func: 3458 subprog_end = subprog[idx + 1].start; 3459 for (; i < subprog_end; i++) { 3460 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 3461 continue; 3462 /* remember insn and function to return to */ 3463 ret_insn[frame] = i + 1; 3464 ret_prog[frame] = idx; 3465 3466 /* find the callee */ 3467 i = i + insn[i].imm + 1; 3468 idx = find_subprog(env, i); 3469 if (idx < 0) { 3470 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 3471 i); 3472 return -EFAULT; 3473 } 3474 3475 if (subprog[idx].has_tail_call) 3476 tail_call_reachable = true; 3477 3478 frame++; 3479 if (frame >= MAX_CALL_FRAMES) { 3480 verbose(env, "the call stack of %d frames is too deep !\n", 3481 frame); 3482 return -E2BIG; 3483 } 3484 goto process_func; 3485 } 3486 /* if tail call got detected across bpf2bpf calls then mark each of the 3487 * currently present subprog frames as tail call reachable subprogs; 3488 * this info will be utilized by JIT so that we will be preserving the 3489 * tail call counter throughout bpf2bpf calls combined with tailcalls 3490 */ 3491 if (tail_call_reachable) 3492 for (j = 0; j < frame; j++) 3493 subprog[ret_prog[j]].tail_call_reachable = true; 3494 3495 /* end of for() loop means the last insn of the 'subprog' 3496 * was reached. Doesn't matter whether it was JA or EXIT 3497 */ 3498 if (frame == 0) 3499 return 0; 3500 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 3501 frame--; 3502 i = ret_insn[frame]; 3503 idx = ret_prog[frame]; 3504 goto continue_func; 3505 } 3506 3507 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 3508 static int get_callee_stack_depth(struct bpf_verifier_env *env, 3509 const struct bpf_insn *insn, int idx) 3510 { 3511 int start = idx + insn->imm + 1, subprog; 3512 3513 subprog = find_subprog(env, start); 3514 if (subprog < 0) { 3515 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 3516 start); 3517 return -EFAULT; 3518 } 3519 return env->subprog_info[subprog].stack_depth; 3520 } 3521 #endif 3522 3523 int check_ctx_reg(struct bpf_verifier_env *env, 3524 const struct bpf_reg_state *reg, int regno) 3525 { 3526 /* Access to ctx or passing it to a helper is only allowed in 3527 * its original, unmodified form. 3528 */ 3529 3530 if (reg->off) { 3531 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n", 3532 regno, reg->off); 3533 return -EACCES; 3534 } 3535 3536 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3537 char tn_buf[48]; 3538 3539 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3540 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf); 3541 return -EACCES; 3542 } 3543 3544 return 0; 3545 } 3546 3547 static int __check_buffer_access(struct bpf_verifier_env *env, 3548 const char *buf_info, 3549 const struct bpf_reg_state *reg, 3550 int regno, int off, int size) 3551 { 3552 if (off < 0) { 3553 verbose(env, 3554 "R%d invalid %s buffer access: off=%d, size=%d\n", 3555 regno, buf_info, off, size); 3556 return -EACCES; 3557 } 3558 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3559 char tn_buf[48]; 3560 3561 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3562 verbose(env, 3563 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 3564 regno, off, tn_buf); 3565 return -EACCES; 3566 } 3567 3568 return 0; 3569 } 3570 3571 static int check_tp_buffer_access(struct bpf_verifier_env *env, 3572 const struct bpf_reg_state *reg, 3573 int regno, int off, int size) 3574 { 3575 int err; 3576 3577 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 3578 if (err) 3579 return err; 3580 3581 if (off + size > env->prog->aux->max_tp_access) 3582 env->prog->aux->max_tp_access = off + size; 3583 3584 return 0; 3585 } 3586 3587 static int check_buffer_access(struct bpf_verifier_env *env, 3588 const struct bpf_reg_state *reg, 3589 int regno, int off, int size, 3590 bool zero_size_allowed, 3591 const char *buf_info, 3592 u32 *max_access) 3593 { 3594 int err; 3595 3596 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 3597 if (err) 3598 return err; 3599 3600 if (off + size > *max_access) 3601 *max_access = off + size; 3602 3603 return 0; 3604 } 3605 3606 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 3607 static void zext_32_to_64(struct bpf_reg_state *reg) 3608 { 3609 reg->var_off = tnum_subreg(reg->var_off); 3610 __reg_assign_32_into_64(reg); 3611 } 3612 3613 /* truncate register to smaller size (in bytes) 3614 * must be called with size < BPF_REG_SIZE 3615 */ 3616 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 3617 { 3618 u64 mask; 3619 3620 /* clear high bits in bit representation */ 3621 reg->var_off = tnum_cast(reg->var_off, size); 3622 3623 /* fix arithmetic bounds */ 3624 mask = ((u64)1 << (size * 8)) - 1; 3625 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 3626 reg->umin_value &= mask; 3627 reg->umax_value &= mask; 3628 } else { 3629 reg->umin_value = 0; 3630 reg->umax_value = mask; 3631 } 3632 reg->smin_value = reg->umin_value; 3633 reg->smax_value = reg->umax_value; 3634 3635 /* If size is smaller than 32bit register the 32bit register 3636 * values are also truncated so we push 64-bit bounds into 3637 * 32-bit bounds. Above were truncated < 32-bits already. 3638 */ 3639 if (size >= 4) 3640 return; 3641 __reg_combine_64_into_32(reg); 3642 } 3643 3644 static bool bpf_map_is_rdonly(const struct bpf_map *map) 3645 { 3646 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen; 3647 } 3648 3649 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 3650 { 3651 void *ptr; 3652 u64 addr; 3653 int err; 3654 3655 err = map->ops->map_direct_value_addr(map, &addr, off); 3656 if (err) 3657 return err; 3658 ptr = (void *)(long)addr + off; 3659 3660 switch (size) { 3661 case sizeof(u8): 3662 *val = (u64)*(u8 *)ptr; 3663 break; 3664 case sizeof(u16): 3665 *val = (u64)*(u16 *)ptr; 3666 break; 3667 case sizeof(u32): 3668 *val = (u64)*(u32 *)ptr; 3669 break; 3670 case sizeof(u64): 3671 *val = *(u64 *)ptr; 3672 break; 3673 default: 3674 return -EINVAL; 3675 } 3676 return 0; 3677 } 3678 3679 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 3680 struct bpf_reg_state *regs, 3681 int regno, int off, int size, 3682 enum bpf_access_type atype, 3683 int value_regno) 3684 { 3685 struct bpf_reg_state *reg = regs + regno; 3686 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 3687 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 3688 u32 btf_id; 3689 int ret; 3690 3691 if (off < 0) { 3692 verbose(env, 3693 "R%d is ptr_%s invalid negative access: off=%d\n", 3694 regno, tname, off); 3695 return -EACCES; 3696 } 3697 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3698 char tn_buf[48]; 3699 3700 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3701 verbose(env, 3702 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 3703 regno, tname, off, tn_buf); 3704 return -EACCES; 3705 } 3706 3707 if (env->ops->btf_struct_access) { 3708 ret = env->ops->btf_struct_access(&env->log, reg->btf, t, 3709 off, size, atype, &btf_id); 3710 } else { 3711 if (atype != BPF_READ) { 3712 verbose(env, "only read is supported\n"); 3713 return -EACCES; 3714 } 3715 3716 ret = btf_struct_access(&env->log, reg->btf, t, off, size, 3717 atype, &btf_id); 3718 } 3719 3720 if (ret < 0) 3721 return ret; 3722 3723 if (atype == BPF_READ && value_regno >= 0) 3724 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id); 3725 3726 return 0; 3727 } 3728 3729 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 3730 struct bpf_reg_state *regs, 3731 int regno, int off, int size, 3732 enum bpf_access_type atype, 3733 int value_regno) 3734 { 3735 struct bpf_reg_state *reg = regs + regno; 3736 struct bpf_map *map = reg->map_ptr; 3737 const struct btf_type *t; 3738 const char *tname; 3739 u32 btf_id; 3740 int ret; 3741 3742 if (!btf_vmlinux) { 3743 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 3744 return -ENOTSUPP; 3745 } 3746 3747 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 3748 verbose(env, "map_ptr access not supported for map type %d\n", 3749 map->map_type); 3750 return -ENOTSUPP; 3751 } 3752 3753 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 3754 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 3755 3756 if (!env->allow_ptr_to_map_access) { 3757 verbose(env, 3758 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 3759 tname); 3760 return -EPERM; 3761 } 3762 3763 if (off < 0) { 3764 verbose(env, "R%d is %s invalid negative access: off=%d\n", 3765 regno, tname, off); 3766 return -EACCES; 3767 } 3768 3769 if (atype != BPF_READ) { 3770 verbose(env, "only read from %s is supported\n", tname); 3771 return -EACCES; 3772 } 3773 3774 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id); 3775 if (ret < 0) 3776 return ret; 3777 3778 if (value_regno >= 0) 3779 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id); 3780 3781 return 0; 3782 } 3783 3784 /* Check that the stack access at the given offset is within bounds. The 3785 * maximum valid offset is -1. 3786 * 3787 * The minimum valid offset is -MAX_BPF_STACK for writes, and 3788 * -state->allocated_stack for reads. 3789 */ 3790 static int check_stack_slot_within_bounds(int off, 3791 struct bpf_func_state *state, 3792 enum bpf_access_type t) 3793 { 3794 int min_valid_off; 3795 3796 if (t == BPF_WRITE) 3797 min_valid_off = -MAX_BPF_STACK; 3798 else 3799 min_valid_off = -state->allocated_stack; 3800 3801 if (off < min_valid_off || off > -1) 3802 return -EACCES; 3803 return 0; 3804 } 3805 3806 /* Check that the stack access at 'regno + off' falls within the maximum stack 3807 * bounds. 3808 * 3809 * 'off' includes `regno->offset`, but not its dynamic part (if any). 3810 */ 3811 static int check_stack_access_within_bounds( 3812 struct bpf_verifier_env *env, 3813 int regno, int off, int access_size, 3814 enum stack_access_src src, enum bpf_access_type type) 3815 { 3816 struct bpf_reg_state *regs = cur_regs(env); 3817 struct bpf_reg_state *reg = regs + regno; 3818 struct bpf_func_state *state = func(env, reg); 3819 int min_off, max_off; 3820 int err; 3821 char *err_extra; 3822 3823 if (src == ACCESS_HELPER) 3824 /* We don't know if helpers are reading or writing (or both). */ 3825 err_extra = " indirect access to"; 3826 else if (type == BPF_READ) 3827 err_extra = " read from"; 3828 else 3829 err_extra = " write to"; 3830 3831 if (tnum_is_const(reg->var_off)) { 3832 min_off = reg->var_off.value + off; 3833 if (access_size > 0) 3834 max_off = min_off + access_size - 1; 3835 else 3836 max_off = min_off; 3837 } else { 3838 if (reg->smax_value >= BPF_MAX_VAR_OFF || 3839 reg->smin_value <= -BPF_MAX_VAR_OFF) { 3840 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 3841 err_extra, regno); 3842 return -EACCES; 3843 } 3844 min_off = reg->smin_value + off; 3845 if (access_size > 0) 3846 max_off = reg->smax_value + off + access_size - 1; 3847 else 3848 max_off = min_off; 3849 } 3850 3851 err = check_stack_slot_within_bounds(min_off, state, type); 3852 if (!err) 3853 err = check_stack_slot_within_bounds(max_off, state, type); 3854 3855 if (err) { 3856 if (tnum_is_const(reg->var_off)) { 3857 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 3858 err_extra, regno, off, access_size); 3859 } else { 3860 char tn_buf[48]; 3861 3862 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3863 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 3864 err_extra, regno, tn_buf, access_size); 3865 } 3866 } 3867 return err; 3868 } 3869 3870 /* check whether memory at (regno + off) is accessible for t = (read | write) 3871 * if t==write, value_regno is a register which value is stored into memory 3872 * if t==read, value_regno is a register which will receive the value from memory 3873 * if t==write && value_regno==-1, some unknown value is stored into memory 3874 * if t==read && value_regno==-1, don't care what we read from memory 3875 */ 3876 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 3877 int off, int bpf_size, enum bpf_access_type t, 3878 int value_regno, bool strict_alignment_once) 3879 { 3880 struct bpf_reg_state *regs = cur_regs(env); 3881 struct bpf_reg_state *reg = regs + regno; 3882 struct bpf_func_state *state; 3883 int size, err = 0; 3884 3885 size = bpf_size_to_bytes(bpf_size); 3886 if (size < 0) 3887 return size; 3888 3889 /* alignment checks will add in reg->off themselves */ 3890 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 3891 if (err) 3892 return err; 3893 3894 /* for access checks, reg->off is just part of off */ 3895 off += reg->off; 3896 3897 if (reg->type == PTR_TO_MAP_KEY) { 3898 if (t == BPF_WRITE) { 3899 verbose(env, "write to change key R%d not allowed\n", regno); 3900 return -EACCES; 3901 } 3902 3903 err = check_mem_region_access(env, regno, off, size, 3904 reg->map_ptr->key_size, false); 3905 if (err) 3906 return err; 3907 if (value_regno >= 0) 3908 mark_reg_unknown(env, regs, value_regno); 3909 } else if (reg->type == PTR_TO_MAP_VALUE) { 3910 if (t == BPF_WRITE && value_regno >= 0 && 3911 is_pointer_value(env, value_regno)) { 3912 verbose(env, "R%d leaks addr into map\n", value_regno); 3913 return -EACCES; 3914 } 3915 err = check_map_access_type(env, regno, off, size, t); 3916 if (err) 3917 return err; 3918 err = check_map_access(env, regno, off, size, false); 3919 if (!err && t == BPF_READ && value_regno >= 0) { 3920 struct bpf_map *map = reg->map_ptr; 3921 3922 /* if map is read-only, track its contents as scalars */ 3923 if (tnum_is_const(reg->var_off) && 3924 bpf_map_is_rdonly(map) && 3925 map->ops->map_direct_value_addr) { 3926 int map_off = off + reg->var_off.value; 3927 u64 val = 0; 3928 3929 err = bpf_map_direct_read(map, map_off, size, 3930 &val); 3931 if (err) 3932 return err; 3933 3934 regs[value_regno].type = SCALAR_VALUE; 3935 __mark_reg_known(®s[value_regno], val); 3936 } else { 3937 mark_reg_unknown(env, regs, value_regno); 3938 } 3939 } 3940 } else if (reg->type == PTR_TO_MEM) { 3941 if (t == BPF_WRITE && value_regno >= 0 && 3942 is_pointer_value(env, value_regno)) { 3943 verbose(env, "R%d leaks addr into mem\n", value_regno); 3944 return -EACCES; 3945 } 3946 err = check_mem_region_access(env, regno, off, size, 3947 reg->mem_size, false); 3948 if (!err && t == BPF_READ && value_regno >= 0) 3949 mark_reg_unknown(env, regs, value_regno); 3950 } else if (reg->type == PTR_TO_CTX) { 3951 enum bpf_reg_type reg_type = SCALAR_VALUE; 3952 struct btf *btf = NULL; 3953 u32 btf_id = 0; 3954 3955 if (t == BPF_WRITE && value_regno >= 0 && 3956 is_pointer_value(env, value_regno)) { 3957 verbose(env, "R%d leaks addr into ctx\n", value_regno); 3958 return -EACCES; 3959 } 3960 3961 err = check_ctx_reg(env, reg, regno); 3962 if (err < 0) 3963 return err; 3964 3965 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, &btf_id); 3966 if (err) 3967 verbose_linfo(env, insn_idx, "; "); 3968 if (!err && t == BPF_READ && value_regno >= 0) { 3969 /* ctx access returns either a scalar, or a 3970 * PTR_TO_PACKET[_META,_END]. In the latter 3971 * case, we know the offset is zero. 3972 */ 3973 if (reg_type == SCALAR_VALUE) { 3974 mark_reg_unknown(env, regs, value_regno); 3975 } else { 3976 mark_reg_known_zero(env, regs, 3977 value_regno); 3978 if (reg_type_may_be_null(reg_type)) 3979 regs[value_regno].id = ++env->id_gen; 3980 /* A load of ctx field could have different 3981 * actual load size with the one encoded in the 3982 * insn. When the dst is PTR, it is for sure not 3983 * a sub-register. 3984 */ 3985 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 3986 if (reg_type == PTR_TO_BTF_ID || 3987 reg_type == PTR_TO_BTF_ID_OR_NULL) { 3988 regs[value_regno].btf = btf; 3989 regs[value_regno].btf_id = btf_id; 3990 } 3991 } 3992 regs[value_regno].type = reg_type; 3993 } 3994 3995 } else if (reg->type == PTR_TO_STACK) { 3996 /* Basic bounds checks. */ 3997 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 3998 if (err) 3999 return err; 4000 4001 state = func(env, reg); 4002 err = update_stack_depth(env, state, off); 4003 if (err) 4004 return err; 4005 4006 if (t == BPF_READ) 4007 err = check_stack_read(env, regno, off, size, 4008 value_regno); 4009 else 4010 err = check_stack_write(env, regno, off, size, 4011 value_regno, insn_idx); 4012 } else if (reg_is_pkt_pointer(reg)) { 4013 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 4014 verbose(env, "cannot write into packet\n"); 4015 return -EACCES; 4016 } 4017 if (t == BPF_WRITE && value_regno >= 0 && 4018 is_pointer_value(env, value_regno)) { 4019 verbose(env, "R%d leaks addr into packet\n", 4020 value_regno); 4021 return -EACCES; 4022 } 4023 err = check_packet_access(env, regno, off, size, false); 4024 if (!err && t == BPF_READ && value_regno >= 0) 4025 mark_reg_unknown(env, regs, value_regno); 4026 } else if (reg->type == PTR_TO_FLOW_KEYS) { 4027 if (t == BPF_WRITE && value_regno >= 0 && 4028 is_pointer_value(env, value_regno)) { 4029 verbose(env, "R%d leaks addr into flow keys\n", 4030 value_regno); 4031 return -EACCES; 4032 } 4033 4034 err = check_flow_keys_access(env, off, size); 4035 if (!err && t == BPF_READ && value_regno >= 0) 4036 mark_reg_unknown(env, regs, value_regno); 4037 } else if (type_is_sk_pointer(reg->type)) { 4038 if (t == BPF_WRITE) { 4039 verbose(env, "R%d cannot write into %s\n", 4040 regno, reg_type_str[reg->type]); 4041 return -EACCES; 4042 } 4043 err = check_sock_access(env, insn_idx, regno, off, size, t); 4044 if (!err && value_regno >= 0) 4045 mark_reg_unknown(env, regs, value_regno); 4046 } else if (reg->type == PTR_TO_TP_BUFFER) { 4047 err = check_tp_buffer_access(env, reg, regno, off, size); 4048 if (!err && t == BPF_READ && value_regno >= 0) 4049 mark_reg_unknown(env, regs, value_regno); 4050 } else if (reg->type == PTR_TO_BTF_ID) { 4051 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 4052 value_regno); 4053 } else if (reg->type == CONST_PTR_TO_MAP) { 4054 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 4055 value_regno); 4056 } else if (reg->type == PTR_TO_RDONLY_BUF) { 4057 if (t == BPF_WRITE) { 4058 verbose(env, "R%d cannot write into %s\n", 4059 regno, reg_type_str[reg->type]); 4060 return -EACCES; 4061 } 4062 err = check_buffer_access(env, reg, regno, off, size, false, 4063 "rdonly", 4064 &env->prog->aux->max_rdonly_access); 4065 if (!err && value_regno >= 0) 4066 mark_reg_unknown(env, regs, value_regno); 4067 } else if (reg->type == PTR_TO_RDWR_BUF) { 4068 err = check_buffer_access(env, reg, regno, off, size, false, 4069 "rdwr", 4070 &env->prog->aux->max_rdwr_access); 4071 if (!err && t == BPF_READ && value_regno >= 0) 4072 mark_reg_unknown(env, regs, value_regno); 4073 } else { 4074 verbose(env, "R%d invalid mem access '%s'\n", regno, 4075 reg_type_str[reg->type]); 4076 return -EACCES; 4077 } 4078 4079 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 4080 regs[value_regno].type == SCALAR_VALUE) { 4081 /* b/h/w load zero-extends, mark upper bits as known 0 */ 4082 coerce_reg_to_size(®s[value_regno], size); 4083 } 4084 return err; 4085 } 4086 4087 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 4088 { 4089 int load_reg; 4090 int err; 4091 4092 switch (insn->imm) { 4093 case BPF_ADD: 4094 case BPF_ADD | BPF_FETCH: 4095 case BPF_AND: 4096 case BPF_AND | BPF_FETCH: 4097 case BPF_OR: 4098 case BPF_OR | BPF_FETCH: 4099 case BPF_XOR: 4100 case BPF_XOR | BPF_FETCH: 4101 case BPF_XCHG: 4102 case BPF_CMPXCHG: 4103 break; 4104 default: 4105 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 4106 return -EINVAL; 4107 } 4108 4109 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 4110 verbose(env, "invalid atomic operand size\n"); 4111 return -EINVAL; 4112 } 4113 4114 /* check src1 operand */ 4115 err = check_reg_arg(env, insn->src_reg, SRC_OP); 4116 if (err) 4117 return err; 4118 4119 /* check src2 operand */ 4120 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 4121 if (err) 4122 return err; 4123 4124 if (insn->imm == BPF_CMPXCHG) { 4125 /* Check comparison of R0 with memory location */ 4126 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 4127 if (err) 4128 return err; 4129 } 4130 4131 if (is_pointer_value(env, insn->src_reg)) { 4132 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 4133 return -EACCES; 4134 } 4135 4136 if (is_ctx_reg(env, insn->dst_reg) || 4137 is_pkt_reg(env, insn->dst_reg) || 4138 is_flow_key_reg(env, insn->dst_reg) || 4139 is_sk_reg(env, insn->dst_reg)) { 4140 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 4141 insn->dst_reg, 4142 reg_type_str[reg_state(env, insn->dst_reg)->type]); 4143 return -EACCES; 4144 } 4145 4146 if (insn->imm & BPF_FETCH) { 4147 if (insn->imm == BPF_CMPXCHG) 4148 load_reg = BPF_REG_0; 4149 else 4150 load_reg = insn->src_reg; 4151 4152 /* check and record load of old value */ 4153 err = check_reg_arg(env, load_reg, DST_OP); 4154 if (err) 4155 return err; 4156 } else { 4157 /* This instruction accesses a memory location but doesn't 4158 * actually load it into a register. 4159 */ 4160 load_reg = -1; 4161 } 4162 4163 /* check whether we can read the memory */ 4164 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 4165 BPF_SIZE(insn->code), BPF_READ, load_reg, true); 4166 if (err) 4167 return err; 4168 4169 /* check whether we can write into the same memory */ 4170 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 4171 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 4172 if (err) 4173 return err; 4174 4175 return 0; 4176 } 4177 4178 /* When register 'regno' is used to read the stack (either directly or through 4179 * a helper function) make sure that it's within stack boundary and, depending 4180 * on the access type, that all elements of the stack are initialized. 4181 * 4182 * 'off' includes 'regno->off', but not its dynamic part (if any). 4183 * 4184 * All registers that have been spilled on the stack in the slots within the 4185 * read offsets are marked as read. 4186 */ 4187 static int check_stack_range_initialized( 4188 struct bpf_verifier_env *env, int regno, int off, 4189 int access_size, bool zero_size_allowed, 4190 enum stack_access_src type, struct bpf_call_arg_meta *meta) 4191 { 4192 struct bpf_reg_state *reg = reg_state(env, regno); 4193 struct bpf_func_state *state = func(env, reg); 4194 int err, min_off, max_off, i, j, slot, spi; 4195 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 4196 enum bpf_access_type bounds_check_type; 4197 /* Some accesses can write anything into the stack, others are 4198 * read-only. 4199 */ 4200 bool clobber = false; 4201 4202 if (access_size == 0 && !zero_size_allowed) { 4203 verbose(env, "invalid zero-sized read\n"); 4204 return -EACCES; 4205 } 4206 4207 if (type == ACCESS_HELPER) { 4208 /* The bounds checks for writes are more permissive than for 4209 * reads. However, if raw_mode is not set, we'll do extra 4210 * checks below. 4211 */ 4212 bounds_check_type = BPF_WRITE; 4213 clobber = true; 4214 } else { 4215 bounds_check_type = BPF_READ; 4216 } 4217 err = check_stack_access_within_bounds(env, regno, off, access_size, 4218 type, bounds_check_type); 4219 if (err) 4220 return err; 4221 4222 4223 if (tnum_is_const(reg->var_off)) { 4224 min_off = max_off = reg->var_off.value + off; 4225 } else { 4226 /* Variable offset is prohibited for unprivileged mode for 4227 * simplicity since it requires corresponding support in 4228 * Spectre masking for stack ALU. 4229 * See also retrieve_ptr_limit(). 4230 */ 4231 if (!env->bypass_spec_v1) { 4232 char tn_buf[48]; 4233 4234 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4235 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 4236 regno, err_extra, tn_buf); 4237 return -EACCES; 4238 } 4239 /* Only initialized buffer on stack is allowed to be accessed 4240 * with variable offset. With uninitialized buffer it's hard to 4241 * guarantee that whole memory is marked as initialized on 4242 * helper return since specific bounds are unknown what may 4243 * cause uninitialized stack leaking. 4244 */ 4245 if (meta && meta->raw_mode) 4246 meta = NULL; 4247 4248 min_off = reg->smin_value + off; 4249 max_off = reg->smax_value + off; 4250 } 4251 4252 if (meta && meta->raw_mode) { 4253 meta->access_size = access_size; 4254 meta->regno = regno; 4255 return 0; 4256 } 4257 4258 for (i = min_off; i < max_off + access_size; i++) { 4259 u8 *stype; 4260 4261 slot = -i - 1; 4262 spi = slot / BPF_REG_SIZE; 4263 if (state->allocated_stack <= slot) 4264 goto err; 4265 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4266 if (*stype == STACK_MISC) 4267 goto mark; 4268 if (*stype == STACK_ZERO) { 4269 if (clobber) { 4270 /* helper can write anything into the stack */ 4271 *stype = STACK_MISC; 4272 } 4273 goto mark; 4274 } 4275 4276 if (state->stack[spi].slot_type[0] == STACK_SPILL && 4277 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID) 4278 goto mark; 4279 4280 if (state->stack[spi].slot_type[0] == STACK_SPILL && 4281 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 4282 env->allow_ptr_leaks)) { 4283 if (clobber) { 4284 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 4285 for (j = 0; j < BPF_REG_SIZE; j++) 4286 state->stack[spi].slot_type[j] = STACK_MISC; 4287 } 4288 goto mark; 4289 } 4290 4291 err: 4292 if (tnum_is_const(reg->var_off)) { 4293 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 4294 err_extra, regno, min_off, i - min_off, access_size); 4295 } else { 4296 char tn_buf[48]; 4297 4298 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4299 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 4300 err_extra, regno, tn_buf, i - min_off, access_size); 4301 } 4302 return -EACCES; 4303 mark: 4304 /* reading any byte out of 8-byte 'spill_slot' will cause 4305 * the whole slot to be marked as 'read' 4306 */ 4307 mark_reg_read(env, &state->stack[spi].spilled_ptr, 4308 state->stack[spi].spilled_ptr.parent, 4309 REG_LIVE_READ64); 4310 } 4311 return update_stack_depth(env, state, min_off); 4312 } 4313 4314 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 4315 int access_size, bool zero_size_allowed, 4316 struct bpf_call_arg_meta *meta) 4317 { 4318 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4319 4320 switch (reg->type) { 4321 case PTR_TO_PACKET: 4322 case PTR_TO_PACKET_META: 4323 return check_packet_access(env, regno, reg->off, access_size, 4324 zero_size_allowed); 4325 case PTR_TO_MAP_KEY: 4326 return check_mem_region_access(env, regno, reg->off, access_size, 4327 reg->map_ptr->key_size, false); 4328 case PTR_TO_MAP_VALUE: 4329 if (check_map_access_type(env, regno, reg->off, access_size, 4330 meta && meta->raw_mode ? BPF_WRITE : 4331 BPF_READ)) 4332 return -EACCES; 4333 return check_map_access(env, regno, reg->off, access_size, 4334 zero_size_allowed); 4335 case PTR_TO_MEM: 4336 return check_mem_region_access(env, regno, reg->off, 4337 access_size, reg->mem_size, 4338 zero_size_allowed); 4339 case PTR_TO_RDONLY_BUF: 4340 if (meta && meta->raw_mode) 4341 return -EACCES; 4342 return check_buffer_access(env, reg, regno, reg->off, 4343 access_size, zero_size_allowed, 4344 "rdonly", 4345 &env->prog->aux->max_rdonly_access); 4346 case PTR_TO_RDWR_BUF: 4347 return check_buffer_access(env, reg, regno, reg->off, 4348 access_size, zero_size_allowed, 4349 "rdwr", 4350 &env->prog->aux->max_rdwr_access); 4351 case PTR_TO_STACK: 4352 return check_stack_range_initialized( 4353 env, 4354 regno, reg->off, access_size, 4355 zero_size_allowed, ACCESS_HELPER, meta); 4356 default: /* scalar_value or invalid ptr */ 4357 /* Allow zero-byte read from NULL, regardless of pointer type */ 4358 if (zero_size_allowed && access_size == 0 && 4359 register_is_null(reg)) 4360 return 0; 4361 4362 verbose(env, "R%d type=%s expected=%s\n", regno, 4363 reg_type_str[reg->type], 4364 reg_type_str[PTR_TO_STACK]); 4365 return -EACCES; 4366 } 4367 } 4368 4369 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4370 u32 regno, u32 mem_size) 4371 { 4372 if (register_is_null(reg)) 4373 return 0; 4374 4375 if (reg_type_may_be_null(reg->type)) { 4376 /* Assuming that the register contains a value check if the memory 4377 * access is safe. Temporarily save and restore the register's state as 4378 * the conversion shouldn't be visible to a caller. 4379 */ 4380 const struct bpf_reg_state saved_reg = *reg; 4381 int rv; 4382 4383 mark_ptr_not_null_reg(reg); 4384 rv = check_helper_mem_access(env, regno, mem_size, true, NULL); 4385 *reg = saved_reg; 4386 return rv; 4387 } 4388 4389 return check_helper_mem_access(env, regno, mem_size, true, NULL); 4390 } 4391 4392 /* Implementation details: 4393 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL 4394 * Two bpf_map_lookups (even with the same key) will have different reg->id. 4395 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after 4396 * value_or_null->value transition, since the verifier only cares about 4397 * the range of access to valid map value pointer and doesn't care about actual 4398 * address of the map element. 4399 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 4400 * reg->id > 0 after value_or_null->value transition. By doing so 4401 * two bpf_map_lookups will be considered two different pointers that 4402 * point to different bpf_spin_locks. 4403 * The verifier allows taking only one bpf_spin_lock at a time to avoid 4404 * dead-locks. 4405 * Since only one bpf_spin_lock is allowed the checks are simpler than 4406 * reg_is_refcounted() logic. The verifier needs to remember only 4407 * one spin_lock instead of array of acquired_refs. 4408 * cur_state->active_spin_lock remembers which map value element got locked 4409 * and clears it after bpf_spin_unlock. 4410 */ 4411 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 4412 bool is_lock) 4413 { 4414 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4415 struct bpf_verifier_state *cur = env->cur_state; 4416 bool is_const = tnum_is_const(reg->var_off); 4417 struct bpf_map *map = reg->map_ptr; 4418 u64 val = reg->var_off.value; 4419 4420 if (!is_const) { 4421 verbose(env, 4422 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 4423 regno); 4424 return -EINVAL; 4425 } 4426 if (!map->btf) { 4427 verbose(env, 4428 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 4429 map->name); 4430 return -EINVAL; 4431 } 4432 if (!map_value_has_spin_lock(map)) { 4433 if (map->spin_lock_off == -E2BIG) 4434 verbose(env, 4435 "map '%s' has more than one 'struct bpf_spin_lock'\n", 4436 map->name); 4437 else if (map->spin_lock_off == -ENOENT) 4438 verbose(env, 4439 "map '%s' doesn't have 'struct bpf_spin_lock'\n", 4440 map->name); 4441 else 4442 verbose(env, 4443 "map '%s' is not a struct type or bpf_spin_lock is mangled\n", 4444 map->name); 4445 return -EINVAL; 4446 } 4447 if (map->spin_lock_off != val + reg->off) { 4448 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n", 4449 val + reg->off); 4450 return -EINVAL; 4451 } 4452 if (is_lock) { 4453 if (cur->active_spin_lock) { 4454 verbose(env, 4455 "Locking two bpf_spin_locks are not allowed\n"); 4456 return -EINVAL; 4457 } 4458 cur->active_spin_lock = reg->id; 4459 } else { 4460 if (!cur->active_spin_lock) { 4461 verbose(env, "bpf_spin_unlock without taking a lock\n"); 4462 return -EINVAL; 4463 } 4464 if (cur->active_spin_lock != reg->id) { 4465 verbose(env, "bpf_spin_unlock of different lock\n"); 4466 return -EINVAL; 4467 } 4468 cur->active_spin_lock = 0; 4469 } 4470 return 0; 4471 } 4472 4473 static bool arg_type_is_mem_ptr(enum bpf_arg_type type) 4474 { 4475 return type == ARG_PTR_TO_MEM || 4476 type == ARG_PTR_TO_MEM_OR_NULL || 4477 type == ARG_PTR_TO_UNINIT_MEM; 4478 } 4479 4480 static bool arg_type_is_mem_size(enum bpf_arg_type type) 4481 { 4482 return type == ARG_CONST_SIZE || 4483 type == ARG_CONST_SIZE_OR_ZERO; 4484 } 4485 4486 static bool arg_type_is_alloc_size(enum bpf_arg_type type) 4487 { 4488 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO; 4489 } 4490 4491 static bool arg_type_is_int_ptr(enum bpf_arg_type type) 4492 { 4493 return type == ARG_PTR_TO_INT || 4494 type == ARG_PTR_TO_LONG; 4495 } 4496 4497 static int int_ptr_type_to_size(enum bpf_arg_type type) 4498 { 4499 if (type == ARG_PTR_TO_INT) 4500 return sizeof(u32); 4501 else if (type == ARG_PTR_TO_LONG) 4502 return sizeof(u64); 4503 4504 return -EINVAL; 4505 } 4506 4507 static int resolve_map_arg_type(struct bpf_verifier_env *env, 4508 const struct bpf_call_arg_meta *meta, 4509 enum bpf_arg_type *arg_type) 4510 { 4511 if (!meta->map_ptr) { 4512 /* kernel subsystem misconfigured verifier */ 4513 verbose(env, "invalid map_ptr to access map->type\n"); 4514 return -EACCES; 4515 } 4516 4517 switch (meta->map_ptr->map_type) { 4518 case BPF_MAP_TYPE_SOCKMAP: 4519 case BPF_MAP_TYPE_SOCKHASH: 4520 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 4521 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 4522 } else { 4523 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 4524 return -EINVAL; 4525 } 4526 break; 4527 4528 default: 4529 break; 4530 } 4531 return 0; 4532 } 4533 4534 struct bpf_reg_types { 4535 const enum bpf_reg_type types[10]; 4536 u32 *btf_id; 4537 }; 4538 4539 static const struct bpf_reg_types map_key_value_types = { 4540 .types = { 4541 PTR_TO_STACK, 4542 PTR_TO_PACKET, 4543 PTR_TO_PACKET_META, 4544 PTR_TO_MAP_KEY, 4545 PTR_TO_MAP_VALUE, 4546 }, 4547 }; 4548 4549 static const struct bpf_reg_types sock_types = { 4550 .types = { 4551 PTR_TO_SOCK_COMMON, 4552 PTR_TO_SOCKET, 4553 PTR_TO_TCP_SOCK, 4554 PTR_TO_XDP_SOCK, 4555 }, 4556 }; 4557 4558 #ifdef CONFIG_NET 4559 static const struct bpf_reg_types btf_id_sock_common_types = { 4560 .types = { 4561 PTR_TO_SOCK_COMMON, 4562 PTR_TO_SOCKET, 4563 PTR_TO_TCP_SOCK, 4564 PTR_TO_XDP_SOCK, 4565 PTR_TO_BTF_ID, 4566 }, 4567 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 4568 }; 4569 #endif 4570 4571 static const struct bpf_reg_types mem_types = { 4572 .types = { 4573 PTR_TO_STACK, 4574 PTR_TO_PACKET, 4575 PTR_TO_PACKET_META, 4576 PTR_TO_MAP_KEY, 4577 PTR_TO_MAP_VALUE, 4578 PTR_TO_MEM, 4579 PTR_TO_RDONLY_BUF, 4580 PTR_TO_RDWR_BUF, 4581 }, 4582 }; 4583 4584 static const struct bpf_reg_types int_ptr_types = { 4585 .types = { 4586 PTR_TO_STACK, 4587 PTR_TO_PACKET, 4588 PTR_TO_PACKET_META, 4589 PTR_TO_MAP_KEY, 4590 PTR_TO_MAP_VALUE, 4591 }, 4592 }; 4593 4594 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 4595 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 4596 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 4597 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } }; 4598 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 4599 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } }; 4600 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } }; 4601 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } }; 4602 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 4603 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 4604 4605 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 4606 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types, 4607 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types, 4608 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types, 4609 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types, 4610 [ARG_CONST_SIZE] = &scalar_types, 4611 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 4612 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 4613 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 4614 [ARG_PTR_TO_CTX] = &context_types, 4615 [ARG_PTR_TO_CTX_OR_NULL] = &context_types, 4616 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 4617 #ifdef CONFIG_NET 4618 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 4619 #endif 4620 [ARG_PTR_TO_SOCKET] = &fullsock_types, 4621 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types, 4622 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 4623 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 4624 [ARG_PTR_TO_MEM] = &mem_types, 4625 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types, 4626 [ARG_PTR_TO_UNINIT_MEM] = &mem_types, 4627 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types, 4628 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types, 4629 [ARG_PTR_TO_INT] = &int_ptr_types, 4630 [ARG_PTR_TO_LONG] = &int_ptr_types, 4631 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 4632 [ARG_PTR_TO_FUNC] = &func_ptr_types, 4633 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types, 4634 }; 4635 4636 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 4637 enum bpf_arg_type arg_type, 4638 const u32 *arg_btf_id) 4639 { 4640 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4641 enum bpf_reg_type expected, type = reg->type; 4642 const struct bpf_reg_types *compatible; 4643 int i, j; 4644 4645 compatible = compatible_reg_types[arg_type]; 4646 if (!compatible) { 4647 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 4648 return -EFAULT; 4649 } 4650 4651 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 4652 expected = compatible->types[i]; 4653 if (expected == NOT_INIT) 4654 break; 4655 4656 if (type == expected) 4657 goto found; 4658 } 4659 4660 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]); 4661 for (j = 0; j + 1 < i; j++) 4662 verbose(env, "%s, ", reg_type_str[compatible->types[j]]); 4663 verbose(env, "%s\n", reg_type_str[compatible->types[j]]); 4664 return -EACCES; 4665 4666 found: 4667 if (type == PTR_TO_BTF_ID) { 4668 if (!arg_btf_id) { 4669 if (!compatible->btf_id) { 4670 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 4671 return -EFAULT; 4672 } 4673 arg_btf_id = compatible->btf_id; 4674 } 4675 4676 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 4677 btf_vmlinux, *arg_btf_id)) { 4678 verbose(env, "R%d is of type %s but %s is expected\n", 4679 regno, kernel_type_name(reg->btf, reg->btf_id), 4680 kernel_type_name(btf_vmlinux, *arg_btf_id)); 4681 return -EACCES; 4682 } 4683 4684 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4685 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n", 4686 regno); 4687 return -EACCES; 4688 } 4689 } 4690 4691 return 0; 4692 } 4693 4694 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 4695 struct bpf_call_arg_meta *meta, 4696 const struct bpf_func_proto *fn) 4697 { 4698 u32 regno = BPF_REG_1 + arg; 4699 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4700 enum bpf_arg_type arg_type = fn->arg_type[arg]; 4701 enum bpf_reg_type type = reg->type; 4702 int err = 0; 4703 4704 if (arg_type == ARG_DONTCARE) 4705 return 0; 4706 4707 err = check_reg_arg(env, regno, SRC_OP); 4708 if (err) 4709 return err; 4710 4711 if (arg_type == ARG_ANYTHING) { 4712 if (is_pointer_value(env, regno)) { 4713 verbose(env, "R%d leaks addr into helper function\n", 4714 regno); 4715 return -EACCES; 4716 } 4717 return 0; 4718 } 4719 4720 if (type_is_pkt_pointer(type) && 4721 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 4722 verbose(env, "helper access to the packet is not allowed\n"); 4723 return -EACCES; 4724 } 4725 4726 if (arg_type == ARG_PTR_TO_MAP_VALUE || 4727 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE || 4728 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) { 4729 err = resolve_map_arg_type(env, meta, &arg_type); 4730 if (err) 4731 return err; 4732 } 4733 4734 if (register_is_null(reg) && arg_type_may_be_null(arg_type)) 4735 /* A NULL register has a SCALAR_VALUE type, so skip 4736 * type checking. 4737 */ 4738 goto skip_type_check; 4739 4740 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]); 4741 if (err) 4742 return err; 4743 4744 if (type == PTR_TO_CTX) { 4745 err = check_ctx_reg(env, reg, regno); 4746 if (err < 0) 4747 return err; 4748 } 4749 4750 skip_type_check: 4751 if (reg->ref_obj_id) { 4752 if (meta->ref_obj_id) { 4753 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 4754 regno, reg->ref_obj_id, 4755 meta->ref_obj_id); 4756 return -EFAULT; 4757 } 4758 meta->ref_obj_id = reg->ref_obj_id; 4759 } 4760 4761 if (arg_type == ARG_CONST_MAP_PTR) { 4762 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 4763 meta->map_ptr = reg->map_ptr; 4764 } else if (arg_type == ARG_PTR_TO_MAP_KEY) { 4765 /* bpf_map_xxx(..., map_ptr, ..., key) call: 4766 * check that [key, key + map->key_size) are within 4767 * stack limits and initialized 4768 */ 4769 if (!meta->map_ptr) { 4770 /* in function declaration map_ptr must come before 4771 * map_key, so that it's verified and known before 4772 * we have to check map_key here. Otherwise it means 4773 * that kernel subsystem misconfigured verifier 4774 */ 4775 verbose(env, "invalid map_ptr to access map->key\n"); 4776 return -EACCES; 4777 } 4778 err = check_helper_mem_access(env, regno, 4779 meta->map_ptr->key_size, false, 4780 NULL); 4781 } else if (arg_type == ARG_PTR_TO_MAP_VALUE || 4782 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL && 4783 !register_is_null(reg)) || 4784 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) { 4785 /* bpf_map_xxx(..., map_ptr, ..., value) call: 4786 * check [value, value + map->value_size) validity 4787 */ 4788 if (!meta->map_ptr) { 4789 /* kernel subsystem misconfigured verifier */ 4790 verbose(env, "invalid map_ptr to access map->value\n"); 4791 return -EACCES; 4792 } 4793 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE); 4794 err = check_helper_mem_access(env, regno, 4795 meta->map_ptr->value_size, false, 4796 meta); 4797 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) { 4798 if (!reg->btf_id) { 4799 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 4800 return -EACCES; 4801 } 4802 meta->ret_btf = reg->btf; 4803 meta->ret_btf_id = reg->btf_id; 4804 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) { 4805 if (meta->func_id == BPF_FUNC_spin_lock) { 4806 if (process_spin_lock(env, regno, true)) 4807 return -EACCES; 4808 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 4809 if (process_spin_lock(env, regno, false)) 4810 return -EACCES; 4811 } else { 4812 verbose(env, "verifier internal error\n"); 4813 return -EFAULT; 4814 } 4815 } else if (arg_type == ARG_PTR_TO_FUNC) { 4816 meta->subprogno = reg->subprogno; 4817 } else if (arg_type_is_mem_ptr(arg_type)) { 4818 /* The access to this pointer is only checked when we hit the 4819 * next is_mem_size argument below. 4820 */ 4821 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM); 4822 } else if (arg_type_is_mem_size(arg_type)) { 4823 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); 4824 4825 /* This is used to refine r0 return value bounds for helpers 4826 * that enforce this value as an upper bound on return values. 4827 * See do_refine_retval_range() for helpers that can refine 4828 * the return value. C type of helper is u32 so we pull register 4829 * bound from umax_value however, if negative verifier errors 4830 * out. Only upper bounds can be learned because retval is an 4831 * int type and negative retvals are allowed. 4832 */ 4833 meta->msize_max_value = reg->umax_value; 4834 4835 /* The register is SCALAR_VALUE; the access check 4836 * happens using its boundaries. 4837 */ 4838 if (!tnum_is_const(reg->var_off)) 4839 /* For unprivileged variable accesses, disable raw 4840 * mode so that the program is required to 4841 * initialize all the memory that the helper could 4842 * just partially fill up. 4843 */ 4844 meta = NULL; 4845 4846 if (reg->smin_value < 0) { 4847 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 4848 regno); 4849 return -EACCES; 4850 } 4851 4852 if (reg->umin_value == 0) { 4853 err = check_helper_mem_access(env, regno - 1, 0, 4854 zero_size_allowed, 4855 meta); 4856 if (err) 4857 return err; 4858 } 4859 4860 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 4861 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 4862 regno); 4863 return -EACCES; 4864 } 4865 err = check_helper_mem_access(env, regno - 1, 4866 reg->umax_value, 4867 zero_size_allowed, meta); 4868 if (!err) 4869 err = mark_chain_precision(env, regno); 4870 } else if (arg_type_is_alloc_size(arg_type)) { 4871 if (!tnum_is_const(reg->var_off)) { 4872 verbose(env, "R%d is not a known constant'\n", 4873 regno); 4874 return -EACCES; 4875 } 4876 meta->mem_size = reg->var_off.value; 4877 } else if (arg_type_is_int_ptr(arg_type)) { 4878 int size = int_ptr_type_to_size(arg_type); 4879 4880 err = check_helper_mem_access(env, regno, size, false, meta); 4881 if (err) 4882 return err; 4883 err = check_ptr_alignment(env, reg, 0, size, true); 4884 } 4885 4886 return err; 4887 } 4888 4889 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 4890 { 4891 enum bpf_attach_type eatype = env->prog->expected_attach_type; 4892 enum bpf_prog_type type = resolve_prog_type(env->prog); 4893 4894 if (func_id != BPF_FUNC_map_update_elem) 4895 return false; 4896 4897 /* It's not possible to get access to a locked struct sock in these 4898 * contexts, so updating is safe. 4899 */ 4900 switch (type) { 4901 case BPF_PROG_TYPE_TRACING: 4902 if (eatype == BPF_TRACE_ITER) 4903 return true; 4904 break; 4905 case BPF_PROG_TYPE_SOCKET_FILTER: 4906 case BPF_PROG_TYPE_SCHED_CLS: 4907 case BPF_PROG_TYPE_SCHED_ACT: 4908 case BPF_PROG_TYPE_XDP: 4909 case BPF_PROG_TYPE_SK_REUSEPORT: 4910 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4911 case BPF_PROG_TYPE_SK_LOOKUP: 4912 return true; 4913 default: 4914 break; 4915 } 4916 4917 verbose(env, "cannot update sockmap in this context\n"); 4918 return false; 4919 } 4920 4921 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 4922 { 4923 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64); 4924 } 4925 4926 static int check_map_func_compatibility(struct bpf_verifier_env *env, 4927 struct bpf_map *map, int func_id) 4928 { 4929 if (!map) 4930 return 0; 4931 4932 /* We need a two way check, first is from map perspective ... */ 4933 switch (map->map_type) { 4934 case BPF_MAP_TYPE_PROG_ARRAY: 4935 if (func_id != BPF_FUNC_tail_call) 4936 goto error; 4937 break; 4938 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 4939 if (func_id != BPF_FUNC_perf_event_read && 4940 func_id != BPF_FUNC_perf_event_output && 4941 func_id != BPF_FUNC_skb_output && 4942 func_id != BPF_FUNC_perf_event_read_value && 4943 func_id != BPF_FUNC_xdp_output) 4944 goto error; 4945 break; 4946 case BPF_MAP_TYPE_RINGBUF: 4947 if (func_id != BPF_FUNC_ringbuf_output && 4948 func_id != BPF_FUNC_ringbuf_reserve && 4949 func_id != BPF_FUNC_ringbuf_submit && 4950 func_id != BPF_FUNC_ringbuf_discard && 4951 func_id != BPF_FUNC_ringbuf_query) 4952 goto error; 4953 break; 4954 case BPF_MAP_TYPE_STACK_TRACE: 4955 if (func_id != BPF_FUNC_get_stackid) 4956 goto error; 4957 break; 4958 case BPF_MAP_TYPE_CGROUP_ARRAY: 4959 if (func_id != BPF_FUNC_skb_under_cgroup && 4960 func_id != BPF_FUNC_current_task_under_cgroup) 4961 goto error; 4962 break; 4963 case BPF_MAP_TYPE_CGROUP_STORAGE: 4964 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 4965 if (func_id != BPF_FUNC_get_local_storage) 4966 goto error; 4967 break; 4968 case BPF_MAP_TYPE_DEVMAP: 4969 case BPF_MAP_TYPE_DEVMAP_HASH: 4970 if (func_id != BPF_FUNC_redirect_map && 4971 func_id != BPF_FUNC_map_lookup_elem) 4972 goto error; 4973 break; 4974 /* Restrict bpf side of cpumap and xskmap, open when use-cases 4975 * appear. 4976 */ 4977 case BPF_MAP_TYPE_CPUMAP: 4978 if (func_id != BPF_FUNC_redirect_map) 4979 goto error; 4980 break; 4981 case BPF_MAP_TYPE_XSKMAP: 4982 if (func_id != BPF_FUNC_redirect_map && 4983 func_id != BPF_FUNC_map_lookup_elem) 4984 goto error; 4985 break; 4986 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 4987 case BPF_MAP_TYPE_HASH_OF_MAPS: 4988 if (func_id != BPF_FUNC_map_lookup_elem) 4989 goto error; 4990 break; 4991 case BPF_MAP_TYPE_SOCKMAP: 4992 if (func_id != BPF_FUNC_sk_redirect_map && 4993 func_id != BPF_FUNC_sock_map_update && 4994 func_id != BPF_FUNC_map_delete_elem && 4995 func_id != BPF_FUNC_msg_redirect_map && 4996 func_id != BPF_FUNC_sk_select_reuseport && 4997 func_id != BPF_FUNC_map_lookup_elem && 4998 !may_update_sockmap(env, func_id)) 4999 goto error; 5000 break; 5001 case BPF_MAP_TYPE_SOCKHASH: 5002 if (func_id != BPF_FUNC_sk_redirect_hash && 5003 func_id != BPF_FUNC_sock_hash_update && 5004 func_id != BPF_FUNC_map_delete_elem && 5005 func_id != BPF_FUNC_msg_redirect_hash && 5006 func_id != BPF_FUNC_sk_select_reuseport && 5007 func_id != BPF_FUNC_map_lookup_elem && 5008 !may_update_sockmap(env, func_id)) 5009 goto error; 5010 break; 5011 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 5012 if (func_id != BPF_FUNC_sk_select_reuseport) 5013 goto error; 5014 break; 5015 case BPF_MAP_TYPE_QUEUE: 5016 case BPF_MAP_TYPE_STACK: 5017 if (func_id != BPF_FUNC_map_peek_elem && 5018 func_id != BPF_FUNC_map_pop_elem && 5019 func_id != BPF_FUNC_map_push_elem) 5020 goto error; 5021 break; 5022 case BPF_MAP_TYPE_SK_STORAGE: 5023 if (func_id != BPF_FUNC_sk_storage_get && 5024 func_id != BPF_FUNC_sk_storage_delete) 5025 goto error; 5026 break; 5027 case BPF_MAP_TYPE_INODE_STORAGE: 5028 if (func_id != BPF_FUNC_inode_storage_get && 5029 func_id != BPF_FUNC_inode_storage_delete) 5030 goto error; 5031 break; 5032 case BPF_MAP_TYPE_TASK_STORAGE: 5033 if (func_id != BPF_FUNC_task_storage_get && 5034 func_id != BPF_FUNC_task_storage_delete) 5035 goto error; 5036 break; 5037 default: 5038 break; 5039 } 5040 5041 /* ... and second from the function itself. */ 5042 switch (func_id) { 5043 case BPF_FUNC_tail_call: 5044 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 5045 goto error; 5046 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 5047 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 5048 return -EINVAL; 5049 } 5050 break; 5051 case BPF_FUNC_perf_event_read: 5052 case BPF_FUNC_perf_event_output: 5053 case BPF_FUNC_perf_event_read_value: 5054 case BPF_FUNC_skb_output: 5055 case BPF_FUNC_xdp_output: 5056 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 5057 goto error; 5058 break; 5059 case BPF_FUNC_get_stackid: 5060 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 5061 goto error; 5062 break; 5063 case BPF_FUNC_current_task_under_cgroup: 5064 case BPF_FUNC_skb_under_cgroup: 5065 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 5066 goto error; 5067 break; 5068 case BPF_FUNC_redirect_map: 5069 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 5070 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 5071 map->map_type != BPF_MAP_TYPE_CPUMAP && 5072 map->map_type != BPF_MAP_TYPE_XSKMAP) 5073 goto error; 5074 break; 5075 case BPF_FUNC_sk_redirect_map: 5076 case BPF_FUNC_msg_redirect_map: 5077 case BPF_FUNC_sock_map_update: 5078 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 5079 goto error; 5080 break; 5081 case BPF_FUNC_sk_redirect_hash: 5082 case BPF_FUNC_msg_redirect_hash: 5083 case BPF_FUNC_sock_hash_update: 5084 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 5085 goto error; 5086 break; 5087 case BPF_FUNC_get_local_storage: 5088 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 5089 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 5090 goto error; 5091 break; 5092 case BPF_FUNC_sk_select_reuseport: 5093 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 5094 map->map_type != BPF_MAP_TYPE_SOCKMAP && 5095 map->map_type != BPF_MAP_TYPE_SOCKHASH) 5096 goto error; 5097 break; 5098 case BPF_FUNC_map_peek_elem: 5099 case BPF_FUNC_map_pop_elem: 5100 case BPF_FUNC_map_push_elem: 5101 if (map->map_type != BPF_MAP_TYPE_QUEUE && 5102 map->map_type != BPF_MAP_TYPE_STACK) 5103 goto error; 5104 break; 5105 case BPF_FUNC_sk_storage_get: 5106 case BPF_FUNC_sk_storage_delete: 5107 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 5108 goto error; 5109 break; 5110 case BPF_FUNC_inode_storage_get: 5111 case BPF_FUNC_inode_storage_delete: 5112 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 5113 goto error; 5114 break; 5115 case BPF_FUNC_task_storage_get: 5116 case BPF_FUNC_task_storage_delete: 5117 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 5118 goto error; 5119 break; 5120 default: 5121 break; 5122 } 5123 5124 return 0; 5125 error: 5126 verbose(env, "cannot pass map_type %d into func %s#%d\n", 5127 map->map_type, func_id_name(func_id), func_id); 5128 return -EINVAL; 5129 } 5130 5131 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 5132 { 5133 int count = 0; 5134 5135 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 5136 count++; 5137 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 5138 count++; 5139 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 5140 count++; 5141 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 5142 count++; 5143 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 5144 count++; 5145 5146 /* We only support one arg being in raw mode at the moment, 5147 * which is sufficient for the helper functions we have 5148 * right now. 5149 */ 5150 return count <= 1; 5151 } 5152 5153 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr, 5154 enum bpf_arg_type arg_next) 5155 { 5156 return (arg_type_is_mem_ptr(arg_curr) && 5157 !arg_type_is_mem_size(arg_next)) || 5158 (!arg_type_is_mem_ptr(arg_curr) && 5159 arg_type_is_mem_size(arg_next)); 5160 } 5161 5162 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 5163 { 5164 /* bpf_xxx(..., buf, len) call will access 'len' 5165 * bytes from memory 'buf'. Both arg types need 5166 * to be paired, so make sure there's no buggy 5167 * helper function specification. 5168 */ 5169 if (arg_type_is_mem_size(fn->arg1_type) || 5170 arg_type_is_mem_ptr(fn->arg5_type) || 5171 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) || 5172 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) || 5173 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) || 5174 check_args_pair_invalid(fn->arg4_type, fn->arg5_type)) 5175 return false; 5176 5177 return true; 5178 } 5179 5180 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id) 5181 { 5182 int count = 0; 5183 5184 if (arg_type_may_be_refcounted(fn->arg1_type)) 5185 count++; 5186 if (arg_type_may_be_refcounted(fn->arg2_type)) 5187 count++; 5188 if (arg_type_may_be_refcounted(fn->arg3_type)) 5189 count++; 5190 if (arg_type_may_be_refcounted(fn->arg4_type)) 5191 count++; 5192 if (arg_type_may_be_refcounted(fn->arg5_type)) 5193 count++; 5194 5195 /* A reference acquiring function cannot acquire 5196 * another refcounted ptr. 5197 */ 5198 if (may_be_acquire_function(func_id) && count) 5199 return false; 5200 5201 /* We only support one arg being unreferenced at the moment, 5202 * which is sufficient for the helper functions we have right now. 5203 */ 5204 return count <= 1; 5205 } 5206 5207 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 5208 { 5209 int i; 5210 5211 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 5212 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i]) 5213 return false; 5214 5215 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i]) 5216 return false; 5217 } 5218 5219 return true; 5220 } 5221 5222 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 5223 { 5224 return check_raw_mode_ok(fn) && 5225 check_arg_pair_ok(fn) && 5226 check_btf_id_ok(fn) && 5227 check_refcount_ok(fn, func_id) ? 0 : -EINVAL; 5228 } 5229 5230 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 5231 * are now invalid, so turn them into unknown SCALAR_VALUE. 5232 */ 5233 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env, 5234 struct bpf_func_state *state) 5235 { 5236 struct bpf_reg_state *regs = state->regs, *reg; 5237 int i; 5238 5239 for (i = 0; i < MAX_BPF_REG; i++) 5240 if (reg_is_pkt_pointer_any(®s[i])) 5241 mark_reg_unknown(env, regs, i); 5242 5243 bpf_for_each_spilled_reg(i, state, reg) { 5244 if (!reg) 5245 continue; 5246 if (reg_is_pkt_pointer_any(reg)) 5247 __mark_reg_unknown(env, reg); 5248 } 5249 } 5250 5251 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 5252 { 5253 struct bpf_verifier_state *vstate = env->cur_state; 5254 int i; 5255 5256 for (i = 0; i <= vstate->curframe; i++) 5257 __clear_all_pkt_pointers(env, vstate->frame[i]); 5258 } 5259 5260 enum { 5261 AT_PKT_END = -1, 5262 BEYOND_PKT_END = -2, 5263 }; 5264 5265 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 5266 { 5267 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5268 struct bpf_reg_state *reg = &state->regs[regn]; 5269 5270 if (reg->type != PTR_TO_PACKET) 5271 /* PTR_TO_PACKET_META is not supported yet */ 5272 return; 5273 5274 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 5275 * How far beyond pkt_end it goes is unknown. 5276 * if (!range_open) it's the case of pkt >= pkt_end 5277 * if (range_open) it's the case of pkt > pkt_end 5278 * hence this pointer is at least 1 byte bigger than pkt_end 5279 */ 5280 if (range_open) 5281 reg->range = BEYOND_PKT_END; 5282 else 5283 reg->range = AT_PKT_END; 5284 } 5285 5286 static void release_reg_references(struct bpf_verifier_env *env, 5287 struct bpf_func_state *state, 5288 int ref_obj_id) 5289 { 5290 struct bpf_reg_state *regs = state->regs, *reg; 5291 int i; 5292 5293 for (i = 0; i < MAX_BPF_REG; i++) 5294 if (regs[i].ref_obj_id == ref_obj_id) 5295 mark_reg_unknown(env, regs, i); 5296 5297 bpf_for_each_spilled_reg(i, state, reg) { 5298 if (!reg) 5299 continue; 5300 if (reg->ref_obj_id == ref_obj_id) 5301 __mark_reg_unknown(env, reg); 5302 } 5303 } 5304 5305 /* The pointer with the specified id has released its reference to kernel 5306 * resources. Identify all copies of the same pointer and clear the reference. 5307 */ 5308 static int release_reference(struct bpf_verifier_env *env, 5309 int ref_obj_id) 5310 { 5311 struct bpf_verifier_state *vstate = env->cur_state; 5312 int err; 5313 int i; 5314 5315 err = release_reference_state(cur_func(env), ref_obj_id); 5316 if (err) 5317 return err; 5318 5319 for (i = 0; i <= vstate->curframe; i++) 5320 release_reg_references(env, vstate->frame[i], ref_obj_id); 5321 5322 return 0; 5323 } 5324 5325 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 5326 struct bpf_reg_state *regs) 5327 { 5328 int i; 5329 5330 /* after the call registers r0 - r5 were scratched */ 5331 for (i = 0; i < CALLER_SAVED_REGS; i++) { 5332 mark_reg_not_init(env, regs, caller_saved[i]); 5333 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 5334 } 5335 } 5336 5337 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 5338 struct bpf_func_state *caller, 5339 struct bpf_func_state *callee, 5340 int insn_idx); 5341 5342 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 5343 int *insn_idx, int subprog, 5344 set_callee_state_fn set_callee_state_cb) 5345 { 5346 struct bpf_verifier_state *state = env->cur_state; 5347 struct bpf_func_info_aux *func_info_aux; 5348 struct bpf_func_state *caller, *callee; 5349 int err; 5350 bool is_global = false; 5351 5352 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 5353 verbose(env, "the call stack of %d frames is too deep\n", 5354 state->curframe + 2); 5355 return -E2BIG; 5356 } 5357 5358 caller = state->frame[state->curframe]; 5359 if (state->frame[state->curframe + 1]) { 5360 verbose(env, "verifier bug. Frame %d already allocated\n", 5361 state->curframe + 1); 5362 return -EFAULT; 5363 } 5364 5365 func_info_aux = env->prog->aux->func_info_aux; 5366 if (func_info_aux) 5367 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 5368 err = btf_check_func_arg_match(env, subprog, caller->regs); 5369 if (err == -EFAULT) 5370 return err; 5371 if (is_global) { 5372 if (err) { 5373 verbose(env, "Caller passes invalid args into func#%d\n", 5374 subprog); 5375 return err; 5376 } else { 5377 if (env->log.level & BPF_LOG_LEVEL) 5378 verbose(env, 5379 "Func#%d is global and valid. Skipping.\n", 5380 subprog); 5381 clear_caller_saved_regs(env, caller->regs); 5382 5383 /* All global functions return a 64-bit SCALAR_VALUE */ 5384 mark_reg_unknown(env, caller->regs, BPF_REG_0); 5385 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 5386 5387 /* continue with next insn after call */ 5388 return 0; 5389 } 5390 } 5391 5392 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 5393 if (!callee) 5394 return -ENOMEM; 5395 state->frame[state->curframe + 1] = callee; 5396 5397 /* callee cannot access r0, r6 - r9 for reading and has to write 5398 * into its own stack before reading from it. 5399 * callee can read/write into caller's stack 5400 */ 5401 init_func_state(env, callee, 5402 /* remember the callsite, it will be used by bpf_exit */ 5403 *insn_idx /* callsite */, 5404 state->curframe + 1 /* frameno within this callchain */, 5405 subprog /* subprog number within this prog */); 5406 5407 /* Transfer references to the callee */ 5408 err = transfer_reference_state(callee, caller); 5409 if (err) 5410 return err; 5411 5412 err = set_callee_state_cb(env, caller, callee, *insn_idx); 5413 if (err) 5414 return err; 5415 5416 clear_caller_saved_regs(env, caller->regs); 5417 5418 /* only increment it after check_reg_arg() finished */ 5419 state->curframe++; 5420 5421 /* and go analyze first insn of the callee */ 5422 *insn_idx = env->subprog_info[subprog].start - 1; 5423 5424 if (env->log.level & BPF_LOG_LEVEL) { 5425 verbose(env, "caller:\n"); 5426 print_verifier_state(env, caller); 5427 verbose(env, "callee:\n"); 5428 print_verifier_state(env, callee); 5429 } 5430 return 0; 5431 } 5432 5433 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 5434 struct bpf_func_state *caller, 5435 struct bpf_func_state *callee) 5436 { 5437 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 5438 * void *callback_ctx, u64 flags); 5439 * callback_fn(struct bpf_map *map, void *key, void *value, 5440 * void *callback_ctx); 5441 */ 5442 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 5443 5444 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 5445 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 5446 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 5447 5448 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 5449 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 5450 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 5451 5452 /* pointer to stack or null */ 5453 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 5454 5455 /* unused */ 5456 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 5457 return 0; 5458 } 5459 5460 static int set_callee_state(struct bpf_verifier_env *env, 5461 struct bpf_func_state *caller, 5462 struct bpf_func_state *callee, int insn_idx) 5463 { 5464 int i; 5465 5466 /* copy r1 - r5 args that callee can access. The copy includes parent 5467 * pointers, which connects us up to the liveness chain 5468 */ 5469 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 5470 callee->regs[i] = caller->regs[i]; 5471 return 0; 5472 } 5473 5474 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 5475 int *insn_idx) 5476 { 5477 int subprog, target_insn; 5478 5479 target_insn = *insn_idx + insn->imm + 1; 5480 subprog = find_subprog(env, target_insn); 5481 if (subprog < 0) { 5482 verbose(env, "verifier bug. No program starts at insn %d\n", 5483 target_insn); 5484 return -EFAULT; 5485 } 5486 5487 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 5488 } 5489 5490 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 5491 struct bpf_func_state *caller, 5492 struct bpf_func_state *callee, 5493 int insn_idx) 5494 { 5495 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 5496 struct bpf_map *map; 5497 int err; 5498 5499 if (bpf_map_ptr_poisoned(insn_aux)) { 5500 verbose(env, "tail_call abusing map_ptr\n"); 5501 return -EINVAL; 5502 } 5503 5504 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 5505 if (!map->ops->map_set_for_each_callback_args || 5506 !map->ops->map_for_each_callback) { 5507 verbose(env, "callback function not allowed for map\n"); 5508 return -ENOTSUPP; 5509 } 5510 5511 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 5512 if (err) 5513 return err; 5514 5515 callee->in_callback_fn = true; 5516 return 0; 5517 } 5518 5519 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 5520 { 5521 struct bpf_verifier_state *state = env->cur_state; 5522 struct bpf_func_state *caller, *callee; 5523 struct bpf_reg_state *r0; 5524 int err; 5525 5526 callee = state->frame[state->curframe]; 5527 r0 = &callee->regs[BPF_REG_0]; 5528 if (r0->type == PTR_TO_STACK) { 5529 /* technically it's ok to return caller's stack pointer 5530 * (or caller's caller's pointer) back to the caller, 5531 * since these pointers are valid. Only current stack 5532 * pointer will be invalid as soon as function exits, 5533 * but let's be conservative 5534 */ 5535 verbose(env, "cannot return stack pointer to the caller\n"); 5536 return -EINVAL; 5537 } 5538 5539 state->curframe--; 5540 caller = state->frame[state->curframe]; 5541 if (callee->in_callback_fn) { 5542 /* enforce R0 return value range [0, 1]. */ 5543 struct tnum range = tnum_range(0, 1); 5544 5545 if (r0->type != SCALAR_VALUE) { 5546 verbose(env, "R0 not a scalar value\n"); 5547 return -EACCES; 5548 } 5549 if (!tnum_in(range, r0->var_off)) { 5550 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 5551 return -EINVAL; 5552 } 5553 } else { 5554 /* return to the caller whatever r0 had in the callee */ 5555 caller->regs[BPF_REG_0] = *r0; 5556 } 5557 5558 /* Transfer references to the caller */ 5559 err = transfer_reference_state(caller, callee); 5560 if (err) 5561 return err; 5562 5563 *insn_idx = callee->callsite + 1; 5564 if (env->log.level & BPF_LOG_LEVEL) { 5565 verbose(env, "returning from callee:\n"); 5566 print_verifier_state(env, callee); 5567 verbose(env, "to caller at %d:\n", *insn_idx); 5568 print_verifier_state(env, caller); 5569 } 5570 /* clear everything in the callee */ 5571 free_func_state(callee); 5572 state->frame[state->curframe + 1] = NULL; 5573 return 0; 5574 } 5575 5576 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 5577 int func_id, 5578 struct bpf_call_arg_meta *meta) 5579 { 5580 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 5581 5582 if (ret_type != RET_INTEGER || 5583 (func_id != BPF_FUNC_get_stack && 5584 func_id != BPF_FUNC_probe_read_str && 5585 func_id != BPF_FUNC_probe_read_kernel_str && 5586 func_id != BPF_FUNC_probe_read_user_str)) 5587 return; 5588 5589 ret_reg->smax_value = meta->msize_max_value; 5590 ret_reg->s32_max_value = meta->msize_max_value; 5591 ret_reg->smin_value = -MAX_ERRNO; 5592 ret_reg->s32_min_value = -MAX_ERRNO; 5593 __reg_deduce_bounds(ret_reg); 5594 __reg_bound_offset(ret_reg); 5595 __update_reg_bounds(ret_reg); 5596 } 5597 5598 static int 5599 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 5600 int func_id, int insn_idx) 5601 { 5602 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 5603 struct bpf_map *map = meta->map_ptr; 5604 5605 if (func_id != BPF_FUNC_tail_call && 5606 func_id != BPF_FUNC_map_lookup_elem && 5607 func_id != BPF_FUNC_map_update_elem && 5608 func_id != BPF_FUNC_map_delete_elem && 5609 func_id != BPF_FUNC_map_push_elem && 5610 func_id != BPF_FUNC_map_pop_elem && 5611 func_id != BPF_FUNC_map_peek_elem && 5612 func_id != BPF_FUNC_for_each_map_elem && 5613 func_id != BPF_FUNC_redirect_map) 5614 return 0; 5615 5616 if (map == NULL) { 5617 verbose(env, "kernel subsystem misconfigured verifier\n"); 5618 return -EINVAL; 5619 } 5620 5621 /* In case of read-only, some additional restrictions 5622 * need to be applied in order to prevent altering the 5623 * state of the map from program side. 5624 */ 5625 if ((map->map_flags & BPF_F_RDONLY_PROG) && 5626 (func_id == BPF_FUNC_map_delete_elem || 5627 func_id == BPF_FUNC_map_update_elem || 5628 func_id == BPF_FUNC_map_push_elem || 5629 func_id == BPF_FUNC_map_pop_elem)) { 5630 verbose(env, "write into map forbidden\n"); 5631 return -EACCES; 5632 } 5633 5634 if (!BPF_MAP_PTR(aux->map_ptr_state)) 5635 bpf_map_ptr_store(aux, meta->map_ptr, 5636 !meta->map_ptr->bypass_spec_v1); 5637 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 5638 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 5639 !meta->map_ptr->bypass_spec_v1); 5640 return 0; 5641 } 5642 5643 static int 5644 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 5645 int func_id, int insn_idx) 5646 { 5647 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 5648 struct bpf_reg_state *regs = cur_regs(env), *reg; 5649 struct bpf_map *map = meta->map_ptr; 5650 struct tnum range; 5651 u64 val; 5652 int err; 5653 5654 if (func_id != BPF_FUNC_tail_call) 5655 return 0; 5656 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 5657 verbose(env, "kernel subsystem misconfigured verifier\n"); 5658 return -EINVAL; 5659 } 5660 5661 range = tnum_range(0, map->max_entries - 1); 5662 reg = ®s[BPF_REG_3]; 5663 5664 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) { 5665 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 5666 return 0; 5667 } 5668 5669 err = mark_chain_precision(env, BPF_REG_3); 5670 if (err) 5671 return err; 5672 5673 val = reg->var_off.value; 5674 if (bpf_map_key_unseen(aux)) 5675 bpf_map_key_store(aux, val); 5676 else if (!bpf_map_key_poisoned(aux) && 5677 bpf_map_key_immediate(aux) != val) 5678 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 5679 return 0; 5680 } 5681 5682 static int check_reference_leak(struct bpf_verifier_env *env) 5683 { 5684 struct bpf_func_state *state = cur_func(env); 5685 int i; 5686 5687 for (i = 0; i < state->acquired_refs; i++) { 5688 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 5689 state->refs[i].id, state->refs[i].insn_idx); 5690 } 5691 return state->acquired_refs ? -EINVAL : 0; 5692 } 5693 5694 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 5695 int *insn_idx_p) 5696 { 5697 const struct bpf_func_proto *fn = NULL; 5698 struct bpf_reg_state *regs; 5699 struct bpf_call_arg_meta meta; 5700 int insn_idx = *insn_idx_p; 5701 bool changes_data; 5702 int i, err, func_id; 5703 5704 /* find function prototype */ 5705 func_id = insn->imm; 5706 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 5707 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 5708 func_id); 5709 return -EINVAL; 5710 } 5711 5712 if (env->ops->get_func_proto) 5713 fn = env->ops->get_func_proto(func_id, env->prog); 5714 if (!fn) { 5715 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 5716 func_id); 5717 return -EINVAL; 5718 } 5719 5720 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 5721 if (!env->prog->gpl_compatible && fn->gpl_only) { 5722 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 5723 return -EINVAL; 5724 } 5725 5726 if (fn->allowed && !fn->allowed(env->prog)) { 5727 verbose(env, "helper call is not allowed in probe\n"); 5728 return -EINVAL; 5729 } 5730 5731 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 5732 changes_data = bpf_helper_changes_pkt_data(fn->func); 5733 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 5734 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 5735 func_id_name(func_id), func_id); 5736 return -EINVAL; 5737 } 5738 5739 memset(&meta, 0, sizeof(meta)); 5740 meta.pkt_access = fn->pkt_access; 5741 5742 err = check_func_proto(fn, func_id); 5743 if (err) { 5744 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 5745 func_id_name(func_id), func_id); 5746 return err; 5747 } 5748 5749 meta.func_id = func_id; 5750 /* check args */ 5751 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 5752 err = check_func_arg(env, i, &meta, fn); 5753 if (err) 5754 return err; 5755 } 5756 5757 err = record_func_map(env, &meta, func_id, insn_idx); 5758 if (err) 5759 return err; 5760 5761 err = record_func_key(env, &meta, func_id, insn_idx); 5762 if (err) 5763 return err; 5764 5765 /* Mark slots with STACK_MISC in case of raw mode, stack offset 5766 * is inferred from register state. 5767 */ 5768 for (i = 0; i < meta.access_size; i++) { 5769 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 5770 BPF_WRITE, -1, false); 5771 if (err) 5772 return err; 5773 } 5774 5775 if (func_id == BPF_FUNC_tail_call) { 5776 err = check_reference_leak(env); 5777 if (err) { 5778 verbose(env, "tail_call would lead to reference leak\n"); 5779 return err; 5780 } 5781 } else if (is_release_function(func_id)) { 5782 err = release_reference(env, meta.ref_obj_id); 5783 if (err) { 5784 verbose(env, "func %s#%d reference has not been acquired before\n", 5785 func_id_name(func_id), func_id); 5786 return err; 5787 } 5788 } 5789 5790 regs = cur_regs(env); 5791 5792 /* check that flags argument in get_local_storage(map, flags) is 0, 5793 * this is required because get_local_storage() can't return an error. 5794 */ 5795 if (func_id == BPF_FUNC_get_local_storage && 5796 !register_is_null(®s[BPF_REG_2])) { 5797 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 5798 return -EINVAL; 5799 } 5800 5801 if (func_id == BPF_FUNC_for_each_map_elem) { 5802 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 5803 set_map_elem_callback_state); 5804 if (err < 0) 5805 return -EINVAL; 5806 } 5807 5808 /* reset caller saved regs */ 5809 for (i = 0; i < CALLER_SAVED_REGS; i++) { 5810 mark_reg_not_init(env, regs, caller_saved[i]); 5811 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 5812 } 5813 5814 /* helper call returns 64-bit value. */ 5815 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 5816 5817 /* update return register (already marked as written above) */ 5818 if (fn->ret_type == RET_INTEGER) { 5819 /* sets type to SCALAR_VALUE */ 5820 mark_reg_unknown(env, regs, BPF_REG_0); 5821 } else if (fn->ret_type == RET_VOID) { 5822 regs[BPF_REG_0].type = NOT_INIT; 5823 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL || 5824 fn->ret_type == RET_PTR_TO_MAP_VALUE) { 5825 /* There is no offset yet applied, variable or fixed */ 5826 mark_reg_known_zero(env, regs, BPF_REG_0); 5827 /* remember map_ptr, so that check_map_access() 5828 * can check 'value_size' boundary of memory access 5829 * to map element returned from bpf_map_lookup_elem() 5830 */ 5831 if (meta.map_ptr == NULL) { 5832 verbose(env, 5833 "kernel subsystem misconfigured verifier\n"); 5834 return -EINVAL; 5835 } 5836 regs[BPF_REG_0].map_ptr = meta.map_ptr; 5837 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) { 5838 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE; 5839 if (map_value_has_spin_lock(meta.map_ptr)) 5840 regs[BPF_REG_0].id = ++env->id_gen; 5841 } else { 5842 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; 5843 } 5844 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) { 5845 mark_reg_known_zero(env, regs, BPF_REG_0); 5846 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL; 5847 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) { 5848 mark_reg_known_zero(env, regs, BPF_REG_0); 5849 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL; 5850 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) { 5851 mark_reg_known_zero(env, regs, BPF_REG_0); 5852 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL; 5853 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) { 5854 mark_reg_known_zero(env, regs, BPF_REG_0); 5855 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL; 5856 regs[BPF_REG_0].mem_size = meta.mem_size; 5857 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL || 5858 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) { 5859 const struct btf_type *t; 5860 5861 mark_reg_known_zero(env, regs, BPF_REG_0); 5862 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 5863 if (!btf_type_is_struct(t)) { 5864 u32 tsize; 5865 const struct btf_type *ret; 5866 const char *tname; 5867 5868 /* resolve the type size of ksym. */ 5869 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 5870 if (IS_ERR(ret)) { 5871 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 5872 verbose(env, "unable to resolve the size of type '%s': %ld\n", 5873 tname, PTR_ERR(ret)); 5874 return -EINVAL; 5875 } 5876 regs[BPF_REG_0].type = 5877 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ? 5878 PTR_TO_MEM : PTR_TO_MEM_OR_NULL; 5879 regs[BPF_REG_0].mem_size = tsize; 5880 } else { 5881 regs[BPF_REG_0].type = 5882 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ? 5883 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL; 5884 regs[BPF_REG_0].btf = meta.ret_btf; 5885 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 5886 } 5887 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL || 5888 fn->ret_type == RET_PTR_TO_BTF_ID) { 5889 int ret_btf_id; 5890 5891 mark_reg_known_zero(env, regs, BPF_REG_0); 5892 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ? 5893 PTR_TO_BTF_ID : 5894 PTR_TO_BTF_ID_OR_NULL; 5895 ret_btf_id = *fn->ret_btf_id; 5896 if (ret_btf_id == 0) { 5897 verbose(env, "invalid return type %d of func %s#%d\n", 5898 fn->ret_type, func_id_name(func_id), func_id); 5899 return -EINVAL; 5900 } 5901 /* current BPF helper definitions are only coming from 5902 * built-in code with type IDs from vmlinux BTF 5903 */ 5904 regs[BPF_REG_0].btf = btf_vmlinux; 5905 regs[BPF_REG_0].btf_id = ret_btf_id; 5906 } else { 5907 verbose(env, "unknown return type %d of func %s#%d\n", 5908 fn->ret_type, func_id_name(func_id), func_id); 5909 return -EINVAL; 5910 } 5911 5912 if (reg_type_may_be_null(regs[BPF_REG_0].type)) 5913 regs[BPF_REG_0].id = ++env->id_gen; 5914 5915 if (is_ptr_cast_function(func_id)) { 5916 /* For release_reference() */ 5917 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 5918 } else if (is_acquire_function(func_id, meta.map_ptr)) { 5919 int id = acquire_reference_state(env, insn_idx); 5920 5921 if (id < 0) 5922 return id; 5923 /* For mark_ptr_or_null_reg() */ 5924 regs[BPF_REG_0].id = id; 5925 /* For release_reference() */ 5926 regs[BPF_REG_0].ref_obj_id = id; 5927 } 5928 5929 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 5930 5931 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 5932 if (err) 5933 return err; 5934 5935 if ((func_id == BPF_FUNC_get_stack || 5936 func_id == BPF_FUNC_get_task_stack) && 5937 !env->prog->has_callchain_buf) { 5938 const char *err_str; 5939 5940 #ifdef CONFIG_PERF_EVENTS 5941 err = get_callchain_buffers(sysctl_perf_event_max_stack); 5942 err_str = "cannot get callchain buffer for func %s#%d\n"; 5943 #else 5944 err = -ENOTSUPP; 5945 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 5946 #endif 5947 if (err) { 5948 verbose(env, err_str, func_id_name(func_id), func_id); 5949 return err; 5950 } 5951 5952 env->prog->has_callchain_buf = true; 5953 } 5954 5955 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 5956 env->prog->call_get_stack = true; 5957 5958 if (changes_data) 5959 clear_all_pkt_pointers(env); 5960 return 0; 5961 } 5962 5963 static bool signed_add_overflows(s64 a, s64 b) 5964 { 5965 /* Do the add in u64, where overflow is well-defined */ 5966 s64 res = (s64)((u64)a + (u64)b); 5967 5968 if (b < 0) 5969 return res > a; 5970 return res < a; 5971 } 5972 5973 static bool signed_add32_overflows(s32 a, s32 b) 5974 { 5975 /* Do the add in u32, where overflow is well-defined */ 5976 s32 res = (s32)((u32)a + (u32)b); 5977 5978 if (b < 0) 5979 return res > a; 5980 return res < a; 5981 } 5982 5983 static bool signed_sub_overflows(s64 a, s64 b) 5984 { 5985 /* Do the sub in u64, where overflow is well-defined */ 5986 s64 res = (s64)((u64)a - (u64)b); 5987 5988 if (b < 0) 5989 return res < a; 5990 return res > a; 5991 } 5992 5993 static bool signed_sub32_overflows(s32 a, s32 b) 5994 { 5995 /* Do the sub in u32, where overflow is well-defined */ 5996 s32 res = (s32)((u32)a - (u32)b); 5997 5998 if (b < 0) 5999 return res < a; 6000 return res > a; 6001 } 6002 6003 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 6004 const struct bpf_reg_state *reg, 6005 enum bpf_reg_type type) 6006 { 6007 bool known = tnum_is_const(reg->var_off); 6008 s64 val = reg->var_off.value; 6009 s64 smin = reg->smin_value; 6010 6011 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 6012 verbose(env, "math between %s pointer and %lld is not allowed\n", 6013 reg_type_str[type], val); 6014 return false; 6015 } 6016 6017 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 6018 verbose(env, "%s pointer offset %d is not allowed\n", 6019 reg_type_str[type], reg->off); 6020 return false; 6021 } 6022 6023 if (smin == S64_MIN) { 6024 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 6025 reg_type_str[type]); 6026 return false; 6027 } 6028 6029 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 6030 verbose(env, "value %lld makes %s pointer be out of bounds\n", 6031 smin, reg_type_str[type]); 6032 return false; 6033 } 6034 6035 return true; 6036 } 6037 6038 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 6039 { 6040 return &env->insn_aux_data[env->insn_idx]; 6041 } 6042 6043 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 6044 u32 *ptr_limit, u8 opcode, bool off_is_neg) 6045 { 6046 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) || 6047 (opcode == BPF_SUB && !off_is_neg); 6048 u32 off, max; 6049 6050 switch (ptr_reg->type) { 6051 case PTR_TO_STACK: 6052 /* Offset 0 is out-of-bounds, but acceptable start for the 6053 * left direction, see BPF_REG_FP. 6054 */ 6055 max = MAX_BPF_STACK + mask_to_left; 6056 /* Indirect variable offset stack access is prohibited in 6057 * unprivileged mode so it's not handled here. 6058 */ 6059 off = ptr_reg->off + ptr_reg->var_off.value; 6060 if (mask_to_left) 6061 *ptr_limit = MAX_BPF_STACK + off; 6062 else 6063 *ptr_limit = -off - 1; 6064 return *ptr_limit >= max ? -ERANGE : 0; 6065 case PTR_TO_MAP_KEY: 6066 /* Currently, this code is not exercised as the only use 6067 * is bpf_for_each_map_elem() helper which requires 6068 * bpf_capble. The code has been tested manually for 6069 * future use. 6070 */ 6071 if (mask_to_left) { 6072 *ptr_limit = ptr_reg->umax_value + ptr_reg->off; 6073 } else { 6074 off = ptr_reg->smin_value + ptr_reg->off; 6075 *ptr_limit = ptr_reg->map_ptr->key_size - off; 6076 } 6077 return 0; 6078 case PTR_TO_MAP_VALUE: 6079 max = ptr_reg->map_ptr->value_size; 6080 if (mask_to_left) { 6081 *ptr_limit = ptr_reg->umax_value + ptr_reg->off; 6082 } else { 6083 off = ptr_reg->smin_value + ptr_reg->off; 6084 *ptr_limit = ptr_reg->map_ptr->value_size - off - 1; 6085 } 6086 return *ptr_limit >= max ? -ERANGE : 0; 6087 default: 6088 return -EINVAL; 6089 } 6090 } 6091 6092 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 6093 const struct bpf_insn *insn) 6094 { 6095 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 6096 } 6097 6098 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 6099 u32 alu_state, u32 alu_limit) 6100 { 6101 /* If we arrived here from different branches with different 6102 * state or limits to sanitize, then this won't work. 6103 */ 6104 if (aux->alu_state && 6105 (aux->alu_state != alu_state || 6106 aux->alu_limit != alu_limit)) 6107 return -EACCES; 6108 6109 /* Corresponding fixup done in do_misc_fixups(). */ 6110 aux->alu_state = alu_state; 6111 aux->alu_limit = alu_limit; 6112 return 0; 6113 } 6114 6115 static int sanitize_val_alu(struct bpf_verifier_env *env, 6116 struct bpf_insn *insn) 6117 { 6118 struct bpf_insn_aux_data *aux = cur_aux(env); 6119 6120 if (can_skip_alu_sanitation(env, insn)) 6121 return 0; 6122 6123 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 6124 } 6125 6126 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 6127 struct bpf_insn *insn, 6128 const struct bpf_reg_state *ptr_reg, 6129 struct bpf_reg_state *dst_reg, 6130 bool off_is_neg) 6131 { 6132 struct bpf_verifier_state *vstate = env->cur_state; 6133 struct bpf_insn_aux_data *aux = cur_aux(env); 6134 bool ptr_is_dst_reg = ptr_reg == dst_reg; 6135 u8 opcode = BPF_OP(insn->code); 6136 u32 alu_state, alu_limit; 6137 struct bpf_reg_state tmp; 6138 bool ret; 6139 int err; 6140 6141 if (can_skip_alu_sanitation(env, insn)) 6142 return 0; 6143 6144 /* We already marked aux for masking from non-speculative 6145 * paths, thus we got here in the first place. We only care 6146 * to explore bad access from here. 6147 */ 6148 if (vstate->speculative) 6149 goto do_sim; 6150 6151 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 6152 alu_state |= ptr_is_dst_reg ? 6153 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 6154 6155 err = retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg); 6156 if (err < 0) 6157 return err; 6158 6159 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 6160 if (err < 0) 6161 return err; 6162 do_sim: 6163 /* Simulate and find potential out-of-bounds access under 6164 * speculative execution from truncation as a result of 6165 * masking when off was not within expected range. If off 6166 * sits in dst, then we temporarily need to move ptr there 6167 * to simulate dst (== 0) +/-= ptr. Needed, for example, 6168 * for cases where we use K-based arithmetic in one direction 6169 * and truncated reg-based in the other in order to explore 6170 * bad access. 6171 */ 6172 if (!ptr_is_dst_reg) { 6173 tmp = *dst_reg; 6174 *dst_reg = *ptr_reg; 6175 } 6176 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true); 6177 if (!ptr_is_dst_reg && ret) 6178 *dst_reg = tmp; 6179 return !ret ? -EFAULT : 0; 6180 } 6181 6182 /* check that stack access falls within stack limits and that 'reg' doesn't 6183 * have a variable offset. 6184 * 6185 * Variable offset is prohibited for unprivileged mode for simplicity since it 6186 * requires corresponding support in Spectre masking for stack ALU. See also 6187 * retrieve_ptr_limit(). 6188 * 6189 * 6190 * 'off' includes 'reg->off'. 6191 */ 6192 static int check_stack_access_for_ptr_arithmetic( 6193 struct bpf_verifier_env *env, 6194 int regno, 6195 const struct bpf_reg_state *reg, 6196 int off) 6197 { 6198 if (!tnum_is_const(reg->var_off)) { 6199 char tn_buf[48]; 6200 6201 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6202 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 6203 regno, tn_buf, off); 6204 return -EACCES; 6205 } 6206 6207 if (off >= 0 || off < -MAX_BPF_STACK) { 6208 verbose(env, "R%d stack pointer arithmetic goes out of range, " 6209 "prohibited for !root; off=%d\n", regno, off); 6210 return -EACCES; 6211 } 6212 6213 return 0; 6214 } 6215 6216 6217 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 6218 * Caller should also handle BPF_MOV case separately. 6219 * If we return -EACCES, caller may want to try again treating pointer as a 6220 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 6221 */ 6222 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 6223 struct bpf_insn *insn, 6224 const struct bpf_reg_state *ptr_reg, 6225 const struct bpf_reg_state *off_reg) 6226 { 6227 struct bpf_verifier_state *vstate = env->cur_state; 6228 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6229 struct bpf_reg_state *regs = state->regs, *dst_reg; 6230 bool known = tnum_is_const(off_reg->var_off); 6231 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 6232 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 6233 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 6234 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 6235 u32 dst = insn->dst_reg, src = insn->src_reg; 6236 u8 opcode = BPF_OP(insn->code); 6237 int ret; 6238 6239 dst_reg = ®s[dst]; 6240 6241 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 6242 smin_val > smax_val || umin_val > umax_val) { 6243 /* Taint dst register if offset had invalid bounds derived from 6244 * e.g. dead branches. 6245 */ 6246 __mark_reg_unknown(env, dst_reg); 6247 return 0; 6248 } 6249 6250 if (BPF_CLASS(insn->code) != BPF_ALU64) { 6251 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 6252 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 6253 __mark_reg_unknown(env, dst_reg); 6254 return 0; 6255 } 6256 6257 verbose(env, 6258 "R%d 32-bit pointer arithmetic prohibited\n", 6259 dst); 6260 return -EACCES; 6261 } 6262 6263 switch (ptr_reg->type) { 6264 case PTR_TO_MAP_VALUE_OR_NULL: 6265 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 6266 dst, reg_type_str[ptr_reg->type]); 6267 return -EACCES; 6268 case CONST_PTR_TO_MAP: 6269 /* smin_val represents the known value */ 6270 if (known && smin_val == 0 && opcode == BPF_ADD) 6271 break; 6272 fallthrough; 6273 case PTR_TO_PACKET_END: 6274 case PTR_TO_SOCKET: 6275 case PTR_TO_SOCKET_OR_NULL: 6276 case PTR_TO_SOCK_COMMON: 6277 case PTR_TO_SOCK_COMMON_OR_NULL: 6278 case PTR_TO_TCP_SOCK: 6279 case PTR_TO_TCP_SOCK_OR_NULL: 6280 case PTR_TO_XDP_SOCK: 6281 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 6282 dst, reg_type_str[ptr_reg->type]); 6283 return -EACCES; 6284 case PTR_TO_MAP_KEY: 6285 case PTR_TO_MAP_VALUE: 6286 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) { 6287 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n", 6288 off_reg == dst_reg ? dst : src); 6289 return -EACCES; 6290 } 6291 fallthrough; 6292 default: 6293 break; 6294 } 6295 6296 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 6297 * The id may be overwritten later if we create a new variable offset. 6298 */ 6299 dst_reg->type = ptr_reg->type; 6300 dst_reg->id = ptr_reg->id; 6301 6302 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 6303 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 6304 return -EINVAL; 6305 6306 /* pointer types do not carry 32-bit bounds at the moment. */ 6307 __mark_reg32_unbounded(dst_reg); 6308 6309 switch (opcode) { 6310 case BPF_ADD: 6311 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0); 6312 if (ret < 0) { 6313 verbose(env, "R%d tried to add from different maps, paths, or prohibited types\n", dst); 6314 return ret; 6315 } 6316 /* We can take a fixed offset as long as it doesn't overflow 6317 * the s32 'off' field 6318 */ 6319 if (known && (ptr_reg->off + smin_val == 6320 (s64)(s32)(ptr_reg->off + smin_val))) { 6321 /* pointer += K. Accumulate it into fixed offset */ 6322 dst_reg->smin_value = smin_ptr; 6323 dst_reg->smax_value = smax_ptr; 6324 dst_reg->umin_value = umin_ptr; 6325 dst_reg->umax_value = umax_ptr; 6326 dst_reg->var_off = ptr_reg->var_off; 6327 dst_reg->off = ptr_reg->off + smin_val; 6328 dst_reg->raw = ptr_reg->raw; 6329 break; 6330 } 6331 /* A new variable offset is created. Note that off_reg->off 6332 * == 0, since it's a scalar. 6333 * dst_reg gets the pointer type and since some positive 6334 * integer value was added to the pointer, give it a new 'id' 6335 * if it's a PTR_TO_PACKET. 6336 * this creates a new 'base' pointer, off_reg (variable) gets 6337 * added into the variable offset, and we copy the fixed offset 6338 * from ptr_reg. 6339 */ 6340 if (signed_add_overflows(smin_ptr, smin_val) || 6341 signed_add_overflows(smax_ptr, smax_val)) { 6342 dst_reg->smin_value = S64_MIN; 6343 dst_reg->smax_value = S64_MAX; 6344 } else { 6345 dst_reg->smin_value = smin_ptr + smin_val; 6346 dst_reg->smax_value = smax_ptr + smax_val; 6347 } 6348 if (umin_ptr + umin_val < umin_ptr || 6349 umax_ptr + umax_val < umax_ptr) { 6350 dst_reg->umin_value = 0; 6351 dst_reg->umax_value = U64_MAX; 6352 } else { 6353 dst_reg->umin_value = umin_ptr + umin_val; 6354 dst_reg->umax_value = umax_ptr + umax_val; 6355 } 6356 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 6357 dst_reg->off = ptr_reg->off; 6358 dst_reg->raw = ptr_reg->raw; 6359 if (reg_is_pkt_pointer(ptr_reg)) { 6360 dst_reg->id = ++env->id_gen; 6361 /* something was added to pkt_ptr, set range to zero */ 6362 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 6363 } 6364 break; 6365 case BPF_SUB: 6366 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0); 6367 if (ret < 0) { 6368 verbose(env, "R%d tried to sub from different maps, paths, or prohibited types\n", dst); 6369 return ret; 6370 } 6371 if (dst_reg == off_reg) { 6372 /* scalar -= pointer. Creates an unknown scalar */ 6373 verbose(env, "R%d tried to subtract pointer from scalar\n", 6374 dst); 6375 return -EACCES; 6376 } 6377 /* We don't allow subtraction from FP, because (according to 6378 * test_verifier.c test "invalid fp arithmetic", JITs might not 6379 * be able to deal with it. 6380 */ 6381 if (ptr_reg->type == PTR_TO_STACK) { 6382 verbose(env, "R%d subtraction from stack pointer prohibited\n", 6383 dst); 6384 return -EACCES; 6385 } 6386 if (known && (ptr_reg->off - smin_val == 6387 (s64)(s32)(ptr_reg->off - smin_val))) { 6388 /* pointer -= K. Subtract it from fixed offset */ 6389 dst_reg->smin_value = smin_ptr; 6390 dst_reg->smax_value = smax_ptr; 6391 dst_reg->umin_value = umin_ptr; 6392 dst_reg->umax_value = umax_ptr; 6393 dst_reg->var_off = ptr_reg->var_off; 6394 dst_reg->id = ptr_reg->id; 6395 dst_reg->off = ptr_reg->off - smin_val; 6396 dst_reg->raw = ptr_reg->raw; 6397 break; 6398 } 6399 /* A new variable offset is created. If the subtrahend is known 6400 * nonnegative, then any reg->range we had before is still good. 6401 */ 6402 if (signed_sub_overflows(smin_ptr, smax_val) || 6403 signed_sub_overflows(smax_ptr, smin_val)) { 6404 /* Overflow possible, we know nothing */ 6405 dst_reg->smin_value = S64_MIN; 6406 dst_reg->smax_value = S64_MAX; 6407 } else { 6408 dst_reg->smin_value = smin_ptr - smax_val; 6409 dst_reg->smax_value = smax_ptr - smin_val; 6410 } 6411 if (umin_ptr < umax_val) { 6412 /* Overflow possible, we know nothing */ 6413 dst_reg->umin_value = 0; 6414 dst_reg->umax_value = U64_MAX; 6415 } else { 6416 /* Cannot overflow (as long as bounds are consistent) */ 6417 dst_reg->umin_value = umin_ptr - umax_val; 6418 dst_reg->umax_value = umax_ptr - umin_val; 6419 } 6420 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 6421 dst_reg->off = ptr_reg->off; 6422 dst_reg->raw = ptr_reg->raw; 6423 if (reg_is_pkt_pointer(ptr_reg)) { 6424 dst_reg->id = ++env->id_gen; 6425 /* something was added to pkt_ptr, set range to zero */ 6426 if (smin_val < 0) 6427 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 6428 } 6429 break; 6430 case BPF_AND: 6431 case BPF_OR: 6432 case BPF_XOR: 6433 /* bitwise ops on pointers are troublesome, prohibit. */ 6434 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 6435 dst, bpf_alu_string[opcode >> 4]); 6436 return -EACCES; 6437 default: 6438 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 6439 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 6440 dst, bpf_alu_string[opcode >> 4]); 6441 return -EACCES; 6442 } 6443 6444 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 6445 return -EINVAL; 6446 6447 __update_reg_bounds(dst_reg); 6448 __reg_deduce_bounds(dst_reg); 6449 __reg_bound_offset(dst_reg); 6450 6451 /* For unprivileged we require that resulting offset must be in bounds 6452 * in order to be able to sanitize access later on. 6453 */ 6454 if (!env->bypass_spec_v1) { 6455 if (dst_reg->type == PTR_TO_MAP_VALUE && 6456 check_map_access(env, dst, dst_reg->off, 1, false)) { 6457 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 6458 "prohibited for !root\n", dst); 6459 return -EACCES; 6460 } else if (dst_reg->type == PTR_TO_STACK && 6461 check_stack_access_for_ptr_arithmetic( 6462 env, dst, dst_reg, dst_reg->off + 6463 dst_reg->var_off.value)) { 6464 return -EACCES; 6465 } 6466 } 6467 6468 return 0; 6469 } 6470 6471 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 6472 struct bpf_reg_state *src_reg) 6473 { 6474 s32 smin_val = src_reg->s32_min_value; 6475 s32 smax_val = src_reg->s32_max_value; 6476 u32 umin_val = src_reg->u32_min_value; 6477 u32 umax_val = src_reg->u32_max_value; 6478 6479 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 6480 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 6481 dst_reg->s32_min_value = S32_MIN; 6482 dst_reg->s32_max_value = S32_MAX; 6483 } else { 6484 dst_reg->s32_min_value += smin_val; 6485 dst_reg->s32_max_value += smax_val; 6486 } 6487 if (dst_reg->u32_min_value + umin_val < umin_val || 6488 dst_reg->u32_max_value + umax_val < umax_val) { 6489 dst_reg->u32_min_value = 0; 6490 dst_reg->u32_max_value = U32_MAX; 6491 } else { 6492 dst_reg->u32_min_value += umin_val; 6493 dst_reg->u32_max_value += umax_val; 6494 } 6495 } 6496 6497 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 6498 struct bpf_reg_state *src_reg) 6499 { 6500 s64 smin_val = src_reg->smin_value; 6501 s64 smax_val = src_reg->smax_value; 6502 u64 umin_val = src_reg->umin_value; 6503 u64 umax_val = src_reg->umax_value; 6504 6505 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 6506 signed_add_overflows(dst_reg->smax_value, smax_val)) { 6507 dst_reg->smin_value = S64_MIN; 6508 dst_reg->smax_value = S64_MAX; 6509 } else { 6510 dst_reg->smin_value += smin_val; 6511 dst_reg->smax_value += smax_val; 6512 } 6513 if (dst_reg->umin_value + umin_val < umin_val || 6514 dst_reg->umax_value + umax_val < umax_val) { 6515 dst_reg->umin_value = 0; 6516 dst_reg->umax_value = U64_MAX; 6517 } else { 6518 dst_reg->umin_value += umin_val; 6519 dst_reg->umax_value += umax_val; 6520 } 6521 } 6522 6523 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 6524 struct bpf_reg_state *src_reg) 6525 { 6526 s32 smin_val = src_reg->s32_min_value; 6527 s32 smax_val = src_reg->s32_max_value; 6528 u32 umin_val = src_reg->u32_min_value; 6529 u32 umax_val = src_reg->u32_max_value; 6530 6531 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 6532 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 6533 /* Overflow possible, we know nothing */ 6534 dst_reg->s32_min_value = S32_MIN; 6535 dst_reg->s32_max_value = S32_MAX; 6536 } else { 6537 dst_reg->s32_min_value -= smax_val; 6538 dst_reg->s32_max_value -= smin_val; 6539 } 6540 if (dst_reg->u32_min_value < umax_val) { 6541 /* Overflow possible, we know nothing */ 6542 dst_reg->u32_min_value = 0; 6543 dst_reg->u32_max_value = U32_MAX; 6544 } else { 6545 /* Cannot overflow (as long as bounds are consistent) */ 6546 dst_reg->u32_min_value -= umax_val; 6547 dst_reg->u32_max_value -= umin_val; 6548 } 6549 } 6550 6551 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 6552 struct bpf_reg_state *src_reg) 6553 { 6554 s64 smin_val = src_reg->smin_value; 6555 s64 smax_val = src_reg->smax_value; 6556 u64 umin_val = src_reg->umin_value; 6557 u64 umax_val = src_reg->umax_value; 6558 6559 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 6560 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 6561 /* Overflow possible, we know nothing */ 6562 dst_reg->smin_value = S64_MIN; 6563 dst_reg->smax_value = S64_MAX; 6564 } else { 6565 dst_reg->smin_value -= smax_val; 6566 dst_reg->smax_value -= smin_val; 6567 } 6568 if (dst_reg->umin_value < umax_val) { 6569 /* Overflow possible, we know nothing */ 6570 dst_reg->umin_value = 0; 6571 dst_reg->umax_value = U64_MAX; 6572 } else { 6573 /* Cannot overflow (as long as bounds are consistent) */ 6574 dst_reg->umin_value -= umax_val; 6575 dst_reg->umax_value -= umin_val; 6576 } 6577 } 6578 6579 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 6580 struct bpf_reg_state *src_reg) 6581 { 6582 s32 smin_val = src_reg->s32_min_value; 6583 u32 umin_val = src_reg->u32_min_value; 6584 u32 umax_val = src_reg->u32_max_value; 6585 6586 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 6587 /* Ain't nobody got time to multiply that sign */ 6588 __mark_reg32_unbounded(dst_reg); 6589 return; 6590 } 6591 /* Both values are positive, so we can work with unsigned and 6592 * copy the result to signed (unless it exceeds S32_MAX). 6593 */ 6594 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 6595 /* Potential overflow, we know nothing */ 6596 __mark_reg32_unbounded(dst_reg); 6597 return; 6598 } 6599 dst_reg->u32_min_value *= umin_val; 6600 dst_reg->u32_max_value *= umax_val; 6601 if (dst_reg->u32_max_value > S32_MAX) { 6602 /* Overflow possible, we know nothing */ 6603 dst_reg->s32_min_value = S32_MIN; 6604 dst_reg->s32_max_value = S32_MAX; 6605 } else { 6606 dst_reg->s32_min_value = dst_reg->u32_min_value; 6607 dst_reg->s32_max_value = dst_reg->u32_max_value; 6608 } 6609 } 6610 6611 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 6612 struct bpf_reg_state *src_reg) 6613 { 6614 s64 smin_val = src_reg->smin_value; 6615 u64 umin_val = src_reg->umin_value; 6616 u64 umax_val = src_reg->umax_value; 6617 6618 if (smin_val < 0 || dst_reg->smin_value < 0) { 6619 /* Ain't nobody got time to multiply that sign */ 6620 __mark_reg64_unbounded(dst_reg); 6621 return; 6622 } 6623 /* Both values are positive, so we can work with unsigned and 6624 * copy the result to signed (unless it exceeds S64_MAX). 6625 */ 6626 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 6627 /* Potential overflow, we know nothing */ 6628 __mark_reg64_unbounded(dst_reg); 6629 return; 6630 } 6631 dst_reg->umin_value *= umin_val; 6632 dst_reg->umax_value *= umax_val; 6633 if (dst_reg->umax_value > S64_MAX) { 6634 /* Overflow possible, we know nothing */ 6635 dst_reg->smin_value = S64_MIN; 6636 dst_reg->smax_value = S64_MAX; 6637 } else { 6638 dst_reg->smin_value = dst_reg->umin_value; 6639 dst_reg->smax_value = dst_reg->umax_value; 6640 } 6641 } 6642 6643 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 6644 struct bpf_reg_state *src_reg) 6645 { 6646 bool src_known = tnum_subreg_is_const(src_reg->var_off); 6647 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 6648 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 6649 s32 smin_val = src_reg->s32_min_value; 6650 u32 umax_val = src_reg->u32_max_value; 6651 6652 /* Assuming scalar64_min_max_and will be called so its safe 6653 * to skip updating register for known 32-bit case. 6654 */ 6655 if (src_known && dst_known) 6656 return; 6657 6658 /* We get our minimum from the var_off, since that's inherently 6659 * bitwise. Our maximum is the minimum of the operands' maxima. 6660 */ 6661 dst_reg->u32_min_value = var32_off.value; 6662 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 6663 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 6664 /* Lose signed bounds when ANDing negative numbers, 6665 * ain't nobody got time for that. 6666 */ 6667 dst_reg->s32_min_value = S32_MIN; 6668 dst_reg->s32_max_value = S32_MAX; 6669 } else { 6670 /* ANDing two positives gives a positive, so safe to 6671 * cast result into s64. 6672 */ 6673 dst_reg->s32_min_value = dst_reg->u32_min_value; 6674 dst_reg->s32_max_value = dst_reg->u32_max_value; 6675 } 6676 6677 } 6678 6679 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 6680 struct bpf_reg_state *src_reg) 6681 { 6682 bool src_known = tnum_is_const(src_reg->var_off); 6683 bool dst_known = tnum_is_const(dst_reg->var_off); 6684 s64 smin_val = src_reg->smin_value; 6685 u64 umax_val = src_reg->umax_value; 6686 6687 if (src_known && dst_known) { 6688 __mark_reg_known(dst_reg, dst_reg->var_off.value); 6689 return; 6690 } 6691 6692 /* We get our minimum from the var_off, since that's inherently 6693 * bitwise. Our maximum is the minimum of the operands' maxima. 6694 */ 6695 dst_reg->umin_value = dst_reg->var_off.value; 6696 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 6697 if (dst_reg->smin_value < 0 || smin_val < 0) { 6698 /* Lose signed bounds when ANDing negative numbers, 6699 * ain't nobody got time for that. 6700 */ 6701 dst_reg->smin_value = S64_MIN; 6702 dst_reg->smax_value = S64_MAX; 6703 } else { 6704 /* ANDing two positives gives a positive, so safe to 6705 * cast result into s64. 6706 */ 6707 dst_reg->smin_value = dst_reg->umin_value; 6708 dst_reg->smax_value = dst_reg->umax_value; 6709 } 6710 /* We may learn something more from the var_off */ 6711 __update_reg_bounds(dst_reg); 6712 } 6713 6714 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 6715 struct bpf_reg_state *src_reg) 6716 { 6717 bool src_known = tnum_subreg_is_const(src_reg->var_off); 6718 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 6719 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 6720 s32 smin_val = src_reg->s32_min_value; 6721 u32 umin_val = src_reg->u32_min_value; 6722 6723 /* Assuming scalar64_min_max_or will be called so it is safe 6724 * to skip updating register for known case. 6725 */ 6726 if (src_known && dst_known) 6727 return; 6728 6729 /* We get our maximum from the var_off, and our minimum is the 6730 * maximum of the operands' minima 6731 */ 6732 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 6733 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 6734 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 6735 /* Lose signed bounds when ORing negative numbers, 6736 * ain't nobody got time for that. 6737 */ 6738 dst_reg->s32_min_value = S32_MIN; 6739 dst_reg->s32_max_value = S32_MAX; 6740 } else { 6741 /* ORing two positives gives a positive, so safe to 6742 * cast result into s64. 6743 */ 6744 dst_reg->s32_min_value = dst_reg->u32_min_value; 6745 dst_reg->s32_max_value = dst_reg->u32_max_value; 6746 } 6747 } 6748 6749 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 6750 struct bpf_reg_state *src_reg) 6751 { 6752 bool src_known = tnum_is_const(src_reg->var_off); 6753 bool dst_known = tnum_is_const(dst_reg->var_off); 6754 s64 smin_val = src_reg->smin_value; 6755 u64 umin_val = src_reg->umin_value; 6756 6757 if (src_known && dst_known) { 6758 __mark_reg_known(dst_reg, dst_reg->var_off.value); 6759 return; 6760 } 6761 6762 /* We get our maximum from the var_off, and our minimum is the 6763 * maximum of the operands' minima 6764 */ 6765 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 6766 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 6767 if (dst_reg->smin_value < 0 || smin_val < 0) { 6768 /* Lose signed bounds when ORing negative numbers, 6769 * ain't nobody got time for that. 6770 */ 6771 dst_reg->smin_value = S64_MIN; 6772 dst_reg->smax_value = S64_MAX; 6773 } else { 6774 /* ORing two positives gives a positive, so safe to 6775 * cast result into s64. 6776 */ 6777 dst_reg->smin_value = dst_reg->umin_value; 6778 dst_reg->smax_value = dst_reg->umax_value; 6779 } 6780 /* We may learn something more from the var_off */ 6781 __update_reg_bounds(dst_reg); 6782 } 6783 6784 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 6785 struct bpf_reg_state *src_reg) 6786 { 6787 bool src_known = tnum_subreg_is_const(src_reg->var_off); 6788 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 6789 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 6790 s32 smin_val = src_reg->s32_min_value; 6791 6792 /* Assuming scalar64_min_max_xor will be called so it is safe 6793 * to skip updating register for known case. 6794 */ 6795 if (src_known && dst_known) 6796 return; 6797 6798 /* We get both minimum and maximum from the var32_off. */ 6799 dst_reg->u32_min_value = var32_off.value; 6800 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 6801 6802 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 6803 /* XORing two positive sign numbers gives a positive, 6804 * so safe to cast u32 result into s32. 6805 */ 6806 dst_reg->s32_min_value = dst_reg->u32_min_value; 6807 dst_reg->s32_max_value = dst_reg->u32_max_value; 6808 } else { 6809 dst_reg->s32_min_value = S32_MIN; 6810 dst_reg->s32_max_value = S32_MAX; 6811 } 6812 } 6813 6814 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 6815 struct bpf_reg_state *src_reg) 6816 { 6817 bool src_known = tnum_is_const(src_reg->var_off); 6818 bool dst_known = tnum_is_const(dst_reg->var_off); 6819 s64 smin_val = src_reg->smin_value; 6820 6821 if (src_known && dst_known) { 6822 /* dst_reg->var_off.value has been updated earlier */ 6823 __mark_reg_known(dst_reg, dst_reg->var_off.value); 6824 return; 6825 } 6826 6827 /* We get both minimum and maximum from the var_off. */ 6828 dst_reg->umin_value = dst_reg->var_off.value; 6829 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 6830 6831 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 6832 /* XORing two positive sign numbers gives a positive, 6833 * so safe to cast u64 result into s64. 6834 */ 6835 dst_reg->smin_value = dst_reg->umin_value; 6836 dst_reg->smax_value = dst_reg->umax_value; 6837 } else { 6838 dst_reg->smin_value = S64_MIN; 6839 dst_reg->smax_value = S64_MAX; 6840 } 6841 6842 __update_reg_bounds(dst_reg); 6843 } 6844 6845 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 6846 u64 umin_val, u64 umax_val) 6847 { 6848 /* We lose all sign bit information (except what we can pick 6849 * up from var_off) 6850 */ 6851 dst_reg->s32_min_value = S32_MIN; 6852 dst_reg->s32_max_value = S32_MAX; 6853 /* If we might shift our top bit out, then we know nothing */ 6854 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 6855 dst_reg->u32_min_value = 0; 6856 dst_reg->u32_max_value = U32_MAX; 6857 } else { 6858 dst_reg->u32_min_value <<= umin_val; 6859 dst_reg->u32_max_value <<= umax_val; 6860 } 6861 } 6862 6863 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 6864 struct bpf_reg_state *src_reg) 6865 { 6866 u32 umax_val = src_reg->u32_max_value; 6867 u32 umin_val = src_reg->u32_min_value; 6868 /* u32 alu operation will zext upper bits */ 6869 struct tnum subreg = tnum_subreg(dst_reg->var_off); 6870 6871 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 6872 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 6873 /* Not required but being careful mark reg64 bounds as unknown so 6874 * that we are forced to pick them up from tnum and zext later and 6875 * if some path skips this step we are still safe. 6876 */ 6877 __mark_reg64_unbounded(dst_reg); 6878 __update_reg32_bounds(dst_reg); 6879 } 6880 6881 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 6882 u64 umin_val, u64 umax_val) 6883 { 6884 /* Special case <<32 because it is a common compiler pattern to sign 6885 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 6886 * positive we know this shift will also be positive so we can track 6887 * bounds correctly. Otherwise we lose all sign bit information except 6888 * what we can pick up from var_off. Perhaps we can generalize this 6889 * later to shifts of any length. 6890 */ 6891 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 6892 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 6893 else 6894 dst_reg->smax_value = S64_MAX; 6895 6896 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 6897 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 6898 else 6899 dst_reg->smin_value = S64_MIN; 6900 6901 /* If we might shift our top bit out, then we know nothing */ 6902 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 6903 dst_reg->umin_value = 0; 6904 dst_reg->umax_value = U64_MAX; 6905 } else { 6906 dst_reg->umin_value <<= umin_val; 6907 dst_reg->umax_value <<= umax_val; 6908 } 6909 } 6910 6911 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 6912 struct bpf_reg_state *src_reg) 6913 { 6914 u64 umax_val = src_reg->umax_value; 6915 u64 umin_val = src_reg->umin_value; 6916 6917 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 6918 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 6919 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 6920 6921 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 6922 /* We may learn something more from the var_off */ 6923 __update_reg_bounds(dst_reg); 6924 } 6925 6926 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 6927 struct bpf_reg_state *src_reg) 6928 { 6929 struct tnum subreg = tnum_subreg(dst_reg->var_off); 6930 u32 umax_val = src_reg->u32_max_value; 6931 u32 umin_val = src_reg->u32_min_value; 6932 6933 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 6934 * be negative, then either: 6935 * 1) src_reg might be zero, so the sign bit of the result is 6936 * unknown, so we lose our signed bounds 6937 * 2) it's known negative, thus the unsigned bounds capture the 6938 * signed bounds 6939 * 3) the signed bounds cross zero, so they tell us nothing 6940 * about the result 6941 * If the value in dst_reg is known nonnegative, then again the 6942 * unsigned bounds capture the signed bounds. 6943 * Thus, in all cases it suffices to blow away our signed bounds 6944 * and rely on inferring new ones from the unsigned bounds and 6945 * var_off of the result. 6946 */ 6947 dst_reg->s32_min_value = S32_MIN; 6948 dst_reg->s32_max_value = S32_MAX; 6949 6950 dst_reg->var_off = tnum_rshift(subreg, umin_val); 6951 dst_reg->u32_min_value >>= umax_val; 6952 dst_reg->u32_max_value >>= umin_val; 6953 6954 __mark_reg64_unbounded(dst_reg); 6955 __update_reg32_bounds(dst_reg); 6956 } 6957 6958 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 6959 struct bpf_reg_state *src_reg) 6960 { 6961 u64 umax_val = src_reg->umax_value; 6962 u64 umin_val = src_reg->umin_value; 6963 6964 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 6965 * be negative, then either: 6966 * 1) src_reg might be zero, so the sign bit of the result is 6967 * unknown, so we lose our signed bounds 6968 * 2) it's known negative, thus the unsigned bounds capture the 6969 * signed bounds 6970 * 3) the signed bounds cross zero, so they tell us nothing 6971 * about the result 6972 * If the value in dst_reg is known nonnegative, then again the 6973 * unsigned bounds capture the signed bounds. 6974 * Thus, in all cases it suffices to blow away our signed bounds 6975 * and rely on inferring new ones from the unsigned bounds and 6976 * var_off of the result. 6977 */ 6978 dst_reg->smin_value = S64_MIN; 6979 dst_reg->smax_value = S64_MAX; 6980 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 6981 dst_reg->umin_value >>= umax_val; 6982 dst_reg->umax_value >>= umin_val; 6983 6984 /* Its not easy to operate on alu32 bounds here because it depends 6985 * on bits being shifted in. Take easy way out and mark unbounded 6986 * so we can recalculate later from tnum. 6987 */ 6988 __mark_reg32_unbounded(dst_reg); 6989 __update_reg_bounds(dst_reg); 6990 } 6991 6992 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 6993 struct bpf_reg_state *src_reg) 6994 { 6995 u64 umin_val = src_reg->u32_min_value; 6996 6997 /* Upon reaching here, src_known is true and 6998 * umax_val is equal to umin_val. 6999 */ 7000 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 7001 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 7002 7003 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 7004 7005 /* blow away the dst_reg umin_value/umax_value and rely on 7006 * dst_reg var_off to refine the result. 7007 */ 7008 dst_reg->u32_min_value = 0; 7009 dst_reg->u32_max_value = U32_MAX; 7010 7011 __mark_reg64_unbounded(dst_reg); 7012 __update_reg32_bounds(dst_reg); 7013 } 7014 7015 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 7016 struct bpf_reg_state *src_reg) 7017 { 7018 u64 umin_val = src_reg->umin_value; 7019 7020 /* Upon reaching here, src_known is true and umax_val is equal 7021 * to umin_val. 7022 */ 7023 dst_reg->smin_value >>= umin_val; 7024 dst_reg->smax_value >>= umin_val; 7025 7026 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 7027 7028 /* blow away the dst_reg umin_value/umax_value and rely on 7029 * dst_reg var_off to refine the result. 7030 */ 7031 dst_reg->umin_value = 0; 7032 dst_reg->umax_value = U64_MAX; 7033 7034 /* Its not easy to operate on alu32 bounds here because it depends 7035 * on bits being shifted in from upper 32-bits. Take easy way out 7036 * and mark unbounded so we can recalculate later from tnum. 7037 */ 7038 __mark_reg32_unbounded(dst_reg); 7039 __update_reg_bounds(dst_reg); 7040 } 7041 7042 /* WARNING: This function does calculations on 64-bit values, but the actual 7043 * execution may occur on 32-bit values. Therefore, things like bitshifts 7044 * need extra checks in the 32-bit case. 7045 */ 7046 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 7047 struct bpf_insn *insn, 7048 struct bpf_reg_state *dst_reg, 7049 struct bpf_reg_state src_reg) 7050 { 7051 struct bpf_reg_state *regs = cur_regs(env); 7052 u8 opcode = BPF_OP(insn->code); 7053 bool src_known; 7054 s64 smin_val, smax_val; 7055 u64 umin_val, umax_val; 7056 s32 s32_min_val, s32_max_val; 7057 u32 u32_min_val, u32_max_val; 7058 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 7059 u32 dst = insn->dst_reg; 7060 int ret; 7061 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 7062 7063 smin_val = src_reg.smin_value; 7064 smax_val = src_reg.smax_value; 7065 umin_val = src_reg.umin_value; 7066 umax_val = src_reg.umax_value; 7067 7068 s32_min_val = src_reg.s32_min_value; 7069 s32_max_val = src_reg.s32_max_value; 7070 u32_min_val = src_reg.u32_min_value; 7071 u32_max_val = src_reg.u32_max_value; 7072 7073 if (alu32) { 7074 src_known = tnum_subreg_is_const(src_reg.var_off); 7075 if ((src_known && 7076 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 7077 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 7078 /* Taint dst register if offset had invalid bounds 7079 * derived from e.g. dead branches. 7080 */ 7081 __mark_reg_unknown(env, dst_reg); 7082 return 0; 7083 } 7084 } else { 7085 src_known = tnum_is_const(src_reg.var_off); 7086 if ((src_known && 7087 (smin_val != smax_val || umin_val != umax_val)) || 7088 smin_val > smax_val || umin_val > umax_val) { 7089 /* Taint dst register if offset had invalid bounds 7090 * derived from e.g. dead branches. 7091 */ 7092 __mark_reg_unknown(env, dst_reg); 7093 return 0; 7094 } 7095 } 7096 7097 if (!src_known && 7098 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 7099 __mark_reg_unknown(env, dst_reg); 7100 return 0; 7101 } 7102 7103 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 7104 * There are two classes of instructions: The first class we track both 7105 * alu32 and alu64 sign/unsigned bounds independently this provides the 7106 * greatest amount of precision when alu operations are mixed with jmp32 7107 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 7108 * and BPF_OR. This is possible because these ops have fairly easy to 7109 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 7110 * See alu32 verifier tests for examples. The second class of 7111 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 7112 * with regards to tracking sign/unsigned bounds because the bits may 7113 * cross subreg boundaries in the alu64 case. When this happens we mark 7114 * the reg unbounded in the subreg bound space and use the resulting 7115 * tnum to calculate an approximation of the sign/unsigned bounds. 7116 */ 7117 switch (opcode) { 7118 case BPF_ADD: 7119 ret = sanitize_val_alu(env, insn); 7120 if (ret < 0) { 7121 verbose(env, "R%d tried to add from different pointers or scalars\n", dst); 7122 return ret; 7123 } 7124 scalar32_min_max_add(dst_reg, &src_reg); 7125 scalar_min_max_add(dst_reg, &src_reg); 7126 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 7127 break; 7128 case BPF_SUB: 7129 ret = sanitize_val_alu(env, insn); 7130 if (ret < 0) { 7131 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst); 7132 return ret; 7133 } 7134 scalar32_min_max_sub(dst_reg, &src_reg); 7135 scalar_min_max_sub(dst_reg, &src_reg); 7136 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 7137 break; 7138 case BPF_MUL: 7139 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 7140 scalar32_min_max_mul(dst_reg, &src_reg); 7141 scalar_min_max_mul(dst_reg, &src_reg); 7142 break; 7143 case BPF_AND: 7144 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 7145 scalar32_min_max_and(dst_reg, &src_reg); 7146 scalar_min_max_and(dst_reg, &src_reg); 7147 break; 7148 case BPF_OR: 7149 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 7150 scalar32_min_max_or(dst_reg, &src_reg); 7151 scalar_min_max_or(dst_reg, &src_reg); 7152 break; 7153 case BPF_XOR: 7154 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 7155 scalar32_min_max_xor(dst_reg, &src_reg); 7156 scalar_min_max_xor(dst_reg, &src_reg); 7157 break; 7158 case BPF_LSH: 7159 if (umax_val >= insn_bitness) { 7160 /* Shifts greater than 31 or 63 are undefined. 7161 * This includes shifts by a negative number. 7162 */ 7163 mark_reg_unknown(env, regs, insn->dst_reg); 7164 break; 7165 } 7166 if (alu32) 7167 scalar32_min_max_lsh(dst_reg, &src_reg); 7168 else 7169 scalar_min_max_lsh(dst_reg, &src_reg); 7170 break; 7171 case BPF_RSH: 7172 if (umax_val >= insn_bitness) { 7173 /* Shifts greater than 31 or 63 are undefined. 7174 * This includes shifts by a negative number. 7175 */ 7176 mark_reg_unknown(env, regs, insn->dst_reg); 7177 break; 7178 } 7179 if (alu32) 7180 scalar32_min_max_rsh(dst_reg, &src_reg); 7181 else 7182 scalar_min_max_rsh(dst_reg, &src_reg); 7183 break; 7184 case BPF_ARSH: 7185 if (umax_val >= insn_bitness) { 7186 /* Shifts greater than 31 or 63 are undefined. 7187 * This includes shifts by a negative number. 7188 */ 7189 mark_reg_unknown(env, regs, insn->dst_reg); 7190 break; 7191 } 7192 if (alu32) 7193 scalar32_min_max_arsh(dst_reg, &src_reg); 7194 else 7195 scalar_min_max_arsh(dst_reg, &src_reg); 7196 break; 7197 default: 7198 mark_reg_unknown(env, regs, insn->dst_reg); 7199 break; 7200 } 7201 7202 /* ALU32 ops are zero extended into 64bit register */ 7203 if (alu32) 7204 zext_32_to_64(dst_reg); 7205 7206 __update_reg_bounds(dst_reg); 7207 __reg_deduce_bounds(dst_reg); 7208 __reg_bound_offset(dst_reg); 7209 return 0; 7210 } 7211 7212 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 7213 * and var_off. 7214 */ 7215 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 7216 struct bpf_insn *insn) 7217 { 7218 struct bpf_verifier_state *vstate = env->cur_state; 7219 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7220 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 7221 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 7222 u8 opcode = BPF_OP(insn->code); 7223 int err; 7224 7225 dst_reg = ®s[insn->dst_reg]; 7226 src_reg = NULL; 7227 if (dst_reg->type != SCALAR_VALUE) 7228 ptr_reg = dst_reg; 7229 else 7230 /* Make sure ID is cleared otherwise dst_reg min/max could be 7231 * incorrectly propagated into other registers by find_equal_scalars() 7232 */ 7233 dst_reg->id = 0; 7234 if (BPF_SRC(insn->code) == BPF_X) { 7235 src_reg = ®s[insn->src_reg]; 7236 if (src_reg->type != SCALAR_VALUE) { 7237 if (dst_reg->type != SCALAR_VALUE) { 7238 /* Combining two pointers by any ALU op yields 7239 * an arbitrary scalar. Disallow all math except 7240 * pointer subtraction 7241 */ 7242 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 7243 mark_reg_unknown(env, regs, insn->dst_reg); 7244 return 0; 7245 } 7246 verbose(env, "R%d pointer %s pointer prohibited\n", 7247 insn->dst_reg, 7248 bpf_alu_string[opcode >> 4]); 7249 return -EACCES; 7250 } else { 7251 /* scalar += pointer 7252 * This is legal, but we have to reverse our 7253 * src/dest handling in computing the range 7254 */ 7255 err = mark_chain_precision(env, insn->dst_reg); 7256 if (err) 7257 return err; 7258 return adjust_ptr_min_max_vals(env, insn, 7259 src_reg, dst_reg); 7260 } 7261 } else if (ptr_reg) { 7262 /* pointer += scalar */ 7263 err = mark_chain_precision(env, insn->src_reg); 7264 if (err) 7265 return err; 7266 return adjust_ptr_min_max_vals(env, insn, 7267 dst_reg, src_reg); 7268 } 7269 } else { 7270 /* Pretend the src is a reg with a known value, since we only 7271 * need to be able to read from this state. 7272 */ 7273 off_reg.type = SCALAR_VALUE; 7274 __mark_reg_known(&off_reg, insn->imm); 7275 src_reg = &off_reg; 7276 if (ptr_reg) /* pointer += K */ 7277 return adjust_ptr_min_max_vals(env, insn, 7278 ptr_reg, src_reg); 7279 } 7280 7281 /* Got here implies adding two SCALAR_VALUEs */ 7282 if (WARN_ON_ONCE(ptr_reg)) { 7283 print_verifier_state(env, state); 7284 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 7285 return -EINVAL; 7286 } 7287 if (WARN_ON(!src_reg)) { 7288 print_verifier_state(env, state); 7289 verbose(env, "verifier internal error: no src_reg\n"); 7290 return -EINVAL; 7291 } 7292 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 7293 } 7294 7295 /* check validity of 32-bit and 64-bit arithmetic operations */ 7296 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 7297 { 7298 struct bpf_reg_state *regs = cur_regs(env); 7299 u8 opcode = BPF_OP(insn->code); 7300 int err; 7301 7302 if (opcode == BPF_END || opcode == BPF_NEG) { 7303 if (opcode == BPF_NEG) { 7304 if (BPF_SRC(insn->code) != 0 || 7305 insn->src_reg != BPF_REG_0 || 7306 insn->off != 0 || insn->imm != 0) { 7307 verbose(env, "BPF_NEG uses reserved fields\n"); 7308 return -EINVAL; 7309 } 7310 } else { 7311 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 7312 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 7313 BPF_CLASS(insn->code) == BPF_ALU64) { 7314 verbose(env, "BPF_END uses reserved fields\n"); 7315 return -EINVAL; 7316 } 7317 } 7318 7319 /* check src operand */ 7320 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7321 if (err) 7322 return err; 7323 7324 if (is_pointer_value(env, insn->dst_reg)) { 7325 verbose(env, "R%d pointer arithmetic prohibited\n", 7326 insn->dst_reg); 7327 return -EACCES; 7328 } 7329 7330 /* check dest operand */ 7331 err = check_reg_arg(env, insn->dst_reg, DST_OP); 7332 if (err) 7333 return err; 7334 7335 } else if (opcode == BPF_MOV) { 7336 7337 if (BPF_SRC(insn->code) == BPF_X) { 7338 if (insn->imm != 0 || insn->off != 0) { 7339 verbose(env, "BPF_MOV uses reserved fields\n"); 7340 return -EINVAL; 7341 } 7342 7343 /* check src operand */ 7344 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7345 if (err) 7346 return err; 7347 } else { 7348 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 7349 verbose(env, "BPF_MOV uses reserved fields\n"); 7350 return -EINVAL; 7351 } 7352 } 7353 7354 /* check dest operand, mark as required later */ 7355 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 7356 if (err) 7357 return err; 7358 7359 if (BPF_SRC(insn->code) == BPF_X) { 7360 struct bpf_reg_state *src_reg = regs + insn->src_reg; 7361 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 7362 7363 if (BPF_CLASS(insn->code) == BPF_ALU64) { 7364 /* case: R1 = R2 7365 * copy register state to dest reg 7366 */ 7367 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 7368 /* Assign src and dst registers the same ID 7369 * that will be used by find_equal_scalars() 7370 * to propagate min/max range. 7371 */ 7372 src_reg->id = ++env->id_gen; 7373 *dst_reg = *src_reg; 7374 dst_reg->live |= REG_LIVE_WRITTEN; 7375 dst_reg->subreg_def = DEF_NOT_SUBREG; 7376 } else { 7377 /* R1 = (u32) R2 */ 7378 if (is_pointer_value(env, insn->src_reg)) { 7379 verbose(env, 7380 "R%d partial copy of pointer\n", 7381 insn->src_reg); 7382 return -EACCES; 7383 } else if (src_reg->type == SCALAR_VALUE) { 7384 *dst_reg = *src_reg; 7385 /* Make sure ID is cleared otherwise 7386 * dst_reg min/max could be incorrectly 7387 * propagated into src_reg by find_equal_scalars() 7388 */ 7389 dst_reg->id = 0; 7390 dst_reg->live |= REG_LIVE_WRITTEN; 7391 dst_reg->subreg_def = env->insn_idx + 1; 7392 } else { 7393 mark_reg_unknown(env, regs, 7394 insn->dst_reg); 7395 } 7396 zext_32_to_64(dst_reg); 7397 } 7398 } else { 7399 /* case: R = imm 7400 * remember the value we stored into this reg 7401 */ 7402 /* clear any state __mark_reg_known doesn't set */ 7403 mark_reg_unknown(env, regs, insn->dst_reg); 7404 regs[insn->dst_reg].type = SCALAR_VALUE; 7405 if (BPF_CLASS(insn->code) == BPF_ALU64) { 7406 __mark_reg_known(regs + insn->dst_reg, 7407 insn->imm); 7408 } else { 7409 __mark_reg_known(regs + insn->dst_reg, 7410 (u32)insn->imm); 7411 } 7412 } 7413 7414 } else if (opcode > BPF_END) { 7415 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 7416 return -EINVAL; 7417 7418 } else { /* all other ALU ops: and, sub, xor, add, ... */ 7419 7420 if (BPF_SRC(insn->code) == BPF_X) { 7421 if (insn->imm != 0 || insn->off != 0) { 7422 verbose(env, "BPF_ALU uses reserved fields\n"); 7423 return -EINVAL; 7424 } 7425 /* check src1 operand */ 7426 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7427 if (err) 7428 return err; 7429 } else { 7430 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 7431 verbose(env, "BPF_ALU uses reserved fields\n"); 7432 return -EINVAL; 7433 } 7434 } 7435 7436 /* check src2 operand */ 7437 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7438 if (err) 7439 return err; 7440 7441 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 7442 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 7443 verbose(env, "div by zero\n"); 7444 return -EINVAL; 7445 } 7446 7447 if ((opcode == BPF_LSH || opcode == BPF_RSH || 7448 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 7449 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 7450 7451 if (insn->imm < 0 || insn->imm >= size) { 7452 verbose(env, "invalid shift %d\n", insn->imm); 7453 return -EINVAL; 7454 } 7455 } 7456 7457 /* check dest operand */ 7458 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 7459 if (err) 7460 return err; 7461 7462 return adjust_reg_min_max_vals(env, insn); 7463 } 7464 7465 return 0; 7466 } 7467 7468 static void __find_good_pkt_pointers(struct bpf_func_state *state, 7469 struct bpf_reg_state *dst_reg, 7470 enum bpf_reg_type type, int new_range) 7471 { 7472 struct bpf_reg_state *reg; 7473 int i; 7474 7475 for (i = 0; i < MAX_BPF_REG; i++) { 7476 reg = &state->regs[i]; 7477 if (reg->type == type && reg->id == dst_reg->id) 7478 /* keep the maximum range already checked */ 7479 reg->range = max(reg->range, new_range); 7480 } 7481 7482 bpf_for_each_spilled_reg(i, state, reg) { 7483 if (!reg) 7484 continue; 7485 if (reg->type == type && reg->id == dst_reg->id) 7486 reg->range = max(reg->range, new_range); 7487 } 7488 } 7489 7490 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 7491 struct bpf_reg_state *dst_reg, 7492 enum bpf_reg_type type, 7493 bool range_right_open) 7494 { 7495 int new_range, i; 7496 7497 if (dst_reg->off < 0 || 7498 (dst_reg->off == 0 && range_right_open)) 7499 /* This doesn't give us any range */ 7500 return; 7501 7502 if (dst_reg->umax_value > MAX_PACKET_OFF || 7503 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 7504 /* Risk of overflow. For instance, ptr + (1<<63) may be less 7505 * than pkt_end, but that's because it's also less than pkt. 7506 */ 7507 return; 7508 7509 new_range = dst_reg->off; 7510 if (range_right_open) 7511 new_range--; 7512 7513 /* Examples for register markings: 7514 * 7515 * pkt_data in dst register: 7516 * 7517 * r2 = r3; 7518 * r2 += 8; 7519 * if (r2 > pkt_end) goto <handle exception> 7520 * <access okay> 7521 * 7522 * r2 = r3; 7523 * r2 += 8; 7524 * if (r2 < pkt_end) goto <access okay> 7525 * <handle exception> 7526 * 7527 * Where: 7528 * r2 == dst_reg, pkt_end == src_reg 7529 * r2=pkt(id=n,off=8,r=0) 7530 * r3=pkt(id=n,off=0,r=0) 7531 * 7532 * pkt_data in src register: 7533 * 7534 * r2 = r3; 7535 * r2 += 8; 7536 * if (pkt_end >= r2) goto <access okay> 7537 * <handle exception> 7538 * 7539 * r2 = r3; 7540 * r2 += 8; 7541 * if (pkt_end <= r2) goto <handle exception> 7542 * <access okay> 7543 * 7544 * Where: 7545 * pkt_end == dst_reg, r2 == src_reg 7546 * r2=pkt(id=n,off=8,r=0) 7547 * r3=pkt(id=n,off=0,r=0) 7548 * 7549 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 7550 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 7551 * and [r3, r3 + 8-1) respectively is safe to access depending on 7552 * the check. 7553 */ 7554 7555 /* If our ids match, then we must have the same max_value. And we 7556 * don't care about the other reg's fixed offset, since if it's too big 7557 * the range won't allow anything. 7558 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 7559 */ 7560 for (i = 0; i <= vstate->curframe; i++) 7561 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type, 7562 new_range); 7563 } 7564 7565 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 7566 { 7567 struct tnum subreg = tnum_subreg(reg->var_off); 7568 s32 sval = (s32)val; 7569 7570 switch (opcode) { 7571 case BPF_JEQ: 7572 if (tnum_is_const(subreg)) 7573 return !!tnum_equals_const(subreg, val); 7574 break; 7575 case BPF_JNE: 7576 if (tnum_is_const(subreg)) 7577 return !tnum_equals_const(subreg, val); 7578 break; 7579 case BPF_JSET: 7580 if ((~subreg.mask & subreg.value) & val) 7581 return 1; 7582 if (!((subreg.mask | subreg.value) & val)) 7583 return 0; 7584 break; 7585 case BPF_JGT: 7586 if (reg->u32_min_value > val) 7587 return 1; 7588 else if (reg->u32_max_value <= val) 7589 return 0; 7590 break; 7591 case BPF_JSGT: 7592 if (reg->s32_min_value > sval) 7593 return 1; 7594 else if (reg->s32_max_value <= sval) 7595 return 0; 7596 break; 7597 case BPF_JLT: 7598 if (reg->u32_max_value < val) 7599 return 1; 7600 else if (reg->u32_min_value >= val) 7601 return 0; 7602 break; 7603 case BPF_JSLT: 7604 if (reg->s32_max_value < sval) 7605 return 1; 7606 else if (reg->s32_min_value >= sval) 7607 return 0; 7608 break; 7609 case BPF_JGE: 7610 if (reg->u32_min_value >= val) 7611 return 1; 7612 else if (reg->u32_max_value < val) 7613 return 0; 7614 break; 7615 case BPF_JSGE: 7616 if (reg->s32_min_value >= sval) 7617 return 1; 7618 else if (reg->s32_max_value < sval) 7619 return 0; 7620 break; 7621 case BPF_JLE: 7622 if (reg->u32_max_value <= val) 7623 return 1; 7624 else if (reg->u32_min_value > val) 7625 return 0; 7626 break; 7627 case BPF_JSLE: 7628 if (reg->s32_max_value <= sval) 7629 return 1; 7630 else if (reg->s32_min_value > sval) 7631 return 0; 7632 break; 7633 } 7634 7635 return -1; 7636 } 7637 7638 7639 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 7640 { 7641 s64 sval = (s64)val; 7642 7643 switch (opcode) { 7644 case BPF_JEQ: 7645 if (tnum_is_const(reg->var_off)) 7646 return !!tnum_equals_const(reg->var_off, val); 7647 break; 7648 case BPF_JNE: 7649 if (tnum_is_const(reg->var_off)) 7650 return !tnum_equals_const(reg->var_off, val); 7651 break; 7652 case BPF_JSET: 7653 if ((~reg->var_off.mask & reg->var_off.value) & val) 7654 return 1; 7655 if (!((reg->var_off.mask | reg->var_off.value) & val)) 7656 return 0; 7657 break; 7658 case BPF_JGT: 7659 if (reg->umin_value > val) 7660 return 1; 7661 else if (reg->umax_value <= val) 7662 return 0; 7663 break; 7664 case BPF_JSGT: 7665 if (reg->smin_value > sval) 7666 return 1; 7667 else if (reg->smax_value <= sval) 7668 return 0; 7669 break; 7670 case BPF_JLT: 7671 if (reg->umax_value < val) 7672 return 1; 7673 else if (reg->umin_value >= val) 7674 return 0; 7675 break; 7676 case BPF_JSLT: 7677 if (reg->smax_value < sval) 7678 return 1; 7679 else if (reg->smin_value >= sval) 7680 return 0; 7681 break; 7682 case BPF_JGE: 7683 if (reg->umin_value >= val) 7684 return 1; 7685 else if (reg->umax_value < val) 7686 return 0; 7687 break; 7688 case BPF_JSGE: 7689 if (reg->smin_value >= sval) 7690 return 1; 7691 else if (reg->smax_value < sval) 7692 return 0; 7693 break; 7694 case BPF_JLE: 7695 if (reg->umax_value <= val) 7696 return 1; 7697 else if (reg->umin_value > val) 7698 return 0; 7699 break; 7700 case BPF_JSLE: 7701 if (reg->smax_value <= sval) 7702 return 1; 7703 else if (reg->smin_value > sval) 7704 return 0; 7705 break; 7706 } 7707 7708 return -1; 7709 } 7710 7711 /* compute branch direction of the expression "if (reg opcode val) goto target;" 7712 * and return: 7713 * 1 - branch will be taken and "goto target" will be executed 7714 * 0 - branch will not be taken and fall-through to next insn 7715 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 7716 * range [0,10] 7717 */ 7718 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 7719 bool is_jmp32) 7720 { 7721 if (__is_pointer_value(false, reg)) { 7722 if (!reg_type_not_null(reg->type)) 7723 return -1; 7724 7725 /* If pointer is valid tests against zero will fail so we can 7726 * use this to direct branch taken. 7727 */ 7728 if (val != 0) 7729 return -1; 7730 7731 switch (opcode) { 7732 case BPF_JEQ: 7733 return 0; 7734 case BPF_JNE: 7735 return 1; 7736 default: 7737 return -1; 7738 } 7739 } 7740 7741 if (is_jmp32) 7742 return is_branch32_taken(reg, val, opcode); 7743 return is_branch64_taken(reg, val, opcode); 7744 } 7745 7746 static int flip_opcode(u32 opcode) 7747 { 7748 /* How can we transform "a <op> b" into "b <op> a"? */ 7749 static const u8 opcode_flip[16] = { 7750 /* these stay the same */ 7751 [BPF_JEQ >> 4] = BPF_JEQ, 7752 [BPF_JNE >> 4] = BPF_JNE, 7753 [BPF_JSET >> 4] = BPF_JSET, 7754 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 7755 [BPF_JGE >> 4] = BPF_JLE, 7756 [BPF_JGT >> 4] = BPF_JLT, 7757 [BPF_JLE >> 4] = BPF_JGE, 7758 [BPF_JLT >> 4] = BPF_JGT, 7759 [BPF_JSGE >> 4] = BPF_JSLE, 7760 [BPF_JSGT >> 4] = BPF_JSLT, 7761 [BPF_JSLE >> 4] = BPF_JSGE, 7762 [BPF_JSLT >> 4] = BPF_JSGT 7763 }; 7764 return opcode_flip[opcode >> 4]; 7765 } 7766 7767 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 7768 struct bpf_reg_state *src_reg, 7769 u8 opcode) 7770 { 7771 struct bpf_reg_state *pkt; 7772 7773 if (src_reg->type == PTR_TO_PACKET_END) { 7774 pkt = dst_reg; 7775 } else if (dst_reg->type == PTR_TO_PACKET_END) { 7776 pkt = src_reg; 7777 opcode = flip_opcode(opcode); 7778 } else { 7779 return -1; 7780 } 7781 7782 if (pkt->range >= 0) 7783 return -1; 7784 7785 switch (opcode) { 7786 case BPF_JLE: 7787 /* pkt <= pkt_end */ 7788 fallthrough; 7789 case BPF_JGT: 7790 /* pkt > pkt_end */ 7791 if (pkt->range == BEYOND_PKT_END) 7792 /* pkt has at last one extra byte beyond pkt_end */ 7793 return opcode == BPF_JGT; 7794 break; 7795 case BPF_JLT: 7796 /* pkt < pkt_end */ 7797 fallthrough; 7798 case BPF_JGE: 7799 /* pkt >= pkt_end */ 7800 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 7801 return opcode == BPF_JGE; 7802 break; 7803 } 7804 return -1; 7805 } 7806 7807 /* Adjusts the register min/max values in the case that the dst_reg is the 7808 * variable register that we are working on, and src_reg is a constant or we're 7809 * simply doing a BPF_K check. 7810 * In JEQ/JNE cases we also adjust the var_off values. 7811 */ 7812 static void reg_set_min_max(struct bpf_reg_state *true_reg, 7813 struct bpf_reg_state *false_reg, 7814 u64 val, u32 val32, 7815 u8 opcode, bool is_jmp32) 7816 { 7817 struct tnum false_32off = tnum_subreg(false_reg->var_off); 7818 struct tnum false_64off = false_reg->var_off; 7819 struct tnum true_32off = tnum_subreg(true_reg->var_off); 7820 struct tnum true_64off = true_reg->var_off; 7821 s64 sval = (s64)val; 7822 s32 sval32 = (s32)val32; 7823 7824 /* If the dst_reg is a pointer, we can't learn anything about its 7825 * variable offset from the compare (unless src_reg were a pointer into 7826 * the same object, but we don't bother with that. 7827 * Since false_reg and true_reg have the same type by construction, we 7828 * only need to check one of them for pointerness. 7829 */ 7830 if (__is_pointer_value(false, false_reg)) 7831 return; 7832 7833 switch (opcode) { 7834 case BPF_JEQ: 7835 case BPF_JNE: 7836 { 7837 struct bpf_reg_state *reg = 7838 opcode == BPF_JEQ ? true_reg : false_reg; 7839 7840 /* JEQ/JNE comparison doesn't change the register equivalence. 7841 * r1 = r2; 7842 * if (r1 == 42) goto label; 7843 * ... 7844 * label: // here both r1 and r2 are known to be 42. 7845 * 7846 * Hence when marking register as known preserve it's ID. 7847 */ 7848 if (is_jmp32) 7849 __mark_reg32_known(reg, val32); 7850 else 7851 ___mark_reg_known(reg, val); 7852 break; 7853 } 7854 case BPF_JSET: 7855 if (is_jmp32) { 7856 false_32off = tnum_and(false_32off, tnum_const(~val32)); 7857 if (is_power_of_2(val32)) 7858 true_32off = tnum_or(true_32off, 7859 tnum_const(val32)); 7860 } else { 7861 false_64off = tnum_and(false_64off, tnum_const(~val)); 7862 if (is_power_of_2(val)) 7863 true_64off = tnum_or(true_64off, 7864 tnum_const(val)); 7865 } 7866 break; 7867 case BPF_JGE: 7868 case BPF_JGT: 7869 { 7870 if (is_jmp32) { 7871 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 7872 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 7873 7874 false_reg->u32_max_value = min(false_reg->u32_max_value, 7875 false_umax); 7876 true_reg->u32_min_value = max(true_reg->u32_min_value, 7877 true_umin); 7878 } else { 7879 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 7880 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 7881 7882 false_reg->umax_value = min(false_reg->umax_value, false_umax); 7883 true_reg->umin_value = max(true_reg->umin_value, true_umin); 7884 } 7885 break; 7886 } 7887 case BPF_JSGE: 7888 case BPF_JSGT: 7889 { 7890 if (is_jmp32) { 7891 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 7892 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 7893 7894 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 7895 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 7896 } else { 7897 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 7898 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 7899 7900 false_reg->smax_value = min(false_reg->smax_value, false_smax); 7901 true_reg->smin_value = max(true_reg->smin_value, true_smin); 7902 } 7903 break; 7904 } 7905 case BPF_JLE: 7906 case BPF_JLT: 7907 { 7908 if (is_jmp32) { 7909 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 7910 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 7911 7912 false_reg->u32_min_value = max(false_reg->u32_min_value, 7913 false_umin); 7914 true_reg->u32_max_value = min(true_reg->u32_max_value, 7915 true_umax); 7916 } else { 7917 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 7918 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 7919 7920 false_reg->umin_value = max(false_reg->umin_value, false_umin); 7921 true_reg->umax_value = min(true_reg->umax_value, true_umax); 7922 } 7923 break; 7924 } 7925 case BPF_JSLE: 7926 case BPF_JSLT: 7927 { 7928 if (is_jmp32) { 7929 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 7930 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 7931 7932 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 7933 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 7934 } else { 7935 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 7936 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 7937 7938 false_reg->smin_value = max(false_reg->smin_value, false_smin); 7939 true_reg->smax_value = min(true_reg->smax_value, true_smax); 7940 } 7941 break; 7942 } 7943 default: 7944 return; 7945 } 7946 7947 if (is_jmp32) { 7948 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 7949 tnum_subreg(false_32off)); 7950 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 7951 tnum_subreg(true_32off)); 7952 __reg_combine_32_into_64(false_reg); 7953 __reg_combine_32_into_64(true_reg); 7954 } else { 7955 false_reg->var_off = false_64off; 7956 true_reg->var_off = true_64off; 7957 __reg_combine_64_into_32(false_reg); 7958 __reg_combine_64_into_32(true_reg); 7959 } 7960 } 7961 7962 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 7963 * the variable reg. 7964 */ 7965 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 7966 struct bpf_reg_state *false_reg, 7967 u64 val, u32 val32, 7968 u8 opcode, bool is_jmp32) 7969 { 7970 opcode = flip_opcode(opcode); 7971 /* This uses zero as "not present in table"; luckily the zero opcode, 7972 * BPF_JA, can't get here. 7973 */ 7974 if (opcode) 7975 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 7976 } 7977 7978 /* Regs are known to be equal, so intersect their min/max/var_off */ 7979 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 7980 struct bpf_reg_state *dst_reg) 7981 { 7982 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 7983 dst_reg->umin_value); 7984 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 7985 dst_reg->umax_value); 7986 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 7987 dst_reg->smin_value); 7988 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 7989 dst_reg->smax_value); 7990 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 7991 dst_reg->var_off); 7992 /* We might have learned new bounds from the var_off. */ 7993 __update_reg_bounds(src_reg); 7994 __update_reg_bounds(dst_reg); 7995 /* We might have learned something about the sign bit. */ 7996 __reg_deduce_bounds(src_reg); 7997 __reg_deduce_bounds(dst_reg); 7998 /* We might have learned some bits from the bounds. */ 7999 __reg_bound_offset(src_reg); 8000 __reg_bound_offset(dst_reg); 8001 /* Intersecting with the old var_off might have improved our bounds 8002 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 8003 * then new var_off is (0; 0x7f...fc) which improves our umax. 8004 */ 8005 __update_reg_bounds(src_reg); 8006 __update_reg_bounds(dst_reg); 8007 } 8008 8009 static void reg_combine_min_max(struct bpf_reg_state *true_src, 8010 struct bpf_reg_state *true_dst, 8011 struct bpf_reg_state *false_src, 8012 struct bpf_reg_state *false_dst, 8013 u8 opcode) 8014 { 8015 switch (opcode) { 8016 case BPF_JEQ: 8017 __reg_combine_min_max(true_src, true_dst); 8018 break; 8019 case BPF_JNE: 8020 __reg_combine_min_max(false_src, false_dst); 8021 break; 8022 } 8023 } 8024 8025 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 8026 struct bpf_reg_state *reg, u32 id, 8027 bool is_null) 8028 { 8029 if (reg_type_may_be_null(reg->type) && reg->id == id && 8030 !WARN_ON_ONCE(!reg->id)) { 8031 /* Old offset (both fixed and variable parts) should 8032 * have been known-zero, because we don't allow pointer 8033 * arithmetic on pointers that might be NULL. 8034 */ 8035 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || 8036 !tnum_equals_const(reg->var_off, 0) || 8037 reg->off)) { 8038 __mark_reg_known_zero(reg); 8039 reg->off = 0; 8040 } 8041 if (is_null) { 8042 reg->type = SCALAR_VALUE; 8043 /* We don't need id and ref_obj_id from this point 8044 * onwards anymore, thus we should better reset it, 8045 * so that state pruning has chances to take effect. 8046 */ 8047 reg->id = 0; 8048 reg->ref_obj_id = 0; 8049 8050 return; 8051 } 8052 8053 mark_ptr_not_null_reg(reg); 8054 8055 if (!reg_may_point_to_spin_lock(reg)) { 8056 /* For not-NULL ptr, reg->ref_obj_id will be reset 8057 * in release_reg_references(). 8058 * 8059 * reg->id is still used by spin_lock ptr. Other 8060 * than spin_lock ptr type, reg->id can be reset. 8061 */ 8062 reg->id = 0; 8063 } 8064 } 8065 } 8066 8067 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id, 8068 bool is_null) 8069 { 8070 struct bpf_reg_state *reg; 8071 int i; 8072 8073 for (i = 0; i < MAX_BPF_REG; i++) 8074 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null); 8075 8076 bpf_for_each_spilled_reg(i, state, reg) { 8077 if (!reg) 8078 continue; 8079 mark_ptr_or_null_reg(state, reg, id, is_null); 8080 } 8081 } 8082 8083 /* The logic is similar to find_good_pkt_pointers(), both could eventually 8084 * be folded together at some point. 8085 */ 8086 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 8087 bool is_null) 8088 { 8089 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8090 struct bpf_reg_state *regs = state->regs; 8091 u32 ref_obj_id = regs[regno].ref_obj_id; 8092 u32 id = regs[regno].id; 8093 int i; 8094 8095 if (ref_obj_id && ref_obj_id == id && is_null) 8096 /* regs[regno] is in the " == NULL" branch. 8097 * No one could have freed the reference state before 8098 * doing the NULL check. 8099 */ 8100 WARN_ON_ONCE(release_reference_state(state, id)); 8101 8102 for (i = 0; i <= vstate->curframe; i++) 8103 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null); 8104 } 8105 8106 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 8107 struct bpf_reg_state *dst_reg, 8108 struct bpf_reg_state *src_reg, 8109 struct bpf_verifier_state *this_branch, 8110 struct bpf_verifier_state *other_branch) 8111 { 8112 if (BPF_SRC(insn->code) != BPF_X) 8113 return false; 8114 8115 /* Pointers are always 64-bit. */ 8116 if (BPF_CLASS(insn->code) == BPF_JMP32) 8117 return false; 8118 8119 switch (BPF_OP(insn->code)) { 8120 case BPF_JGT: 8121 if ((dst_reg->type == PTR_TO_PACKET && 8122 src_reg->type == PTR_TO_PACKET_END) || 8123 (dst_reg->type == PTR_TO_PACKET_META && 8124 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8125 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 8126 find_good_pkt_pointers(this_branch, dst_reg, 8127 dst_reg->type, false); 8128 mark_pkt_end(other_branch, insn->dst_reg, true); 8129 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8130 src_reg->type == PTR_TO_PACKET) || 8131 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8132 src_reg->type == PTR_TO_PACKET_META)) { 8133 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 8134 find_good_pkt_pointers(other_branch, src_reg, 8135 src_reg->type, true); 8136 mark_pkt_end(this_branch, insn->src_reg, false); 8137 } else { 8138 return false; 8139 } 8140 break; 8141 case BPF_JLT: 8142 if ((dst_reg->type == PTR_TO_PACKET && 8143 src_reg->type == PTR_TO_PACKET_END) || 8144 (dst_reg->type == PTR_TO_PACKET_META && 8145 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8146 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 8147 find_good_pkt_pointers(other_branch, dst_reg, 8148 dst_reg->type, true); 8149 mark_pkt_end(this_branch, insn->dst_reg, false); 8150 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8151 src_reg->type == PTR_TO_PACKET) || 8152 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8153 src_reg->type == PTR_TO_PACKET_META)) { 8154 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 8155 find_good_pkt_pointers(this_branch, src_reg, 8156 src_reg->type, false); 8157 mark_pkt_end(other_branch, insn->src_reg, true); 8158 } else { 8159 return false; 8160 } 8161 break; 8162 case BPF_JGE: 8163 if ((dst_reg->type == PTR_TO_PACKET && 8164 src_reg->type == PTR_TO_PACKET_END) || 8165 (dst_reg->type == PTR_TO_PACKET_META && 8166 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8167 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 8168 find_good_pkt_pointers(this_branch, dst_reg, 8169 dst_reg->type, true); 8170 mark_pkt_end(other_branch, insn->dst_reg, false); 8171 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8172 src_reg->type == PTR_TO_PACKET) || 8173 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8174 src_reg->type == PTR_TO_PACKET_META)) { 8175 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 8176 find_good_pkt_pointers(other_branch, src_reg, 8177 src_reg->type, false); 8178 mark_pkt_end(this_branch, insn->src_reg, true); 8179 } else { 8180 return false; 8181 } 8182 break; 8183 case BPF_JLE: 8184 if ((dst_reg->type == PTR_TO_PACKET && 8185 src_reg->type == PTR_TO_PACKET_END) || 8186 (dst_reg->type == PTR_TO_PACKET_META && 8187 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8188 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 8189 find_good_pkt_pointers(other_branch, dst_reg, 8190 dst_reg->type, false); 8191 mark_pkt_end(this_branch, insn->dst_reg, true); 8192 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8193 src_reg->type == PTR_TO_PACKET) || 8194 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8195 src_reg->type == PTR_TO_PACKET_META)) { 8196 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 8197 find_good_pkt_pointers(this_branch, src_reg, 8198 src_reg->type, true); 8199 mark_pkt_end(other_branch, insn->src_reg, false); 8200 } else { 8201 return false; 8202 } 8203 break; 8204 default: 8205 return false; 8206 } 8207 8208 return true; 8209 } 8210 8211 static void find_equal_scalars(struct bpf_verifier_state *vstate, 8212 struct bpf_reg_state *known_reg) 8213 { 8214 struct bpf_func_state *state; 8215 struct bpf_reg_state *reg; 8216 int i, j; 8217 8218 for (i = 0; i <= vstate->curframe; i++) { 8219 state = vstate->frame[i]; 8220 for (j = 0; j < MAX_BPF_REG; j++) { 8221 reg = &state->regs[j]; 8222 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 8223 *reg = *known_reg; 8224 } 8225 8226 bpf_for_each_spilled_reg(j, state, reg) { 8227 if (!reg) 8228 continue; 8229 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 8230 *reg = *known_reg; 8231 } 8232 } 8233 } 8234 8235 static int check_cond_jmp_op(struct bpf_verifier_env *env, 8236 struct bpf_insn *insn, int *insn_idx) 8237 { 8238 struct bpf_verifier_state *this_branch = env->cur_state; 8239 struct bpf_verifier_state *other_branch; 8240 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 8241 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 8242 u8 opcode = BPF_OP(insn->code); 8243 bool is_jmp32; 8244 int pred = -1; 8245 int err; 8246 8247 /* Only conditional jumps are expected to reach here. */ 8248 if (opcode == BPF_JA || opcode > BPF_JSLE) { 8249 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 8250 return -EINVAL; 8251 } 8252 8253 if (BPF_SRC(insn->code) == BPF_X) { 8254 if (insn->imm != 0) { 8255 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 8256 return -EINVAL; 8257 } 8258 8259 /* check src1 operand */ 8260 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8261 if (err) 8262 return err; 8263 8264 if (is_pointer_value(env, insn->src_reg)) { 8265 verbose(env, "R%d pointer comparison prohibited\n", 8266 insn->src_reg); 8267 return -EACCES; 8268 } 8269 src_reg = ®s[insn->src_reg]; 8270 } else { 8271 if (insn->src_reg != BPF_REG_0) { 8272 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 8273 return -EINVAL; 8274 } 8275 } 8276 8277 /* check src2 operand */ 8278 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8279 if (err) 8280 return err; 8281 8282 dst_reg = ®s[insn->dst_reg]; 8283 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 8284 8285 if (BPF_SRC(insn->code) == BPF_K) { 8286 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 8287 } else if (src_reg->type == SCALAR_VALUE && 8288 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 8289 pred = is_branch_taken(dst_reg, 8290 tnum_subreg(src_reg->var_off).value, 8291 opcode, 8292 is_jmp32); 8293 } else if (src_reg->type == SCALAR_VALUE && 8294 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 8295 pred = is_branch_taken(dst_reg, 8296 src_reg->var_off.value, 8297 opcode, 8298 is_jmp32); 8299 } else if (reg_is_pkt_pointer_any(dst_reg) && 8300 reg_is_pkt_pointer_any(src_reg) && 8301 !is_jmp32) { 8302 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 8303 } 8304 8305 if (pred >= 0) { 8306 /* If we get here with a dst_reg pointer type it is because 8307 * above is_branch_taken() special cased the 0 comparison. 8308 */ 8309 if (!__is_pointer_value(false, dst_reg)) 8310 err = mark_chain_precision(env, insn->dst_reg); 8311 if (BPF_SRC(insn->code) == BPF_X && !err && 8312 !__is_pointer_value(false, src_reg)) 8313 err = mark_chain_precision(env, insn->src_reg); 8314 if (err) 8315 return err; 8316 } 8317 if (pred == 1) { 8318 /* only follow the goto, ignore fall-through */ 8319 *insn_idx += insn->off; 8320 return 0; 8321 } else if (pred == 0) { 8322 /* only follow fall-through branch, since 8323 * that's where the program will go 8324 */ 8325 return 0; 8326 } 8327 8328 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 8329 false); 8330 if (!other_branch) 8331 return -EFAULT; 8332 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 8333 8334 /* detect if we are comparing against a constant value so we can adjust 8335 * our min/max values for our dst register. 8336 * this is only legit if both are scalars (or pointers to the same 8337 * object, I suppose, but we don't support that right now), because 8338 * otherwise the different base pointers mean the offsets aren't 8339 * comparable. 8340 */ 8341 if (BPF_SRC(insn->code) == BPF_X) { 8342 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 8343 8344 if (dst_reg->type == SCALAR_VALUE && 8345 src_reg->type == SCALAR_VALUE) { 8346 if (tnum_is_const(src_reg->var_off) || 8347 (is_jmp32 && 8348 tnum_is_const(tnum_subreg(src_reg->var_off)))) 8349 reg_set_min_max(&other_branch_regs[insn->dst_reg], 8350 dst_reg, 8351 src_reg->var_off.value, 8352 tnum_subreg(src_reg->var_off).value, 8353 opcode, is_jmp32); 8354 else if (tnum_is_const(dst_reg->var_off) || 8355 (is_jmp32 && 8356 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 8357 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 8358 src_reg, 8359 dst_reg->var_off.value, 8360 tnum_subreg(dst_reg->var_off).value, 8361 opcode, is_jmp32); 8362 else if (!is_jmp32 && 8363 (opcode == BPF_JEQ || opcode == BPF_JNE)) 8364 /* Comparing for equality, we can combine knowledge */ 8365 reg_combine_min_max(&other_branch_regs[insn->src_reg], 8366 &other_branch_regs[insn->dst_reg], 8367 src_reg, dst_reg, opcode); 8368 if (src_reg->id && 8369 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 8370 find_equal_scalars(this_branch, src_reg); 8371 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 8372 } 8373 8374 } 8375 } else if (dst_reg->type == SCALAR_VALUE) { 8376 reg_set_min_max(&other_branch_regs[insn->dst_reg], 8377 dst_reg, insn->imm, (u32)insn->imm, 8378 opcode, is_jmp32); 8379 } 8380 8381 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 8382 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 8383 find_equal_scalars(this_branch, dst_reg); 8384 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 8385 } 8386 8387 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 8388 * NOTE: these optimizations below are related with pointer comparison 8389 * which will never be JMP32. 8390 */ 8391 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 8392 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 8393 reg_type_may_be_null(dst_reg->type)) { 8394 /* Mark all identical registers in each branch as either 8395 * safe or unknown depending R == 0 or R != 0 conditional. 8396 */ 8397 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 8398 opcode == BPF_JNE); 8399 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 8400 opcode == BPF_JEQ); 8401 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 8402 this_branch, other_branch) && 8403 is_pointer_value(env, insn->dst_reg)) { 8404 verbose(env, "R%d pointer comparison prohibited\n", 8405 insn->dst_reg); 8406 return -EACCES; 8407 } 8408 if (env->log.level & BPF_LOG_LEVEL) 8409 print_verifier_state(env, this_branch->frame[this_branch->curframe]); 8410 return 0; 8411 } 8412 8413 /* verify BPF_LD_IMM64 instruction */ 8414 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 8415 { 8416 struct bpf_insn_aux_data *aux = cur_aux(env); 8417 struct bpf_reg_state *regs = cur_regs(env); 8418 struct bpf_reg_state *dst_reg; 8419 struct bpf_map *map; 8420 int err; 8421 8422 if (BPF_SIZE(insn->code) != BPF_DW) { 8423 verbose(env, "invalid BPF_LD_IMM insn\n"); 8424 return -EINVAL; 8425 } 8426 if (insn->off != 0) { 8427 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 8428 return -EINVAL; 8429 } 8430 8431 err = check_reg_arg(env, insn->dst_reg, DST_OP); 8432 if (err) 8433 return err; 8434 8435 dst_reg = ®s[insn->dst_reg]; 8436 if (insn->src_reg == 0) { 8437 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 8438 8439 dst_reg->type = SCALAR_VALUE; 8440 __mark_reg_known(®s[insn->dst_reg], imm); 8441 return 0; 8442 } 8443 8444 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 8445 mark_reg_known_zero(env, regs, insn->dst_reg); 8446 8447 dst_reg->type = aux->btf_var.reg_type; 8448 switch (dst_reg->type) { 8449 case PTR_TO_MEM: 8450 dst_reg->mem_size = aux->btf_var.mem_size; 8451 break; 8452 case PTR_TO_BTF_ID: 8453 case PTR_TO_PERCPU_BTF_ID: 8454 dst_reg->btf = aux->btf_var.btf; 8455 dst_reg->btf_id = aux->btf_var.btf_id; 8456 break; 8457 default: 8458 verbose(env, "bpf verifier is misconfigured\n"); 8459 return -EFAULT; 8460 } 8461 return 0; 8462 } 8463 8464 if (insn->src_reg == BPF_PSEUDO_FUNC) { 8465 struct bpf_prog_aux *aux = env->prog->aux; 8466 u32 subprogno = insn[1].imm; 8467 8468 if (!aux->func_info) { 8469 verbose(env, "missing btf func_info\n"); 8470 return -EINVAL; 8471 } 8472 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 8473 verbose(env, "callback function not static\n"); 8474 return -EINVAL; 8475 } 8476 8477 dst_reg->type = PTR_TO_FUNC; 8478 dst_reg->subprogno = subprogno; 8479 return 0; 8480 } 8481 8482 map = env->used_maps[aux->map_index]; 8483 mark_reg_known_zero(env, regs, insn->dst_reg); 8484 dst_reg->map_ptr = map; 8485 8486 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) { 8487 dst_reg->type = PTR_TO_MAP_VALUE; 8488 dst_reg->off = aux->map_off; 8489 if (map_value_has_spin_lock(map)) 8490 dst_reg->id = ++env->id_gen; 8491 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) { 8492 dst_reg->type = CONST_PTR_TO_MAP; 8493 } else { 8494 verbose(env, "bpf verifier is misconfigured\n"); 8495 return -EINVAL; 8496 } 8497 8498 return 0; 8499 } 8500 8501 static bool may_access_skb(enum bpf_prog_type type) 8502 { 8503 switch (type) { 8504 case BPF_PROG_TYPE_SOCKET_FILTER: 8505 case BPF_PROG_TYPE_SCHED_CLS: 8506 case BPF_PROG_TYPE_SCHED_ACT: 8507 return true; 8508 default: 8509 return false; 8510 } 8511 } 8512 8513 /* verify safety of LD_ABS|LD_IND instructions: 8514 * - they can only appear in the programs where ctx == skb 8515 * - since they are wrappers of function calls, they scratch R1-R5 registers, 8516 * preserve R6-R9, and store return value into R0 8517 * 8518 * Implicit input: 8519 * ctx == skb == R6 == CTX 8520 * 8521 * Explicit input: 8522 * SRC == any register 8523 * IMM == 32-bit immediate 8524 * 8525 * Output: 8526 * R0 - 8/16/32-bit skb data converted to cpu endianness 8527 */ 8528 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 8529 { 8530 struct bpf_reg_state *regs = cur_regs(env); 8531 static const int ctx_reg = BPF_REG_6; 8532 u8 mode = BPF_MODE(insn->code); 8533 int i, err; 8534 8535 if (!may_access_skb(resolve_prog_type(env->prog))) { 8536 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 8537 return -EINVAL; 8538 } 8539 8540 if (!env->ops->gen_ld_abs) { 8541 verbose(env, "bpf verifier is misconfigured\n"); 8542 return -EINVAL; 8543 } 8544 8545 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 8546 BPF_SIZE(insn->code) == BPF_DW || 8547 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 8548 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 8549 return -EINVAL; 8550 } 8551 8552 /* check whether implicit source operand (register R6) is readable */ 8553 err = check_reg_arg(env, ctx_reg, SRC_OP); 8554 if (err) 8555 return err; 8556 8557 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 8558 * gen_ld_abs() may terminate the program at runtime, leading to 8559 * reference leak. 8560 */ 8561 err = check_reference_leak(env); 8562 if (err) { 8563 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 8564 return err; 8565 } 8566 8567 if (env->cur_state->active_spin_lock) { 8568 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 8569 return -EINVAL; 8570 } 8571 8572 if (regs[ctx_reg].type != PTR_TO_CTX) { 8573 verbose(env, 8574 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 8575 return -EINVAL; 8576 } 8577 8578 if (mode == BPF_IND) { 8579 /* check explicit source operand */ 8580 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8581 if (err) 8582 return err; 8583 } 8584 8585 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg); 8586 if (err < 0) 8587 return err; 8588 8589 /* reset caller saved regs to unreadable */ 8590 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8591 mark_reg_not_init(env, regs, caller_saved[i]); 8592 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8593 } 8594 8595 /* mark destination R0 register as readable, since it contains 8596 * the value fetched from the packet. 8597 * Already marked as written above. 8598 */ 8599 mark_reg_unknown(env, regs, BPF_REG_0); 8600 /* ld_abs load up to 32-bit skb data. */ 8601 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 8602 return 0; 8603 } 8604 8605 static int check_return_code(struct bpf_verifier_env *env) 8606 { 8607 struct tnum enforce_attach_type_range = tnum_unknown; 8608 const struct bpf_prog *prog = env->prog; 8609 struct bpf_reg_state *reg; 8610 struct tnum range = tnum_range(0, 1); 8611 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 8612 int err; 8613 const bool is_subprog = env->cur_state->frame[0]->subprogno; 8614 8615 /* LSM and struct_ops func-ptr's return type could be "void" */ 8616 if (!is_subprog && 8617 (prog_type == BPF_PROG_TYPE_STRUCT_OPS || 8618 prog_type == BPF_PROG_TYPE_LSM) && 8619 !prog->aux->attach_func_proto->type) 8620 return 0; 8621 8622 /* eBPF calling convetion is such that R0 is used 8623 * to return the value from eBPF program. 8624 * Make sure that it's readable at this time 8625 * of bpf_exit, which means that program wrote 8626 * something into it earlier 8627 */ 8628 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 8629 if (err) 8630 return err; 8631 8632 if (is_pointer_value(env, BPF_REG_0)) { 8633 verbose(env, "R0 leaks addr as return value\n"); 8634 return -EACCES; 8635 } 8636 8637 reg = cur_regs(env) + BPF_REG_0; 8638 if (is_subprog) { 8639 if (reg->type != SCALAR_VALUE) { 8640 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 8641 reg_type_str[reg->type]); 8642 return -EINVAL; 8643 } 8644 return 0; 8645 } 8646 8647 switch (prog_type) { 8648 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 8649 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 8650 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 8651 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 8652 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 8653 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 8654 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 8655 range = tnum_range(1, 1); 8656 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 8657 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 8658 range = tnum_range(0, 3); 8659 break; 8660 case BPF_PROG_TYPE_CGROUP_SKB: 8661 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 8662 range = tnum_range(0, 3); 8663 enforce_attach_type_range = tnum_range(2, 3); 8664 } 8665 break; 8666 case BPF_PROG_TYPE_CGROUP_SOCK: 8667 case BPF_PROG_TYPE_SOCK_OPS: 8668 case BPF_PROG_TYPE_CGROUP_DEVICE: 8669 case BPF_PROG_TYPE_CGROUP_SYSCTL: 8670 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 8671 break; 8672 case BPF_PROG_TYPE_RAW_TRACEPOINT: 8673 if (!env->prog->aux->attach_btf_id) 8674 return 0; 8675 range = tnum_const(0); 8676 break; 8677 case BPF_PROG_TYPE_TRACING: 8678 switch (env->prog->expected_attach_type) { 8679 case BPF_TRACE_FENTRY: 8680 case BPF_TRACE_FEXIT: 8681 range = tnum_const(0); 8682 break; 8683 case BPF_TRACE_RAW_TP: 8684 case BPF_MODIFY_RETURN: 8685 return 0; 8686 case BPF_TRACE_ITER: 8687 break; 8688 default: 8689 return -ENOTSUPP; 8690 } 8691 break; 8692 case BPF_PROG_TYPE_SK_LOOKUP: 8693 range = tnum_range(SK_DROP, SK_PASS); 8694 break; 8695 case BPF_PROG_TYPE_EXT: 8696 /* freplace program can return anything as its return value 8697 * depends on the to-be-replaced kernel func or bpf program. 8698 */ 8699 default: 8700 return 0; 8701 } 8702 8703 if (reg->type != SCALAR_VALUE) { 8704 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 8705 reg_type_str[reg->type]); 8706 return -EINVAL; 8707 } 8708 8709 if (!tnum_in(range, reg->var_off)) { 8710 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 8711 return -EINVAL; 8712 } 8713 8714 if (!tnum_is_unknown(enforce_attach_type_range) && 8715 tnum_in(enforce_attach_type_range, reg->var_off)) 8716 env->prog->enforce_expected_attach_type = 1; 8717 return 0; 8718 } 8719 8720 /* non-recursive DFS pseudo code 8721 * 1 procedure DFS-iterative(G,v): 8722 * 2 label v as discovered 8723 * 3 let S be a stack 8724 * 4 S.push(v) 8725 * 5 while S is not empty 8726 * 6 t <- S.pop() 8727 * 7 if t is what we're looking for: 8728 * 8 return t 8729 * 9 for all edges e in G.adjacentEdges(t) do 8730 * 10 if edge e is already labelled 8731 * 11 continue with the next edge 8732 * 12 w <- G.adjacentVertex(t,e) 8733 * 13 if vertex w is not discovered and not explored 8734 * 14 label e as tree-edge 8735 * 15 label w as discovered 8736 * 16 S.push(w) 8737 * 17 continue at 5 8738 * 18 else if vertex w is discovered 8739 * 19 label e as back-edge 8740 * 20 else 8741 * 21 // vertex w is explored 8742 * 22 label e as forward- or cross-edge 8743 * 23 label t as explored 8744 * 24 S.pop() 8745 * 8746 * convention: 8747 * 0x10 - discovered 8748 * 0x11 - discovered and fall-through edge labelled 8749 * 0x12 - discovered and fall-through and branch edges labelled 8750 * 0x20 - explored 8751 */ 8752 8753 enum { 8754 DISCOVERED = 0x10, 8755 EXPLORED = 0x20, 8756 FALLTHROUGH = 1, 8757 BRANCH = 2, 8758 }; 8759 8760 static u32 state_htab_size(struct bpf_verifier_env *env) 8761 { 8762 return env->prog->len; 8763 } 8764 8765 static struct bpf_verifier_state_list **explored_state( 8766 struct bpf_verifier_env *env, 8767 int idx) 8768 { 8769 struct bpf_verifier_state *cur = env->cur_state; 8770 struct bpf_func_state *state = cur->frame[cur->curframe]; 8771 8772 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 8773 } 8774 8775 static void init_explored_state(struct bpf_verifier_env *env, int idx) 8776 { 8777 env->insn_aux_data[idx].prune_point = true; 8778 } 8779 8780 enum { 8781 DONE_EXPLORING = 0, 8782 KEEP_EXPLORING = 1, 8783 }; 8784 8785 /* t, w, e - match pseudo-code above: 8786 * t - index of current instruction 8787 * w - next instruction 8788 * e - edge 8789 */ 8790 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 8791 bool loop_ok) 8792 { 8793 int *insn_stack = env->cfg.insn_stack; 8794 int *insn_state = env->cfg.insn_state; 8795 8796 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 8797 return DONE_EXPLORING; 8798 8799 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 8800 return DONE_EXPLORING; 8801 8802 if (w < 0 || w >= env->prog->len) { 8803 verbose_linfo(env, t, "%d: ", t); 8804 verbose(env, "jump out of range from insn %d to %d\n", t, w); 8805 return -EINVAL; 8806 } 8807 8808 if (e == BRANCH) 8809 /* mark branch target for state pruning */ 8810 init_explored_state(env, w); 8811 8812 if (insn_state[w] == 0) { 8813 /* tree-edge */ 8814 insn_state[t] = DISCOVERED | e; 8815 insn_state[w] = DISCOVERED; 8816 if (env->cfg.cur_stack >= env->prog->len) 8817 return -E2BIG; 8818 insn_stack[env->cfg.cur_stack++] = w; 8819 return KEEP_EXPLORING; 8820 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 8821 if (loop_ok && env->bpf_capable) 8822 return DONE_EXPLORING; 8823 verbose_linfo(env, t, "%d: ", t); 8824 verbose_linfo(env, w, "%d: ", w); 8825 verbose(env, "back-edge from insn %d to %d\n", t, w); 8826 return -EINVAL; 8827 } else if (insn_state[w] == EXPLORED) { 8828 /* forward- or cross-edge */ 8829 insn_state[t] = DISCOVERED | e; 8830 } else { 8831 verbose(env, "insn state internal bug\n"); 8832 return -EFAULT; 8833 } 8834 return DONE_EXPLORING; 8835 } 8836 8837 static int visit_func_call_insn(int t, int insn_cnt, 8838 struct bpf_insn *insns, 8839 struct bpf_verifier_env *env, 8840 bool visit_callee) 8841 { 8842 int ret; 8843 8844 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 8845 if (ret) 8846 return ret; 8847 8848 if (t + 1 < insn_cnt) 8849 init_explored_state(env, t + 1); 8850 if (visit_callee) { 8851 init_explored_state(env, t); 8852 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, 8853 env, false); 8854 } 8855 return ret; 8856 } 8857 8858 /* Visits the instruction at index t and returns one of the following: 8859 * < 0 - an error occurred 8860 * DONE_EXPLORING - the instruction was fully explored 8861 * KEEP_EXPLORING - there is still work to be done before it is fully explored 8862 */ 8863 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env) 8864 { 8865 struct bpf_insn *insns = env->prog->insnsi; 8866 int ret; 8867 8868 if (bpf_pseudo_func(insns + t)) 8869 return visit_func_call_insn(t, insn_cnt, insns, env, true); 8870 8871 /* All non-branch instructions have a single fall-through edge. */ 8872 if (BPF_CLASS(insns[t].code) != BPF_JMP && 8873 BPF_CLASS(insns[t].code) != BPF_JMP32) 8874 return push_insn(t, t + 1, FALLTHROUGH, env, false); 8875 8876 switch (BPF_OP(insns[t].code)) { 8877 case BPF_EXIT: 8878 return DONE_EXPLORING; 8879 8880 case BPF_CALL: 8881 return visit_func_call_insn(t, insn_cnt, insns, env, 8882 insns[t].src_reg == BPF_PSEUDO_CALL); 8883 8884 case BPF_JA: 8885 if (BPF_SRC(insns[t].code) != BPF_K) 8886 return -EINVAL; 8887 8888 /* unconditional jump with single edge */ 8889 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env, 8890 true); 8891 if (ret) 8892 return ret; 8893 8894 /* unconditional jmp is not a good pruning point, 8895 * but it's marked, since backtracking needs 8896 * to record jmp history in is_state_visited(). 8897 */ 8898 init_explored_state(env, t + insns[t].off + 1); 8899 /* tell verifier to check for equivalent states 8900 * after every call and jump 8901 */ 8902 if (t + 1 < insn_cnt) 8903 init_explored_state(env, t + 1); 8904 8905 return ret; 8906 8907 default: 8908 /* conditional jump with two edges */ 8909 init_explored_state(env, t); 8910 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 8911 if (ret) 8912 return ret; 8913 8914 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true); 8915 } 8916 } 8917 8918 /* non-recursive depth-first-search to detect loops in BPF program 8919 * loop == back-edge in directed graph 8920 */ 8921 static int check_cfg(struct bpf_verifier_env *env) 8922 { 8923 int insn_cnt = env->prog->len; 8924 int *insn_stack, *insn_state; 8925 int ret = 0; 8926 int i; 8927 8928 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 8929 if (!insn_state) 8930 return -ENOMEM; 8931 8932 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 8933 if (!insn_stack) { 8934 kvfree(insn_state); 8935 return -ENOMEM; 8936 } 8937 8938 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 8939 insn_stack[0] = 0; /* 0 is the first instruction */ 8940 env->cfg.cur_stack = 1; 8941 8942 while (env->cfg.cur_stack > 0) { 8943 int t = insn_stack[env->cfg.cur_stack - 1]; 8944 8945 ret = visit_insn(t, insn_cnt, env); 8946 switch (ret) { 8947 case DONE_EXPLORING: 8948 insn_state[t] = EXPLORED; 8949 env->cfg.cur_stack--; 8950 break; 8951 case KEEP_EXPLORING: 8952 break; 8953 default: 8954 if (ret > 0) { 8955 verbose(env, "visit_insn internal bug\n"); 8956 ret = -EFAULT; 8957 } 8958 goto err_free; 8959 } 8960 } 8961 8962 if (env->cfg.cur_stack < 0) { 8963 verbose(env, "pop stack internal bug\n"); 8964 ret = -EFAULT; 8965 goto err_free; 8966 } 8967 8968 for (i = 0; i < insn_cnt; i++) { 8969 if (insn_state[i] != EXPLORED) { 8970 verbose(env, "unreachable insn %d\n", i); 8971 ret = -EINVAL; 8972 goto err_free; 8973 } 8974 } 8975 ret = 0; /* cfg looks good */ 8976 8977 err_free: 8978 kvfree(insn_state); 8979 kvfree(insn_stack); 8980 env->cfg.insn_state = env->cfg.insn_stack = NULL; 8981 return ret; 8982 } 8983 8984 static int check_abnormal_return(struct bpf_verifier_env *env) 8985 { 8986 int i; 8987 8988 for (i = 1; i < env->subprog_cnt; i++) { 8989 if (env->subprog_info[i].has_ld_abs) { 8990 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 8991 return -EINVAL; 8992 } 8993 if (env->subprog_info[i].has_tail_call) { 8994 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 8995 return -EINVAL; 8996 } 8997 } 8998 return 0; 8999 } 9000 9001 /* The minimum supported BTF func info size */ 9002 #define MIN_BPF_FUNCINFO_SIZE 8 9003 #define MAX_FUNCINFO_REC_SIZE 252 9004 9005 static int check_btf_func(struct bpf_verifier_env *env, 9006 const union bpf_attr *attr, 9007 union bpf_attr __user *uattr) 9008 { 9009 const struct btf_type *type, *func_proto, *ret_type; 9010 u32 i, nfuncs, urec_size, min_size; 9011 u32 krec_size = sizeof(struct bpf_func_info); 9012 struct bpf_func_info *krecord; 9013 struct bpf_func_info_aux *info_aux = NULL; 9014 struct bpf_prog *prog; 9015 const struct btf *btf; 9016 void __user *urecord; 9017 u32 prev_offset = 0; 9018 bool scalar_return; 9019 int ret = -ENOMEM; 9020 9021 nfuncs = attr->func_info_cnt; 9022 if (!nfuncs) { 9023 if (check_abnormal_return(env)) 9024 return -EINVAL; 9025 return 0; 9026 } 9027 9028 if (nfuncs != env->subprog_cnt) { 9029 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 9030 return -EINVAL; 9031 } 9032 9033 urec_size = attr->func_info_rec_size; 9034 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 9035 urec_size > MAX_FUNCINFO_REC_SIZE || 9036 urec_size % sizeof(u32)) { 9037 verbose(env, "invalid func info rec size %u\n", urec_size); 9038 return -EINVAL; 9039 } 9040 9041 prog = env->prog; 9042 btf = prog->aux->btf; 9043 9044 urecord = u64_to_user_ptr(attr->func_info); 9045 min_size = min_t(u32, krec_size, urec_size); 9046 9047 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 9048 if (!krecord) 9049 return -ENOMEM; 9050 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 9051 if (!info_aux) 9052 goto err_free; 9053 9054 for (i = 0; i < nfuncs; i++) { 9055 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 9056 if (ret) { 9057 if (ret == -E2BIG) { 9058 verbose(env, "nonzero tailing record in func info"); 9059 /* set the size kernel expects so loader can zero 9060 * out the rest of the record. 9061 */ 9062 if (put_user(min_size, &uattr->func_info_rec_size)) 9063 ret = -EFAULT; 9064 } 9065 goto err_free; 9066 } 9067 9068 if (copy_from_user(&krecord[i], urecord, min_size)) { 9069 ret = -EFAULT; 9070 goto err_free; 9071 } 9072 9073 /* check insn_off */ 9074 ret = -EINVAL; 9075 if (i == 0) { 9076 if (krecord[i].insn_off) { 9077 verbose(env, 9078 "nonzero insn_off %u for the first func info record", 9079 krecord[i].insn_off); 9080 goto err_free; 9081 } 9082 } else if (krecord[i].insn_off <= prev_offset) { 9083 verbose(env, 9084 "same or smaller insn offset (%u) than previous func info record (%u)", 9085 krecord[i].insn_off, prev_offset); 9086 goto err_free; 9087 } 9088 9089 if (env->subprog_info[i].start != krecord[i].insn_off) { 9090 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 9091 goto err_free; 9092 } 9093 9094 /* check type_id */ 9095 type = btf_type_by_id(btf, krecord[i].type_id); 9096 if (!type || !btf_type_is_func(type)) { 9097 verbose(env, "invalid type id %d in func info", 9098 krecord[i].type_id); 9099 goto err_free; 9100 } 9101 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 9102 9103 func_proto = btf_type_by_id(btf, type->type); 9104 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 9105 /* btf_func_check() already verified it during BTF load */ 9106 goto err_free; 9107 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 9108 scalar_return = 9109 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type); 9110 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 9111 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 9112 goto err_free; 9113 } 9114 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 9115 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 9116 goto err_free; 9117 } 9118 9119 prev_offset = krecord[i].insn_off; 9120 urecord += urec_size; 9121 } 9122 9123 prog->aux->func_info = krecord; 9124 prog->aux->func_info_cnt = nfuncs; 9125 prog->aux->func_info_aux = info_aux; 9126 return 0; 9127 9128 err_free: 9129 kvfree(krecord); 9130 kfree(info_aux); 9131 return ret; 9132 } 9133 9134 static void adjust_btf_func(struct bpf_verifier_env *env) 9135 { 9136 struct bpf_prog_aux *aux = env->prog->aux; 9137 int i; 9138 9139 if (!aux->func_info) 9140 return; 9141 9142 for (i = 0; i < env->subprog_cnt; i++) 9143 aux->func_info[i].insn_off = env->subprog_info[i].start; 9144 } 9145 9146 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \ 9147 sizeof(((struct bpf_line_info *)(0))->line_col)) 9148 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 9149 9150 static int check_btf_line(struct bpf_verifier_env *env, 9151 const union bpf_attr *attr, 9152 union bpf_attr __user *uattr) 9153 { 9154 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 9155 struct bpf_subprog_info *sub; 9156 struct bpf_line_info *linfo; 9157 struct bpf_prog *prog; 9158 const struct btf *btf; 9159 void __user *ulinfo; 9160 int err; 9161 9162 nr_linfo = attr->line_info_cnt; 9163 if (!nr_linfo) 9164 return 0; 9165 9166 rec_size = attr->line_info_rec_size; 9167 if (rec_size < MIN_BPF_LINEINFO_SIZE || 9168 rec_size > MAX_LINEINFO_REC_SIZE || 9169 rec_size & (sizeof(u32) - 1)) 9170 return -EINVAL; 9171 9172 /* Need to zero it in case the userspace may 9173 * pass in a smaller bpf_line_info object. 9174 */ 9175 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 9176 GFP_KERNEL | __GFP_NOWARN); 9177 if (!linfo) 9178 return -ENOMEM; 9179 9180 prog = env->prog; 9181 btf = prog->aux->btf; 9182 9183 s = 0; 9184 sub = env->subprog_info; 9185 ulinfo = u64_to_user_ptr(attr->line_info); 9186 expected_size = sizeof(struct bpf_line_info); 9187 ncopy = min_t(u32, expected_size, rec_size); 9188 for (i = 0; i < nr_linfo; i++) { 9189 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 9190 if (err) { 9191 if (err == -E2BIG) { 9192 verbose(env, "nonzero tailing record in line_info"); 9193 if (put_user(expected_size, 9194 &uattr->line_info_rec_size)) 9195 err = -EFAULT; 9196 } 9197 goto err_free; 9198 } 9199 9200 if (copy_from_user(&linfo[i], ulinfo, ncopy)) { 9201 err = -EFAULT; 9202 goto err_free; 9203 } 9204 9205 /* 9206 * Check insn_off to ensure 9207 * 1) strictly increasing AND 9208 * 2) bounded by prog->len 9209 * 9210 * The linfo[0].insn_off == 0 check logically falls into 9211 * the later "missing bpf_line_info for func..." case 9212 * because the first linfo[0].insn_off must be the 9213 * first sub also and the first sub must have 9214 * subprog_info[0].start == 0. 9215 */ 9216 if ((i && linfo[i].insn_off <= prev_offset) || 9217 linfo[i].insn_off >= prog->len) { 9218 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 9219 i, linfo[i].insn_off, prev_offset, 9220 prog->len); 9221 err = -EINVAL; 9222 goto err_free; 9223 } 9224 9225 if (!prog->insnsi[linfo[i].insn_off].code) { 9226 verbose(env, 9227 "Invalid insn code at line_info[%u].insn_off\n", 9228 i); 9229 err = -EINVAL; 9230 goto err_free; 9231 } 9232 9233 if (!btf_name_by_offset(btf, linfo[i].line_off) || 9234 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 9235 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 9236 err = -EINVAL; 9237 goto err_free; 9238 } 9239 9240 if (s != env->subprog_cnt) { 9241 if (linfo[i].insn_off == sub[s].start) { 9242 sub[s].linfo_idx = i; 9243 s++; 9244 } else if (sub[s].start < linfo[i].insn_off) { 9245 verbose(env, "missing bpf_line_info for func#%u\n", s); 9246 err = -EINVAL; 9247 goto err_free; 9248 } 9249 } 9250 9251 prev_offset = linfo[i].insn_off; 9252 ulinfo += rec_size; 9253 } 9254 9255 if (s != env->subprog_cnt) { 9256 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 9257 env->subprog_cnt - s, s); 9258 err = -EINVAL; 9259 goto err_free; 9260 } 9261 9262 prog->aux->linfo = linfo; 9263 prog->aux->nr_linfo = nr_linfo; 9264 9265 return 0; 9266 9267 err_free: 9268 kvfree(linfo); 9269 return err; 9270 } 9271 9272 static int check_btf_info(struct bpf_verifier_env *env, 9273 const union bpf_attr *attr, 9274 union bpf_attr __user *uattr) 9275 { 9276 struct btf *btf; 9277 int err; 9278 9279 if (!attr->func_info_cnt && !attr->line_info_cnt) { 9280 if (check_abnormal_return(env)) 9281 return -EINVAL; 9282 return 0; 9283 } 9284 9285 btf = btf_get_by_fd(attr->prog_btf_fd); 9286 if (IS_ERR(btf)) 9287 return PTR_ERR(btf); 9288 if (btf_is_kernel(btf)) { 9289 btf_put(btf); 9290 return -EACCES; 9291 } 9292 env->prog->aux->btf = btf; 9293 9294 err = check_btf_func(env, attr, uattr); 9295 if (err) 9296 return err; 9297 9298 err = check_btf_line(env, attr, uattr); 9299 if (err) 9300 return err; 9301 9302 return 0; 9303 } 9304 9305 /* check %cur's range satisfies %old's */ 9306 static bool range_within(struct bpf_reg_state *old, 9307 struct bpf_reg_state *cur) 9308 { 9309 return old->umin_value <= cur->umin_value && 9310 old->umax_value >= cur->umax_value && 9311 old->smin_value <= cur->smin_value && 9312 old->smax_value >= cur->smax_value && 9313 old->u32_min_value <= cur->u32_min_value && 9314 old->u32_max_value >= cur->u32_max_value && 9315 old->s32_min_value <= cur->s32_min_value && 9316 old->s32_max_value >= cur->s32_max_value; 9317 } 9318 9319 /* Maximum number of register states that can exist at once */ 9320 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) 9321 struct idpair { 9322 u32 old; 9323 u32 cur; 9324 }; 9325 9326 /* If in the old state two registers had the same id, then they need to have 9327 * the same id in the new state as well. But that id could be different from 9328 * the old state, so we need to track the mapping from old to new ids. 9329 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 9330 * regs with old id 5 must also have new id 9 for the new state to be safe. But 9331 * regs with a different old id could still have new id 9, we don't care about 9332 * that. 9333 * So we look through our idmap to see if this old id has been seen before. If 9334 * so, we require the new id to match; otherwise, we add the id pair to the map. 9335 */ 9336 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) 9337 { 9338 unsigned int i; 9339 9340 for (i = 0; i < ID_MAP_SIZE; i++) { 9341 if (!idmap[i].old) { 9342 /* Reached an empty slot; haven't seen this id before */ 9343 idmap[i].old = old_id; 9344 idmap[i].cur = cur_id; 9345 return true; 9346 } 9347 if (idmap[i].old == old_id) 9348 return idmap[i].cur == cur_id; 9349 } 9350 /* We ran out of idmap slots, which should be impossible */ 9351 WARN_ON_ONCE(1); 9352 return false; 9353 } 9354 9355 static void clean_func_state(struct bpf_verifier_env *env, 9356 struct bpf_func_state *st) 9357 { 9358 enum bpf_reg_liveness live; 9359 int i, j; 9360 9361 for (i = 0; i < BPF_REG_FP; i++) { 9362 live = st->regs[i].live; 9363 /* liveness must not touch this register anymore */ 9364 st->regs[i].live |= REG_LIVE_DONE; 9365 if (!(live & REG_LIVE_READ)) 9366 /* since the register is unused, clear its state 9367 * to make further comparison simpler 9368 */ 9369 __mark_reg_not_init(env, &st->regs[i]); 9370 } 9371 9372 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 9373 live = st->stack[i].spilled_ptr.live; 9374 /* liveness must not touch this stack slot anymore */ 9375 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 9376 if (!(live & REG_LIVE_READ)) { 9377 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 9378 for (j = 0; j < BPF_REG_SIZE; j++) 9379 st->stack[i].slot_type[j] = STACK_INVALID; 9380 } 9381 } 9382 } 9383 9384 static void clean_verifier_state(struct bpf_verifier_env *env, 9385 struct bpf_verifier_state *st) 9386 { 9387 int i; 9388 9389 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 9390 /* all regs in this state in all frames were already marked */ 9391 return; 9392 9393 for (i = 0; i <= st->curframe; i++) 9394 clean_func_state(env, st->frame[i]); 9395 } 9396 9397 /* the parentage chains form a tree. 9398 * the verifier states are added to state lists at given insn and 9399 * pushed into state stack for future exploration. 9400 * when the verifier reaches bpf_exit insn some of the verifer states 9401 * stored in the state lists have their final liveness state already, 9402 * but a lot of states will get revised from liveness point of view when 9403 * the verifier explores other branches. 9404 * Example: 9405 * 1: r0 = 1 9406 * 2: if r1 == 100 goto pc+1 9407 * 3: r0 = 2 9408 * 4: exit 9409 * when the verifier reaches exit insn the register r0 in the state list of 9410 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 9411 * of insn 2 and goes exploring further. At the insn 4 it will walk the 9412 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 9413 * 9414 * Since the verifier pushes the branch states as it sees them while exploring 9415 * the program the condition of walking the branch instruction for the second 9416 * time means that all states below this branch were already explored and 9417 * their final liveness markes are already propagated. 9418 * Hence when the verifier completes the search of state list in is_state_visited() 9419 * we can call this clean_live_states() function to mark all liveness states 9420 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 9421 * will not be used. 9422 * This function also clears the registers and stack for states that !READ 9423 * to simplify state merging. 9424 * 9425 * Important note here that walking the same branch instruction in the callee 9426 * doesn't meant that the states are DONE. The verifier has to compare 9427 * the callsites 9428 */ 9429 static void clean_live_states(struct bpf_verifier_env *env, int insn, 9430 struct bpf_verifier_state *cur) 9431 { 9432 struct bpf_verifier_state_list *sl; 9433 int i; 9434 9435 sl = *explored_state(env, insn); 9436 while (sl) { 9437 if (sl->state.branches) 9438 goto next; 9439 if (sl->state.insn_idx != insn || 9440 sl->state.curframe != cur->curframe) 9441 goto next; 9442 for (i = 0; i <= cur->curframe; i++) 9443 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 9444 goto next; 9445 clean_verifier_state(env, &sl->state); 9446 next: 9447 sl = sl->next; 9448 } 9449 } 9450 9451 /* Returns true if (rold safe implies rcur safe) */ 9452 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 9453 struct idpair *idmap) 9454 { 9455 bool equal; 9456 9457 if (!(rold->live & REG_LIVE_READ)) 9458 /* explored state didn't use this */ 9459 return true; 9460 9461 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0; 9462 9463 if (rold->type == PTR_TO_STACK) 9464 /* two stack pointers are equal only if they're pointing to 9465 * the same stack frame, since fp-8 in foo != fp-8 in bar 9466 */ 9467 return equal && rold->frameno == rcur->frameno; 9468 9469 if (equal) 9470 return true; 9471 9472 if (rold->type == NOT_INIT) 9473 /* explored state can't have used this */ 9474 return true; 9475 if (rcur->type == NOT_INIT) 9476 return false; 9477 switch (rold->type) { 9478 case SCALAR_VALUE: 9479 if (rcur->type == SCALAR_VALUE) { 9480 if (!rold->precise && !rcur->precise) 9481 return true; 9482 /* new val must satisfy old val knowledge */ 9483 return range_within(rold, rcur) && 9484 tnum_in(rold->var_off, rcur->var_off); 9485 } else { 9486 /* We're trying to use a pointer in place of a scalar. 9487 * Even if the scalar was unbounded, this could lead to 9488 * pointer leaks because scalars are allowed to leak 9489 * while pointers are not. We could make this safe in 9490 * special cases if root is calling us, but it's 9491 * probably not worth the hassle. 9492 */ 9493 return false; 9494 } 9495 case PTR_TO_MAP_KEY: 9496 case PTR_TO_MAP_VALUE: 9497 /* If the new min/max/var_off satisfy the old ones and 9498 * everything else matches, we are OK. 9499 * 'id' is not compared, since it's only used for maps with 9500 * bpf_spin_lock inside map element and in such cases if 9501 * the rest of the prog is valid for one map element then 9502 * it's valid for all map elements regardless of the key 9503 * used in bpf_map_lookup() 9504 */ 9505 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 9506 range_within(rold, rcur) && 9507 tnum_in(rold->var_off, rcur->var_off); 9508 case PTR_TO_MAP_VALUE_OR_NULL: 9509 /* a PTR_TO_MAP_VALUE could be safe to use as a 9510 * PTR_TO_MAP_VALUE_OR_NULL into the same map. 9511 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- 9512 * checked, doing so could have affected others with the same 9513 * id, and we can't check for that because we lost the id when 9514 * we converted to a PTR_TO_MAP_VALUE. 9515 */ 9516 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) 9517 return false; 9518 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) 9519 return false; 9520 /* Check our ids match any regs they're supposed to */ 9521 return check_ids(rold->id, rcur->id, idmap); 9522 case PTR_TO_PACKET_META: 9523 case PTR_TO_PACKET: 9524 if (rcur->type != rold->type) 9525 return false; 9526 /* We must have at least as much range as the old ptr 9527 * did, so that any accesses which were safe before are 9528 * still safe. This is true even if old range < old off, 9529 * since someone could have accessed through (ptr - k), or 9530 * even done ptr -= k in a register, to get a safe access. 9531 */ 9532 if (rold->range > rcur->range) 9533 return false; 9534 /* If the offsets don't match, we can't trust our alignment; 9535 * nor can we be sure that we won't fall out of range. 9536 */ 9537 if (rold->off != rcur->off) 9538 return false; 9539 /* id relations must be preserved */ 9540 if (rold->id && !check_ids(rold->id, rcur->id, idmap)) 9541 return false; 9542 /* new val must satisfy old val knowledge */ 9543 return range_within(rold, rcur) && 9544 tnum_in(rold->var_off, rcur->var_off); 9545 case PTR_TO_CTX: 9546 case CONST_PTR_TO_MAP: 9547 case PTR_TO_PACKET_END: 9548 case PTR_TO_FLOW_KEYS: 9549 case PTR_TO_SOCKET: 9550 case PTR_TO_SOCKET_OR_NULL: 9551 case PTR_TO_SOCK_COMMON: 9552 case PTR_TO_SOCK_COMMON_OR_NULL: 9553 case PTR_TO_TCP_SOCK: 9554 case PTR_TO_TCP_SOCK_OR_NULL: 9555 case PTR_TO_XDP_SOCK: 9556 /* Only valid matches are exact, which memcmp() above 9557 * would have accepted 9558 */ 9559 default: 9560 /* Don't know what's going on, just say it's not safe */ 9561 return false; 9562 } 9563 9564 /* Shouldn't get here; if we do, say it's not safe */ 9565 WARN_ON_ONCE(1); 9566 return false; 9567 } 9568 9569 static bool stacksafe(struct bpf_func_state *old, 9570 struct bpf_func_state *cur, 9571 struct idpair *idmap) 9572 { 9573 int i, spi; 9574 9575 /* walk slots of the explored stack and ignore any additional 9576 * slots in the current stack, since explored(safe) state 9577 * didn't use them 9578 */ 9579 for (i = 0; i < old->allocated_stack; i++) { 9580 spi = i / BPF_REG_SIZE; 9581 9582 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 9583 i += BPF_REG_SIZE - 1; 9584 /* explored state didn't use this */ 9585 continue; 9586 } 9587 9588 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 9589 continue; 9590 9591 /* explored stack has more populated slots than current stack 9592 * and these slots were used 9593 */ 9594 if (i >= cur->allocated_stack) 9595 return false; 9596 9597 /* if old state was safe with misc data in the stack 9598 * it will be safe with zero-initialized stack. 9599 * The opposite is not true 9600 */ 9601 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 9602 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 9603 continue; 9604 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 9605 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 9606 /* Ex: old explored (safe) state has STACK_SPILL in 9607 * this stack slot, but current has STACK_MISC -> 9608 * this verifier states are not equivalent, 9609 * return false to continue verification of this path 9610 */ 9611 return false; 9612 if (i % BPF_REG_SIZE) 9613 continue; 9614 if (old->stack[spi].slot_type[0] != STACK_SPILL) 9615 continue; 9616 if (!regsafe(&old->stack[spi].spilled_ptr, 9617 &cur->stack[spi].spilled_ptr, 9618 idmap)) 9619 /* when explored and current stack slot are both storing 9620 * spilled registers, check that stored pointers types 9621 * are the same as well. 9622 * Ex: explored safe path could have stored 9623 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 9624 * but current path has stored: 9625 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 9626 * such verifier states are not equivalent. 9627 * return false to continue verification of this path 9628 */ 9629 return false; 9630 } 9631 return true; 9632 } 9633 9634 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur) 9635 { 9636 if (old->acquired_refs != cur->acquired_refs) 9637 return false; 9638 return !memcmp(old->refs, cur->refs, 9639 sizeof(*old->refs) * old->acquired_refs); 9640 } 9641 9642 /* compare two verifier states 9643 * 9644 * all states stored in state_list are known to be valid, since 9645 * verifier reached 'bpf_exit' instruction through them 9646 * 9647 * this function is called when verifier exploring different branches of 9648 * execution popped from the state stack. If it sees an old state that has 9649 * more strict register state and more strict stack state then this execution 9650 * branch doesn't need to be explored further, since verifier already 9651 * concluded that more strict state leads to valid finish. 9652 * 9653 * Therefore two states are equivalent if register state is more conservative 9654 * and explored stack state is more conservative than the current one. 9655 * Example: 9656 * explored current 9657 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 9658 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 9659 * 9660 * In other words if current stack state (one being explored) has more 9661 * valid slots than old one that already passed validation, it means 9662 * the verifier can stop exploring and conclude that current state is valid too 9663 * 9664 * Similarly with registers. If explored state has register type as invalid 9665 * whereas register type in current state is meaningful, it means that 9666 * the current state will reach 'bpf_exit' instruction safely 9667 */ 9668 static bool func_states_equal(struct bpf_func_state *old, 9669 struct bpf_func_state *cur) 9670 { 9671 struct idpair *idmap; 9672 bool ret = false; 9673 int i; 9674 9675 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); 9676 /* If we failed to allocate the idmap, just say it's not safe */ 9677 if (!idmap) 9678 return false; 9679 9680 for (i = 0; i < MAX_BPF_REG; i++) { 9681 if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) 9682 goto out_free; 9683 } 9684 9685 if (!stacksafe(old, cur, idmap)) 9686 goto out_free; 9687 9688 if (!refsafe(old, cur)) 9689 goto out_free; 9690 ret = true; 9691 out_free: 9692 kfree(idmap); 9693 return ret; 9694 } 9695 9696 static bool states_equal(struct bpf_verifier_env *env, 9697 struct bpf_verifier_state *old, 9698 struct bpf_verifier_state *cur) 9699 { 9700 int i; 9701 9702 if (old->curframe != cur->curframe) 9703 return false; 9704 9705 /* Verification state from speculative execution simulation 9706 * must never prune a non-speculative execution one. 9707 */ 9708 if (old->speculative && !cur->speculative) 9709 return false; 9710 9711 if (old->active_spin_lock != cur->active_spin_lock) 9712 return false; 9713 9714 /* for states to be equal callsites have to be the same 9715 * and all frame states need to be equivalent 9716 */ 9717 for (i = 0; i <= old->curframe; i++) { 9718 if (old->frame[i]->callsite != cur->frame[i]->callsite) 9719 return false; 9720 if (!func_states_equal(old->frame[i], cur->frame[i])) 9721 return false; 9722 } 9723 return true; 9724 } 9725 9726 /* Return 0 if no propagation happened. Return negative error code if error 9727 * happened. Otherwise, return the propagated bit. 9728 */ 9729 static int propagate_liveness_reg(struct bpf_verifier_env *env, 9730 struct bpf_reg_state *reg, 9731 struct bpf_reg_state *parent_reg) 9732 { 9733 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 9734 u8 flag = reg->live & REG_LIVE_READ; 9735 int err; 9736 9737 /* When comes here, read flags of PARENT_REG or REG could be any of 9738 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 9739 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 9740 */ 9741 if (parent_flag == REG_LIVE_READ64 || 9742 /* Or if there is no read flag from REG. */ 9743 !flag || 9744 /* Or if the read flag from REG is the same as PARENT_REG. */ 9745 parent_flag == flag) 9746 return 0; 9747 9748 err = mark_reg_read(env, reg, parent_reg, flag); 9749 if (err) 9750 return err; 9751 9752 return flag; 9753 } 9754 9755 /* A write screens off any subsequent reads; but write marks come from the 9756 * straight-line code between a state and its parent. When we arrive at an 9757 * equivalent state (jump target or such) we didn't arrive by the straight-line 9758 * code, so read marks in the state must propagate to the parent regardless 9759 * of the state's write marks. That's what 'parent == state->parent' comparison 9760 * in mark_reg_read() is for. 9761 */ 9762 static int propagate_liveness(struct bpf_verifier_env *env, 9763 const struct bpf_verifier_state *vstate, 9764 struct bpf_verifier_state *vparent) 9765 { 9766 struct bpf_reg_state *state_reg, *parent_reg; 9767 struct bpf_func_state *state, *parent; 9768 int i, frame, err = 0; 9769 9770 if (vparent->curframe != vstate->curframe) { 9771 WARN(1, "propagate_live: parent frame %d current frame %d\n", 9772 vparent->curframe, vstate->curframe); 9773 return -EFAULT; 9774 } 9775 /* Propagate read liveness of registers... */ 9776 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 9777 for (frame = 0; frame <= vstate->curframe; frame++) { 9778 parent = vparent->frame[frame]; 9779 state = vstate->frame[frame]; 9780 parent_reg = parent->regs; 9781 state_reg = state->regs; 9782 /* We don't need to worry about FP liveness, it's read-only */ 9783 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 9784 err = propagate_liveness_reg(env, &state_reg[i], 9785 &parent_reg[i]); 9786 if (err < 0) 9787 return err; 9788 if (err == REG_LIVE_READ64) 9789 mark_insn_zext(env, &parent_reg[i]); 9790 } 9791 9792 /* Propagate stack slots. */ 9793 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 9794 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 9795 parent_reg = &parent->stack[i].spilled_ptr; 9796 state_reg = &state->stack[i].spilled_ptr; 9797 err = propagate_liveness_reg(env, state_reg, 9798 parent_reg); 9799 if (err < 0) 9800 return err; 9801 } 9802 } 9803 return 0; 9804 } 9805 9806 /* find precise scalars in the previous equivalent state and 9807 * propagate them into the current state 9808 */ 9809 static int propagate_precision(struct bpf_verifier_env *env, 9810 const struct bpf_verifier_state *old) 9811 { 9812 struct bpf_reg_state *state_reg; 9813 struct bpf_func_state *state; 9814 int i, err = 0; 9815 9816 state = old->frame[old->curframe]; 9817 state_reg = state->regs; 9818 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 9819 if (state_reg->type != SCALAR_VALUE || 9820 !state_reg->precise) 9821 continue; 9822 if (env->log.level & BPF_LOG_LEVEL2) 9823 verbose(env, "propagating r%d\n", i); 9824 err = mark_chain_precision(env, i); 9825 if (err < 0) 9826 return err; 9827 } 9828 9829 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 9830 if (state->stack[i].slot_type[0] != STACK_SPILL) 9831 continue; 9832 state_reg = &state->stack[i].spilled_ptr; 9833 if (state_reg->type != SCALAR_VALUE || 9834 !state_reg->precise) 9835 continue; 9836 if (env->log.level & BPF_LOG_LEVEL2) 9837 verbose(env, "propagating fp%d\n", 9838 (-i - 1) * BPF_REG_SIZE); 9839 err = mark_chain_precision_stack(env, i); 9840 if (err < 0) 9841 return err; 9842 } 9843 return 0; 9844 } 9845 9846 static bool states_maybe_looping(struct bpf_verifier_state *old, 9847 struct bpf_verifier_state *cur) 9848 { 9849 struct bpf_func_state *fold, *fcur; 9850 int i, fr = cur->curframe; 9851 9852 if (old->curframe != fr) 9853 return false; 9854 9855 fold = old->frame[fr]; 9856 fcur = cur->frame[fr]; 9857 for (i = 0; i < MAX_BPF_REG; i++) 9858 if (memcmp(&fold->regs[i], &fcur->regs[i], 9859 offsetof(struct bpf_reg_state, parent))) 9860 return false; 9861 return true; 9862 } 9863 9864 9865 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 9866 { 9867 struct bpf_verifier_state_list *new_sl; 9868 struct bpf_verifier_state_list *sl, **pprev; 9869 struct bpf_verifier_state *cur = env->cur_state, *new; 9870 int i, j, err, states_cnt = 0; 9871 bool add_new_state = env->test_state_freq ? true : false; 9872 9873 cur->last_insn_idx = env->prev_insn_idx; 9874 if (!env->insn_aux_data[insn_idx].prune_point) 9875 /* this 'insn_idx' instruction wasn't marked, so we will not 9876 * be doing state search here 9877 */ 9878 return 0; 9879 9880 /* bpf progs typically have pruning point every 4 instructions 9881 * http://vger.kernel.org/bpfconf2019.html#session-1 9882 * Do not add new state for future pruning if the verifier hasn't seen 9883 * at least 2 jumps and at least 8 instructions. 9884 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 9885 * In tests that amounts to up to 50% reduction into total verifier 9886 * memory consumption and 20% verifier time speedup. 9887 */ 9888 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 9889 env->insn_processed - env->prev_insn_processed >= 8) 9890 add_new_state = true; 9891 9892 pprev = explored_state(env, insn_idx); 9893 sl = *pprev; 9894 9895 clean_live_states(env, insn_idx, cur); 9896 9897 while (sl) { 9898 states_cnt++; 9899 if (sl->state.insn_idx != insn_idx) 9900 goto next; 9901 if (sl->state.branches) { 9902 if (states_maybe_looping(&sl->state, cur) && 9903 states_equal(env, &sl->state, cur)) { 9904 verbose_linfo(env, insn_idx, "; "); 9905 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 9906 return -EINVAL; 9907 } 9908 /* if the verifier is processing a loop, avoid adding new state 9909 * too often, since different loop iterations have distinct 9910 * states and may not help future pruning. 9911 * This threshold shouldn't be too low to make sure that 9912 * a loop with large bound will be rejected quickly. 9913 * The most abusive loop will be: 9914 * r1 += 1 9915 * if r1 < 1000000 goto pc-2 9916 * 1M insn_procssed limit / 100 == 10k peak states. 9917 * This threshold shouldn't be too high either, since states 9918 * at the end of the loop are likely to be useful in pruning. 9919 */ 9920 if (env->jmps_processed - env->prev_jmps_processed < 20 && 9921 env->insn_processed - env->prev_insn_processed < 100) 9922 add_new_state = false; 9923 goto miss; 9924 } 9925 if (states_equal(env, &sl->state, cur)) { 9926 sl->hit_cnt++; 9927 /* reached equivalent register/stack state, 9928 * prune the search. 9929 * Registers read by the continuation are read by us. 9930 * If we have any write marks in env->cur_state, they 9931 * will prevent corresponding reads in the continuation 9932 * from reaching our parent (an explored_state). Our 9933 * own state will get the read marks recorded, but 9934 * they'll be immediately forgotten as we're pruning 9935 * this state and will pop a new one. 9936 */ 9937 err = propagate_liveness(env, &sl->state, cur); 9938 9939 /* if previous state reached the exit with precision and 9940 * current state is equivalent to it (except precsion marks) 9941 * the precision needs to be propagated back in 9942 * the current state. 9943 */ 9944 err = err ? : push_jmp_history(env, cur); 9945 err = err ? : propagate_precision(env, &sl->state); 9946 if (err) 9947 return err; 9948 return 1; 9949 } 9950 miss: 9951 /* when new state is not going to be added do not increase miss count. 9952 * Otherwise several loop iterations will remove the state 9953 * recorded earlier. The goal of these heuristics is to have 9954 * states from some iterations of the loop (some in the beginning 9955 * and some at the end) to help pruning. 9956 */ 9957 if (add_new_state) 9958 sl->miss_cnt++; 9959 /* heuristic to determine whether this state is beneficial 9960 * to keep checking from state equivalence point of view. 9961 * Higher numbers increase max_states_per_insn and verification time, 9962 * but do not meaningfully decrease insn_processed. 9963 */ 9964 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 9965 /* the state is unlikely to be useful. Remove it to 9966 * speed up verification 9967 */ 9968 *pprev = sl->next; 9969 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 9970 u32 br = sl->state.branches; 9971 9972 WARN_ONCE(br, 9973 "BUG live_done but branches_to_explore %d\n", 9974 br); 9975 free_verifier_state(&sl->state, false); 9976 kfree(sl); 9977 env->peak_states--; 9978 } else { 9979 /* cannot free this state, since parentage chain may 9980 * walk it later. Add it for free_list instead to 9981 * be freed at the end of verification 9982 */ 9983 sl->next = env->free_list; 9984 env->free_list = sl; 9985 } 9986 sl = *pprev; 9987 continue; 9988 } 9989 next: 9990 pprev = &sl->next; 9991 sl = *pprev; 9992 } 9993 9994 if (env->max_states_per_insn < states_cnt) 9995 env->max_states_per_insn = states_cnt; 9996 9997 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 9998 return push_jmp_history(env, cur); 9999 10000 if (!add_new_state) 10001 return push_jmp_history(env, cur); 10002 10003 /* There were no equivalent states, remember the current one. 10004 * Technically the current state is not proven to be safe yet, 10005 * but it will either reach outer most bpf_exit (which means it's safe) 10006 * or it will be rejected. When there are no loops the verifier won't be 10007 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 10008 * again on the way to bpf_exit. 10009 * When looping the sl->state.branches will be > 0 and this state 10010 * will not be considered for equivalence until branches == 0. 10011 */ 10012 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 10013 if (!new_sl) 10014 return -ENOMEM; 10015 env->total_states++; 10016 env->peak_states++; 10017 env->prev_jmps_processed = env->jmps_processed; 10018 env->prev_insn_processed = env->insn_processed; 10019 10020 /* add new state to the head of linked list */ 10021 new = &new_sl->state; 10022 err = copy_verifier_state(new, cur); 10023 if (err) { 10024 free_verifier_state(new, false); 10025 kfree(new_sl); 10026 return err; 10027 } 10028 new->insn_idx = insn_idx; 10029 WARN_ONCE(new->branches != 1, 10030 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 10031 10032 cur->parent = new; 10033 cur->first_insn_idx = insn_idx; 10034 clear_jmp_history(cur); 10035 new_sl->next = *explored_state(env, insn_idx); 10036 *explored_state(env, insn_idx) = new_sl; 10037 /* connect new state to parentage chain. Current frame needs all 10038 * registers connected. Only r6 - r9 of the callers are alive (pushed 10039 * to the stack implicitly by JITs) so in callers' frames connect just 10040 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 10041 * the state of the call instruction (with WRITTEN set), and r0 comes 10042 * from callee with its full parentage chain, anyway. 10043 */ 10044 /* clear write marks in current state: the writes we did are not writes 10045 * our child did, so they don't screen off its reads from us. 10046 * (There are no read marks in current state, because reads always mark 10047 * their parent and current state never has children yet. Only 10048 * explored_states can get read marks.) 10049 */ 10050 for (j = 0; j <= cur->curframe; j++) { 10051 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 10052 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 10053 for (i = 0; i < BPF_REG_FP; i++) 10054 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 10055 } 10056 10057 /* all stack frames are accessible from callee, clear them all */ 10058 for (j = 0; j <= cur->curframe; j++) { 10059 struct bpf_func_state *frame = cur->frame[j]; 10060 struct bpf_func_state *newframe = new->frame[j]; 10061 10062 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 10063 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 10064 frame->stack[i].spilled_ptr.parent = 10065 &newframe->stack[i].spilled_ptr; 10066 } 10067 } 10068 return 0; 10069 } 10070 10071 /* Return true if it's OK to have the same insn return a different type. */ 10072 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 10073 { 10074 switch (type) { 10075 case PTR_TO_CTX: 10076 case PTR_TO_SOCKET: 10077 case PTR_TO_SOCKET_OR_NULL: 10078 case PTR_TO_SOCK_COMMON: 10079 case PTR_TO_SOCK_COMMON_OR_NULL: 10080 case PTR_TO_TCP_SOCK: 10081 case PTR_TO_TCP_SOCK_OR_NULL: 10082 case PTR_TO_XDP_SOCK: 10083 case PTR_TO_BTF_ID: 10084 case PTR_TO_BTF_ID_OR_NULL: 10085 return false; 10086 default: 10087 return true; 10088 } 10089 } 10090 10091 /* If an instruction was previously used with particular pointer types, then we 10092 * need to be careful to avoid cases such as the below, where it may be ok 10093 * for one branch accessing the pointer, but not ok for the other branch: 10094 * 10095 * R1 = sock_ptr 10096 * goto X; 10097 * ... 10098 * R1 = some_other_valid_ptr; 10099 * goto X; 10100 * ... 10101 * R2 = *(u32 *)(R1 + 0); 10102 */ 10103 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 10104 { 10105 return src != prev && (!reg_type_mismatch_ok(src) || 10106 !reg_type_mismatch_ok(prev)); 10107 } 10108 10109 static int do_check(struct bpf_verifier_env *env) 10110 { 10111 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 10112 struct bpf_verifier_state *state = env->cur_state; 10113 struct bpf_insn *insns = env->prog->insnsi; 10114 struct bpf_reg_state *regs; 10115 int insn_cnt = env->prog->len; 10116 bool do_print_state = false; 10117 int prev_insn_idx = -1; 10118 10119 for (;;) { 10120 struct bpf_insn *insn; 10121 u8 class; 10122 int err; 10123 10124 env->prev_insn_idx = prev_insn_idx; 10125 if (env->insn_idx >= insn_cnt) { 10126 verbose(env, "invalid insn idx %d insn_cnt %d\n", 10127 env->insn_idx, insn_cnt); 10128 return -EFAULT; 10129 } 10130 10131 insn = &insns[env->insn_idx]; 10132 class = BPF_CLASS(insn->code); 10133 10134 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 10135 verbose(env, 10136 "BPF program is too large. Processed %d insn\n", 10137 env->insn_processed); 10138 return -E2BIG; 10139 } 10140 10141 err = is_state_visited(env, env->insn_idx); 10142 if (err < 0) 10143 return err; 10144 if (err == 1) { 10145 /* found equivalent state, can prune the search */ 10146 if (env->log.level & BPF_LOG_LEVEL) { 10147 if (do_print_state) 10148 verbose(env, "\nfrom %d to %d%s: safe\n", 10149 env->prev_insn_idx, env->insn_idx, 10150 env->cur_state->speculative ? 10151 " (speculative execution)" : ""); 10152 else 10153 verbose(env, "%d: safe\n", env->insn_idx); 10154 } 10155 goto process_bpf_exit; 10156 } 10157 10158 if (signal_pending(current)) 10159 return -EAGAIN; 10160 10161 if (need_resched()) 10162 cond_resched(); 10163 10164 if (env->log.level & BPF_LOG_LEVEL2 || 10165 (env->log.level & BPF_LOG_LEVEL && do_print_state)) { 10166 if (env->log.level & BPF_LOG_LEVEL2) 10167 verbose(env, "%d:", env->insn_idx); 10168 else 10169 verbose(env, "\nfrom %d to %d%s:", 10170 env->prev_insn_idx, env->insn_idx, 10171 env->cur_state->speculative ? 10172 " (speculative execution)" : ""); 10173 print_verifier_state(env, state->frame[state->curframe]); 10174 do_print_state = false; 10175 } 10176 10177 if (env->log.level & BPF_LOG_LEVEL) { 10178 const struct bpf_insn_cbs cbs = { 10179 .cb_print = verbose, 10180 .private_data = env, 10181 }; 10182 10183 verbose_linfo(env, env->insn_idx, "; "); 10184 verbose(env, "%d: ", env->insn_idx); 10185 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 10186 } 10187 10188 if (bpf_prog_is_dev_bound(env->prog->aux)) { 10189 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 10190 env->prev_insn_idx); 10191 if (err) 10192 return err; 10193 } 10194 10195 regs = cur_regs(env); 10196 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 10197 prev_insn_idx = env->insn_idx; 10198 10199 if (class == BPF_ALU || class == BPF_ALU64) { 10200 err = check_alu_op(env, insn); 10201 if (err) 10202 return err; 10203 10204 } else if (class == BPF_LDX) { 10205 enum bpf_reg_type *prev_src_type, src_reg_type; 10206 10207 /* check for reserved fields is already done */ 10208 10209 /* check src operand */ 10210 err = check_reg_arg(env, insn->src_reg, SRC_OP); 10211 if (err) 10212 return err; 10213 10214 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 10215 if (err) 10216 return err; 10217 10218 src_reg_type = regs[insn->src_reg].type; 10219 10220 /* check that memory (src_reg + off) is readable, 10221 * the state of dst_reg will be updated by this func 10222 */ 10223 err = check_mem_access(env, env->insn_idx, insn->src_reg, 10224 insn->off, BPF_SIZE(insn->code), 10225 BPF_READ, insn->dst_reg, false); 10226 if (err) 10227 return err; 10228 10229 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 10230 10231 if (*prev_src_type == NOT_INIT) { 10232 /* saw a valid insn 10233 * dst_reg = *(u32 *)(src_reg + off) 10234 * save type to validate intersecting paths 10235 */ 10236 *prev_src_type = src_reg_type; 10237 10238 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 10239 /* ABuser program is trying to use the same insn 10240 * dst_reg = *(u32*) (src_reg + off) 10241 * with different pointer types: 10242 * src_reg == ctx in one branch and 10243 * src_reg == stack|map in some other branch. 10244 * Reject it. 10245 */ 10246 verbose(env, "same insn cannot be used with different pointers\n"); 10247 return -EINVAL; 10248 } 10249 10250 } else if (class == BPF_STX) { 10251 enum bpf_reg_type *prev_dst_type, dst_reg_type; 10252 10253 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 10254 err = check_atomic(env, env->insn_idx, insn); 10255 if (err) 10256 return err; 10257 env->insn_idx++; 10258 continue; 10259 } 10260 10261 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 10262 verbose(env, "BPF_STX uses reserved fields\n"); 10263 return -EINVAL; 10264 } 10265 10266 /* check src1 operand */ 10267 err = check_reg_arg(env, insn->src_reg, SRC_OP); 10268 if (err) 10269 return err; 10270 /* check src2 operand */ 10271 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 10272 if (err) 10273 return err; 10274 10275 dst_reg_type = regs[insn->dst_reg].type; 10276 10277 /* check that memory (dst_reg + off) is writeable */ 10278 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 10279 insn->off, BPF_SIZE(insn->code), 10280 BPF_WRITE, insn->src_reg, false); 10281 if (err) 10282 return err; 10283 10284 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 10285 10286 if (*prev_dst_type == NOT_INIT) { 10287 *prev_dst_type = dst_reg_type; 10288 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 10289 verbose(env, "same insn cannot be used with different pointers\n"); 10290 return -EINVAL; 10291 } 10292 10293 } else if (class == BPF_ST) { 10294 if (BPF_MODE(insn->code) != BPF_MEM || 10295 insn->src_reg != BPF_REG_0) { 10296 verbose(env, "BPF_ST uses reserved fields\n"); 10297 return -EINVAL; 10298 } 10299 /* check src operand */ 10300 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 10301 if (err) 10302 return err; 10303 10304 if (is_ctx_reg(env, insn->dst_reg)) { 10305 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 10306 insn->dst_reg, 10307 reg_type_str[reg_state(env, insn->dst_reg)->type]); 10308 return -EACCES; 10309 } 10310 10311 /* check that memory (dst_reg + off) is writeable */ 10312 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 10313 insn->off, BPF_SIZE(insn->code), 10314 BPF_WRITE, -1, false); 10315 if (err) 10316 return err; 10317 10318 } else if (class == BPF_JMP || class == BPF_JMP32) { 10319 u8 opcode = BPF_OP(insn->code); 10320 10321 env->jmps_processed++; 10322 if (opcode == BPF_CALL) { 10323 if (BPF_SRC(insn->code) != BPF_K || 10324 insn->off != 0 || 10325 (insn->src_reg != BPF_REG_0 && 10326 insn->src_reg != BPF_PSEUDO_CALL) || 10327 insn->dst_reg != BPF_REG_0 || 10328 class == BPF_JMP32) { 10329 verbose(env, "BPF_CALL uses reserved fields\n"); 10330 return -EINVAL; 10331 } 10332 10333 if (env->cur_state->active_spin_lock && 10334 (insn->src_reg == BPF_PSEUDO_CALL || 10335 insn->imm != BPF_FUNC_spin_unlock)) { 10336 verbose(env, "function calls are not allowed while holding a lock\n"); 10337 return -EINVAL; 10338 } 10339 if (insn->src_reg == BPF_PSEUDO_CALL) 10340 err = check_func_call(env, insn, &env->insn_idx); 10341 else 10342 err = check_helper_call(env, insn, &env->insn_idx); 10343 if (err) 10344 return err; 10345 } else if (opcode == BPF_JA) { 10346 if (BPF_SRC(insn->code) != BPF_K || 10347 insn->imm != 0 || 10348 insn->src_reg != BPF_REG_0 || 10349 insn->dst_reg != BPF_REG_0 || 10350 class == BPF_JMP32) { 10351 verbose(env, "BPF_JA uses reserved fields\n"); 10352 return -EINVAL; 10353 } 10354 10355 env->insn_idx += insn->off + 1; 10356 continue; 10357 10358 } else if (opcode == BPF_EXIT) { 10359 if (BPF_SRC(insn->code) != BPF_K || 10360 insn->imm != 0 || 10361 insn->src_reg != BPF_REG_0 || 10362 insn->dst_reg != BPF_REG_0 || 10363 class == BPF_JMP32) { 10364 verbose(env, "BPF_EXIT uses reserved fields\n"); 10365 return -EINVAL; 10366 } 10367 10368 if (env->cur_state->active_spin_lock) { 10369 verbose(env, "bpf_spin_unlock is missing\n"); 10370 return -EINVAL; 10371 } 10372 10373 if (state->curframe) { 10374 /* exit from nested function */ 10375 err = prepare_func_exit(env, &env->insn_idx); 10376 if (err) 10377 return err; 10378 do_print_state = true; 10379 continue; 10380 } 10381 10382 err = check_reference_leak(env); 10383 if (err) 10384 return err; 10385 10386 err = check_return_code(env); 10387 if (err) 10388 return err; 10389 process_bpf_exit: 10390 update_branch_counts(env, env->cur_state); 10391 err = pop_stack(env, &prev_insn_idx, 10392 &env->insn_idx, pop_log); 10393 if (err < 0) { 10394 if (err != -ENOENT) 10395 return err; 10396 break; 10397 } else { 10398 do_print_state = true; 10399 continue; 10400 } 10401 } else { 10402 err = check_cond_jmp_op(env, insn, &env->insn_idx); 10403 if (err) 10404 return err; 10405 } 10406 } else if (class == BPF_LD) { 10407 u8 mode = BPF_MODE(insn->code); 10408 10409 if (mode == BPF_ABS || mode == BPF_IND) { 10410 err = check_ld_abs(env, insn); 10411 if (err) 10412 return err; 10413 10414 } else if (mode == BPF_IMM) { 10415 err = check_ld_imm(env, insn); 10416 if (err) 10417 return err; 10418 10419 env->insn_idx++; 10420 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 10421 } else { 10422 verbose(env, "invalid BPF_LD mode\n"); 10423 return -EINVAL; 10424 } 10425 } else { 10426 verbose(env, "unknown insn class %d\n", class); 10427 return -EINVAL; 10428 } 10429 10430 env->insn_idx++; 10431 } 10432 10433 return 0; 10434 } 10435 10436 static int find_btf_percpu_datasec(struct btf *btf) 10437 { 10438 const struct btf_type *t; 10439 const char *tname; 10440 int i, n; 10441 10442 /* 10443 * Both vmlinux and module each have their own ".data..percpu" 10444 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 10445 * types to look at only module's own BTF types. 10446 */ 10447 n = btf_nr_types(btf); 10448 if (btf_is_module(btf)) 10449 i = btf_nr_types(btf_vmlinux); 10450 else 10451 i = 1; 10452 10453 for(; i < n; i++) { 10454 t = btf_type_by_id(btf, i); 10455 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 10456 continue; 10457 10458 tname = btf_name_by_offset(btf, t->name_off); 10459 if (!strcmp(tname, ".data..percpu")) 10460 return i; 10461 } 10462 10463 return -ENOENT; 10464 } 10465 10466 /* replace pseudo btf_id with kernel symbol address */ 10467 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 10468 struct bpf_insn *insn, 10469 struct bpf_insn_aux_data *aux) 10470 { 10471 const struct btf_var_secinfo *vsi; 10472 const struct btf_type *datasec; 10473 struct btf_mod_pair *btf_mod; 10474 const struct btf_type *t; 10475 const char *sym_name; 10476 bool percpu = false; 10477 u32 type, id = insn->imm; 10478 struct btf *btf; 10479 s32 datasec_id; 10480 u64 addr; 10481 int i, btf_fd, err; 10482 10483 btf_fd = insn[1].imm; 10484 if (btf_fd) { 10485 btf = btf_get_by_fd(btf_fd); 10486 if (IS_ERR(btf)) { 10487 verbose(env, "invalid module BTF object FD specified.\n"); 10488 return -EINVAL; 10489 } 10490 } else { 10491 if (!btf_vmlinux) { 10492 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 10493 return -EINVAL; 10494 } 10495 btf = btf_vmlinux; 10496 btf_get(btf); 10497 } 10498 10499 t = btf_type_by_id(btf, id); 10500 if (!t) { 10501 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 10502 err = -ENOENT; 10503 goto err_put; 10504 } 10505 10506 if (!btf_type_is_var(t)) { 10507 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id); 10508 err = -EINVAL; 10509 goto err_put; 10510 } 10511 10512 sym_name = btf_name_by_offset(btf, t->name_off); 10513 addr = kallsyms_lookup_name(sym_name); 10514 if (!addr) { 10515 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 10516 sym_name); 10517 err = -ENOENT; 10518 goto err_put; 10519 } 10520 10521 datasec_id = find_btf_percpu_datasec(btf); 10522 if (datasec_id > 0) { 10523 datasec = btf_type_by_id(btf, datasec_id); 10524 for_each_vsi(i, datasec, vsi) { 10525 if (vsi->type == id) { 10526 percpu = true; 10527 break; 10528 } 10529 } 10530 } 10531 10532 insn[0].imm = (u32)addr; 10533 insn[1].imm = addr >> 32; 10534 10535 type = t->type; 10536 t = btf_type_skip_modifiers(btf, type, NULL); 10537 if (percpu) { 10538 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID; 10539 aux->btf_var.btf = btf; 10540 aux->btf_var.btf_id = type; 10541 } else if (!btf_type_is_struct(t)) { 10542 const struct btf_type *ret; 10543 const char *tname; 10544 u32 tsize; 10545 10546 /* resolve the type size of ksym. */ 10547 ret = btf_resolve_size(btf, t, &tsize); 10548 if (IS_ERR(ret)) { 10549 tname = btf_name_by_offset(btf, t->name_off); 10550 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 10551 tname, PTR_ERR(ret)); 10552 err = -EINVAL; 10553 goto err_put; 10554 } 10555 aux->btf_var.reg_type = PTR_TO_MEM; 10556 aux->btf_var.mem_size = tsize; 10557 } else { 10558 aux->btf_var.reg_type = PTR_TO_BTF_ID; 10559 aux->btf_var.btf = btf; 10560 aux->btf_var.btf_id = type; 10561 } 10562 10563 /* check whether we recorded this BTF (and maybe module) already */ 10564 for (i = 0; i < env->used_btf_cnt; i++) { 10565 if (env->used_btfs[i].btf == btf) { 10566 btf_put(btf); 10567 return 0; 10568 } 10569 } 10570 10571 if (env->used_btf_cnt >= MAX_USED_BTFS) { 10572 err = -E2BIG; 10573 goto err_put; 10574 } 10575 10576 btf_mod = &env->used_btfs[env->used_btf_cnt]; 10577 btf_mod->btf = btf; 10578 btf_mod->module = NULL; 10579 10580 /* if we reference variables from kernel module, bump its refcount */ 10581 if (btf_is_module(btf)) { 10582 btf_mod->module = btf_try_get_module(btf); 10583 if (!btf_mod->module) { 10584 err = -ENXIO; 10585 goto err_put; 10586 } 10587 } 10588 10589 env->used_btf_cnt++; 10590 10591 return 0; 10592 err_put: 10593 btf_put(btf); 10594 return err; 10595 } 10596 10597 static int check_map_prealloc(struct bpf_map *map) 10598 { 10599 return (map->map_type != BPF_MAP_TYPE_HASH && 10600 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 10601 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || 10602 !(map->map_flags & BPF_F_NO_PREALLOC); 10603 } 10604 10605 static bool is_tracing_prog_type(enum bpf_prog_type type) 10606 { 10607 switch (type) { 10608 case BPF_PROG_TYPE_KPROBE: 10609 case BPF_PROG_TYPE_TRACEPOINT: 10610 case BPF_PROG_TYPE_PERF_EVENT: 10611 case BPF_PROG_TYPE_RAW_TRACEPOINT: 10612 return true; 10613 default: 10614 return false; 10615 } 10616 } 10617 10618 static bool is_preallocated_map(struct bpf_map *map) 10619 { 10620 if (!check_map_prealloc(map)) 10621 return false; 10622 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) 10623 return false; 10624 return true; 10625 } 10626 10627 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 10628 struct bpf_map *map, 10629 struct bpf_prog *prog) 10630 10631 { 10632 enum bpf_prog_type prog_type = resolve_prog_type(prog); 10633 /* 10634 * Validate that trace type programs use preallocated hash maps. 10635 * 10636 * For programs attached to PERF events this is mandatory as the 10637 * perf NMI can hit any arbitrary code sequence. 10638 * 10639 * All other trace types using preallocated hash maps are unsafe as 10640 * well because tracepoint or kprobes can be inside locked regions 10641 * of the memory allocator or at a place where a recursion into the 10642 * memory allocator would see inconsistent state. 10643 * 10644 * On RT enabled kernels run-time allocation of all trace type 10645 * programs is strictly prohibited due to lock type constraints. On 10646 * !RT kernels it is allowed for backwards compatibility reasons for 10647 * now, but warnings are emitted so developers are made aware of 10648 * the unsafety and can fix their programs before this is enforced. 10649 */ 10650 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) { 10651 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) { 10652 verbose(env, "perf_event programs can only use preallocated hash map\n"); 10653 return -EINVAL; 10654 } 10655 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 10656 verbose(env, "trace type programs can only use preallocated hash map\n"); 10657 return -EINVAL; 10658 } 10659 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n"); 10660 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n"); 10661 } 10662 10663 if (map_value_has_spin_lock(map)) { 10664 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 10665 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 10666 return -EINVAL; 10667 } 10668 10669 if (is_tracing_prog_type(prog_type)) { 10670 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 10671 return -EINVAL; 10672 } 10673 10674 if (prog->aux->sleepable) { 10675 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 10676 return -EINVAL; 10677 } 10678 } 10679 10680 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) && 10681 !bpf_offload_prog_map_match(prog, map)) { 10682 verbose(env, "offload device mismatch between prog and map\n"); 10683 return -EINVAL; 10684 } 10685 10686 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 10687 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 10688 return -EINVAL; 10689 } 10690 10691 if (prog->aux->sleepable) 10692 switch (map->map_type) { 10693 case BPF_MAP_TYPE_HASH: 10694 case BPF_MAP_TYPE_LRU_HASH: 10695 case BPF_MAP_TYPE_ARRAY: 10696 case BPF_MAP_TYPE_PERCPU_HASH: 10697 case BPF_MAP_TYPE_PERCPU_ARRAY: 10698 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 10699 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 10700 case BPF_MAP_TYPE_HASH_OF_MAPS: 10701 if (!is_preallocated_map(map)) { 10702 verbose(env, 10703 "Sleepable programs can only use preallocated maps\n"); 10704 return -EINVAL; 10705 } 10706 break; 10707 case BPF_MAP_TYPE_RINGBUF: 10708 break; 10709 default: 10710 verbose(env, 10711 "Sleepable programs can only use array, hash, and ringbuf maps\n"); 10712 return -EINVAL; 10713 } 10714 10715 return 0; 10716 } 10717 10718 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 10719 { 10720 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 10721 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 10722 } 10723 10724 /* find and rewrite pseudo imm in ld_imm64 instructions: 10725 * 10726 * 1. if it accesses map FD, replace it with actual map pointer. 10727 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 10728 * 10729 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 10730 */ 10731 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 10732 { 10733 struct bpf_insn *insn = env->prog->insnsi; 10734 int insn_cnt = env->prog->len; 10735 int i, j, err; 10736 10737 err = bpf_prog_calc_tag(env->prog); 10738 if (err) 10739 return err; 10740 10741 for (i = 0; i < insn_cnt; i++, insn++) { 10742 if (BPF_CLASS(insn->code) == BPF_LDX && 10743 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 10744 verbose(env, "BPF_LDX uses reserved fields\n"); 10745 return -EINVAL; 10746 } 10747 10748 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 10749 struct bpf_insn_aux_data *aux; 10750 struct bpf_map *map; 10751 struct fd f; 10752 u64 addr; 10753 10754 if (i == insn_cnt - 1 || insn[1].code != 0 || 10755 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 10756 insn[1].off != 0) { 10757 verbose(env, "invalid bpf_ld_imm64 insn\n"); 10758 return -EINVAL; 10759 } 10760 10761 if (insn[0].src_reg == 0) 10762 /* valid generic load 64-bit imm */ 10763 goto next_insn; 10764 10765 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 10766 aux = &env->insn_aux_data[i]; 10767 err = check_pseudo_btf_id(env, insn, aux); 10768 if (err) 10769 return err; 10770 goto next_insn; 10771 } 10772 10773 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 10774 aux = &env->insn_aux_data[i]; 10775 aux->ptr_type = PTR_TO_FUNC; 10776 goto next_insn; 10777 } 10778 10779 /* In final convert_pseudo_ld_imm64() step, this is 10780 * converted into regular 64-bit imm load insn. 10781 */ 10782 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD && 10783 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) || 10784 (insn[0].src_reg == BPF_PSEUDO_MAP_FD && 10785 insn[1].imm != 0)) { 10786 verbose(env, 10787 "unrecognized bpf_ld_imm64 insn\n"); 10788 return -EINVAL; 10789 } 10790 10791 f = fdget(insn[0].imm); 10792 map = __bpf_map_get(f); 10793 if (IS_ERR(map)) { 10794 verbose(env, "fd %d is not pointing to valid bpf_map\n", 10795 insn[0].imm); 10796 return PTR_ERR(map); 10797 } 10798 10799 err = check_map_prog_compatibility(env, map, env->prog); 10800 if (err) { 10801 fdput(f); 10802 return err; 10803 } 10804 10805 aux = &env->insn_aux_data[i]; 10806 if (insn->src_reg == BPF_PSEUDO_MAP_FD) { 10807 addr = (unsigned long)map; 10808 } else { 10809 u32 off = insn[1].imm; 10810 10811 if (off >= BPF_MAX_VAR_OFF) { 10812 verbose(env, "direct value offset of %u is not allowed\n", off); 10813 fdput(f); 10814 return -EINVAL; 10815 } 10816 10817 if (!map->ops->map_direct_value_addr) { 10818 verbose(env, "no direct value access support for this map type\n"); 10819 fdput(f); 10820 return -EINVAL; 10821 } 10822 10823 err = map->ops->map_direct_value_addr(map, &addr, off); 10824 if (err) { 10825 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 10826 map->value_size, off); 10827 fdput(f); 10828 return err; 10829 } 10830 10831 aux->map_off = off; 10832 addr += off; 10833 } 10834 10835 insn[0].imm = (u32)addr; 10836 insn[1].imm = addr >> 32; 10837 10838 /* check whether we recorded this map already */ 10839 for (j = 0; j < env->used_map_cnt; j++) { 10840 if (env->used_maps[j] == map) { 10841 aux->map_index = j; 10842 fdput(f); 10843 goto next_insn; 10844 } 10845 } 10846 10847 if (env->used_map_cnt >= MAX_USED_MAPS) { 10848 fdput(f); 10849 return -E2BIG; 10850 } 10851 10852 /* hold the map. If the program is rejected by verifier, 10853 * the map will be released by release_maps() or it 10854 * will be used by the valid program until it's unloaded 10855 * and all maps are released in free_used_maps() 10856 */ 10857 bpf_map_inc(map); 10858 10859 aux->map_index = env->used_map_cnt; 10860 env->used_maps[env->used_map_cnt++] = map; 10861 10862 if (bpf_map_is_cgroup_storage(map) && 10863 bpf_cgroup_storage_assign(env->prog->aux, map)) { 10864 verbose(env, "only one cgroup storage of each type is allowed\n"); 10865 fdput(f); 10866 return -EBUSY; 10867 } 10868 10869 fdput(f); 10870 next_insn: 10871 insn++; 10872 i++; 10873 continue; 10874 } 10875 10876 /* Basic sanity check before we invest more work here. */ 10877 if (!bpf_opcode_in_insntable(insn->code)) { 10878 verbose(env, "unknown opcode %02x\n", insn->code); 10879 return -EINVAL; 10880 } 10881 } 10882 10883 /* now all pseudo BPF_LD_IMM64 instructions load valid 10884 * 'struct bpf_map *' into a register instead of user map_fd. 10885 * These pointers will be used later by verifier to validate map access. 10886 */ 10887 return 0; 10888 } 10889 10890 /* drop refcnt of maps used by the rejected program */ 10891 static void release_maps(struct bpf_verifier_env *env) 10892 { 10893 __bpf_free_used_maps(env->prog->aux, env->used_maps, 10894 env->used_map_cnt); 10895 } 10896 10897 /* drop refcnt of maps used by the rejected program */ 10898 static void release_btfs(struct bpf_verifier_env *env) 10899 { 10900 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 10901 env->used_btf_cnt); 10902 } 10903 10904 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 10905 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 10906 { 10907 struct bpf_insn *insn = env->prog->insnsi; 10908 int insn_cnt = env->prog->len; 10909 int i; 10910 10911 for (i = 0; i < insn_cnt; i++, insn++) { 10912 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 10913 continue; 10914 if (insn->src_reg == BPF_PSEUDO_FUNC) 10915 continue; 10916 insn->src_reg = 0; 10917 } 10918 } 10919 10920 /* single env->prog->insni[off] instruction was replaced with the range 10921 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 10922 * [0, off) and [off, end) to new locations, so the patched range stays zero 10923 */ 10924 static int adjust_insn_aux_data(struct bpf_verifier_env *env, 10925 struct bpf_prog *new_prog, u32 off, u32 cnt) 10926 { 10927 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; 10928 struct bpf_insn *insn = new_prog->insnsi; 10929 u32 prog_len; 10930 int i; 10931 10932 /* aux info at OFF always needs adjustment, no matter fast path 10933 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 10934 * original insn at old prog. 10935 */ 10936 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 10937 10938 if (cnt == 1) 10939 return 0; 10940 prog_len = new_prog->len; 10941 new_data = vzalloc(array_size(prog_len, 10942 sizeof(struct bpf_insn_aux_data))); 10943 if (!new_data) 10944 return -ENOMEM; 10945 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 10946 memcpy(new_data + off + cnt - 1, old_data + off, 10947 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 10948 for (i = off; i < off + cnt - 1; i++) { 10949 new_data[i].seen = env->pass_cnt; 10950 new_data[i].zext_dst = insn_has_def32(env, insn + i); 10951 } 10952 env->insn_aux_data = new_data; 10953 vfree(old_data); 10954 return 0; 10955 } 10956 10957 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 10958 { 10959 int i; 10960 10961 if (len == 1) 10962 return; 10963 /* NOTE: fake 'exit' subprog should be updated as well. */ 10964 for (i = 0; i <= env->subprog_cnt; i++) { 10965 if (env->subprog_info[i].start <= off) 10966 continue; 10967 env->subprog_info[i].start += len - 1; 10968 } 10969 } 10970 10971 static void adjust_poke_descs(struct bpf_prog *prog, u32 len) 10972 { 10973 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 10974 int i, sz = prog->aux->size_poke_tab; 10975 struct bpf_jit_poke_descriptor *desc; 10976 10977 for (i = 0; i < sz; i++) { 10978 desc = &tab[i]; 10979 desc->insn_idx += len - 1; 10980 } 10981 } 10982 10983 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 10984 const struct bpf_insn *patch, u32 len) 10985 { 10986 struct bpf_prog *new_prog; 10987 10988 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 10989 if (IS_ERR(new_prog)) { 10990 if (PTR_ERR(new_prog) == -ERANGE) 10991 verbose(env, 10992 "insn %d cannot be patched due to 16-bit range\n", 10993 env->insn_aux_data[off].orig_idx); 10994 return NULL; 10995 } 10996 if (adjust_insn_aux_data(env, new_prog, off, len)) 10997 return NULL; 10998 adjust_subprog_starts(env, off, len); 10999 adjust_poke_descs(new_prog, len); 11000 return new_prog; 11001 } 11002 11003 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 11004 u32 off, u32 cnt) 11005 { 11006 int i, j; 11007 11008 /* find first prog starting at or after off (first to remove) */ 11009 for (i = 0; i < env->subprog_cnt; i++) 11010 if (env->subprog_info[i].start >= off) 11011 break; 11012 /* find first prog starting at or after off + cnt (first to stay) */ 11013 for (j = i; j < env->subprog_cnt; j++) 11014 if (env->subprog_info[j].start >= off + cnt) 11015 break; 11016 /* if j doesn't start exactly at off + cnt, we are just removing 11017 * the front of previous prog 11018 */ 11019 if (env->subprog_info[j].start != off + cnt) 11020 j--; 11021 11022 if (j > i) { 11023 struct bpf_prog_aux *aux = env->prog->aux; 11024 int move; 11025 11026 /* move fake 'exit' subprog as well */ 11027 move = env->subprog_cnt + 1 - j; 11028 11029 memmove(env->subprog_info + i, 11030 env->subprog_info + j, 11031 sizeof(*env->subprog_info) * move); 11032 env->subprog_cnt -= j - i; 11033 11034 /* remove func_info */ 11035 if (aux->func_info) { 11036 move = aux->func_info_cnt - j; 11037 11038 memmove(aux->func_info + i, 11039 aux->func_info + j, 11040 sizeof(*aux->func_info) * move); 11041 aux->func_info_cnt -= j - i; 11042 /* func_info->insn_off is set after all code rewrites, 11043 * in adjust_btf_func() - no need to adjust 11044 */ 11045 } 11046 } else { 11047 /* convert i from "first prog to remove" to "first to adjust" */ 11048 if (env->subprog_info[i].start == off) 11049 i++; 11050 } 11051 11052 /* update fake 'exit' subprog as well */ 11053 for (; i <= env->subprog_cnt; i++) 11054 env->subprog_info[i].start -= cnt; 11055 11056 return 0; 11057 } 11058 11059 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 11060 u32 cnt) 11061 { 11062 struct bpf_prog *prog = env->prog; 11063 u32 i, l_off, l_cnt, nr_linfo; 11064 struct bpf_line_info *linfo; 11065 11066 nr_linfo = prog->aux->nr_linfo; 11067 if (!nr_linfo) 11068 return 0; 11069 11070 linfo = prog->aux->linfo; 11071 11072 /* find first line info to remove, count lines to be removed */ 11073 for (i = 0; i < nr_linfo; i++) 11074 if (linfo[i].insn_off >= off) 11075 break; 11076 11077 l_off = i; 11078 l_cnt = 0; 11079 for (; i < nr_linfo; i++) 11080 if (linfo[i].insn_off < off + cnt) 11081 l_cnt++; 11082 else 11083 break; 11084 11085 /* First live insn doesn't match first live linfo, it needs to "inherit" 11086 * last removed linfo. prog is already modified, so prog->len == off 11087 * means no live instructions after (tail of the program was removed). 11088 */ 11089 if (prog->len != off && l_cnt && 11090 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 11091 l_cnt--; 11092 linfo[--i].insn_off = off + cnt; 11093 } 11094 11095 /* remove the line info which refer to the removed instructions */ 11096 if (l_cnt) { 11097 memmove(linfo + l_off, linfo + i, 11098 sizeof(*linfo) * (nr_linfo - i)); 11099 11100 prog->aux->nr_linfo -= l_cnt; 11101 nr_linfo = prog->aux->nr_linfo; 11102 } 11103 11104 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 11105 for (i = l_off; i < nr_linfo; i++) 11106 linfo[i].insn_off -= cnt; 11107 11108 /* fix up all subprogs (incl. 'exit') which start >= off */ 11109 for (i = 0; i <= env->subprog_cnt; i++) 11110 if (env->subprog_info[i].linfo_idx > l_off) { 11111 /* program may have started in the removed region but 11112 * may not be fully removed 11113 */ 11114 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 11115 env->subprog_info[i].linfo_idx -= l_cnt; 11116 else 11117 env->subprog_info[i].linfo_idx = l_off; 11118 } 11119 11120 return 0; 11121 } 11122 11123 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 11124 { 11125 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11126 unsigned int orig_prog_len = env->prog->len; 11127 int err; 11128 11129 if (bpf_prog_is_dev_bound(env->prog->aux)) 11130 bpf_prog_offload_remove_insns(env, off, cnt); 11131 11132 err = bpf_remove_insns(env->prog, off, cnt); 11133 if (err) 11134 return err; 11135 11136 err = adjust_subprog_starts_after_remove(env, off, cnt); 11137 if (err) 11138 return err; 11139 11140 err = bpf_adj_linfo_after_remove(env, off, cnt); 11141 if (err) 11142 return err; 11143 11144 memmove(aux_data + off, aux_data + off + cnt, 11145 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 11146 11147 return 0; 11148 } 11149 11150 /* The verifier does more data flow analysis than llvm and will not 11151 * explore branches that are dead at run time. Malicious programs can 11152 * have dead code too. Therefore replace all dead at-run-time code 11153 * with 'ja -1'. 11154 * 11155 * Just nops are not optimal, e.g. if they would sit at the end of the 11156 * program and through another bug we would manage to jump there, then 11157 * we'd execute beyond program memory otherwise. Returning exception 11158 * code also wouldn't work since we can have subprogs where the dead 11159 * code could be located. 11160 */ 11161 static void sanitize_dead_code(struct bpf_verifier_env *env) 11162 { 11163 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11164 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 11165 struct bpf_insn *insn = env->prog->insnsi; 11166 const int insn_cnt = env->prog->len; 11167 int i; 11168 11169 for (i = 0; i < insn_cnt; i++) { 11170 if (aux_data[i].seen) 11171 continue; 11172 memcpy(insn + i, &trap, sizeof(trap)); 11173 } 11174 } 11175 11176 static bool insn_is_cond_jump(u8 code) 11177 { 11178 u8 op; 11179 11180 if (BPF_CLASS(code) == BPF_JMP32) 11181 return true; 11182 11183 if (BPF_CLASS(code) != BPF_JMP) 11184 return false; 11185 11186 op = BPF_OP(code); 11187 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 11188 } 11189 11190 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 11191 { 11192 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11193 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 11194 struct bpf_insn *insn = env->prog->insnsi; 11195 const int insn_cnt = env->prog->len; 11196 int i; 11197 11198 for (i = 0; i < insn_cnt; i++, insn++) { 11199 if (!insn_is_cond_jump(insn->code)) 11200 continue; 11201 11202 if (!aux_data[i + 1].seen) 11203 ja.off = insn->off; 11204 else if (!aux_data[i + 1 + insn->off].seen) 11205 ja.off = 0; 11206 else 11207 continue; 11208 11209 if (bpf_prog_is_dev_bound(env->prog->aux)) 11210 bpf_prog_offload_replace_insn(env, i, &ja); 11211 11212 memcpy(insn, &ja, sizeof(ja)); 11213 } 11214 } 11215 11216 static int opt_remove_dead_code(struct bpf_verifier_env *env) 11217 { 11218 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11219 int insn_cnt = env->prog->len; 11220 int i, err; 11221 11222 for (i = 0; i < insn_cnt; i++) { 11223 int j; 11224 11225 j = 0; 11226 while (i + j < insn_cnt && !aux_data[i + j].seen) 11227 j++; 11228 if (!j) 11229 continue; 11230 11231 err = verifier_remove_insns(env, i, j); 11232 if (err) 11233 return err; 11234 insn_cnt = env->prog->len; 11235 } 11236 11237 return 0; 11238 } 11239 11240 static int opt_remove_nops(struct bpf_verifier_env *env) 11241 { 11242 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 11243 struct bpf_insn *insn = env->prog->insnsi; 11244 int insn_cnt = env->prog->len; 11245 int i, err; 11246 11247 for (i = 0; i < insn_cnt; i++) { 11248 if (memcmp(&insn[i], &ja, sizeof(ja))) 11249 continue; 11250 11251 err = verifier_remove_insns(env, i, 1); 11252 if (err) 11253 return err; 11254 insn_cnt--; 11255 i--; 11256 } 11257 11258 return 0; 11259 } 11260 11261 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 11262 const union bpf_attr *attr) 11263 { 11264 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 11265 struct bpf_insn_aux_data *aux = env->insn_aux_data; 11266 int i, patch_len, delta = 0, len = env->prog->len; 11267 struct bpf_insn *insns = env->prog->insnsi; 11268 struct bpf_prog *new_prog; 11269 bool rnd_hi32; 11270 11271 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 11272 zext_patch[1] = BPF_ZEXT_REG(0); 11273 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 11274 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 11275 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 11276 for (i = 0; i < len; i++) { 11277 int adj_idx = i + delta; 11278 struct bpf_insn insn; 11279 int load_reg; 11280 11281 insn = insns[adj_idx]; 11282 load_reg = insn_def_regno(&insn); 11283 if (!aux[adj_idx].zext_dst) { 11284 u8 code, class; 11285 u32 imm_rnd; 11286 11287 if (!rnd_hi32) 11288 continue; 11289 11290 code = insn.code; 11291 class = BPF_CLASS(code); 11292 if (load_reg == -1) 11293 continue; 11294 11295 /* NOTE: arg "reg" (the fourth one) is only used for 11296 * BPF_STX + SRC_OP, so it is safe to pass NULL 11297 * here. 11298 */ 11299 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 11300 if (class == BPF_LD && 11301 BPF_MODE(code) == BPF_IMM) 11302 i++; 11303 continue; 11304 } 11305 11306 /* ctx load could be transformed into wider load. */ 11307 if (class == BPF_LDX && 11308 aux[adj_idx].ptr_type == PTR_TO_CTX) 11309 continue; 11310 11311 imm_rnd = get_random_int(); 11312 rnd_hi32_patch[0] = insn; 11313 rnd_hi32_patch[1].imm = imm_rnd; 11314 rnd_hi32_patch[3].dst_reg = load_reg; 11315 patch = rnd_hi32_patch; 11316 patch_len = 4; 11317 goto apply_patch_buffer; 11318 } 11319 11320 /* Add in an zero-extend instruction if a) the JIT has requested 11321 * it or b) it's a CMPXCHG. 11322 * 11323 * The latter is because: BPF_CMPXCHG always loads a value into 11324 * R0, therefore always zero-extends. However some archs' 11325 * equivalent instruction only does this load when the 11326 * comparison is successful. This detail of CMPXCHG is 11327 * orthogonal to the general zero-extension behaviour of the 11328 * CPU, so it's treated independently of bpf_jit_needs_zext. 11329 */ 11330 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 11331 continue; 11332 11333 if (WARN_ON(load_reg == -1)) { 11334 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 11335 return -EFAULT; 11336 } 11337 11338 zext_patch[0] = insn; 11339 zext_patch[1].dst_reg = load_reg; 11340 zext_patch[1].src_reg = load_reg; 11341 patch = zext_patch; 11342 patch_len = 2; 11343 apply_patch_buffer: 11344 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 11345 if (!new_prog) 11346 return -ENOMEM; 11347 env->prog = new_prog; 11348 insns = new_prog->insnsi; 11349 aux = env->insn_aux_data; 11350 delta += patch_len - 1; 11351 } 11352 11353 return 0; 11354 } 11355 11356 /* convert load instructions that access fields of a context type into a 11357 * sequence of instructions that access fields of the underlying structure: 11358 * struct __sk_buff -> struct sk_buff 11359 * struct bpf_sock_ops -> struct sock 11360 */ 11361 static int convert_ctx_accesses(struct bpf_verifier_env *env) 11362 { 11363 const struct bpf_verifier_ops *ops = env->ops; 11364 int i, cnt, size, ctx_field_size, delta = 0; 11365 const int insn_cnt = env->prog->len; 11366 struct bpf_insn insn_buf[16], *insn; 11367 u32 target_size, size_default, off; 11368 struct bpf_prog *new_prog; 11369 enum bpf_access_type type; 11370 bool is_narrower_load; 11371 11372 if (ops->gen_prologue || env->seen_direct_write) { 11373 if (!ops->gen_prologue) { 11374 verbose(env, "bpf verifier is misconfigured\n"); 11375 return -EINVAL; 11376 } 11377 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 11378 env->prog); 11379 if (cnt >= ARRAY_SIZE(insn_buf)) { 11380 verbose(env, "bpf verifier is misconfigured\n"); 11381 return -EINVAL; 11382 } else if (cnt) { 11383 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 11384 if (!new_prog) 11385 return -ENOMEM; 11386 11387 env->prog = new_prog; 11388 delta += cnt - 1; 11389 } 11390 } 11391 11392 if (bpf_prog_is_dev_bound(env->prog->aux)) 11393 return 0; 11394 11395 insn = env->prog->insnsi + delta; 11396 11397 for (i = 0; i < insn_cnt; i++, insn++) { 11398 bpf_convert_ctx_access_t convert_ctx_access; 11399 11400 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 11401 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 11402 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 11403 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) 11404 type = BPF_READ; 11405 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 11406 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 11407 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 11408 insn->code == (BPF_STX | BPF_MEM | BPF_DW)) 11409 type = BPF_WRITE; 11410 else 11411 continue; 11412 11413 if (type == BPF_WRITE && 11414 env->insn_aux_data[i + delta].sanitize_stack_off) { 11415 struct bpf_insn patch[] = { 11416 /* Sanitize suspicious stack slot with zero. 11417 * There are no memory dependencies for this store, 11418 * since it's only using frame pointer and immediate 11419 * constant of zero 11420 */ 11421 BPF_ST_MEM(BPF_DW, BPF_REG_FP, 11422 env->insn_aux_data[i + delta].sanitize_stack_off, 11423 0), 11424 /* the original STX instruction will immediately 11425 * overwrite the same stack slot with appropriate value 11426 */ 11427 *insn, 11428 }; 11429 11430 cnt = ARRAY_SIZE(patch); 11431 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 11432 if (!new_prog) 11433 return -ENOMEM; 11434 11435 delta += cnt - 1; 11436 env->prog = new_prog; 11437 insn = new_prog->insnsi + i + delta; 11438 continue; 11439 } 11440 11441 switch (env->insn_aux_data[i + delta].ptr_type) { 11442 case PTR_TO_CTX: 11443 if (!ops->convert_ctx_access) 11444 continue; 11445 convert_ctx_access = ops->convert_ctx_access; 11446 break; 11447 case PTR_TO_SOCKET: 11448 case PTR_TO_SOCK_COMMON: 11449 convert_ctx_access = bpf_sock_convert_ctx_access; 11450 break; 11451 case PTR_TO_TCP_SOCK: 11452 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 11453 break; 11454 case PTR_TO_XDP_SOCK: 11455 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 11456 break; 11457 case PTR_TO_BTF_ID: 11458 if (type == BPF_READ) { 11459 insn->code = BPF_LDX | BPF_PROBE_MEM | 11460 BPF_SIZE((insn)->code); 11461 env->prog->aux->num_exentries++; 11462 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) { 11463 verbose(env, "Writes through BTF pointers are not allowed\n"); 11464 return -EINVAL; 11465 } 11466 continue; 11467 default: 11468 continue; 11469 } 11470 11471 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 11472 size = BPF_LDST_BYTES(insn); 11473 11474 /* If the read access is a narrower load of the field, 11475 * convert to a 4/8-byte load, to minimum program type specific 11476 * convert_ctx_access changes. If conversion is successful, 11477 * we will apply proper mask to the result. 11478 */ 11479 is_narrower_load = size < ctx_field_size; 11480 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 11481 off = insn->off; 11482 if (is_narrower_load) { 11483 u8 size_code; 11484 11485 if (type == BPF_WRITE) { 11486 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 11487 return -EINVAL; 11488 } 11489 11490 size_code = BPF_H; 11491 if (ctx_field_size == 4) 11492 size_code = BPF_W; 11493 else if (ctx_field_size == 8) 11494 size_code = BPF_DW; 11495 11496 insn->off = off & ~(size_default - 1); 11497 insn->code = BPF_LDX | BPF_MEM | size_code; 11498 } 11499 11500 target_size = 0; 11501 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 11502 &target_size); 11503 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 11504 (ctx_field_size && !target_size)) { 11505 verbose(env, "bpf verifier is misconfigured\n"); 11506 return -EINVAL; 11507 } 11508 11509 if (is_narrower_load && size < target_size) { 11510 u8 shift = bpf_ctx_narrow_access_offset( 11511 off, size, size_default) * 8; 11512 if (ctx_field_size <= 4) { 11513 if (shift) 11514 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 11515 insn->dst_reg, 11516 shift); 11517 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 11518 (1 << size * 8) - 1); 11519 } else { 11520 if (shift) 11521 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 11522 insn->dst_reg, 11523 shift); 11524 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 11525 (1ULL << size * 8) - 1); 11526 } 11527 } 11528 11529 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 11530 if (!new_prog) 11531 return -ENOMEM; 11532 11533 delta += cnt - 1; 11534 11535 /* keep walking new program and skip insns we just inserted */ 11536 env->prog = new_prog; 11537 insn = new_prog->insnsi + i + delta; 11538 } 11539 11540 return 0; 11541 } 11542 11543 static int jit_subprogs(struct bpf_verifier_env *env) 11544 { 11545 struct bpf_prog *prog = env->prog, **func, *tmp; 11546 int i, j, subprog_start, subprog_end = 0, len, subprog; 11547 struct bpf_map *map_ptr; 11548 struct bpf_insn *insn; 11549 void *old_bpf_func; 11550 int err, num_exentries; 11551 11552 if (env->subprog_cnt <= 1) 11553 return 0; 11554 11555 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 11556 if (bpf_pseudo_func(insn)) { 11557 env->insn_aux_data[i].call_imm = insn->imm; 11558 /* subprog is encoded in insn[1].imm */ 11559 continue; 11560 } 11561 11562 if (!bpf_pseudo_call(insn)) 11563 continue; 11564 /* Upon error here we cannot fall back to interpreter but 11565 * need a hard reject of the program. Thus -EFAULT is 11566 * propagated in any case. 11567 */ 11568 subprog = find_subprog(env, i + insn->imm + 1); 11569 if (subprog < 0) { 11570 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 11571 i + insn->imm + 1); 11572 return -EFAULT; 11573 } 11574 /* temporarily remember subprog id inside insn instead of 11575 * aux_data, since next loop will split up all insns into funcs 11576 */ 11577 insn->off = subprog; 11578 /* remember original imm in case JIT fails and fallback 11579 * to interpreter will be needed 11580 */ 11581 env->insn_aux_data[i].call_imm = insn->imm; 11582 /* point imm to __bpf_call_base+1 from JITs point of view */ 11583 insn->imm = 1; 11584 } 11585 11586 err = bpf_prog_alloc_jited_linfo(prog); 11587 if (err) 11588 goto out_undo_insn; 11589 11590 err = -ENOMEM; 11591 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 11592 if (!func) 11593 goto out_undo_insn; 11594 11595 for (i = 0; i < env->subprog_cnt; i++) { 11596 subprog_start = subprog_end; 11597 subprog_end = env->subprog_info[i + 1].start; 11598 11599 len = subprog_end - subprog_start; 11600 /* BPF_PROG_RUN doesn't call subprogs directly, 11601 * hence main prog stats include the runtime of subprogs. 11602 * subprogs don't have IDs and not reachable via prog_get_next_id 11603 * func[i]->stats will never be accessed and stays NULL 11604 */ 11605 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 11606 if (!func[i]) 11607 goto out_free; 11608 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 11609 len * sizeof(struct bpf_insn)); 11610 func[i]->type = prog->type; 11611 func[i]->len = len; 11612 if (bpf_prog_calc_tag(func[i])) 11613 goto out_free; 11614 func[i]->is_func = 1; 11615 func[i]->aux->func_idx = i; 11616 /* the btf and func_info will be freed only at prog->aux */ 11617 func[i]->aux->btf = prog->aux->btf; 11618 func[i]->aux->func_info = prog->aux->func_info; 11619 11620 for (j = 0; j < prog->aux->size_poke_tab; j++) { 11621 u32 insn_idx = prog->aux->poke_tab[j].insn_idx; 11622 int ret; 11623 11624 if (!(insn_idx >= subprog_start && 11625 insn_idx <= subprog_end)) 11626 continue; 11627 11628 ret = bpf_jit_add_poke_descriptor(func[i], 11629 &prog->aux->poke_tab[j]); 11630 if (ret < 0) { 11631 verbose(env, "adding tail call poke descriptor failed\n"); 11632 goto out_free; 11633 } 11634 11635 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1; 11636 11637 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map; 11638 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux); 11639 if (ret < 0) { 11640 verbose(env, "tracking tail call prog failed\n"); 11641 goto out_free; 11642 } 11643 } 11644 11645 /* Use bpf_prog_F_tag to indicate functions in stack traces. 11646 * Long term would need debug info to populate names 11647 */ 11648 func[i]->aux->name[0] = 'F'; 11649 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 11650 func[i]->jit_requested = 1; 11651 func[i]->aux->linfo = prog->aux->linfo; 11652 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 11653 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 11654 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 11655 num_exentries = 0; 11656 insn = func[i]->insnsi; 11657 for (j = 0; j < func[i]->len; j++, insn++) { 11658 if (BPF_CLASS(insn->code) == BPF_LDX && 11659 BPF_MODE(insn->code) == BPF_PROBE_MEM) 11660 num_exentries++; 11661 } 11662 func[i]->aux->num_exentries = num_exentries; 11663 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 11664 func[i] = bpf_int_jit_compile(func[i]); 11665 if (!func[i]->jited) { 11666 err = -ENOTSUPP; 11667 goto out_free; 11668 } 11669 cond_resched(); 11670 } 11671 11672 /* Untrack main program's aux structs so that during map_poke_run() 11673 * we will not stumble upon the unfilled poke descriptors; each 11674 * of the main program's poke descs got distributed across subprogs 11675 * and got tracked onto map, so we are sure that none of them will 11676 * be missed after the operation below 11677 */ 11678 for (i = 0; i < prog->aux->size_poke_tab; i++) { 11679 map_ptr = prog->aux->poke_tab[i].tail_call.map; 11680 11681 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 11682 } 11683 11684 /* at this point all bpf functions were successfully JITed 11685 * now populate all bpf_calls with correct addresses and 11686 * run last pass of JIT 11687 */ 11688 for (i = 0; i < env->subprog_cnt; i++) { 11689 insn = func[i]->insnsi; 11690 for (j = 0; j < func[i]->len; j++, insn++) { 11691 if (bpf_pseudo_func(insn)) { 11692 subprog = insn[1].imm; 11693 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 11694 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 11695 continue; 11696 } 11697 if (!bpf_pseudo_call(insn)) 11698 continue; 11699 subprog = insn->off; 11700 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) - 11701 __bpf_call_base; 11702 } 11703 11704 /* we use the aux data to keep a list of the start addresses 11705 * of the JITed images for each function in the program 11706 * 11707 * for some architectures, such as powerpc64, the imm field 11708 * might not be large enough to hold the offset of the start 11709 * address of the callee's JITed image from __bpf_call_base 11710 * 11711 * in such cases, we can lookup the start address of a callee 11712 * by using its subprog id, available from the off field of 11713 * the call instruction, as an index for this list 11714 */ 11715 func[i]->aux->func = func; 11716 func[i]->aux->func_cnt = env->subprog_cnt; 11717 } 11718 for (i = 0; i < env->subprog_cnt; i++) { 11719 old_bpf_func = func[i]->bpf_func; 11720 tmp = bpf_int_jit_compile(func[i]); 11721 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 11722 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 11723 err = -ENOTSUPP; 11724 goto out_free; 11725 } 11726 cond_resched(); 11727 } 11728 11729 /* finally lock prog and jit images for all functions and 11730 * populate kallsysm 11731 */ 11732 for (i = 0; i < env->subprog_cnt; i++) { 11733 bpf_prog_lock_ro(func[i]); 11734 bpf_prog_kallsyms_add(func[i]); 11735 } 11736 11737 /* Last step: make now unused interpreter insns from main 11738 * prog consistent for later dump requests, so they can 11739 * later look the same as if they were interpreted only. 11740 */ 11741 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 11742 if (bpf_pseudo_func(insn)) { 11743 insn[0].imm = env->insn_aux_data[i].call_imm; 11744 insn[1].imm = find_subprog(env, i + insn[0].imm + 1); 11745 continue; 11746 } 11747 if (!bpf_pseudo_call(insn)) 11748 continue; 11749 insn->off = env->insn_aux_data[i].call_imm; 11750 subprog = find_subprog(env, i + insn->off + 1); 11751 insn->imm = subprog; 11752 } 11753 11754 prog->jited = 1; 11755 prog->bpf_func = func[0]->bpf_func; 11756 prog->aux->func = func; 11757 prog->aux->func_cnt = env->subprog_cnt; 11758 bpf_prog_free_unused_jited_linfo(prog); 11759 return 0; 11760 out_free: 11761 for (i = 0; i < env->subprog_cnt; i++) { 11762 if (!func[i]) 11763 continue; 11764 11765 for (j = 0; j < func[i]->aux->size_poke_tab; j++) { 11766 map_ptr = func[i]->aux->poke_tab[j].tail_call.map; 11767 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux); 11768 } 11769 bpf_jit_free(func[i]); 11770 } 11771 kfree(func); 11772 out_undo_insn: 11773 /* cleanup main prog to be interpreted */ 11774 prog->jit_requested = 0; 11775 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 11776 if (!bpf_pseudo_call(insn)) 11777 continue; 11778 insn->off = 0; 11779 insn->imm = env->insn_aux_data[i].call_imm; 11780 } 11781 bpf_prog_free_jited_linfo(prog); 11782 return err; 11783 } 11784 11785 static int fixup_call_args(struct bpf_verifier_env *env) 11786 { 11787 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 11788 struct bpf_prog *prog = env->prog; 11789 struct bpf_insn *insn = prog->insnsi; 11790 int i, depth; 11791 #endif 11792 int err = 0; 11793 11794 if (env->prog->jit_requested && 11795 !bpf_prog_is_dev_bound(env->prog->aux)) { 11796 err = jit_subprogs(env); 11797 if (err == 0) 11798 return 0; 11799 if (err == -EFAULT) 11800 return err; 11801 } 11802 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 11803 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 11804 /* When JIT fails the progs with bpf2bpf calls and tail_calls 11805 * have to be rejected, since interpreter doesn't support them yet. 11806 */ 11807 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 11808 return -EINVAL; 11809 } 11810 for (i = 0; i < prog->len; i++, insn++) { 11811 if (bpf_pseudo_func(insn)) { 11812 /* When JIT fails the progs with callback calls 11813 * have to be rejected, since interpreter doesn't support them yet. 11814 */ 11815 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 11816 return -EINVAL; 11817 } 11818 11819 if (!bpf_pseudo_call(insn)) 11820 continue; 11821 depth = get_callee_stack_depth(env, insn, i); 11822 if (depth < 0) 11823 return depth; 11824 bpf_patch_call_args(insn, depth); 11825 } 11826 err = 0; 11827 #endif 11828 return err; 11829 } 11830 11831 /* Do various post-verification rewrites in a single program pass. 11832 * These rewrites simplify JIT and interpreter implementations. 11833 */ 11834 static int do_misc_fixups(struct bpf_verifier_env *env) 11835 { 11836 struct bpf_prog *prog = env->prog; 11837 bool expect_blinding = bpf_jit_blinding_enabled(prog); 11838 struct bpf_insn *insn = prog->insnsi; 11839 const struct bpf_func_proto *fn; 11840 const int insn_cnt = prog->len; 11841 const struct bpf_map_ops *ops; 11842 struct bpf_insn_aux_data *aux; 11843 struct bpf_insn insn_buf[16]; 11844 struct bpf_prog *new_prog; 11845 struct bpf_map *map_ptr; 11846 int i, ret, cnt, delta = 0; 11847 11848 for (i = 0; i < insn_cnt; i++, insn++) { 11849 /* Make divide-by-zero exceptions impossible. */ 11850 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 11851 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 11852 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 11853 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 11854 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 11855 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 11856 struct bpf_insn *patchlet; 11857 struct bpf_insn chk_and_div[] = { 11858 /* [R,W]x div 0 -> 0 */ 11859 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 11860 BPF_JNE | BPF_K, insn->src_reg, 11861 0, 2, 0), 11862 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 11863 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 11864 *insn, 11865 }; 11866 struct bpf_insn chk_and_mod[] = { 11867 /* [R,W]x mod 0 -> [R,W]x */ 11868 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 11869 BPF_JEQ | BPF_K, insn->src_reg, 11870 0, 1 + (is64 ? 0 : 1), 0), 11871 *insn, 11872 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 11873 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 11874 }; 11875 11876 patchlet = isdiv ? chk_and_div : chk_and_mod; 11877 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 11878 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 11879 11880 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 11881 if (!new_prog) 11882 return -ENOMEM; 11883 11884 delta += cnt - 1; 11885 env->prog = prog = new_prog; 11886 insn = new_prog->insnsi + i + delta; 11887 continue; 11888 } 11889 11890 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 11891 if (BPF_CLASS(insn->code) == BPF_LD && 11892 (BPF_MODE(insn->code) == BPF_ABS || 11893 BPF_MODE(insn->code) == BPF_IND)) { 11894 cnt = env->ops->gen_ld_abs(insn, insn_buf); 11895 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 11896 verbose(env, "bpf verifier is misconfigured\n"); 11897 return -EINVAL; 11898 } 11899 11900 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 11901 if (!new_prog) 11902 return -ENOMEM; 11903 11904 delta += cnt - 1; 11905 env->prog = prog = new_prog; 11906 insn = new_prog->insnsi + i + delta; 11907 continue; 11908 } 11909 11910 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 11911 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 11912 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 11913 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 11914 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 11915 struct bpf_insn *patch = &insn_buf[0]; 11916 bool issrc, isneg; 11917 u32 off_reg; 11918 11919 aux = &env->insn_aux_data[i + delta]; 11920 if (!aux->alu_state || 11921 aux->alu_state == BPF_ALU_NON_POINTER) 11922 continue; 11923 11924 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 11925 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 11926 BPF_ALU_SANITIZE_SRC; 11927 11928 off_reg = issrc ? insn->src_reg : insn->dst_reg; 11929 if (isneg) 11930 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 11931 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 11932 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 11933 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 11934 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 11935 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 11936 if (issrc) { 11937 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, 11938 off_reg); 11939 insn->src_reg = BPF_REG_AX; 11940 } else { 11941 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg, 11942 BPF_REG_AX); 11943 } 11944 if (isneg) 11945 insn->code = insn->code == code_add ? 11946 code_sub : code_add; 11947 *patch++ = *insn; 11948 if (issrc && isneg) 11949 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 11950 cnt = patch - insn_buf; 11951 11952 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 11953 if (!new_prog) 11954 return -ENOMEM; 11955 11956 delta += cnt - 1; 11957 env->prog = prog = new_prog; 11958 insn = new_prog->insnsi + i + delta; 11959 continue; 11960 } 11961 11962 if (insn->code != (BPF_JMP | BPF_CALL)) 11963 continue; 11964 if (insn->src_reg == BPF_PSEUDO_CALL) 11965 continue; 11966 11967 if (insn->imm == BPF_FUNC_get_route_realm) 11968 prog->dst_needed = 1; 11969 if (insn->imm == BPF_FUNC_get_prandom_u32) 11970 bpf_user_rnd_init_once(); 11971 if (insn->imm == BPF_FUNC_override_return) 11972 prog->kprobe_override = 1; 11973 if (insn->imm == BPF_FUNC_tail_call) { 11974 /* If we tail call into other programs, we 11975 * cannot make any assumptions since they can 11976 * be replaced dynamically during runtime in 11977 * the program array. 11978 */ 11979 prog->cb_access = 1; 11980 if (!allow_tail_call_in_subprogs(env)) 11981 prog->aux->stack_depth = MAX_BPF_STACK; 11982 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 11983 11984 /* mark bpf_tail_call as different opcode to avoid 11985 * conditional branch in the interpeter for every normal 11986 * call and to prevent accidental JITing by JIT compiler 11987 * that doesn't support bpf_tail_call yet 11988 */ 11989 insn->imm = 0; 11990 insn->code = BPF_JMP | BPF_TAIL_CALL; 11991 11992 aux = &env->insn_aux_data[i + delta]; 11993 if (env->bpf_capable && !expect_blinding && 11994 prog->jit_requested && 11995 !bpf_map_key_poisoned(aux) && 11996 !bpf_map_ptr_poisoned(aux) && 11997 !bpf_map_ptr_unpriv(aux)) { 11998 struct bpf_jit_poke_descriptor desc = { 11999 .reason = BPF_POKE_REASON_TAIL_CALL, 12000 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 12001 .tail_call.key = bpf_map_key_immediate(aux), 12002 .insn_idx = i + delta, 12003 }; 12004 12005 ret = bpf_jit_add_poke_descriptor(prog, &desc); 12006 if (ret < 0) { 12007 verbose(env, "adding tail call poke descriptor failed\n"); 12008 return ret; 12009 } 12010 12011 insn->imm = ret + 1; 12012 continue; 12013 } 12014 12015 if (!bpf_map_ptr_unpriv(aux)) 12016 continue; 12017 12018 /* instead of changing every JIT dealing with tail_call 12019 * emit two extra insns: 12020 * if (index >= max_entries) goto out; 12021 * index &= array->index_mask; 12022 * to avoid out-of-bounds cpu speculation 12023 */ 12024 if (bpf_map_ptr_poisoned(aux)) { 12025 verbose(env, "tail_call abusing map_ptr\n"); 12026 return -EINVAL; 12027 } 12028 12029 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 12030 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 12031 map_ptr->max_entries, 2); 12032 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 12033 container_of(map_ptr, 12034 struct bpf_array, 12035 map)->index_mask); 12036 insn_buf[2] = *insn; 12037 cnt = 3; 12038 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12039 if (!new_prog) 12040 return -ENOMEM; 12041 12042 delta += cnt - 1; 12043 env->prog = prog = new_prog; 12044 insn = new_prog->insnsi + i + delta; 12045 continue; 12046 } 12047 12048 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 12049 * and other inlining handlers are currently limited to 64 bit 12050 * only. 12051 */ 12052 if (prog->jit_requested && BITS_PER_LONG == 64 && 12053 (insn->imm == BPF_FUNC_map_lookup_elem || 12054 insn->imm == BPF_FUNC_map_update_elem || 12055 insn->imm == BPF_FUNC_map_delete_elem || 12056 insn->imm == BPF_FUNC_map_push_elem || 12057 insn->imm == BPF_FUNC_map_pop_elem || 12058 insn->imm == BPF_FUNC_map_peek_elem || 12059 insn->imm == BPF_FUNC_redirect_map)) { 12060 aux = &env->insn_aux_data[i + delta]; 12061 if (bpf_map_ptr_poisoned(aux)) 12062 goto patch_call_imm; 12063 12064 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 12065 ops = map_ptr->ops; 12066 if (insn->imm == BPF_FUNC_map_lookup_elem && 12067 ops->map_gen_lookup) { 12068 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 12069 if (cnt == -EOPNOTSUPP) 12070 goto patch_map_ops_generic; 12071 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 12072 verbose(env, "bpf verifier is misconfigured\n"); 12073 return -EINVAL; 12074 } 12075 12076 new_prog = bpf_patch_insn_data(env, i + delta, 12077 insn_buf, cnt); 12078 if (!new_prog) 12079 return -ENOMEM; 12080 12081 delta += cnt - 1; 12082 env->prog = prog = new_prog; 12083 insn = new_prog->insnsi + i + delta; 12084 continue; 12085 } 12086 12087 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 12088 (void *(*)(struct bpf_map *map, void *key))NULL)); 12089 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 12090 (int (*)(struct bpf_map *map, void *key))NULL)); 12091 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 12092 (int (*)(struct bpf_map *map, void *key, void *value, 12093 u64 flags))NULL)); 12094 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 12095 (int (*)(struct bpf_map *map, void *value, 12096 u64 flags))NULL)); 12097 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 12098 (int (*)(struct bpf_map *map, void *value))NULL)); 12099 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 12100 (int (*)(struct bpf_map *map, void *value))NULL)); 12101 BUILD_BUG_ON(!__same_type(ops->map_redirect, 12102 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL)); 12103 12104 patch_map_ops_generic: 12105 switch (insn->imm) { 12106 case BPF_FUNC_map_lookup_elem: 12107 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - 12108 __bpf_call_base; 12109 continue; 12110 case BPF_FUNC_map_update_elem: 12111 insn->imm = BPF_CAST_CALL(ops->map_update_elem) - 12112 __bpf_call_base; 12113 continue; 12114 case BPF_FUNC_map_delete_elem: 12115 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - 12116 __bpf_call_base; 12117 continue; 12118 case BPF_FUNC_map_push_elem: 12119 insn->imm = BPF_CAST_CALL(ops->map_push_elem) - 12120 __bpf_call_base; 12121 continue; 12122 case BPF_FUNC_map_pop_elem: 12123 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) - 12124 __bpf_call_base; 12125 continue; 12126 case BPF_FUNC_map_peek_elem: 12127 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) - 12128 __bpf_call_base; 12129 continue; 12130 case BPF_FUNC_redirect_map: 12131 insn->imm = BPF_CAST_CALL(ops->map_redirect) - 12132 __bpf_call_base; 12133 continue; 12134 } 12135 12136 goto patch_call_imm; 12137 } 12138 12139 /* Implement bpf_jiffies64 inline. */ 12140 if (prog->jit_requested && BITS_PER_LONG == 64 && 12141 insn->imm == BPF_FUNC_jiffies64) { 12142 struct bpf_insn ld_jiffies_addr[2] = { 12143 BPF_LD_IMM64(BPF_REG_0, 12144 (unsigned long)&jiffies), 12145 }; 12146 12147 insn_buf[0] = ld_jiffies_addr[0]; 12148 insn_buf[1] = ld_jiffies_addr[1]; 12149 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 12150 BPF_REG_0, 0); 12151 cnt = 3; 12152 12153 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 12154 cnt); 12155 if (!new_prog) 12156 return -ENOMEM; 12157 12158 delta += cnt - 1; 12159 env->prog = prog = new_prog; 12160 insn = new_prog->insnsi + i + delta; 12161 continue; 12162 } 12163 12164 patch_call_imm: 12165 fn = env->ops->get_func_proto(insn->imm, env->prog); 12166 /* all functions that have prototype and verifier allowed 12167 * programs to call them, must be real in-kernel functions 12168 */ 12169 if (!fn->func) { 12170 verbose(env, 12171 "kernel subsystem misconfigured func %s#%d\n", 12172 func_id_name(insn->imm), insn->imm); 12173 return -EFAULT; 12174 } 12175 insn->imm = fn->func - __bpf_call_base; 12176 } 12177 12178 /* Since poke tab is now finalized, publish aux to tracker. */ 12179 for (i = 0; i < prog->aux->size_poke_tab; i++) { 12180 map_ptr = prog->aux->poke_tab[i].tail_call.map; 12181 if (!map_ptr->ops->map_poke_track || 12182 !map_ptr->ops->map_poke_untrack || 12183 !map_ptr->ops->map_poke_run) { 12184 verbose(env, "bpf verifier is misconfigured\n"); 12185 return -EINVAL; 12186 } 12187 12188 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 12189 if (ret < 0) { 12190 verbose(env, "tracking tail call prog failed\n"); 12191 return ret; 12192 } 12193 } 12194 12195 return 0; 12196 } 12197 12198 static void free_states(struct bpf_verifier_env *env) 12199 { 12200 struct bpf_verifier_state_list *sl, *sln; 12201 int i; 12202 12203 sl = env->free_list; 12204 while (sl) { 12205 sln = sl->next; 12206 free_verifier_state(&sl->state, false); 12207 kfree(sl); 12208 sl = sln; 12209 } 12210 env->free_list = NULL; 12211 12212 if (!env->explored_states) 12213 return; 12214 12215 for (i = 0; i < state_htab_size(env); i++) { 12216 sl = env->explored_states[i]; 12217 12218 while (sl) { 12219 sln = sl->next; 12220 free_verifier_state(&sl->state, false); 12221 kfree(sl); 12222 sl = sln; 12223 } 12224 env->explored_states[i] = NULL; 12225 } 12226 } 12227 12228 /* The verifier is using insn_aux_data[] to store temporary data during 12229 * verification and to store information for passes that run after the 12230 * verification like dead code sanitization. do_check_common() for subprogram N 12231 * may analyze many other subprograms. sanitize_insn_aux_data() clears all 12232 * temporary data after do_check_common() finds that subprogram N cannot be 12233 * verified independently. pass_cnt counts the number of times 12234 * do_check_common() was run and insn->aux->seen tells the pass number 12235 * insn_aux_data was touched. These variables are compared to clear temporary 12236 * data from failed pass. For testing and experiments do_check_common() can be 12237 * run multiple times even when prior attempt to verify is unsuccessful. 12238 */ 12239 static void sanitize_insn_aux_data(struct bpf_verifier_env *env) 12240 { 12241 struct bpf_insn *insn = env->prog->insnsi; 12242 struct bpf_insn_aux_data *aux; 12243 int i, class; 12244 12245 for (i = 0; i < env->prog->len; i++) { 12246 class = BPF_CLASS(insn[i].code); 12247 if (class != BPF_LDX && class != BPF_STX) 12248 continue; 12249 aux = &env->insn_aux_data[i]; 12250 if (aux->seen != env->pass_cnt) 12251 continue; 12252 memset(aux, 0, offsetof(typeof(*aux), orig_idx)); 12253 } 12254 } 12255 12256 static int do_check_common(struct bpf_verifier_env *env, int subprog) 12257 { 12258 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 12259 struct bpf_verifier_state *state; 12260 struct bpf_reg_state *regs; 12261 int ret, i; 12262 12263 env->prev_linfo = NULL; 12264 env->pass_cnt++; 12265 12266 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 12267 if (!state) 12268 return -ENOMEM; 12269 state->curframe = 0; 12270 state->speculative = false; 12271 state->branches = 1; 12272 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 12273 if (!state->frame[0]) { 12274 kfree(state); 12275 return -ENOMEM; 12276 } 12277 env->cur_state = state; 12278 init_func_state(env, state->frame[0], 12279 BPF_MAIN_FUNC /* callsite */, 12280 0 /* frameno */, 12281 subprog); 12282 12283 regs = state->frame[state->curframe]->regs; 12284 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 12285 ret = btf_prepare_func_args(env, subprog, regs); 12286 if (ret) 12287 goto out; 12288 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 12289 if (regs[i].type == PTR_TO_CTX) 12290 mark_reg_known_zero(env, regs, i); 12291 else if (regs[i].type == SCALAR_VALUE) 12292 mark_reg_unknown(env, regs, i); 12293 else if (regs[i].type == PTR_TO_MEM_OR_NULL) { 12294 const u32 mem_size = regs[i].mem_size; 12295 12296 mark_reg_known_zero(env, regs, i); 12297 regs[i].mem_size = mem_size; 12298 regs[i].id = ++env->id_gen; 12299 } 12300 } 12301 } else { 12302 /* 1st arg to a function */ 12303 regs[BPF_REG_1].type = PTR_TO_CTX; 12304 mark_reg_known_zero(env, regs, BPF_REG_1); 12305 ret = btf_check_func_arg_match(env, subprog, regs); 12306 if (ret == -EFAULT) 12307 /* unlikely verifier bug. abort. 12308 * ret == 0 and ret < 0 are sadly acceptable for 12309 * main() function due to backward compatibility. 12310 * Like socket filter program may be written as: 12311 * int bpf_prog(struct pt_regs *ctx) 12312 * and never dereference that ctx in the program. 12313 * 'struct pt_regs' is a type mismatch for socket 12314 * filter that should be using 'struct __sk_buff'. 12315 */ 12316 goto out; 12317 } 12318 12319 ret = do_check(env); 12320 out: 12321 /* check for NULL is necessary, since cur_state can be freed inside 12322 * do_check() under memory pressure. 12323 */ 12324 if (env->cur_state) { 12325 free_verifier_state(env->cur_state, true); 12326 env->cur_state = NULL; 12327 } 12328 while (!pop_stack(env, NULL, NULL, false)); 12329 if (!ret && pop_log) 12330 bpf_vlog_reset(&env->log, 0); 12331 free_states(env); 12332 if (ret) 12333 /* clean aux data in case subprog was rejected */ 12334 sanitize_insn_aux_data(env); 12335 return ret; 12336 } 12337 12338 /* Verify all global functions in a BPF program one by one based on their BTF. 12339 * All global functions must pass verification. Otherwise the whole program is rejected. 12340 * Consider: 12341 * int bar(int); 12342 * int foo(int f) 12343 * { 12344 * return bar(f); 12345 * } 12346 * int bar(int b) 12347 * { 12348 * ... 12349 * } 12350 * foo() will be verified first for R1=any_scalar_value. During verification it 12351 * will be assumed that bar() already verified successfully and call to bar() 12352 * from foo() will be checked for type match only. Later bar() will be verified 12353 * independently to check that it's safe for R1=any_scalar_value. 12354 */ 12355 static int do_check_subprogs(struct bpf_verifier_env *env) 12356 { 12357 struct bpf_prog_aux *aux = env->prog->aux; 12358 int i, ret; 12359 12360 if (!aux->func_info) 12361 return 0; 12362 12363 for (i = 1; i < env->subprog_cnt; i++) { 12364 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 12365 continue; 12366 env->insn_idx = env->subprog_info[i].start; 12367 WARN_ON_ONCE(env->insn_idx == 0); 12368 ret = do_check_common(env, i); 12369 if (ret) { 12370 return ret; 12371 } else if (env->log.level & BPF_LOG_LEVEL) { 12372 verbose(env, 12373 "Func#%d is safe for any args that match its prototype\n", 12374 i); 12375 } 12376 } 12377 return 0; 12378 } 12379 12380 static int do_check_main(struct bpf_verifier_env *env) 12381 { 12382 int ret; 12383 12384 env->insn_idx = 0; 12385 ret = do_check_common(env, 0); 12386 if (!ret) 12387 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 12388 return ret; 12389 } 12390 12391 12392 static void print_verification_stats(struct bpf_verifier_env *env) 12393 { 12394 int i; 12395 12396 if (env->log.level & BPF_LOG_STATS) { 12397 verbose(env, "verification time %lld usec\n", 12398 div_u64(env->verification_time, 1000)); 12399 verbose(env, "stack depth "); 12400 for (i = 0; i < env->subprog_cnt; i++) { 12401 u32 depth = env->subprog_info[i].stack_depth; 12402 12403 verbose(env, "%d", depth); 12404 if (i + 1 < env->subprog_cnt) 12405 verbose(env, "+"); 12406 } 12407 verbose(env, "\n"); 12408 } 12409 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 12410 "total_states %d peak_states %d mark_read %d\n", 12411 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 12412 env->max_states_per_insn, env->total_states, 12413 env->peak_states, env->longest_mark_read_walk); 12414 } 12415 12416 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 12417 { 12418 const struct btf_type *t, *func_proto; 12419 const struct bpf_struct_ops *st_ops; 12420 const struct btf_member *member; 12421 struct bpf_prog *prog = env->prog; 12422 u32 btf_id, member_idx; 12423 const char *mname; 12424 12425 btf_id = prog->aux->attach_btf_id; 12426 st_ops = bpf_struct_ops_find(btf_id); 12427 if (!st_ops) { 12428 verbose(env, "attach_btf_id %u is not a supported struct\n", 12429 btf_id); 12430 return -ENOTSUPP; 12431 } 12432 12433 t = st_ops->type; 12434 member_idx = prog->expected_attach_type; 12435 if (member_idx >= btf_type_vlen(t)) { 12436 verbose(env, "attach to invalid member idx %u of struct %s\n", 12437 member_idx, st_ops->name); 12438 return -EINVAL; 12439 } 12440 12441 member = &btf_type_member(t)[member_idx]; 12442 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 12443 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 12444 NULL); 12445 if (!func_proto) { 12446 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 12447 mname, member_idx, st_ops->name); 12448 return -EINVAL; 12449 } 12450 12451 if (st_ops->check_member) { 12452 int err = st_ops->check_member(t, member); 12453 12454 if (err) { 12455 verbose(env, "attach to unsupported member %s of struct %s\n", 12456 mname, st_ops->name); 12457 return err; 12458 } 12459 } 12460 12461 prog->aux->attach_func_proto = func_proto; 12462 prog->aux->attach_func_name = mname; 12463 env->ops = st_ops->verifier_ops; 12464 12465 return 0; 12466 } 12467 #define SECURITY_PREFIX "security_" 12468 12469 static int check_attach_modify_return(unsigned long addr, const char *func_name) 12470 { 12471 if (within_error_injection_list(addr) || 12472 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 12473 return 0; 12474 12475 return -EINVAL; 12476 } 12477 12478 /* list of non-sleepable functions that are otherwise on 12479 * ALLOW_ERROR_INJECTION list 12480 */ 12481 BTF_SET_START(btf_non_sleepable_error_inject) 12482 /* Three functions below can be called from sleepable and non-sleepable context. 12483 * Assume non-sleepable from bpf safety point of view. 12484 */ 12485 BTF_ID(func, __add_to_page_cache_locked) 12486 BTF_ID(func, should_fail_alloc_page) 12487 BTF_ID(func, should_failslab) 12488 BTF_SET_END(btf_non_sleepable_error_inject) 12489 12490 static int check_non_sleepable_error_inject(u32 btf_id) 12491 { 12492 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 12493 } 12494 12495 int bpf_check_attach_target(struct bpf_verifier_log *log, 12496 const struct bpf_prog *prog, 12497 const struct bpf_prog *tgt_prog, 12498 u32 btf_id, 12499 struct bpf_attach_target_info *tgt_info) 12500 { 12501 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 12502 const char prefix[] = "btf_trace_"; 12503 int ret = 0, subprog = -1, i; 12504 const struct btf_type *t; 12505 bool conservative = true; 12506 const char *tname; 12507 struct btf *btf; 12508 long addr = 0; 12509 12510 if (!btf_id) { 12511 bpf_log(log, "Tracing programs must provide btf_id\n"); 12512 return -EINVAL; 12513 } 12514 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 12515 if (!btf) { 12516 bpf_log(log, 12517 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 12518 return -EINVAL; 12519 } 12520 t = btf_type_by_id(btf, btf_id); 12521 if (!t) { 12522 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 12523 return -EINVAL; 12524 } 12525 tname = btf_name_by_offset(btf, t->name_off); 12526 if (!tname) { 12527 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 12528 return -EINVAL; 12529 } 12530 if (tgt_prog) { 12531 struct bpf_prog_aux *aux = tgt_prog->aux; 12532 12533 for (i = 0; i < aux->func_info_cnt; i++) 12534 if (aux->func_info[i].type_id == btf_id) { 12535 subprog = i; 12536 break; 12537 } 12538 if (subprog == -1) { 12539 bpf_log(log, "Subprog %s doesn't exist\n", tname); 12540 return -EINVAL; 12541 } 12542 conservative = aux->func_info_aux[subprog].unreliable; 12543 if (prog_extension) { 12544 if (conservative) { 12545 bpf_log(log, 12546 "Cannot replace static functions\n"); 12547 return -EINVAL; 12548 } 12549 if (!prog->jit_requested) { 12550 bpf_log(log, 12551 "Extension programs should be JITed\n"); 12552 return -EINVAL; 12553 } 12554 } 12555 if (!tgt_prog->jited) { 12556 bpf_log(log, "Can attach to only JITed progs\n"); 12557 return -EINVAL; 12558 } 12559 if (tgt_prog->type == prog->type) { 12560 /* Cannot fentry/fexit another fentry/fexit program. 12561 * Cannot attach program extension to another extension. 12562 * It's ok to attach fentry/fexit to extension program. 12563 */ 12564 bpf_log(log, "Cannot recursively attach\n"); 12565 return -EINVAL; 12566 } 12567 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 12568 prog_extension && 12569 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 12570 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 12571 /* Program extensions can extend all program types 12572 * except fentry/fexit. The reason is the following. 12573 * The fentry/fexit programs are used for performance 12574 * analysis, stats and can be attached to any program 12575 * type except themselves. When extension program is 12576 * replacing XDP function it is necessary to allow 12577 * performance analysis of all functions. Both original 12578 * XDP program and its program extension. Hence 12579 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 12580 * allowed. If extending of fentry/fexit was allowed it 12581 * would be possible to create long call chain 12582 * fentry->extension->fentry->extension beyond 12583 * reasonable stack size. Hence extending fentry is not 12584 * allowed. 12585 */ 12586 bpf_log(log, "Cannot extend fentry/fexit\n"); 12587 return -EINVAL; 12588 } 12589 } else { 12590 if (prog_extension) { 12591 bpf_log(log, "Cannot replace kernel functions\n"); 12592 return -EINVAL; 12593 } 12594 } 12595 12596 switch (prog->expected_attach_type) { 12597 case BPF_TRACE_RAW_TP: 12598 if (tgt_prog) { 12599 bpf_log(log, 12600 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 12601 return -EINVAL; 12602 } 12603 if (!btf_type_is_typedef(t)) { 12604 bpf_log(log, "attach_btf_id %u is not a typedef\n", 12605 btf_id); 12606 return -EINVAL; 12607 } 12608 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 12609 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 12610 btf_id, tname); 12611 return -EINVAL; 12612 } 12613 tname += sizeof(prefix) - 1; 12614 t = btf_type_by_id(btf, t->type); 12615 if (!btf_type_is_ptr(t)) 12616 /* should never happen in valid vmlinux build */ 12617 return -EINVAL; 12618 t = btf_type_by_id(btf, t->type); 12619 if (!btf_type_is_func_proto(t)) 12620 /* should never happen in valid vmlinux build */ 12621 return -EINVAL; 12622 12623 break; 12624 case BPF_TRACE_ITER: 12625 if (!btf_type_is_func(t)) { 12626 bpf_log(log, "attach_btf_id %u is not a function\n", 12627 btf_id); 12628 return -EINVAL; 12629 } 12630 t = btf_type_by_id(btf, t->type); 12631 if (!btf_type_is_func_proto(t)) 12632 return -EINVAL; 12633 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 12634 if (ret) 12635 return ret; 12636 break; 12637 default: 12638 if (!prog_extension) 12639 return -EINVAL; 12640 fallthrough; 12641 case BPF_MODIFY_RETURN: 12642 case BPF_LSM_MAC: 12643 case BPF_TRACE_FENTRY: 12644 case BPF_TRACE_FEXIT: 12645 if (!btf_type_is_func(t)) { 12646 bpf_log(log, "attach_btf_id %u is not a function\n", 12647 btf_id); 12648 return -EINVAL; 12649 } 12650 if (prog_extension && 12651 btf_check_type_match(log, prog, btf, t)) 12652 return -EINVAL; 12653 t = btf_type_by_id(btf, t->type); 12654 if (!btf_type_is_func_proto(t)) 12655 return -EINVAL; 12656 12657 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 12658 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 12659 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 12660 return -EINVAL; 12661 12662 if (tgt_prog && conservative) 12663 t = NULL; 12664 12665 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 12666 if (ret < 0) 12667 return ret; 12668 12669 if (tgt_prog) { 12670 if (subprog == 0) 12671 addr = (long) tgt_prog->bpf_func; 12672 else 12673 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 12674 } else { 12675 addr = kallsyms_lookup_name(tname); 12676 if (!addr) { 12677 bpf_log(log, 12678 "The address of function %s cannot be found\n", 12679 tname); 12680 return -ENOENT; 12681 } 12682 } 12683 12684 if (prog->aux->sleepable) { 12685 ret = -EINVAL; 12686 switch (prog->type) { 12687 case BPF_PROG_TYPE_TRACING: 12688 /* fentry/fexit/fmod_ret progs can be sleepable only if they are 12689 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 12690 */ 12691 if (!check_non_sleepable_error_inject(btf_id) && 12692 within_error_injection_list(addr)) 12693 ret = 0; 12694 break; 12695 case BPF_PROG_TYPE_LSM: 12696 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 12697 * Only some of them are sleepable. 12698 */ 12699 if (bpf_lsm_is_sleepable_hook(btf_id)) 12700 ret = 0; 12701 break; 12702 default: 12703 break; 12704 } 12705 if (ret) { 12706 bpf_log(log, "%s is not sleepable\n", tname); 12707 return ret; 12708 } 12709 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 12710 if (tgt_prog) { 12711 bpf_log(log, "can't modify return codes of BPF programs\n"); 12712 return -EINVAL; 12713 } 12714 ret = check_attach_modify_return(addr, tname); 12715 if (ret) { 12716 bpf_log(log, "%s() is not modifiable\n", tname); 12717 return ret; 12718 } 12719 } 12720 12721 break; 12722 } 12723 tgt_info->tgt_addr = addr; 12724 tgt_info->tgt_name = tname; 12725 tgt_info->tgt_type = t; 12726 return 0; 12727 } 12728 12729 static int check_attach_btf_id(struct bpf_verifier_env *env) 12730 { 12731 struct bpf_prog *prog = env->prog; 12732 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 12733 struct bpf_attach_target_info tgt_info = {}; 12734 u32 btf_id = prog->aux->attach_btf_id; 12735 struct bpf_trampoline *tr; 12736 int ret; 12737 u64 key; 12738 12739 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING && 12740 prog->type != BPF_PROG_TYPE_LSM) { 12741 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n"); 12742 return -EINVAL; 12743 } 12744 12745 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 12746 return check_struct_ops_btf_id(env); 12747 12748 if (prog->type != BPF_PROG_TYPE_TRACING && 12749 prog->type != BPF_PROG_TYPE_LSM && 12750 prog->type != BPF_PROG_TYPE_EXT) 12751 return 0; 12752 12753 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 12754 if (ret) 12755 return ret; 12756 12757 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 12758 /* to make freplace equivalent to their targets, they need to 12759 * inherit env->ops and expected_attach_type for the rest of the 12760 * verification 12761 */ 12762 env->ops = bpf_verifier_ops[tgt_prog->type]; 12763 prog->expected_attach_type = tgt_prog->expected_attach_type; 12764 } 12765 12766 /* store info about the attachment target that will be used later */ 12767 prog->aux->attach_func_proto = tgt_info.tgt_type; 12768 prog->aux->attach_func_name = tgt_info.tgt_name; 12769 12770 if (tgt_prog) { 12771 prog->aux->saved_dst_prog_type = tgt_prog->type; 12772 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 12773 } 12774 12775 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 12776 prog->aux->attach_btf_trace = true; 12777 return 0; 12778 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 12779 if (!bpf_iter_prog_supported(prog)) 12780 return -EINVAL; 12781 return 0; 12782 } 12783 12784 if (prog->type == BPF_PROG_TYPE_LSM) { 12785 ret = bpf_lsm_verify_prog(&env->log, prog); 12786 if (ret < 0) 12787 return ret; 12788 } 12789 12790 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 12791 tr = bpf_trampoline_get(key, &tgt_info); 12792 if (!tr) 12793 return -ENOMEM; 12794 12795 prog->aux->dst_trampoline = tr; 12796 return 0; 12797 } 12798 12799 struct btf *bpf_get_btf_vmlinux(void) 12800 { 12801 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 12802 mutex_lock(&bpf_verifier_lock); 12803 if (!btf_vmlinux) 12804 btf_vmlinux = btf_parse_vmlinux(); 12805 mutex_unlock(&bpf_verifier_lock); 12806 } 12807 return btf_vmlinux; 12808 } 12809 12810 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, 12811 union bpf_attr __user *uattr) 12812 { 12813 u64 start_time = ktime_get_ns(); 12814 struct bpf_verifier_env *env; 12815 struct bpf_verifier_log *log; 12816 int i, len, ret = -EINVAL; 12817 bool is_priv; 12818 12819 /* no program is valid */ 12820 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 12821 return -EINVAL; 12822 12823 /* 'struct bpf_verifier_env' can be global, but since it's not small, 12824 * allocate/free it every time bpf_check() is called 12825 */ 12826 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 12827 if (!env) 12828 return -ENOMEM; 12829 log = &env->log; 12830 12831 len = (*prog)->len; 12832 env->insn_aux_data = 12833 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 12834 ret = -ENOMEM; 12835 if (!env->insn_aux_data) 12836 goto err_free_env; 12837 for (i = 0; i < len; i++) 12838 env->insn_aux_data[i].orig_idx = i; 12839 env->prog = *prog; 12840 env->ops = bpf_verifier_ops[env->prog->type]; 12841 is_priv = bpf_capable(); 12842 12843 bpf_get_btf_vmlinux(); 12844 12845 /* grab the mutex to protect few globals used by verifier */ 12846 if (!is_priv) 12847 mutex_lock(&bpf_verifier_lock); 12848 12849 if (attr->log_level || attr->log_buf || attr->log_size) { 12850 /* user requested verbose verifier output 12851 * and supplied buffer to store the verification trace 12852 */ 12853 log->level = attr->log_level; 12854 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 12855 log->len_total = attr->log_size; 12856 12857 ret = -EINVAL; 12858 /* log attributes have to be sane */ 12859 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 || 12860 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK) 12861 goto err_unlock; 12862 } 12863 12864 if (IS_ERR(btf_vmlinux)) { 12865 /* Either gcc or pahole or kernel are broken. */ 12866 verbose(env, "in-kernel BTF is malformed\n"); 12867 ret = PTR_ERR(btf_vmlinux); 12868 goto skip_full_check; 12869 } 12870 12871 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 12872 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 12873 env->strict_alignment = true; 12874 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 12875 env->strict_alignment = false; 12876 12877 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 12878 env->allow_uninit_stack = bpf_allow_uninit_stack(); 12879 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access(); 12880 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 12881 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 12882 env->bpf_capable = bpf_capable(); 12883 12884 if (is_priv) 12885 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 12886 12887 if (bpf_prog_is_dev_bound(env->prog->aux)) { 12888 ret = bpf_prog_offload_verifier_prep(env->prog); 12889 if (ret) 12890 goto skip_full_check; 12891 } 12892 12893 env->explored_states = kvcalloc(state_htab_size(env), 12894 sizeof(struct bpf_verifier_state_list *), 12895 GFP_USER); 12896 ret = -ENOMEM; 12897 if (!env->explored_states) 12898 goto skip_full_check; 12899 12900 ret = check_subprogs(env); 12901 if (ret < 0) 12902 goto skip_full_check; 12903 12904 ret = check_btf_info(env, attr, uattr); 12905 if (ret < 0) 12906 goto skip_full_check; 12907 12908 ret = check_attach_btf_id(env); 12909 if (ret) 12910 goto skip_full_check; 12911 12912 ret = resolve_pseudo_ldimm64(env); 12913 if (ret < 0) 12914 goto skip_full_check; 12915 12916 ret = check_cfg(env); 12917 if (ret < 0) 12918 goto skip_full_check; 12919 12920 ret = do_check_subprogs(env); 12921 ret = ret ?: do_check_main(env); 12922 12923 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux)) 12924 ret = bpf_prog_offload_finalize(env); 12925 12926 skip_full_check: 12927 kvfree(env->explored_states); 12928 12929 if (ret == 0) 12930 ret = check_max_stack_depth(env); 12931 12932 /* instruction rewrites happen after this point */ 12933 if (is_priv) { 12934 if (ret == 0) 12935 opt_hard_wire_dead_code_branches(env); 12936 if (ret == 0) 12937 ret = opt_remove_dead_code(env); 12938 if (ret == 0) 12939 ret = opt_remove_nops(env); 12940 } else { 12941 if (ret == 0) 12942 sanitize_dead_code(env); 12943 } 12944 12945 if (ret == 0) 12946 /* program is valid, convert *(u32*)(ctx + off) accesses */ 12947 ret = convert_ctx_accesses(env); 12948 12949 if (ret == 0) 12950 ret = do_misc_fixups(env); 12951 12952 /* do 32-bit optimization after insn patching has done so those patched 12953 * insns could be handled correctly. 12954 */ 12955 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) { 12956 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 12957 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 12958 : false; 12959 } 12960 12961 if (ret == 0) 12962 ret = fixup_call_args(env); 12963 12964 env->verification_time = ktime_get_ns() - start_time; 12965 print_verification_stats(env); 12966 12967 if (log->level && bpf_verifier_log_full(log)) 12968 ret = -ENOSPC; 12969 if (log->level && !log->ubuf) { 12970 ret = -EFAULT; 12971 goto err_release_maps; 12972 } 12973 12974 if (ret) 12975 goto err_release_maps; 12976 12977 if (env->used_map_cnt) { 12978 /* if program passed verifier, update used_maps in bpf_prog_info */ 12979 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 12980 sizeof(env->used_maps[0]), 12981 GFP_KERNEL); 12982 12983 if (!env->prog->aux->used_maps) { 12984 ret = -ENOMEM; 12985 goto err_release_maps; 12986 } 12987 12988 memcpy(env->prog->aux->used_maps, env->used_maps, 12989 sizeof(env->used_maps[0]) * env->used_map_cnt); 12990 env->prog->aux->used_map_cnt = env->used_map_cnt; 12991 } 12992 if (env->used_btf_cnt) { 12993 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 12994 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 12995 sizeof(env->used_btfs[0]), 12996 GFP_KERNEL); 12997 if (!env->prog->aux->used_btfs) { 12998 ret = -ENOMEM; 12999 goto err_release_maps; 13000 } 13001 13002 memcpy(env->prog->aux->used_btfs, env->used_btfs, 13003 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 13004 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 13005 } 13006 if (env->used_map_cnt || env->used_btf_cnt) { 13007 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 13008 * bpf_ld_imm64 instructions 13009 */ 13010 convert_pseudo_ld_imm64(env); 13011 } 13012 13013 adjust_btf_func(env); 13014 13015 err_release_maps: 13016 if (!env->prog->aux->used_maps) 13017 /* if we didn't copy map pointers into bpf_prog_info, release 13018 * them now. Otherwise free_used_maps() will release them. 13019 */ 13020 release_maps(env); 13021 if (!env->prog->aux->used_btfs) 13022 release_btfs(env); 13023 13024 /* extension progs temporarily inherit the attach_type of their targets 13025 for verification purposes, so set it back to zero before returning 13026 */ 13027 if (env->prog->type == BPF_PROG_TYPE_EXT) 13028 env->prog->expected_attach_type = 0; 13029 13030 *prog = env->prog; 13031 err_unlock: 13032 if (!is_priv) 13033 mutex_unlock(&bpf_verifier_lock); 13034 vfree(env->insn_aux_data); 13035 err_free_env: 13036 kfree(env); 13037 return ret; 13038 } 13039