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 /* string representation of 'enum bpf_reg_type' */ 535 static const char * const reg_type_str[] = { 536 [NOT_INIT] = "?", 537 [SCALAR_VALUE] = "inv", 538 [PTR_TO_CTX] = "ctx", 539 [CONST_PTR_TO_MAP] = "map_ptr", 540 [PTR_TO_MAP_VALUE] = "map_value", 541 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", 542 [PTR_TO_STACK] = "fp", 543 [PTR_TO_PACKET] = "pkt", 544 [PTR_TO_PACKET_META] = "pkt_meta", 545 [PTR_TO_PACKET_END] = "pkt_end", 546 [PTR_TO_FLOW_KEYS] = "flow_keys", 547 [PTR_TO_SOCKET] = "sock", 548 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null", 549 [PTR_TO_SOCK_COMMON] = "sock_common", 550 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null", 551 [PTR_TO_TCP_SOCK] = "tcp_sock", 552 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null", 553 [PTR_TO_TP_BUFFER] = "tp_buffer", 554 [PTR_TO_XDP_SOCK] = "xdp_sock", 555 [PTR_TO_BTF_ID] = "ptr_", 556 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_", 557 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_", 558 [PTR_TO_MEM] = "mem", 559 [PTR_TO_MEM_OR_NULL] = "mem_or_null", 560 [PTR_TO_RDONLY_BUF] = "rdonly_buf", 561 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null", 562 [PTR_TO_RDWR_BUF] = "rdwr_buf", 563 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null", 564 [PTR_TO_FUNC] = "func", 565 [PTR_TO_MAP_KEY] = "map_key", 566 }; 567 568 static char slot_type_char[] = { 569 [STACK_INVALID] = '?', 570 [STACK_SPILL] = 'r', 571 [STACK_MISC] = 'm', 572 [STACK_ZERO] = '0', 573 }; 574 575 static void print_liveness(struct bpf_verifier_env *env, 576 enum bpf_reg_liveness live) 577 { 578 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 579 verbose(env, "_"); 580 if (live & REG_LIVE_READ) 581 verbose(env, "r"); 582 if (live & REG_LIVE_WRITTEN) 583 verbose(env, "w"); 584 if (live & REG_LIVE_DONE) 585 verbose(env, "D"); 586 } 587 588 static struct bpf_func_state *func(struct bpf_verifier_env *env, 589 const struct bpf_reg_state *reg) 590 { 591 struct bpf_verifier_state *cur = env->cur_state; 592 593 return cur->frame[reg->frameno]; 594 } 595 596 static const char *kernel_type_name(const struct btf* btf, u32 id) 597 { 598 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 599 } 600 601 static void print_verifier_state(struct bpf_verifier_env *env, 602 const struct bpf_func_state *state) 603 { 604 const struct bpf_reg_state *reg; 605 enum bpf_reg_type t; 606 int i; 607 608 if (state->frameno) 609 verbose(env, " frame%d:", state->frameno); 610 for (i = 0; i < MAX_BPF_REG; i++) { 611 reg = &state->regs[i]; 612 t = reg->type; 613 if (t == NOT_INIT) 614 continue; 615 verbose(env, " R%d", i); 616 print_liveness(env, reg->live); 617 verbose(env, "=%s", reg_type_str[t]); 618 if (t == SCALAR_VALUE && reg->precise) 619 verbose(env, "P"); 620 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 621 tnum_is_const(reg->var_off)) { 622 /* reg->off should be 0 for SCALAR_VALUE */ 623 verbose(env, "%lld", reg->var_off.value + reg->off); 624 } else { 625 if (t == PTR_TO_BTF_ID || 626 t == PTR_TO_BTF_ID_OR_NULL || 627 t == PTR_TO_PERCPU_BTF_ID) 628 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id)); 629 verbose(env, "(id=%d", reg->id); 630 if (reg_type_may_be_refcounted_or_null(t)) 631 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id); 632 if (t != SCALAR_VALUE) 633 verbose(env, ",off=%d", reg->off); 634 if (type_is_pkt_pointer(t)) 635 verbose(env, ",r=%d", reg->range); 636 else if (t == CONST_PTR_TO_MAP || 637 t == PTR_TO_MAP_KEY || 638 t == PTR_TO_MAP_VALUE || 639 t == PTR_TO_MAP_VALUE_OR_NULL) 640 verbose(env, ",ks=%d,vs=%d", 641 reg->map_ptr->key_size, 642 reg->map_ptr->value_size); 643 if (tnum_is_const(reg->var_off)) { 644 /* Typically an immediate SCALAR_VALUE, but 645 * could be a pointer whose offset is too big 646 * for reg->off 647 */ 648 verbose(env, ",imm=%llx", reg->var_off.value); 649 } else { 650 if (reg->smin_value != reg->umin_value && 651 reg->smin_value != S64_MIN) 652 verbose(env, ",smin_value=%lld", 653 (long long)reg->smin_value); 654 if (reg->smax_value != reg->umax_value && 655 reg->smax_value != S64_MAX) 656 verbose(env, ",smax_value=%lld", 657 (long long)reg->smax_value); 658 if (reg->umin_value != 0) 659 verbose(env, ",umin_value=%llu", 660 (unsigned long long)reg->umin_value); 661 if (reg->umax_value != U64_MAX) 662 verbose(env, ",umax_value=%llu", 663 (unsigned long long)reg->umax_value); 664 if (!tnum_is_unknown(reg->var_off)) { 665 char tn_buf[48]; 666 667 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 668 verbose(env, ",var_off=%s", tn_buf); 669 } 670 if (reg->s32_min_value != reg->smin_value && 671 reg->s32_min_value != S32_MIN) 672 verbose(env, ",s32_min_value=%d", 673 (int)(reg->s32_min_value)); 674 if (reg->s32_max_value != reg->smax_value && 675 reg->s32_max_value != S32_MAX) 676 verbose(env, ",s32_max_value=%d", 677 (int)(reg->s32_max_value)); 678 if (reg->u32_min_value != reg->umin_value && 679 reg->u32_min_value != U32_MIN) 680 verbose(env, ",u32_min_value=%d", 681 (int)(reg->u32_min_value)); 682 if (reg->u32_max_value != reg->umax_value && 683 reg->u32_max_value != U32_MAX) 684 verbose(env, ",u32_max_value=%d", 685 (int)(reg->u32_max_value)); 686 } 687 verbose(env, ")"); 688 } 689 } 690 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 691 char types_buf[BPF_REG_SIZE + 1]; 692 bool valid = false; 693 int j; 694 695 for (j = 0; j < BPF_REG_SIZE; j++) { 696 if (state->stack[i].slot_type[j] != STACK_INVALID) 697 valid = true; 698 types_buf[j] = slot_type_char[ 699 state->stack[i].slot_type[j]]; 700 } 701 types_buf[BPF_REG_SIZE] = 0; 702 if (!valid) 703 continue; 704 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 705 print_liveness(env, state->stack[i].spilled_ptr.live); 706 if (state->stack[i].slot_type[0] == STACK_SPILL) { 707 reg = &state->stack[i].spilled_ptr; 708 t = reg->type; 709 verbose(env, "=%s", reg_type_str[t]); 710 if (t == SCALAR_VALUE && reg->precise) 711 verbose(env, "P"); 712 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 713 verbose(env, "%lld", reg->var_off.value + reg->off); 714 } else { 715 verbose(env, "=%s", types_buf); 716 } 717 } 718 if (state->acquired_refs && state->refs[0].id) { 719 verbose(env, " refs=%d", state->refs[0].id); 720 for (i = 1; i < state->acquired_refs; i++) 721 if (state->refs[i].id) 722 verbose(env, ",%d", state->refs[i].id); 723 } 724 verbose(env, "\n"); 725 } 726 727 #define COPY_STATE_FN(NAME, COUNT, FIELD, SIZE) \ 728 static int copy_##NAME##_state(struct bpf_func_state *dst, \ 729 const struct bpf_func_state *src) \ 730 { \ 731 if (!src->FIELD) \ 732 return 0; \ 733 if (WARN_ON_ONCE(dst->COUNT < src->COUNT)) { \ 734 /* internal bug, make state invalid to reject the program */ \ 735 memset(dst, 0, sizeof(*dst)); \ 736 return -EFAULT; \ 737 } \ 738 memcpy(dst->FIELD, src->FIELD, \ 739 sizeof(*src->FIELD) * (src->COUNT / SIZE)); \ 740 return 0; \ 741 } 742 /* copy_reference_state() */ 743 COPY_STATE_FN(reference, acquired_refs, refs, 1) 744 /* copy_stack_state() */ 745 COPY_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE) 746 #undef COPY_STATE_FN 747 748 #define REALLOC_STATE_FN(NAME, COUNT, FIELD, SIZE) \ 749 static int realloc_##NAME##_state(struct bpf_func_state *state, int size, \ 750 bool copy_old) \ 751 { \ 752 u32 old_size = state->COUNT; \ 753 struct bpf_##NAME##_state *new_##FIELD; \ 754 int slot = size / SIZE; \ 755 \ 756 if (size <= old_size || !size) { \ 757 if (copy_old) \ 758 return 0; \ 759 state->COUNT = slot * SIZE; \ 760 if (!size && old_size) { \ 761 kfree(state->FIELD); \ 762 state->FIELD = NULL; \ 763 } \ 764 return 0; \ 765 } \ 766 new_##FIELD = kmalloc_array(slot, sizeof(struct bpf_##NAME##_state), \ 767 GFP_KERNEL); \ 768 if (!new_##FIELD) \ 769 return -ENOMEM; \ 770 if (copy_old) { \ 771 if (state->FIELD) \ 772 memcpy(new_##FIELD, state->FIELD, \ 773 sizeof(*new_##FIELD) * (old_size / SIZE)); \ 774 memset(new_##FIELD + old_size / SIZE, 0, \ 775 sizeof(*new_##FIELD) * (size - old_size) / SIZE); \ 776 } \ 777 state->COUNT = slot * SIZE; \ 778 kfree(state->FIELD); \ 779 state->FIELD = new_##FIELD; \ 780 return 0; \ 781 } 782 /* realloc_reference_state() */ 783 REALLOC_STATE_FN(reference, acquired_refs, refs, 1) 784 /* realloc_stack_state() */ 785 REALLOC_STATE_FN(stack, allocated_stack, stack, BPF_REG_SIZE) 786 #undef REALLOC_STATE_FN 787 788 /* do_check() starts with zero-sized stack in struct bpf_verifier_state to 789 * make it consume minimal amount of memory. check_stack_write() access from 790 * the program calls into realloc_func_state() to grow the stack size. 791 * Note there is a non-zero 'parent' pointer inside bpf_verifier_state 792 * which realloc_stack_state() copies over. It points to previous 793 * bpf_verifier_state which is never reallocated. 794 */ 795 static int realloc_func_state(struct bpf_func_state *state, int stack_size, 796 int refs_size, bool copy_old) 797 { 798 int err = realloc_reference_state(state, refs_size, copy_old); 799 if (err) 800 return err; 801 return realloc_stack_state(state, stack_size, copy_old); 802 } 803 804 /* Acquire a pointer id from the env and update the state->refs to include 805 * this new pointer reference. 806 * On success, returns a valid pointer id to associate with the register 807 * On failure, returns a negative errno. 808 */ 809 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 810 { 811 struct bpf_func_state *state = cur_func(env); 812 int new_ofs = state->acquired_refs; 813 int id, err; 814 815 err = realloc_reference_state(state, state->acquired_refs + 1, true); 816 if (err) 817 return err; 818 id = ++env->id_gen; 819 state->refs[new_ofs].id = id; 820 state->refs[new_ofs].insn_idx = insn_idx; 821 822 return id; 823 } 824 825 /* release function corresponding to acquire_reference_state(). Idempotent. */ 826 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 827 { 828 int i, last_idx; 829 830 last_idx = state->acquired_refs - 1; 831 for (i = 0; i < state->acquired_refs; i++) { 832 if (state->refs[i].id == ptr_id) { 833 if (last_idx && i != last_idx) 834 memcpy(&state->refs[i], &state->refs[last_idx], 835 sizeof(*state->refs)); 836 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 837 state->acquired_refs--; 838 return 0; 839 } 840 } 841 return -EINVAL; 842 } 843 844 static int transfer_reference_state(struct bpf_func_state *dst, 845 struct bpf_func_state *src) 846 { 847 int err = realloc_reference_state(dst, src->acquired_refs, false); 848 if (err) 849 return err; 850 err = copy_reference_state(dst, src); 851 if (err) 852 return err; 853 return 0; 854 } 855 856 static void free_func_state(struct bpf_func_state *state) 857 { 858 if (!state) 859 return; 860 kfree(state->refs); 861 kfree(state->stack); 862 kfree(state); 863 } 864 865 static void clear_jmp_history(struct bpf_verifier_state *state) 866 { 867 kfree(state->jmp_history); 868 state->jmp_history = NULL; 869 state->jmp_history_cnt = 0; 870 } 871 872 static void free_verifier_state(struct bpf_verifier_state *state, 873 bool free_self) 874 { 875 int i; 876 877 for (i = 0; i <= state->curframe; i++) { 878 free_func_state(state->frame[i]); 879 state->frame[i] = NULL; 880 } 881 clear_jmp_history(state); 882 if (free_self) 883 kfree(state); 884 } 885 886 /* copy verifier state from src to dst growing dst stack space 887 * when necessary to accommodate larger src stack 888 */ 889 static int copy_func_state(struct bpf_func_state *dst, 890 const struct bpf_func_state *src) 891 { 892 int err; 893 894 err = realloc_func_state(dst, src->allocated_stack, src->acquired_refs, 895 false); 896 if (err) 897 return err; 898 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 899 err = copy_reference_state(dst, src); 900 if (err) 901 return err; 902 return copy_stack_state(dst, src); 903 } 904 905 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 906 const struct bpf_verifier_state *src) 907 { 908 struct bpf_func_state *dst; 909 u32 jmp_sz = sizeof(struct bpf_idx_pair) * src->jmp_history_cnt; 910 int i, err; 911 912 if (dst_state->jmp_history_cnt < src->jmp_history_cnt) { 913 kfree(dst_state->jmp_history); 914 dst_state->jmp_history = kmalloc(jmp_sz, GFP_USER); 915 if (!dst_state->jmp_history) 916 return -ENOMEM; 917 } 918 memcpy(dst_state->jmp_history, src->jmp_history, jmp_sz); 919 dst_state->jmp_history_cnt = src->jmp_history_cnt; 920 921 /* if dst has more stack frames then src frame, free them */ 922 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 923 free_func_state(dst_state->frame[i]); 924 dst_state->frame[i] = NULL; 925 } 926 dst_state->speculative = src->speculative; 927 dst_state->curframe = src->curframe; 928 dst_state->active_spin_lock = src->active_spin_lock; 929 dst_state->branches = src->branches; 930 dst_state->parent = src->parent; 931 dst_state->first_insn_idx = src->first_insn_idx; 932 dst_state->last_insn_idx = src->last_insn_idx; 933 for (i = 0; i <= src->curframe; i++) { 934 dst = dst_state->frame[i]; 935 if (!dst) { 936 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 937 if (!dst) 938 return -ENOMEM; 939 dst_state->frame[i] = dst; 940 } 941 err = copy_func_state(dst, src->frame[i]); 942 if (err) 943 return err; 944 } 945 return 0; 946 } 947 948 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 949 { 950 while (st) { 951 u32 br = --st->branches; 952 953 /* WARN_ON(br > 1) technically makes sense here, 954 * but see comment in push_stack(), hence: 955 */ 956 WARN_ONCE((int)br < 0, 957 "BUG update_branch_counts:branches_to_explore=%d\n", 958 br); 959 if (br) 960 break; 961 st = st->parent; 962 } 963 } 964 965 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 966 int *insn_idx, bool pop_log) 967 { 968 struct bpf_verifier_state *cur = env->cur_state; 969 struct bpf_verifier_stack_elem *elem, *head = env->head; 970 int err; 971 972 if (env->head == NULL) 973 return -ENOENT; 974 975 if (cur) { 976 err = copy_verifier_state(cur, &head->st); 977 if (err) 978 return err; 979 } 980 if (pop_log) 981 bpf_vlog_reset(&env->log, head->log_pos); 982 if (insn_idx) 983 *insn_idx = head->insn_idx; 984 if (prev_insn_idx) 985 *prev_insn_idx = head->prev_insn_idx; 986 elem = head->next; 987 free_verifier_state(&head->st, false); 988 kfree(head); 989 env->head = elem; 990 env->stack_size--; 991 return 0; 992 } 993 994 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 995 int insn_idx, int prev_insn_idx, 996 bool speculative) 997 { 998 struct bpf_verifier_state *cur = env->cur_state; 999 struct bpf_verifier_stack_elem *elem; 1000 int err; 1001 1002 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1003 if (!elem) 1004 goto err; 1005 1006 elem->insn_idx = insn_idx; 1007 elem->prev_insn_idx = prev_insn_idx; 1008 elem->next = env->head; 1009 elem->log_pos = env->log.len_used; 1010 env->head = elem; 1011 env->stack_size++; 1012 err = copy_verifier_state(&elem->st, cur); 1013 if (err) 1014 goto err; 1015 elem->st.speculative |= speculative; 1016 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1017 verbose(env, "The sequence of %d jumps is too complex.\n", 1018 env->stack_size); 1019 goto err; 1020 } 1021 if (elem->st.parent) { 1022 ++elem->st.parent->branches; 1023 /* WARN_ON(branches > 2) technically makes sense here, 1024 * but 1025 * 1. speculative states will bump 'branches' for non-branch 1026 * instructions 1027 * 2. is_state_visited() heuristics may decide not to create 1028 * a new state for a sequence of branches and all such current 1029 * and cloned states will be pointing to a single parent state 1030 * which might have large 'branches' count. 1031 */ 1032 } 1033 return &elem->st; 1034 err: 1035 free_verifier_state(env->cur_state, true); 1036 env->cur_state = NULL; 1037 /* pop all elements and return */ 1038 while (!pop_stack(env, NULL, NULL, false)); 1039 return NULL; 1040 } 1041 1042 #define CALLER_SAVED_REGS 6 1043 static const int caller_saved[CALLER_SAVED_REGS] = { 1044 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1045 }; 1046 1047 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1048 struct bpf_reg_state *reg); 1049 1050 /* This helper doesn't clear reg->id */ 1051 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1052 { 1053 reg->var_off = tnum_const(imm); 1054 reg->smin_value = (s64)imm; 1055 reg->smax_value = (s64)imm; 1056 reg->umin_value = imm; 1057 reg->umax_value = imm; 1058 1059 reg->s32_min_value = (s32)imm; 1060 reg->s32_max_value = (s32)imm; 1061 reg->u32_min_value = (u32)imm; 1062 reg->u32_max_value = (u32)imm; 1063 } 1064 1065 /* Mark the unknown part of a register (variable offset or scalar value) as 1066 * known to have the value @imm. 1067 */ 1068 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1069 { 1070 /* Clear id, off, and union(map_ptr, range) */ 1071 memset(((u8 *)reg) + sizeof(reg->type), 0, 1072 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1073 ___mark_reg_known(reg, imm); 1074 } 1075 1076 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1077 { 1078 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1079 reg->s32_min_value = (s32)imm; 1080 reg->s32_max_value = (s32)imm; 1081 reg->u32_min_value = (u32)imm; 1082 reg->u32_max_value = (u32)imm; 1083 } 1084 1085 /* Mark the 'variable offset' part of a register as zero. This should be 1086 * used only on registers holding a pointer type. 1087 */ 1088 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1089 { 1090 __mark_reg_known(reg, 0); 1091 } 1092 1093 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1094 { 1095 __mark_reg_known(reg, 0); 1096 reg->type = SCALAR_VALUE; 1097 } 1098 1099 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1100 struct bpf_reg_state *regs, u32 regno) 1101 { 1102 if (WARN_ON(regno >= MAX_BPF_REG)) { 1103 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1104 /* Something bad happened, let's kill all regs */ 1105 for (regno = 0; regno < MAX_BPF_REG; regno++) 1106 __mark_reg_not_init(env, regs + regno); 1107 return; 1108 } 1109 __mark_reg_known_zero(regs + regno); 1110 } 1111 1112 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1113 { 1114 switch (reg->type) { 1115 case PTR_TO_MAP_VALUE_OR_NULL: { 1116 const struct bpf_map *map = reg->map_ptr; 1117 1118 if (map->inner_map_meta) { 1119 reg->type = CONST_PTR_TO_MAP; 1120 reg->map_ptr = map->inner_map_meta; 1121 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1122 reg->type = PTR_TO_XDP_SOCK; 1123 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1124 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1125 reg->type = PTR_TO_SOCKET; 1126 } else { 1127 reg->type = PTR_TO_MAP_VALUE; 1128 } 1129 break; 1130 } 1131 case PTR_TO_SOCKET_OR_NULL: 1132 reg->type = PTR_TO_SOCKET; 1133 break; 1134 case PTR_TO_SOCK_COMMON_OR_NULL: 1135 reg->type = PTR_TO_SOCK_COMMON; 1136 break; 1137 case PTR_TO_TCP_SOCK_OR_NULL: 1138 reg->type = PTR_TO_TCP_SOCK; 1139 break; 1140 case PTR_TO_BTF_ID_OR_NULL: 1141 reg->type = PTR_TO_BTF_ID; 1142 break; 1143 case PTR_TO_MEM_OR_NULL: 1144 reg->type = PTR_TO_MEM; 1145 break; 1146 case PTR_TO_RDONLY_BUF_OR_NULL: 1147 reg->type = PTR_TO_RDONLY_BUF; 1148 break; 1149 case PTR_TO_RDWR_BUF_OR_NULL: 1150 reg->type = PTR_TO_RDWR_BUF; 1151 break; 1152 default: 1153 WARN_ON("unknown nullable register type"); 1154 } 1155 } 1156 1157 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1158 { 1159 return type_is_pkt_pointer(reg->type); 1160 } 1161 1162 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1163 { 1164 return reg_is_pkt_pointer(reg) || 1165 reg->type == PTR_TO_PACKET_END; 1166 } 1167 1168 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1169 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1170 enum bpf_reg_type which) 1171 { 1172 /* The register can already have a range from prior markings. 1173 * This is fine as long as it hasn't been advanced from its 1174 * origin. 1175 */ 1176 return reg->type == which && 1177 reg->id == 0 && 1178 reg->off == 0 && 1179 tnum_equals_const(reg->var_off, 0); 1180 } 1181 1182 /* Reset the min/max bounds of a register */ 1183 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1184 { 1185 reg->smin_value = S64_MIN; 1186 reg->smax_value = S64_MAX; 1187 reg->umin_value = 0; 1188 reg->umax_value = U64_MAX; 1189 1190 reg->s32_min_value = S32_MIN; 1191 reg->s32_max_value = S32_MAX; 1192 reg->u32_min_value = 0; 1193 reg->u32_max_value = U32_MAX; 1194 } 1195 1196 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1197 { 1198 reg->smin_value = S64_MIN; 1199 reg->smax_value = S64_MAX; 1200 reg->umin_value = 0; 1201 reg->umax_value = U64_MAX; 1202 } 1203 1204 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1205 { 1206 reg->s32_min_value = S32_MIN; 1207 reg->s32_max_value = S32_MAX; 1208 reg->u32_min_value = 0; 1209 reg->u32_max_value = U32_MAX; 1210 } 1211 1212 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1213 { 1214 struct tnum var32_off = tnum_subreg(reg->var_off); 1215 1216 /* min signed is max(sign bit) | min(other bits) */ 1217 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1218 var32_off.value | (var32_off.mask & S32_MIN)); 1219 /* max signed is min(sign bit) | max(other bits) */ 1220 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1221 var32_off.value | (var32_off.mask & S32_MAX)); 1222 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1223 reg->u32_max_value = min(reg->u32_max_value, 1224 (u32)(var32_off.value | var32_off.mask)); 1225 } 1226 1227 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1228 { 1229 /* min signed is max(sign bit) | min(other bits) */ 1230 reg->smin_value = max_t(s64, reg->smin_value, 1231 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1232 /* max signed is min(sign bit) | max(other bits) */ 1233 reg->smax_value = min_t(s64, reg->smax_value, 1234 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1235 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1236 reg->umax_value = min(reg->umax_value, 1237 reg->var_off.value | reg->var_off.mask); 1238 } 1239 1240 static void __update_reg_bounds(struct bpf_reg_state *reg) 1241 { 1242 __update_reg32_bounds(reg); 1243 __update_reg64_bounds(reg); 1244 } 1245 1246 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1247 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1248 { 1249 /* Learn sign from signed bounds. 1250 * If we cannot cross the sign boundary, then signed and unsigned bounds 1251 * are the same, so combine. This works even in the negative case, e.g. 1252 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1253 */ 1254 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 1255 reg->s32_min_value = reg->u32_min_value = 1256 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1257 reg->s32_max_value = reg->u32_max_value = 1258 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1259 return; 1260 } 1261 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1262 * boundary, so we must be careful. 1263 */ 1264 if ((s32)reg->u32_max_value >= 0) { 1265 /* Positive. We can't learn anything from the smin, but smax 1266 * is positive, hence safe. 1267 */ 1268 reg->s32_min_value = reg->u32_min_value; 1269 reg->s32_max_value = reg->u32_max_value = 1270 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1271 } else if ((s32)reg->u32_min_value < 0) { 1272 /* Negative. We can't learn anything from the smax, but smin 1273 * is negative, hence safe. 1274 */ 1275 reg->s32_min_value = reg->u32_min_value = 1276 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1277 reg->s32_max_value = reg->u32_max_value; 1278 } 1279 } 1280 1281 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 1282 { 1283 /* Learn sign from signed bounds. 1284 * If we cannot cross the sign boundary, then signed and unsigned bounds 1285 * are the same, so combine. This works even in the negative case, e.g. 1286 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1287 */ 1288 if (reg->smin_value >= 0 || reg->smax_value < 0) { 1289 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1290 reg->umin_value); 1291 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1292 reg->umax_value); 1293 return; 1294 } 1295 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1296 * boundary, so we must be careful. 1297 */ 1298 if ((s64)reg->umax_value >= 0) { 1299 /* Positive. We can't learn anything from the smin, but smax 1300 * is positive, hence safe. 1301 */ 1302 reg->smin_value = reg->umin_value; 1303 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1304 reg->umax_value); 1305 } else if ((s64)reg->umin_value < 0) { 1306 /* Negative. We can't learn anything from the smax, but smin 1307 * is negative, hence safe. 1308 */ 1309 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1310 reg->umin_value); 1311 reg->smax_value = reg->umax_value; 1312 } 1313 } 1314 1315 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 1316 { 1317 __reg32_deduce_bounds(reg); 1318 __reg64_deduce_bounds(reg); 1319 } 1320 1321 /* Attempts to improve var_off based on unsigned min/max information */ 1322 static void __reg_bound_offset(struct bpf_reg_state *reg) 1323 { 1324 struct tnum var64_off = tnum_intersect(reg->var_off, 1325 tnum_range(reg->umin_value, 1326 reg->umax_value)); 1327 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off), 1328 tnum_range(reg->u32_min_value, 1329 reg->u32_max_value)); 1330 1331 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 1332 } 1333 1334 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 1335 { 1336 reg->umin_value = reg->u32_min_value; 1337 reg->umax_value = reg->u32_max_value; 1338 /* Attempt to pull 32-bit signed bounds into 64-bit bounds 1339 * but must be positive otherwise set to worse case bounds 1340 * and refine later from tnum. 1341 */ 1342 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0) 1343 reg->smax_value = reg->s32_max_value; 1344 else 1345 reg->smax_value = U32_MAX; 1346 if (reg->s32_min_value >= 0) 1347 reg->smin_value = reg->s32_min_value; 1348 else 1349 reg->smin_value = 0; 1350 } 1351 1352 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 1353 { 1354 /* special case when 64-bit register has upper 32-bit register 1355 * zeroed. Typically happens after zext or <<32, >>32 sequence 1356 * allowing us to use 32-bit bounds directly, 1357 */ 1358 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 1359 __reg_assign_32_into_64(reg); 1360 } else { 1361 /* Otherwise the best we can do is push lower 32bit known and 1362 * unknown bits into register (var_off set from jmp logic) 1363 * then learn as much as possible from the 64-bit tnum 1364 * known and unknown bits. The previous smin/smax bounds are 1365 * invalid here because of jmp32 compare so mark them unknown 1366 * so they do not impact tnum bounds calculation. 1367 */ 1368 __mark_reg64_unbounded(reg); 1369 __update_reg_bounds(reg); 1370 } 1371 1372 /* Intersecting with the old var_off might have improved our bounds 1373 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1374 * then new var_off is (0; 0x7f...fc) which improves our umax. 1375 */ 1376 __reg_deduce_bounds(reg); 1377 __reg_bound_offset(reg); 1378 __update_reg_bounds(reg); 1379 } 1380 1381 static bool __reg64_bound_s32(s64 a) 1382 { 1383 return a > S32_MIN && a < S32_MAX; 1384 } 1385 1386 static bool __reg64_bound_u32(u64 a) 1387 { 1388 if (a > U32_MIN && a < U32_MAX) 1389 return true; 1390 return false; 1391 } 1392 1393 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 1394 { 1395 __mark_reg32_unbounded(reg); 1396 1397 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 1398 reg->s32_min_value = (s32)reg->smin_value; 1399 reg->s32_max_value = (s32)reg->smax_value; 1400 } 1401 if (__reg64_bound_u32(reg->umin_value)) 1402 reg->u32_min_value = (u32)reg->umin_value; 1403 if (__reg64_bound_u32(reg->umax_value)) 1404 reg->u32_max_value = (u32)reg->umax_value; 1405 1406 /* Intersecting with the old var_off might have improved our bounds 1407 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1408 * then new var_off is (0; 0x7f...fc) which improves our umax. 1409 */ 1410 __reg_deduce_bounds(reg); 1411 __reg_bound_offset(reg); 1412 __update_reg_bounds(reg); 1413 } 1414 1415 /* Mark a register as having a completely unknown (scalar) value. */ 1416 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1417 struct bpf_reg_state *reg) 1418 { 1419 /* 1420 * Clear type, id, off, and union(map_ptr, range) and 1421 * padding between 'type' and union 1422 */ 1423 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 1424 reg->type = SCALAR_VALUE; 1425 reg->var_off = tnum_unknown; 1426 reg->frameno = 0; 1427 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable; 1428 __mark_reg_unbounded(reg); 1429 } 1430 1431 static void mark_reg_unknown(struct bpf_verifier_env *env, 1432 struct bpf_reg_state *regs, u32 regno) 1433 { 1434 if (WARN_ON(regno >= MAX_BPF_REG)) { 1435 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 1436 /* Something bad happened, let's kill all regs except FP */ 1437 for (regno = 0; regno < BPF_REG_FP; regno++) 1438 __mark_reg_not_init(env, regs + regno); 1439 return; 1440 } 1441 __mark_reg_unknown(env, regs + regno); 1442 } 1443 1444 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1445 struct bpf_reg_state *reg) 1446 { 1447 __mark_reg_unknown(env, reg); 1448 reg->type = NOT_INIT; 1449 } 1450 1451 static void mark_reg_not_init(struct bpf_verifier_env *env, 1452 struct bpf_reg_state *regs, u32 regno) 1453 { 1454 if (WARN_ON(regno >= MAX_BPF_REG)) { 1455 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 1456 /* Something bad happened, let's kill all regs except FP */ 1457 for (regno = 0; regno < BPF_REG_FP; regno++) 1458 __mark_reg_not_init(env, regs + regno); 1459 return; 1460 } 1461 __mark_reg_not_init(env, regs + regno); 1462 } 1463 1464 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 1465 struct bpf_reg_state *regs, u32 regno, 1466 enum bpf_reg_type reg_type, 1467 struct btf *btf, u32 btf_id) 1468 { 1469 if (reg_type == SCALAR_VALUE) { 1470 mark_reg_unknown(env, regs, regno); 1471 return; 1472 } 1473 mark_reg_known_zero(env, regs, regno); 1474 regs[regno].type = PTR_TO_BTF_ID; 1475 regs[regno].btf = btf; 1476 regs[regno].btf_id = btf_id; 1477 } 1478 1479 #define DEF_NOT_SUBREG (0) 1480 static void init_reg_state(struct bpf_verifier_env *env, 1481 struct bpf_func_state *state) 1482 { 1483 struct bpf_reg_state *regs = state->regs; 1484 int i; 1485 1486 for (i = 0; i < MAX_BPF_REG; i++) { 1487 mark_reg_not_init(env, regs, i); 1488 regs[i].live = REG_LIVE_NONE; 1489 regs[i].parent = NULL; 1490 regs[i].subreg_def = DEF_NOT_SUBREG; 1491 } 1492 1493 /* frame pointer */ 1494 regs[BPF_REG_FP].type = PTR_TO_STACK; 1495 mark_reg_known_zero(env, regs, BPF_REG_FP); 1496 regs[BPF_REG_FP].frameno = state->frameno; 1497 } 1498 1499 #define BPF_MAIN_FUNC (-1) 1500 static void init_func_state(struct bpf_verifier_env *env, 1501 struct bpf_func_state *state, 1502 int callsite, int frameno, int subprogno) 1503 { 1504 state->callsite = callsite; 1505 state->frameno = frameno; 1506 state->subprogno = subprogno; 1507 init_reg_state(env, state); 1508 } 1509 1510 enum reg_arg_type { 1511 SRC_OP, /* register is used as source operand */ 1512 DST_OP, /* register is used as destination operand */ 1513 DST_OP_NO_MARK /* same as above, check only, don't mark */ 1514 }; 1515 1516 static int cmp_subprogs(const void *a, const void *b) 1517 { 1518 return ((struct bpf_subprog_info *)a)->start - 1519 ((struct bpf_subprog_info *)b)->start; 1520 } 1521 1522 static int find_subprog(struct bpf_verifier_env *env, int off) 1523 { 1524 struct bpf_subprog_info *p; 1525 1526 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 1527 sizeof(env->subprog_info[0]), cmp_subprogs); 1528 if (!p) 1529 return -ENOENT; 1530 return p - env->subprog_info; 1531 1532 } 1533 1534 static int add_subprog(struct bpf_verifier_env *env, int off) 1535 { 1536 int insn_cnt = env->prog->len; 1537 int ret; 1538 1539 if (off >= insn_cnt || off < 0) { 1540 verbose(env, "call to invalid destination\n"); 1541 return -EINVAL; 1542 } 1543 ret = find_subprog(env, off); 1544 if (ret >= 0) 1545 return ret; 1546 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 1547 verbose(env, "too many subprograms\n"); 1548 return -E2BIG; 1549 } 1550 env->subprog_info[env->subprog_cnt++].start = off; 1551 sort(env->subprog_info, env->subprog_cnt, 1552 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 1553 return env->subprog_cnt - 1; 1554 } 1555 1556 static int check_subprogs(struct bpf_verifier_env *env) 1557 { 1558 int i, ret, subprog_start, subprog_end, off, cur_subprog = 0; 1559 struct bpf_subprog_info *subprog = env->subprog_info; 1560 struct bpf_insn *insn = env->prog->insnsi; 1561 int insn_cnt = env->prog->len; 1562 1563 /* Add entry function. */ 1564 ret = add_subprog(env, 0); 1565 if (ret < 0) 1566 return ret; 1567 1568 /* determine subprog starts. The end is one before the next starts */ 1569 for (i = 0; i < insn_cnt; i++) { 1570 if (bpf_pseudo_func(insn + i)) { 1571 if (!env->bpf_capable) { 1572 verbose(env, 1573 "function pointers are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 1574 return -EPERM; 1575 } 1576 ret = add_subprog(env, i + insn[i].imm + 1); 1577 if (ret < 0) 1578 return ret; 1579 /* remember subprog */ 1580 insn[i + 1].imm = ret; 1581 continue; 1582 } 1583 if (!bpf_pseudo_call(insn + i)) 1584 continue; 1585 if (!env->bpf_capable) { 1586 verbose(env, 1587 "function calls to other bpf functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 1588 return -EPERM; 1589 } 1590 ret = add_subprog(env, i + insn[i].imm + 1); 1591 if (ret < 0) 1592 return ret; 1593 } 1594 1595 /* Add a fake 'exit' subprog which could simplify subprog iteration 1596 * logic. 'subprog_cnt' should not be increased. 1597 */ 1598 subprog[env->subprog_cnt].start = insn_cnt; 1599 1600 if (env->log.level & BPF_LOG_LEVEL2) 1601 for (i = 0; i < env->subprog_cnt; i++) 1602 verbose(env, "func#%d @%d\n", i, subprog[i].start); 1603 1604 /* now check that all jumps are within the same subprog */ 1605 subprog_start = subprog[cur_subprog].start; 1606 subprog_end = subprog[cur_subprog + 1].start; 1607 for (i = 0; i < insn_cnt; i++) { 1608 u8 code = insn[i].code; 1609 1610 if (code == (BPF_JMP | BPF_CALL) && 1611 insn[i].imm == BPF_FUNC_tail_call && 1612 insn[i].src_reg != BPF_PSEUDO_CALL) 1613 subprog[cur_subprog].has_tail_call = true; 1614 if (BPF_CLASS(code) == BPF_LD && 1615 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 1616 subprog[cur_subprog].has_ld_abs = true; 1617 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 1618 goto next; 1619 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 1620 goto next; 1621 off = i + insn[i].off + 1; 1622 if (off < subprog_start || off >= subprog_end) { 1623 verbose(env, "jump out of range from insn %d to %d\n", i, off); 1624 return -EINVAL; 1625 } 1626 next: 1627 if (i == subprog_end - 1) { 1628 /* to avoid fall-through from one subprog into another 1629 * the last insn of the subprog should be either exit 1630 * or unconditional jump back 1631 */ 1632 if (code != (BPF_JMP | BPF_EXIT) && 1633 code != (BPF_JMP | BPF_JA)) { 1634 verbose(env, "last insn is not an exit or jmp\n"); 1635 return -EINVAL; 1636 } 1637 subprog_start = subprog_end; 1638 cur_subprog++; 1639 if (cur_subprog < env->subprog_cnt) 1640 subprog_end = subprog[cur_subprog + 1].start; 1641 } 1642 } 1643 return 0; 1644 } 1645 1646 /* Parentage chain of this register (or stack slot) should take care of all 1647 * issues like callee-saved registers, stack slot allocation time, etc. 1648 */ 1649 static int mark_reg_read(struct bpf_verifier_env *env, 1650 const struct bpf_reg_state *state, 1651 struct bpf_reg_state *parent, u8 flag) 1652 { 1653 bool writes = parent == state->parent; /* Observe write marks */ 1654 int cnt = 0; 1655 1656 while (parent) { 1657 /* if read wasn't screened by an earlier write ... */ 1658 if (writes && state->live & REG_LIVE_WRITTEN) 1659 break; 1660 if (parent->live & REG_LIVE_DONE) { 1661 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 1662 reg_type_str[parent->type], 1663 parent->var_off.value, parent->off); 1664 return -EFAULT; 1665 } 1666 /* The first condition is more likely to be true than the 1667 * second, checked it first. 1668 */ 1669 if ((parent->live & REG_LIVE_READ) == flag || 1670 parent->live & REG_LIVE_READ64) 1671 /* The parentage chain never changes and 1672 * this parent was already marked as LIVE_READ. 1673 * There is no need to keep walking the chain again and 1674 * keep re-marking all parents as LIVE_READ. 1675 * This case happens when the same register is read 1676 * multiple times without writes into it in-between. 1677 * Also, if parent has the stronger REG_LIVE_READ64 set, 1678 * then no need to set the weak REG_LIVE_READ32. 1679 */ 1680 break; 1681 /* ... then we depend on parent's value */ 1682 parent->live |= flag; 1683 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 1684 if (flag == REG_LIVE_READ64) 1685 parent->live &= ~REG_LIVE_READ32; 1686 state = parent; 1687 parent = state->parent; 1688 writes = true; 1689 cnt++; 1690 } 1691 1692 if (env->longest_mark_read_walk < cnt) 1693 env->longest_mark_read_walk = cnt; 1694 return 0; 1695 } 1696 1697 /* This function is supposed to be used by the following 32-bit optimization 1698 * code only. It returns TRUE if the source or destination register operates 1699 * on 64-bit, otherwise return FALSE. 1700 */ 1701 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 1702 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 1703 { 1704 u8 code, class, op; 1705 1706 code = insn->code; 1707 class = BPF_CLASS(code); 1708 op = BPF_OP(code); 1709 if (class == BPF_JMP) { 1710 /* BPF_EXIT for "main" will reach here. Return TRUE 1711 * conservatively. 1712 */ 1713 if (op == BPF_EXIT) 1714 return true; 1715 if (op == BPF_CALL) { 1716 /* BPF to BPF call will reach here because of marking 1717 * caller saved clobber with DST_OP_NO_MARK for which we 1718 * don't care the register def because they are anyway 1719 * marked as NOT_INIT already. 1720 */ 1721 if (insn->src_reg == BPF_PSEUDO_CALL) 1722 return false; 1723 /* Helper call will reach here because of arg type 1724 * check, conservatively return TRUE. 1725 */ 1726 if (t == SRC_OP) 1727 return true; 1728 1729 return false; 1730 } 1731 } 1732 1733 if (class == BPF_ALU64 || class == BPF_JMP || 1734 /* BPF_END always use BPF_ALU class. */ 1735 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 1736 return true; 1737 1738 if (class == BPF_ALU || class == BPF_JMP32) 1739 return false; 1740 1741 if (class == BPF_LDX) { 1742 if (t != SRC_OP) 1743 return BPF_SIZE(code) == BPF_DW; 1744 /* LDX source must be ptr. */ 1745 return true; 1746 } 1747 1748 if (class == BPF_STX) { 1749 if (reg->type != SCALAR_VALUE) 1750 return true; 1751 return BPF_SIZE(code) == BPF_DW; 1752 } 1753 1754 if (class == BPF_LD) { 1755 u8 mode = BPF_MODE(code); 1756 1757 /* LD_IMM64 */ 1758 if (mode == BPF_IMM) 1759 return true; 1760 1761 /* Both LD_IND and LD_ABS return 32-bit data. */ 1762 if (t != SRC_OP) 1763 return false; 1764 1765 /* Implicit ctx ptr. */ 1766 if (regno == BPF_REG_6) 1767 return true; 1768 1769 /* Explicit source could be any width. */ 1770 return true; 1771 } 1772 1773 if (class == BPF_ST) 1774 /* The only source register for BPF_ST is a ptr. */ 1775 return true; 1776 1777 /* Conservatively return true at default. */ 1778 return true; 1779 } 1780 1781 /* Return TRUE if INSN doesn't have explicit value define. */ 1782 static bool insn_no_def(struct bpf_insn *insn) 1783 { 1784 u8 class = BPF_CLASS(insn->code); 1785 1786 return (class == BPF_JMP || class == BPF_JMP32 || 1787 class == BPF_STX || class == BPF_ST); 1788 } 1789 1790 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 1791 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 1792 { 1793 if (insn_no_def(insn)) 1794 return false; 1795 1796 return !is_reg64(env, insn, insn->dst_reg, NULL, DST_OP); 1797 } 1798 1799 static void mark_insn_zext(struct bpf_verifier_env *env, 1800 struct bpf_reg_state *reg) 1801 { 1802 s32 def_idx = reg->subreg_def; 1803 1804 if (def_idx == DEF_NOT_SUBREG) 1805 return; 1806 1807 env->insn_aux_data[def_idx - 1].zext_dst = true; 1808 /* The dst will be zero extended, so won't be sub-register anymore. */ 1809 reg->subreg_def = DEF_NOT_SUBREG; 1810 } 1811 1812 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 1813 enum reg_arg_type t) 1814 { 1815 struct bpf_verifier_state *vstate = env->cur_state; 1816 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 1817 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 1818 struct bpf_reg_state *reg, *regs = state->regs; 1819 bool rw64; 1820 1821 if (regno >= MAX_BPF_REG) { 1822 verbose(env, "R%d is invalid\n", regno); 1823 return -EINVAL; 1824 } 1825 1826 reg = ®s[regno]; 1827 rw64 = is_reg64(env, insn, regno, reg, t); 1828 if (t == SRC_OP) { 1829 /* check whether register used as source operand can be read */ 1830 if (reg->type == NOT_INIT) { 1831 verbose(env, "R%d !read_ok\n", regno); 1832 return -EACCES; 1833 } 1834 /* We don't need to worry about FP liveness because it's read-only */ 1835 if (regno == BPF_REG_FP) 1836 return 0; 1837 1838 if (rw64) 1839 mark_insn_zext(env, reg); 1840 1841 return mark_reg_read(env, reg, reg->parent, 1842 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 1843 } else { 1844 /* check whether register used as dest operand can be written to */ 1845 if (regno == BPF_REG_FP) { 1846 verbose(env, "frame pointer is read only\n"); 1847 return -EACCES; 1848 } 1849 reg->live |= REG_LIVE_WRITTEN; 1850 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 1851 if (t == DST_OP) 1852 mark_reg_unknown(env, regs, regno); 1853 } 1854 return 0; 1855 } 1856 1857 /* for any branch, call, exit record the history of jmps in the given state */ 1858 static int push_jmp_history(struct bpf_verifier_env *env, 1859 struct bpf_verifier_state *cur) 1860 { 1861 u32 cnt = cur->jmp_history_cnt; 1862 struct bpf_idx_pair *p; 1863 1864 cnt++; 1865 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER); 1866 if (!p) 1867 return -ENOMEM; 1868 p[cnt - 1].idx = env->insn_idx; 1869 p[cnt - 1].prev_idx = env->prev_insn_idx; 1870 cur->jmp_history = p; 1871 cur->jmp_history_cnt = cnt; 1872 return 0; 1873 } 1874 1875 /* Backtrack one insn at a time. If idx is not at the top of recorded 1876 * history then previous instruction came from straight line execution. 1877 */ 1878 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 1879 u32 *history) 1880 { 1881 u32 cnt = *history; 1882 1883 if (cnt && st->jmp_history[cnt - 1].idx == i) { 1884 i = st->jmp_history[cnt - 1].prev_idx; 1885 (*history)--; 1886 } else { 1887 i--; 1888 } 1889 return i; 1890 } 1891 1892 /* For given verifier state backtrack_insn() is called from the last insn to 1893 * the first insn. Its purpose is to compute a bitmask of registers and 1894 * stack slots that needs precision in the parent verifier state. 1895 */ 1896 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 1897 u32 *reg_mask, u64 *stack_mask) 1898 { 1899 const struct bpf_insn_cbs cbs = { 1900 .cb_print = verbose, 1901 .private_data = env, 1902 }; 1903 struct bpf_insn *insn = env->prog->insnsi + idx; 1904 u8 class = BPF_CLASS(insn->code); 1905 u8 opcode = BPF_OP(insn->code); 1906 u8 mode = BPF_MODE(insn->code); 1907 u32 dreg = 1u << insn->dst_reg; 1908 u32 sreg = 1u << insn->src_reg; 1909 u32 spi; 1910 1911 if (insn->code == 0) 1912 return 0; 1913 if (env->log.level & BPF_LOG_LEVEL) { 1914 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask); 1915 verbose(env, "%d: ", idx); 1916 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 1917 } 1918 1919 if (class == BPF_ALU || class == BPF_ALU64) { 1920 if (!(*reg_mask & dreg)) 1921 return 0; 1922 if (opcode == BPF_MOV) { 1923 if (BPF_SRC(insn->code) == BPF_X) { 1924 /* dreg = sreg 1925 * dreg needs precision after this insn 1926 * sreg needs precision before this insn 1927 */ 1928 *reg_mask &= ~dreg; 1929 *reg_mask |= sreg; 1930 } else { 1931 /* dreg = K 1932 * dreg needs precision after this insn. 1933 * Corresponding register is already marked 1934 * as precise=true in this verifier state. 1935 * No further markings in parent are necessary 1936 */ 1937 *reg_mask &= ~dreg; 1938 } 1939 } else { 1940 if (BPF_SRC(insn->code) == BPF_X) { 1941 /* dreg += sreg 1942 * both dreg and sreg need precision 1943 * before this insn 1944 */ 1945 *reg_mask |= sreg; 1946 } /* else dreg += K 1947 * dreg still needs precision before this insn 1948 */ 1949 } 1950 } else if (class == BPF_LDX) { 1951 if (!(*reg_mask & dreg)) 1952 return 0; 1953 *reg_mask &= ~dreg; 1954 1955 /* scalars can only be spilled into stack w/o losing precision. 1956 * Load from any other memory can be zero extended. 1957 * The desire to keep that precision is already indicated 1958 * by 'precise' mark in corresponding register of this state. 1959 * No further tracking necessary. 1960 */ 1961 if (insn->src_reg != BPF_REG_FP) 1962 return 0; 1963 if (BPF_SIZE(insn->code) != BPF_DW) 1964 return 0; 1965 1966 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 1967 * that [fp - off] slot contains scalar that needs to be 1968 * tracked with precision 1969 */ 1970 spi = (-insn->off - 1) / BPF_REG_SIZE; 1971 if (spi >= 64) { 1972 verbose(env, "BUG spi %d\n", spi); 1973 WARN_ONCE(1, "verifier backtracking bug"); 1974 return -EFAULT; 1975 } 1976 *stack_mask |= 1ull << spi; 1977 } else if (class == BPF_STX || class == BPF_ST) { 1978 if (*reg_mask & dreg) 1979 /* stx & st shouldn't be using _scalar_ dst_reg 1980 * to access memory. It means backtracking 1981 * encountered a case of pointer subtraction. 1982 */ 1983 return -ENOTSUPP; 1984 /* scalars can only be spilled into stack */ 1985 if (insn->dst_reg != BPF_REG_FP) 1986 return 0; 1987 if (BPF_SIZE(insn->code) != BPF_DW) 1988 return 0; 1989 spi = (-insn->off - 1) / BPF_REG_SIZE; 1990 if (spi >= 64) { 1991 verbose(env, "BUG spi %d\n", spi); 1992 WARN_ONCE(1, "verifier backtracking bug"); 1993 return -EFAULT; 1994 } 1995 if (!(*stack_mask & (1ull << spi))) 1996 return 0; 1997 *stack_mask &= ~(1ull << spi); 1998 if (class == BPF_STX) 1999 *reg_mask |= sreg; 2000 } else if (class == BPF_JMP || class == BPF_JMP32) { 2001 if (opcode == BPF_CALL) { 2002 if (insn->src_reg == BPF_PSEUDO_CALL) 2003 return -ENOTSUPP; 2004 /* regular helper call sets R0 */ 2005 *reg_mask &= ~1; 2006 if (*reg_mask & 0x3f) { 2007 /* if backtracing was looking for registers R1-R5 2008 * they should have been found already. 2009 */ 2010 verbose(env, "BUG regs %x\n", *reg_mask); 2011 WARN_ONCE(1, "verifier backtracking bug"); 2012 return -EFAULT; 2013 } 2014 } else if (opcode == BPF_EXIT) { 2015 return -ENOTSUPP; 2016 } 2017 } else if (class == BPF_LD) { 2018 if (!(*reg_mask & dreg)) 2019 return 0; 2020 *reg_mask &= ~dreg; 2021 /* It's ld_imm64 or ld_abs or ld_ind. 2022 * For ld_imm64 no further tracking of precision 2023 * into parent is necessary 2024 */ 2025 if (mode == BPF_IND || mode == BPF_ABS) 2026 /* to be analyzed */ 2027 return -ENOTSUPP; 2028 } 2029 return 0; 2030 } 2031 2032 /* the scalar precision tracking algorithm: 2033 * . at the start all registers have precise=false. 2034 * . scalar ranges are tracked as normal through alu and jmp insns. 2035 * . once precise value of the scalar register is used in: 2036 * . ptr + scalar alu 2037 * . if (scalar cond K|scalar) 2038 * . helper_call(.., scalar, ...) where ARG_CONST is expected 2039 * backtrack through the verifier states and mark all registers and 2040 * stack slots with spilled constants that these scalar regisers 2041 * should be precise. 2042 * . during state pruning two registers (or spilled stack slots) 2043 * are equivalent if both are not precise. 2044 * 2045 * Note the verifier cannot simply walk register parentage chain, 2046 * since many different registers and stack slots could have been 2047 * used to compute single precise scalar. 2048 * 2049 * The approach of starting with precise=true for all registers and then 2050 * backtrack to mark a register as not precise when the verifier detects 2051 * that program doesn't care about specific value (e.g., when helper 2052 * takes register as ARG_ANYTHING parameter) is not safe. 2053 * 2054 * It's ok to walk single parentage chain of the verifier states. 2055 * It's possible that this backtracking will go all the way till 1st insn. 2056 * All other branches will be explored for needing precision later. 2057 * 2058 * The backtracking needs to deal with cases like: 2059 * 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) 2060 * r9 -= r8 2061 * r5 = r9 2062 * if r5 > 0x79f goto pc+7 2063 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 2064 * r5 += 1 2065 * ... 2066 * call bpf_perf_event_output#25 2067 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 2068 * 2069 * and this case: 2070 * r6 = 1 2071 * call foo // uses callee's r6 inside to compute r0 2072 * r0 += r6 2073 * if r0 == 0 goto 2074 * 2075 * to track above reg_mask/stack_mask needs to be independent for each frame. 2076 * 2077 * Also if parent's curframe > frame where backtracking started, 2078 * the verifier need to mark registers in both frames, otherwise callees 2079 * may incorrectly prune callers. This is similar to 2080 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 2081 * 2082 * For now backtracking falls back into conservative marking. 2083 */ 2084 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 2085 struct bpf_verifier_state *st) 2086 { 2087 struct bpf_func_state *func; 2088 struct bpf_reg_state *reg; 2089 int i, j; 2090 2091 /* big hammer: mark all scalars precise in this path. 2092 * pop_stack may still get !precise scalars. 2093 */ 2094 for (; st; st = st->parent) 2095 for (i = 0; i <= st->curframe; i++) { 2096 func = st->frame[i]; 2097 for (j = 0; j < BPF_REG_FP; j++) { 2098 reg = &func->regs[j]; 2099 if (reg->type != SCALAR_VALUE) 2100 continue; 2101 reg->precise = true; 2102 } 2103 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 2104 if (func->stack[j].slot_type[0] != STACK_SPILL) 2105 continue; 2106 reg = &func->stack[j].spilled_ptr; 2107 if (reg->type != SCALAR_VALUE) 2108 continue; 2109 reg->precise = true; 2110 } 2111 } 2112 } 2113 2114 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno, 2115 int spi) 2116 { 2117 struct bpf_verifier_state *st = env->cur_state; 2118 int first_idx = st->first_insn_idx; 2119 int last_idx = env->insn_idx; 2120 struct bpf_func_state *func; 2121 struct bpf_reg_state *reg; 2122 u32 reg_mask = regno >= 0 ? 1u << regno : 0; 2123 u64 stack_mask = spi >= 0 ? 1ull << spi : 0; 2124 bool skip_first = true; 2125 bool new_marks = false; 2126 int i, err; 2127 2128 if (!env->bpf_capable) 2129 return 0; 2130 2131 func = st->frame[st->curframe]; 2132 if (regno >= 0) { 2133 reg = &func->regs[regno]; 2134 if (reg->type != SCALAR_VALUE) { 2135 WARN_ONCE(1, "backtracing misuse"); 2136 return -EFAULT; 2137 } 2138 if (!reg->precise) 2139 new_marks = true; 2140 else 2141 reg_mask = 0; 2142 reg->precise = true; 2143 } 2144 2145 while (spi >= 0) { 2146 if (func->stack[spi].slot_type[0] != STACK_SPILL) { 2147 stack_mask = 0; 2148 break; 2149 } 2150 reg = &func->stack[spi].spilled_ptr; 2151 if (reg->type != SCALAR_VALUE) { 2152 stack_mask = 0; 2153 break; 2154 } 2155 if (!reg->precise) 2156 new_marks = true; 2157 else 2158 stack_mask = 0; 2159 reg->precise = true; 2160 break; 2161 } 2162 2163 if (!new_marks) 2164 return 0; 2165 if (!reg_mask && !stack_mask) 2166 return 0; 2167 for (;;) { 2168 DECLARE_BITMAP(mask, 64); 2169 u32 history = st->jmp_history_cnt; 2170 2171 if (env->log.level & BPF_LOG_LEVEL) 2172 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx); 2173 for (i = last_idx;;) { 2174 if (skip_first) { 2175 err = 0; 2176 skip_first = false; 2177 } else { 2178 err = backtrack_insn(env, i, ®_mask, &stack_mask); 2179 } 2180 if (err == -ENOTSUPP) { 2181 mark_all_scalars_precise(env, st); 2182 return 0; 2183 } else if (err) { 2184 return err; 2185 } 2186 if (!reg_mask && !stack_mask) 2187 /* Found assignment(s) into tracked register in this state. 2188 * Since this state is already marked, just return. 2189 * Nothing to be tracked further in the parent state. 2190 */ 2191 return 0; 2192 if (i == first_idx) 2193 break; 2194 i = get_prev_insn_idx(st, i, &history); 2195 if (i >= env->prog->len) { 2196 /* This can happen if backtracking reached insn 0 2197 * and there are still reg_mask or stack_mask 2198 * to backtrack. 2199 * It means the backtracking missed the spot where 2200 * particular register was initialized with a constant. 2201 */ 2202 verbose(env, "BUG backtracking idx %d\n", i); 2203 WARN_ONCE(1, "verifier backtracking bug"); 2204 return -EFAULT; 2205 } 2206 } 2207 st = st->parent; 2208 if (!st) 2209 break; 2210 2211 new_marks = false; 2212 func = st->frame[st->curframe]; 2213 bitmap_from_u64(mask, reg_mask); 2214 for_each_set_bit(i, mask, 32) { 2215 reg = &func->regs[i]; 2216 if (reg->type != SCALAR_VALUE) { 2217 reg_mask &= ~(1u << i); 2218 continue; 2219 } 2220 if (!reg->precise) 2221 new_marks = true; 2222 reg->precise = true; 2223 } 2224 2225 bitmap_from_u64(mask, stack_mask); 2226 for_each_set_bit(i, mask, 64) { 2227 if (i >= func->allocated_stack / BPF_REG_SIZE) { 2228 /* the sequence of instructions: 2229 * 2: (bf) r3 = r10 2230 * 3: (7b) *(u64 *)(r3 -8) = r0 2231 * 4: (79) r4 = *(u64 *)(r10 -8) 2232 * doesn't contain jmps. It's backtracked 2233 * as a single block. 2234 * During backtracking insn 3 is not recognized as 2235 * stack access, so at the end of backtracking 2236 * stack slot fp-8 is still marked in stack_mask. 2237 * However the parent state may not have accessed 2238 * fp-8 and it's "unallocated" stack space. 2239 * In such case fallback to conservative. 2240 */ 2241 mark_all_scalars_precise(env, st); 2242 return 0; 2243 } 2244 2245 if (func->stack[i].slot_type[0] != STACK_SPILL) { 2246 stack_mask &= ~(1ull << i); 2247 continue; 2248 } 2249 reg = &func->stack[i].spilled_ptr; 2250 if (reg->type != SCALAR_VALUE) { 2251 stack_mask &= ~(1ull << i); 2252 continue; 2253 } 2254 if (!reg->precise) 2255 new_marks = true; 2256 reg->precise = true; 2257 } 2258 if (env->log.level & BPF_LOG_LEVEL) { 2259 print_verifier_state(env, func); 2260 verbose(env, "parent %s regs=%x stack=%llx marks\n", 2261 new_marks ? "didn't have" : "already had", 2262 reg_mask, stack_mask); 2263 } 2264 2265 if (!reg_mask && !stack_mask) 2266 break; 2267 if (!new_marks) 2268 break; 2269 2270 last_idx = st->last_insn_idx; 2271 first_idx = st->first_insn_idx; 2272 } 2273 return 0; 2274 } 2275 2276 static int mark_chain_precision(struct bpf_verifier_env *env, int regno) 2277 { 2278 return __mark_chain_precision(env, regno, -1); 2279 } 2280 2281 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi) 2282 { 2283 return __mark_chain_precision(env, -1, spi); 2284 } 2285 2286 static bool is_spillable_regtype(enum bpf_reg_type type) 2287 { 2288 switch (type) { 2289 case PTR_TO_MAP_VALUE: 2290 case PTR_TO_MAP_VALUE_OR_NULL: 2291 case PTR_TO_STACK: 2292 case PTR_TO_CTX: 2293 case PTR_TO_PACKET: 2294 case PTR_TO_PACKET_META: 2295 case PTR_TO_PACKET_END: 2296 case PTR_TO_FLOW_KEYS: 2297 case CONST_PTR_TO_MAP: 2298 case PTR_TO_SOCKET: 2299 case PTR_TO_SOCKET_OR_NULL: 2300 case PTR_TO_SOCK_COMMON: 2301 case PTR_TO_SOCK_COMMON_OR_NULL: 2302 case PTR_TO_TCP_SOCK: 2303 case PTR_TO_TCP_SOCK_OR_NULL: 2304 case PTR_TO_XDP_SOCK: 2305 case PTR_TO_BTF_ID: 2306 case PTR_TO_BTF_ID_OR_NULL: 2307 case PTR_TO_RDONLY_BUF: 2308 case PTR_TO_RDONLY_BUF_OR_NULL: 2309 case PTR_TO_RDWR_BUF: 2310 case PTR_TO_RDWR_BUF_OR_NULL: 2311 case PTR_TO_PERCPU_BTF_ID: 2312 case PTR_TO_MEM: 2313 case PTR_TO_MEM_OR_NULL: 2314 case PTR_TO_FUNC: 2315 case PTR_TO_MAP_KEY: 2316 return true; 2317 default: 2318 return false; 2319 } 2320 } 2321 2322 /* Does this register contain a constant zero? */ 2323 static bool register_is_null(struct bpf_reg_state *reg) 2324 { 2325 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 2326 } 2327 2328 static bool register_is_const(struct bpf_reg_state *reg) 2329 { 2330 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 2331 } 2332 2333 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 2334 { 2335 return tnum_is_unknown(reg->var_off) && 2336 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 2337 reg->umin_value == 0 && reg->umax_value == U64_MAX && 2338 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 2339 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 2340 } 2341 2342 static bool register_is_bounded(struct bpf_reg_state *reg) 2343 { 2344 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 2345 } 2346 2347 static bool __is_pointer_value(bool allow_ptr_leaks, 2348 const struct bpf_reg_state *reg) 2349 { 2350 if (allow_ptr_leaks) 2351 return false; 2352 2353 return reg->type != SCALAR_VALUE; 2354 } 2355 2356 static void save_register_state(struct bpf_func_state *state, 2357 int spi, struct bpf_reg_state *reg) 2358 { 2359 int i; 2360 2361 state->stack[spi].spilled_ptr = *reg; 2362 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2363 2364 for (i = 0; i < BPF_REG_SIZE; i++) 2365 state->stack[spi].slot_type[i] = STACK_SPILL; 2366 } 2367 2368 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 2369 * stack boundary and alignment are checked in check_mem_access() 2370 */ 2371 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 2372 /* stack frame we're writing to */ 2373 struct bpf_func_state *state, 2374 int off, int size, int value_regno, 2375 int insn_idx) 2376 { 2377 struct bpf_func_state *cur; /* state of the current function */ 2378 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 2379 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg; 2380 struct bpf_reg_state *reg = NULL; 2381 2382 err = realloc_func_state(state, round_up(slot + 1, BPF_REG_SIZE), 2383 state->acquired_refs, true); 2384 if (err) 2385 return err; 2386 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 2387 * so it's aligned access and [off, off + size) are within stack limits 2388 */ 2389 if (!env->allow_ptr_leaks && 2390 state->stack[spi].slot_type[0] == STACK_SPILL && 2391 size != BPF_REG_SIZE) { 2392 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 2393 return -EACCES; 2394 } 2395 2396 cur = env->cur_state->frame[env->cur_state->curframe]; 2397 if (value_regno >= 0) 2398 reg = &cur->regs[value_regno]; 2399 2400 if (reg && size == BPF_REG_SIZE && register_is_bounded(reg) && 2401 !register_is_null(reg) && env->bpf_capable) { 2402 if (dst_reg != BPF_REG_FP) { 2403 /* The backtracking logic can only recognize explicit 2404 * stack slot address like [fp - 8]. Other spill of 2405 * scalar via different register has to be conervative. 2406 * Backtrack from here and mark all registers as precise 2407 * that contributed into 'reg' being a constant. 2408 */ 2409 err = mark_chain_precision(env, value_regno); 2410 if (err) 2411 return err; 2412 } 2413 save_register_state(state, spi, reg); 2414 } else if (reg && is_spillable_regtype(reg->type)) { 2415 /* register containing pointer is being spilled into stack */ 2416 if (size != BPF_REG_SIZE) { 2417 verbose_linfo(env, insn_idx, "; "); 2418 verbose(env, "invalid size of register spill\n"); 2419 return -EACCES; 2420 } 2421 2422 if (state != cur && reg->type == PTR_TO_STACK) { 2423 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 2424 return -EINVAL; 2425 } 2426 2427 if (!env->bypass_spec_v4) { 2428 bool sanitize = false; 2429 2430 if (state->stack[spi].slot_type[0] == STACK_SPILL && 2431 register_is_const(&state->stack[spi].spilled_ptr)) 2432 sanitize = true; 2433 for (i = 0; i < BPF_REG_SIZE; i++) 2434 if (state->stack[spi].slot_type[i] == STACK_MISC) { 2435 sanitize = true; 2436 break; 2437 } 2438 if (sanitize) { 2439 int *poff = &env->insn_aux_data[insn_idx].sanitize_stack_off; 2440 int soff = (-spi - 1) * BPF_REG_SIZE; 2441 2442 /* detected reuse of integer stack slot with a pointer 2443 * which means either llvm is reusing stack slot or 2444 * an attacker is trying to exploit CVE-2018-3639 2445 * (speculative store bypass) 2446 * Have to sanitize that slot with preemptive 2447 * store of zero. 2448 */ 2449 if (*poff && *poff != soff) { 2450 /* disallow programs where single insn stores 2451 * into two different stack slots, since verifier 2452 * cannot sanitize them 2453 */ 2454 verbose(env, 2455 "insn %d cannot access two stack slots fp%d and fp%d", 2456 insn_idx, *poff, soff); 2457 return -EINVAL; 2458 } 2459 *poff = soff; 2460 } 2461 } 2462 save_register_state(state, spi, reg); 2463 } else { 2464 u8 type = STACK_MISC; 2465 2466 /* regular write of data into stack destroys any spilled ptr */ 2467 state->stack[spi].spilled_ptr.type = NOT_INIT; 2468 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */ 2469 if (state->stack[spi].slot_type[0] == STACK_SPILL) 2470 for (i = 0; i < BPF_REG_SIZE; i++) 2471 state->stack[spi].slot_type[i] = STACK_MISC; 2472 2473 /* only mark the slot as written if all 8 bytes were written 2474 * otherwise read propagation may incorrectly stop too soon 2475 * when stack slots are partially written. 2476 * This heuristic means that read propagation will be 2477 * conservative, since it will add reg_live_read marks 2478 * to stack slots all the way to first state when programs 2479 * writes+reads less than 8 bytes 2480 */ 2481 if (size == BPF_REG_SIZE) 2482 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2483 2484 /* when we zero initialize stack slots mark them as such */ 2485 if (reg && register_is_null(reg)) { 2486 /* backtracking doesn't work for STACK_ZERO yet. */ 2487 err = mark_chain_precision(env, value_regno); 2488 if (err) 2489 return err; 2490 type = STACK_ZERO; 2491 } 2492 2493 /* Mark slots affected by this stack write. */ 2494 for (i = 0; i < size; i++) 2495 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 2496 type; 2497 } 2498 return 0; 2499 } 2500 2501 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 2502 * known to contain a variable offset. 2503 * This function checks whether the write is permitted and conservatively 2504 * tracks the effects of the write, considering that each stack slot in the 2505 * dynamic range is potentially written to. 2506 * 2507 * 'off' includes 'regno->off'. 2508 * 'value_regno' can be -1, meaning that an unknown value is being written to 2509 * the stack. 2510 * 2511 * Spilled pointers in range are not marked as written because we don't know 2512 * what's going to be actually written. This means that read propagation for 2513 * future reads cannot be terminated by this write. 2514 * 2515 * For privileged programs, uninitialized stack slots are considered 2516 * initialized by this write (even though we don't know exactly what offsets 2517 * are going to be written to). The idea is that we don't want the verifier to 2518 * reject future reads that access slots written to through variable offsets. 2519 */ 2520 static int check_stack_write_var_off(struct bpf_verifier_env *env, 2521 /* func where register points to */ 2522 struct bpf_func_state *state, 2523 int ptr_regno, int off, int size, 2524 int value_regno, int insn_idx) 2525 { 2526 struct bpf_func_state *cur; /* state of the current function */ 2527 int min_off, max_off; 2528 int i, err; 2529 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 2530 bool writing_zero = false; 2531 /* set if the fact that we're writing a zero is used to let any 2532 * stack slots remain STACK_ZERO 2533 */ 2534 bool zero_used = false; 2535 2536 cur = env->cur_state->frame[env->cur_state->curframe]; 2537 ptr_reg = &cur->regs[ptr_regno]; 2538 min_off = ptr_reg->smin_value + off; 2539 max_off = ptr_reg->smax_value + off + size; 2540 if (value_regno >= 0) 2541 value_reg = &cur->regs[value_regno]; 2542 if (value_reg && register_is_null(value_reg)) 2543 writing_zero = true; 2544 2545 err = realloc_func_state(state, round_up(-min_off, BPF_REG_SIZE), 2546 state->acquired_refs, true); 2547 if (err) 2548 return err; 2549 2550 2551 /* Variable offset writes destroy any spilled pointers in range. */ 2552 for (i = min_off; i < max_off; i++) { 2553 u8 new_type, *stype; 2554 int slot, spi; 2555 2556 slot = -i - 1; 2557 spi = slot / BPF_REG_SIZE; 2558 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 2559 2560 if (!env->allow_ptr_leaks 2561 && *stype != NOT_INIT 2562 && *stype != SCALAR_VALUE) { 2563 /* Reject the write if there's are spilled pointers in 2564 * range. If we didn't reject here, the ptr status 2565 * would be erased below (even though not all slots are 2566 * actually overwritten), possibly opening the door to 2567 * leaks. 2568 */ 2569 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 2570 insn_idx, i); 2571 return -EINVAL; 2572 } 2573 2574 /* Erase all spilled pointers. */ 2575 state->stack[spi].spilled_ptr.type = NOT_INIT; 2576 2577 /* Update the slot type. */ 2578 new_type = STACK_MISC; 2579 if (writing_zero && *stype == STACK_ZERO) { 2580 new_type = STACK_ZERO; 2581 zero_used = true; 2582 } 2583 /* If the slot is STACK_INVALID, we check whether it's OK to 2584 * pretend that it will be initialized by this write. The slot 2585 * might not actually be written to, and so if we mark it as 2586 * initialized future reads might leak uninitialized memory. 2587 * For privileged programs, we will accept such reads to slots 2588 * that may or may not be written because, if we're reject 2589 * them, the error would be too confusing. 2590 */ 2591 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 2592 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 2593 insn_idx, i); 2594 return -EINVAL; 2595 } 2596 *stype = new_type; 2597 } 2598 if (zero_used) { 2599 /* backtracking doesn't work for STACK_ZERO yet. */ 2600 err = mark_chain_precision(env, value_regno); 2601 if (err) 2602 return err; 2603 } 2604 return 0; 2605 } 2606 2607 /* When register 'dst_regno' is assigned some values from stack[min_off, 2608 * max_off), we set the register's type according to the types of the 2609 * respective stack slots. If all the stack values are known to be zeros, then 2610 * so is the destination reg. Otherwise, the register is considered to be 2611 * SCALAR. This function does not deal with register filling; the caller must 2612 * ensure that all spilled registers in the stack range have been marked as 2613 * read. 2614 */ 2615 static void mark_reg_stack_read(struct bpf_verifier_env *env, 2616 /* func where src register points to */ 2617 struct bpf_func_state *ptr_state, 2618 int min_off, int max_off, int dst_regno) 2619 { 2620 struct bpf_verifier_state *vstate = env->cur_state; 2621 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2622 int i, slot, spi; 2623 u8 *stype; 2624 int zeros = 0; 2625 2626 for (i = min_off; i < max_off; i++) { 2627 slot = -i - 1; 2628 spi = slot / BPF_REG_SIZE; 2629 stype = ptr_state->stack[spi].slot_type; 2630 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 2631 break; 2632 zeros++; 2633 } 2634 if (zeros == max_off - min_off) { 2635 /* any access_size read into register is zero extended, 2636 * so the whole register == const_zero 2637 */ 2638 __mark_reg_const_zero(&state->regs[dst_regno]); 2639 /* backtracking doesn't support STACK_ZERO yet, 2640 * so mark it precise here, so that later 2641 * backtracking can stop here. 2642 * Backtracking may not need this if this register 2643 * doesn't participate in pointer adjustment. 2644 * Forward propagation of precise flag is not 2645 * necessary either. This mark is only to stop 2646 * backtracking. Any register that contributed 2647 * to const 0 was marked precise before spill. 2648 */ 2649 state->regs[dst_regno].precise = true; 2650 } else { 2651 /* have read misc data from the stack */ 2652 mark_reg_unknown(env, state->regs, dst_regno); 2653 } 2654 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 2655 } 2656 2657 /* Read the stack at 'off' and put the results into the register indicated by 2658 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 2659 * spilled reg. 2660 * 2661 * 'dst_regno' can be -1, meaning that the read value is not going to a 2662 * register. 2663 * 2664 * The access is assumed to be within the current stack bounds. 2665 */ 2666 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 2667 /* func where src register points to */ 2668 struct bpf_func_state *reg_state, 2669 int off, int size, int dst_regno) 2670 { 2671 struct bpf_verifier_state *vstate = env->cur_state; 2672 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2673 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 2674 struct bpf_reg_state *reg; 2675 u8 *stype; 2676 2677 stype = reg_state->stack[spi].slot_type; 2678 reg = ®_state->stack[spi].spilled_ptr; 2679 2680 if (stype[0] == STACK_SPILL) { 2681 if (size != BPF_REG_SIZE) { 2682 if (reg->type != SCALAR_VALUE) { 2683 verbose_linfo(env, env->insn_idx, "; "); 2684 verbose(env, "invalid size of register fill\n"); 2685 return -EACCES; 2686 } 2687 if (dst_regno >= 0) { 2688 mark_reg_unknown(env, state->regs, dst_regno); 2689 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 2690 } 2691 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2692 return 0; 2693 } 2694 for (i = 1; i < BPF_REG_SIZE; i++) { 2695 if (stype[(slot - i) % BPF_REG_SIZE] != STACK_SPILL) { 2696 verbose(env, "corrupted spill memory\n"); 2697 return -EACCES; 2698 } 2699 } 2700 2701 if (dst_regno >= 0) { 2702 /* restore register state from stack */ 2703 state->regs[dst_regno] = *reg; 2704 /* mark reg as written since spilled pointer state likely 2705 * has its liveness marks cleared by is_state_visited() 2706 * which resets stack/reg liveness for state transitions 2707 */ 2708 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 2709 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 2710 /* If dst_regno==-1, the caller is asking us whether 2711 * it is acceptable to use this value as a SCALAR_VALUE 2712 * (e.g. for XADD). 2713 * We must not allow unprivileged callers to do that 2714 * with spilled pointers. 2715 */ 2716 verbose(env, "leaking pointer from stack off %d\n", 2717 off); 2718 return -EACCES; 2719 } 2720 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2721 } else { 2722 u8 type; 2723 2724 for (i = 0; i < size; i++) { 2725 type = stype[(slot - i) % BPF_REG_SIZE]; 2726 if (type == STACK_MISC) 2727 continue; 2728 if (type == STACK_ZERO) 2729 continue; 2730 verbose(env, "invalid read from stack off %d+%d size %d\n", 2731 off, i, size); 2732 return -EACCES; 2733 } 2734 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 2735 if (dst_regno >= 0) 2736 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 2737 } 2738 return 0; 2739 } 2740 2741 enum stack_access_src { 2742 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 2743 ACCESS_HELPER = 2, /* the access is performed by a helper */ 2744 }; 2745 2746 static int check_stack_range_initialized(struct bpf_verifier_env *env, 2747 int regno, int off, int access_size, 2748 bool zero_size_allowed, 2749 enum stack_access_src type, 2750 struct bpf_call_arg_meta *meta); 2751 2752 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 2753 { 2754 return cur_regs(env) + regno; 2755 } 2756 2757 /* Read the stack at 'ptr_regno + off' and put the result into the register 2758 * 'dst_regno'. 2759 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 2760 * but not its variable offset. 2761 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 2762 * 2763 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 2764 * filling registers (i.e. reads of spilled register cannot be detected when 2765 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 2766 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 2767 * offset; for a fixed offset check_stack_read_fixed_off should be used 2768 * instead. 2769 */ 2770 static int check_stack_read_var_off(struct bpf_verifier_env *env, 2771 int ptr_regno, int off, int size, int dst_regno) 2772 { 2773 /* The state of the source register. */ 2774 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 2775 struct bpf_func_state *ptr_state = func(env, reg); 2776 int err; 2777 int min_off, max_off; 2778 2779 /* Note that we pass a NULL meta, so raw access will not be permitted. 2780 */ 2781 err = check_stack_range_initialized(env, ptr_regno, off, size, 2782 false, ACCESS_DIRECT, NULL); 2783 if (err) 2784 return err; 2785 2786 min_off = reg->smin_value + off; 2787 max_off = reg->smax_value + off; 2788 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 2789 return 0; 2790 } 2791 2792 /* check_stack_read dispatches to check_stack_read_fixed_off or 2793 * check_stack_read_var_off. 2794 * 2795 * The caller must ensure that the offset falls within the allocated stack 2796 * bounds. 2797 * 2798 * 'dst_regno' is a register which will receive the value from the stack. It 2799 * can be -1, meaning that the read value is not going to a register. 2800 */ 2801 static int check_stack_read(struct bpf_verifier_env *env, 2802 int ptr_regno, int off, int size, 2803 int dst_regno) 2804 { 2805 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 2806 struct bpf_func_state *state = func(env, reg); 2807 int err; 2808 /* Some accesses are only permitted with a static offset. */ 2809 bool var_off = !tnum_is_const(reg->var_off); 2810 2811 /* The offset is required to be static when reads don't go to a 2812 * register, in order to not leak pointers (see 2813 * check_stack_read_fixed_off). 2814 */ 2815 if (dst_regno < 0 && var_off) { 2816 char tn_buf[48]; 2817 2818 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2819 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 2820 tn_buf, off, size); 2821 return -EACCES; 2822 } 2823 /* Variable offset is prohibited for unprivileged mode for simplicity 2824 * since it requires corresponding support in Spectre masking for stack 2825 * ALU. See also retrieve_ptr_limit(). 2826 */ 2827 if (!env->bypass_spec_v1 && var_off) { 2828 char tn_buf[48]; 2829 2830 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 2831 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 2832 ptr_regno, tn_buf); 2833 return -EACCES; 2834 } 2835 2836 if (!var_off) { 2837 off += reg->var_off.value; 2838 err = check_stack_read_fixed_off(env, state, off, size, 2839 dst_regno); 2840 } else { 2841 /* Variable offset stack reads need more conservative handling 2842 * than fixed offset ones. Note that dst_regno >= 0 on this 2843 * branch. 2844 */ 2845 err = check_stack_read_var_off(env, ptr_regno, off, size, 2846 dst_regno); 2847 } 2848 return err; 2849 } 2850 2851 2852 /* check_stack_write dispatches to check_stack_write_fixed_off or 2853 * check_stack_write_var_off. 2854 * 2855 * 'ptr_regno' is the register used as a pointer into the stack. 2856 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 2857 * 'value_regno' is the register whose value we're writing to the stack. It can 2858 * be -1, meaning that we're not writing from a register. 2859 * 2860 * The caller must ensure that the offset falls within the maximum stack size. 2861 */ 2862 static int check_stack_write(struct bpf_verifier_env *env, 2863 int ptr_regno, int off, int size, 2864 int value_regno, int insn_idx) 2865 { 2866 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 2867 struct bpf_func_state *state = func(env, reg); 2868 int err; 2869 2870 if (tnum_is_const(reg->var_off)) { 2871 off += reg->var_off.value; 2872 err = check_stack_write_fixed_off(env, state, off, size, 2873 value_regno, insn_idx); 2874 } else { 2875 /* Variable offset stack reads need more conservative handling 2876 * than fixed offset ones. 2877 */ 2878 err = check_stack_write_var_off(env, state, 2879 ptr_regno, off, size, 2880 value_regno, insn_idx); 2881 } 2882 return err; 2883 } 2884 2885 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 2886 int off, int size, enum bpf_access_type type) 2887 { 2888 struct bpf_reg_state *regs = cur_regs(env); 2889 struct bpf_map *map = regs[regno].map_ptr; 2890 u32 cap = bpf_map_flags_to_cap(map); 2891 2892 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 2893 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 2894 map->value_size, off, size); 2895 return -EACCES; 2896 } 2897 2898 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 2899 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 2900 map->value_size, off, size); 2901 return -EACCES; 2902 } 2903 2904 return 0; 2905 } 2906 2907 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 2908 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 2909 int off, int size, u32 mem_size, 2910 bool zero_size_allowed) 2911 { 2912 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 2913 struct bpf_reg_state *reg; 2914 2915 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 2916 return 0; 2917 2918 reg = &cur_regs(env)[regno]; 2919 switch (reg->type) { 2920 case PTR_TO_MAP_KEY: 2921 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 2922 mem_size, off, size); 2923 break; 2924 case PTR_TO_MAP_VALUE: 2925 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 2926 mem_size, off, size); 2927 break; 2928 case PTR_TO_PACKET: 2929 case PTR_TO_PACKET_META: 2930 case PTR_TO_PACKET_END: 2931 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 2932 off, size, regno, reg->id, off, mem_size); 2933 break; 2934 case PTR_TO_MEM: 2935 default: 2936 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 2937 mem_size, off, size); 2938 } 2939 2940 return -EACCES; 2941 } 2942 2943 /* check read/write into a memory region with possible variable offset */ 2944 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 2945 int off, int size, u32 mem_size, 2946 bool zero_size_allowed) 2947 { 2948 struct bpf_verifier_state *vstate = env->cur_state; 2949 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2950 struct bpf_reg_state *reg = &state->regs[regno]; 2951 int err; 2952 2953 /* We may have adjusted the register pointing to memory region, so we 2954 * need to try adding each of min_value and max_value to off 2955 * to make sure our theoretical access will be safe. 2956 */ 2957 if (env->log.level & BPF_LOG_LEVEL) 2958 print_verifier_state(env, state); 2959 2960 /* The minimum value is only important with signed 2961 * comparisons where we can't assume the floor of a 2962 * value is 0. If we are using signed variables for our 2963 * index'es we need to make sure that whatever we use 2964 * will have a set floor within our range. 2965 */ 2966 if (reg->smin_value < 0 && 2967 (reg->smin_value == S64_MIN || 2968 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 2969 reg->smin_value + off < 0)) { 2970 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 2971 regno); 2972 return -EACCES; 2973 } 2974 err = __check_mem_access(env, regno, reg->smin_value + off, size, 2975 mem_size, zero_size_allowed); 2976 if (err) { 2977 verbose(env, "R%d min value is outside of the allowed memory range\n", 2978 regno); 2979 return err; 2980 } 2981 2982 /* If we haven't set a max value then we need to bail since we can't be 2983 * sure we won't do bad things. 2984 * If reg->umax_value + off could overflow, treat that as unbounded too. 2985 */ 2986 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 2987 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 2988 regno); 2989 return -EACCES; 2990 } 2991 err = __check_mem_access(env, regno, reg->umax_value + off, size, 2992 mem_size, zero_size_allowed); 2993 if (err) { 2994 verbose(env, "R%d max value is outside of the allowed memory range\n", 2995 regno); 2996 return err; 2997 } 2998 2999 return 0; 3000 } 3001 3002 /* check read/write into a map element with possible variable offset */ 3003 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 3004 int off, int size, bool zero_size_allowed) 3005 { 3006 struct bpf_verifier_state *vstate = env->cur_state; 3007 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3008 struct bpf_reg_state *reg = &state->regs[regno]; 3009 struct bpf_map *map = reg->map_ptr; 3010 int err; 3011 3012 err = check_mem_region_access(env, regno, off, size, map->value_size, 3013 zero_size_allowed); 3014 if (err) 3015 return err; 3016 3017 if (map_value_has_spin_lock(map)) { 3018 u32 lock = map->spin_lock_off; 3019 3020 /* if any part of struct bpf_spin_lock can be touched by 3021 * load/store reject this program. 3022 * To check that [x1, x2) overlaps with [y1, y2) 3023 * it is sufficient to check x1 < y2 && y1 < x2. 3024 */ 3025 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) && 3026 lock < reg->umax_value + off + size) { 3027 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n"); 3028 return -EACCES; 3029 } 3030 } 3031 return err; 3032 } 3033 3034 #define MAX_PACKET_OFF 0xffff 3035 3036 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog) 3037 { 3038 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type; 3039 } 3040 3041 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 3042 const struct bpf_call_arg_meta *meta, 3043 enum bpf_access_type t) 3044 { 3045 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 3046 3047 switch (prog_type) { 3048 /* Program types only with direct read access go here! */ 3049 case BPF_PROG_TYPE_LWT_IN: 3050 case BPF_PROG_TYPE_LWT_OUT: 3051 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 3052 case BPF_PROG_TYPE_SK_REUSEPORT: 3053 case BPF_PROG_TYPE_FLOW_DISSECTOR: 3054 case BPF_PROG_TYPE_CGROUP_SKB: 3055 if (t == BPF_WRITE) 3056 return false; 3057 fallthrough; 3058 3059 /* Program types with direct read + write access go here! */ 3060 case BPF_PROG_TYPE_SCHED_CLS: 3061 case BPF_PROG_TYPE_SCHED_ACT: 3062 case BPF_PROG_TYPE_XDP: 3063 case BPF_PROG_TYPE_LWT_XMIT: 3064 case BPF_PROG_TYPE_SK_SKB: 3065 case BPF_PROG_TYPE_SK_MSG: 3066 if (meta) 3067 return meta->pkt_access; 3068 3069 env->seen_direct_write = true; 3070 return true; 3071 3072 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 3073 if (t == BPF_WRITE) 3074 env->seen_direct_write = true; 3075 3076 return true; 3077 3078 default: 3079 return false; 3080 } 3081 } 3082 3083 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 3084 int size, bool zero_size_allowed) 3085 { 3086 struct bpf_reg_state *regs = cur_regs(env); 3087 struct bpf_reg_state *reg = ®s[regno]; 3088 int err; 3089 3090 /* We may have added a variable offset to the packet pointer; but any 3091 * reg->range we have comes after that. We are only checking the fixed 3092 * offset. 3093 */ 3094 3095 /* We don't allow negative numbers, because we aren't tracking enough 3096 * detail to prove they're safe. 3097 */ 3098 if (reg->smin_value < 0) { 3099 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3100 regno); 3101 return -EACCES; 3102 } 3103 3104 err = reg->range < 0 ? -EINVAL : 3105 __check_mem_access(env, regno, off, size, reg->range, 3106 zero_size_allowed); 3107 if (err) { 3108 verbose(env, "R%d offset is outside of the packet\n", regno); 3109 return err; 3110 } 3111 3112 /* __check_mem_access has made sure "off + size - 1" is within u16. 3113 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 3114 * otherwise find_good_pkt_pointers would have refused to set range info 3115 * that __check_mem_access would have rejected this pkt access. 3116 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 3117 */ 3118 env->prog->aux->max_pkt_offset = 3119 max_t(u32, env->prog->aux->max_pkt_offset, 3120 off + reg->umax_value + size - 1); 3121 3122 return err; 3123 } 3124 3125 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 3126 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 3127 enum bpf_access_type t, enum bpf_reg_type *reg_type, 3128 struct btf **btf, u32 *btf_id) 3129 { 3130 struct bpf_insn_access_aux info = { 3131 .reg_type = *reg_type, 3132 .log = &env->log, 3133 }; 3134 3135 if (env->ops->is_valid_access && 3136 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 3137 /* A non zero info.ctx_field_size indicates that this field is a 3138 * candidate for later verifier transformation to load the whole 3139 * field and then apply a mask when accessed with a narrower 3140 * access than actual ctx access size. A zero info.ctx_field_size 3141 * will only allow for whole field access and rejects any other 3142 * type of narrower access. 3143 */ 3144 *reg_type = info.reg_type; 3145 3146 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) { 3147 *btf = info.btf; 3148 *btf_id = info.btf_id; 3149 } else { 3150 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 3151 } 3152 /* remember the offset of last byte accessed in ctx */ 3153 if (env->prog->aux->max_ctx_offset < off + size) 3154 env->prog->aux->max_ctx_offset = off + size; 3155 return 0; 3156 } 3157 3158 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 3159 return -EACCES; 3160 } 3161 3162 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 3163 int size) 3164 { 3165 if (size < 0 || off < 0 || 3166 (u64)off + size > sizeof(struct bpf_flow_keys)) { 3167 verbose(env, "invalid access to flow keys off=%d size=%d\n", 3168 off, size); 3169 return -EACCES; 3170 } 3171 return 0; 3172 } 3173 3174 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 3175 u32 regno, int off, int size, 3176 enum bpf_access_type t) 3177 { 3178 struct bpf_reg_state *regs = cur_regs(env); 3179 struct bpf_reg_state *reg = ®s[regno]; 3180 struct bpf_insn_access_aux info = {}; 3181 bool valid; 3182 3183 if (reg->smin_value < 0) { 3184 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3185 regno); 3186 return -EACCES; 3187 } 3188 3189 switch (reg->type) { 3190 case PTR_TO_SOCK_COMMON: 3191 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 3192 break; 3193 case PTR_TO_SOCKET: 3194 valid = bpf_sock_is_valid_access(off, size, t, &info); 3195 break; 3196 case PTR_TO_TCP_SOCK: 3197 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 3198 break; 3199 case PTR_TO_XDP_SOCK: 3200 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 3201 break; 3202 default: 3203 valid = false; 3204 } 3205 3206 3207 if (valid) { 3208 env->insn_aux_data[insn_idx].ctx_field_size = 3209 info.ctx_field_size; 3210 return 0; 3211 } 3212 3213 verbose(env, "R%d invalid %s access off=%d size=%d\n", 3214 regno, reg_type_str[reg->type], off, size); 3215 3216 return -EACCES; 3217 } 3218 3219 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 3220 { 3221 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 3222 } 3223 3224 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 3225 { 3226 const struct bpf_reg_state *reg = reg_state(env, regno); 3227 3228 return reg->type == PTR_TO_CTX; 3229 } 3230 3231 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 3232 { 3233 const struct bpf_reg_state *reg = reg_state(env, regno); 3234 3235 return type_is_sk_pointer(reg->type); 3236 } 3237 3238 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 3239 { 3240 const struct bpf_reg_state *reg = reg_state(env, regno); 3241 3242 return type_is_pkt_pointer(reg->type); 3243 } 3244 3245 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 3246 { 3247 const struct bpf_reg_state *reg = reg_state(env, regno); 3248 3249 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 3250 return reg->type == PTR_TO_FLOW_KEYS; 3251 } 3252 3253 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 3254 const struct bpf_reg_state *reg, 3255 int off, int size, bool strict) 3256 { 3257 struct tnum reg_off; 3258 int ip_align; 3259 3260 /* Byte size accesses are always allowed. */ 3261 if (!strict || size == 1) 3262 return 0; 3263 3264 /* For platforms that do not have a Kconfig enabling 3265 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 3266 * NET_IP_ALIGN is universally set to '2'. And on platforms 3267 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 3268 * to this code only in strict mode where we want to emulate 3269 * the NET_IP_ALIGN==2 checking. Therefore use an 3270 * unconditional IP align value of '2'. 3271 */ 3272 ip_align = 2; 3273 3274 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 3275 if (!tnum_is_aligned(reg_off, size)) { 3276 char tn_buf[48]; 3277 3278 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3279 verbose(env, 3280 "misaligned packet access off %d+%s+%d+%d size %d\n", 3281 ip_align, tn_buf, reg->off, off, size); 3282 return -EACCES; 3283 } 3284 3285 return 0; 3286 } 3287 3288 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 3289 const struct bpf_reg_state *reg, 3290 const char *pointer_desc, 3291 int off, int size, bool strict) 3292 { 3293 struct tnum reg_off; 3294 3295 /* Byte size accesses are always allowed. */ 3296 if (!strict || size == 1) 3297 return 0; 3298 3299 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 3300 if (!tnum_is_aligned(reg_off, size)) { 3301 char tn_buf[48]; 3302 3303 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3304 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 3305 pointer_desc, tn_buf, reg->off, off, size); 3306 return -EACCES; 3307 } 3308 3309 return 0; 3310 } 3311 3312 static int check_ptr_alignment(struct bpf_verifier_env *env, 3313 const struct bpf_reg_state *reg, int off, 3314 int size, bool strict_alignment_once) 3315 { 3316 bool strict = env->strict_alignment || strict_alignment_once; 3317 const char *pointer_desc = ""; 3318 3319 switch (reg->type) { 3320 case PTR_TO_PACKET: 3321 case PTR_TO_PACKET_META: 3322 /* Special case, because of NET_IP_ALIGN. Given metadata sits 3323 * right in front, treat it the very same way. 3324 */ 3325 return check_pkt_ptr_alignment(env, reg, off, size, strict); 3326 case PTR_TO_FLOW_KEYS: 3327 pointer_desc = "flow keys "; 3328 break; 3329 case PTR_TO_MAP_KEY: 3330 pointer_desc = "key "; 3331 break; 3332 case PTR_TO_MAP_VALUE: 3333 pointer_desc = "value "; 3334 break; 3335 case PTR_TO_CTX: 3336 pointer_desc = "context "; 3337 break; 3338 case PTR_TO_STACK: 3339 pointer_desc = "stack "; 3340 /* The stack spill tracking logic in check_stack_write_fixed_off() 3341 * and check_stack_read_fixed_off() relies on stack accesses being 3342 * aligned. 3343 */ 3344 strict = true; 3345 break; 3346 case PTR_TO_SOCKET: 3347 pointer_desc = "sock "; 3348 break; 3349 case PTR_TO_SOCK_COMMON: 3350 pointer_desc = "sock_common "; 3351 break; 3352 case PTR_TO_TCP_SOCK: 3353 pointer_desc = "tcp_sock "; 3354 break; 3355 case PTR_TO_XDP_SOCK: 3356 pointer_desc = "xdp_sock "; 3357 break; 3358 default: 3359 break; 3360 } 3361 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 3362 strict); 3363 } 3364 3365 static int update_stack_depth(struct bpf_verifier_env *env, 3366 const struct bpf_func_state *func, 3367 int off) 3368 { 3369 u16 stack = env->subprog_info[func->subprogno].stack_depth; 3370 3371 if (stack >= -off) 3372 return 0; 3373 3374 /* update known max for given subprogram */ 3375 env->subprog_info[func->subprogno].stack_depth = -off; 3376 return 0; 3377 } 3378 3379 /* starting from main bpf function walk all instructions of the function 3380 * and recursively walk all callees that given function can call. 3381 * Ignore jump and exit insns. 3382 * Since recursion is prevented by check_cfg() this algorithm 3383 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 3384 */ 3385 static int check_max_stack_depth(struct bpf_verifier_env *env) 3386 { 3387 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 3388 struct bpf_subprog_info *subprog = env->subprog_info; 3389 struct bpf_insn *insn = env->prog->insnsi; 3390 bool tail_call_reachable = false; 3391 int ret_insn[MAX_CALL_FRAMES]; 3392 int ret_prog[MAX_CALL_FRAMES]; 3393 int j; 3394 3395 process_func: 3396 /* protect against potential stack overflow that might happen when 3397 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 3398 * depth for such case down to 256 so that the worst case scenario 3399 * would result in 8k stack size (32 which is tailcall limit * 256 = 3400 * 8k). 3401 * 3402 * To get the idea what might happen, see an example: 3403 * func1 -> sub rsp, 128 3404 * subfunc1 -> sub rsp, 256 3405 * tailcall1 -> add rsp, 256 3406 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 3407 * subfunc2 -> sub rsp, 64 3408 * subfunc22 -> sub rsp, 128 3409 * tailcall2 -> add rsp, 128 3410 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 3411 * 3412 * tailcall will unwind the current stack frame but it will not get rid 3413 * of caller's stack as shown on the example above. 3414 */ 3415 if (idx && subprog[idx].has_tail_call && depth >= 256) { 3416 verbose(env, 3417 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 3418 depth); 3419 return -EACCES; 3420 } 3421 /* round up to 32-bytes, since this is granularity 3422 * of interpreter stack size 3423 */ 3424 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 3425 if (depth > MAX_BPF_STACK) { 3426 verbose(env, "combined stack size of %d calls is %d. Too large\n", 3427 frame + 1, depth); 3428 return -EACCES; 3429 } 3430 continue_func: 3431 subprog_end = subprog[idx + 1].start; 3432 for (; i < subprog_end; i++) { 3433 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 3434 continue; 3435 /* remember insn and function to return to */ 3436 ret_insn[frame] = i + 1; 3437 ret_prog[frame] = idx; 3438 3439 /* find the callee */ 3440 i = i + insn[i].imm + 1; 3441 idx = find_subprog(env, i); 3442 if (idx < 0) { 3443 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 3444 i); 3445 return -EFAULT; 3446 } 3447 3448 if (subprog[idx].has_tail_call) 3449 tail_call_reachable = true; 3450 3451 frame++; 3452 if (frame >= MAX_CALL_FRAMES) { 3453 verbose(env, "the call stack of %d frames is too deep !\n", 3454 frame); 3455 return -E2BIG; 3456 } 3457 goto process_func; 3458 } 3459 /* if tail call got detected across bpf2bpf calls then mark each of the 3460 * currently present subprog frames as tail call reachable subprogs; 3461 * this info will be utilized by JIT so that we will be preserving the 3462 * tail call counter throughout bpf2bpf calls combined with tailcalls 3463 */ 3464 if (tail_call_reachable) 3465 for (j = 0; j < frame; j++) 3466 subprog[ret_prog[j]].tail_call_reachable = true; 3467 3468 /* end of for() loop means the last insn of the 'subprog' 3469 * was reached. Doesn't matter whether it was JA or EXIT 3470 */ 3471 if (frame == 0) 3472 return 0; 3473 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 3474 frame--; 3475 i = ret_insn[frame]; 3476 idx = ret_prog[frame]; 3477 goto continue_func; 3478 } 3479 3480 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 3481 static int get_callee_stack_depth(struct bpf_verifier_env *env, 3482 const struct bpf_insn *insn, int idx) 3483 { 3484 int start = idx + insn->imm + 1, subprog; 3485 3486 subprog = find_subprog(env, start); 3487 if (subprog < 0) { 3488 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 3489 start); 3490 return -EFAULT; 3491 } 3492 return env->subprog_info[subprog].stack_depth; 3493 } 3494 #endif 3495 3496 int check_ctx_reg(struct bpf_verifier_env *env, 3497 const struct bpf_reg_state *reg, int regno) 3498 { 3499 /* Access to ctx or passing it to a helper is only allowed in 3500 * its original, unmodified form. 3501 */ 3502 3503 if (reg->off) { 3504 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n", 3505 regno, reg->off); 3506 return -EACCES; 3507 } 3508 3509 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3510 char tn_buf[48]; 3511 3512 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3513 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf); 3514 return -EACCES; 3515 } 3516 3517 return 0; 3518 } 3519 3520 static int __check_buffer_access(struct bpf_verifier_env *env, 3521 const char *buf_info, 3522 const struct bpf_reg_state *reg, 3523 int regno, int off, int size) 3524 { 3525 if (off < 0) { 3526 verbose(env, 3527 "R%d invalid %s buffer access: off=%d, size=%d\n", 3528 regno, buf_info, off, size); 3529 return -EACCES; 3530 } 3531 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3532 char tn_buf[48]; 3533 3534 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3535 verbose(env, 3536 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 3537 regno, off, tn_buf); 3538 return -EACCES; 3539 } 3540 3541 return 0; 3542 } 3543 3544 static int check_tp_buffer_access(struct bpf_verifier_env *env, 3545 const struct bpf_reg_state *reg, 3546 int regno, int off, int size) 3547 { 3548 int err; 3549 3550 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 3551 if (err) 3552 return err; 3553 3554 if (off + size > env->prog->aux->max_tp_access) 3555 env->prog->aux->max_tp_access = off + size; 3556 3557 return 0; 3558 } 3559 3560 static int check_buffer_access(struct bpf_verifier_env *env, 3561 const struct bpf_reg_state *reg, 3562 int regno, int off, int size, 3563 bool zero_size_allowed, 3564 const char *buf_info, 3565 u32 *max_access) 3566 { 3567 int err; 3568 3569 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 3570 if (err) 3571 return err; 3572 3573 if (off + size > *max_access) 3574 *max_access = off + size; 3575 3576 return 0; 3577 } 3578 3579 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 3580 static void zext_32_to_64(struct bpf_reg_state *reg) 3581 { 3582 reg->var_off = tnum_subreg(reg->var_off); 3583 __reg_assign_32_into_64(reg); 3584 } 3585 3586 /* truncate register to smaller size (in bytes) 3587 * must be called with size < BPF_REG_SIZE 3588 */ 3589 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 3590 { 3591 u64 mask; 3592 3593 /* clear high bits in bit representation */ 3594 reg->var_off = tnum_cast(reg->var_off, size); 3595 3596 /* fix arithmetic bounds */ 3597 mask = ((u64)1 << (size * 8)) - 1; 3598 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 3599 reg->umin_value &= mask; 3600 reg->umax_value &= mask; 3601 } else { 3602 reg->umin_value = 0; 3603 reg->umax_value = mask; 3604 } 3605 reg->smin_value = reg->umin_value; 3606 reg->smax_value = reg->umax_value; 3607 3608 /* If size is smaller than 32bit register the 32bit register 3609 * values are also truncated so we push 64-bit bounds into 3610 * 32-bit bounds. Above were truncated < 32-bits already. 3611 */ 3612 if (size >= 4) 3613 return; 3614 __reg_combine_64_into_32(reg); 3615 } 3616 3617 static bool bpf_map_is_rdonly(const struct bpf_map *map) 3618 { 3619 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen; 3620 } 3621 3622 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 3623 { 3624 void *ptr; 3625 u64 addr; 3626 int err; 3627 3628 err = map->ops->map_direct_value_addr(map, &addr, off); 3629 if (err) 3630 return err; 3631 ptr = (void *)(long)addr + off; 3632 3633 switch (size) { 3634 case sizeof(u8): 3635 *val = (u64)*(u8 *)ptr; 3636 break; 3637 case sizeof(u16): 3638 *val = (u64)*(u16 *)ptr; 3639 break; 3640 case sizeof(u32): 3641 *val = (u64)*(u32 *)ptr; 3642 break; 3643 case sizeof(u64): 3644 *val = *(u64 *)ptr; 3645 break; 3646 default: 3647 return -EINVAL; 3648 } 3649 return 0; 3650 } 3651 3652 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 3653 struct bpf_reg_state *regs, 3654 int regno, int off, int size, 3655 enum bpf_access_type atype, 3656 int value_regno) 3657 { 3658 struct bpf_reg_state *reg = regs + regno; 3659 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 3660 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 3661 u32 btf_id; 3662 int ret; 3663 3664 if (off < 0) { 3665 verbose(env, 3666 "R%d is ptr_%s invalid negative access: off=%d\n", 3667 regno, tname, off); 3668 return -EACCES; 3669 } 3670 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3671 char tn_buf[48]; 3672 3673 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3674 verbose(env, 3675 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 3676 regno, tname, off, tn_buf); 3677 return -EACCES; 3678 } 3679 3680 if (env->ops->btf_struct_access) { 3681 ret = env->ops->btf_struct_access(&env->log, reg->btf, t, 3682 off, size, atype, &btf_id); 3683 } else { 3684 if (atype != BPF_READ) { 3685 verbose(env, "only read is supported\n"); 3686 return -EACCES; 3687 } 3688 3689 ret = btf_struct_access(&env->log, reg->btf, t, off, size, 3690 atype, &btf_id); 3691 } 3692 3693 if (ret < 0) 3694 return ret; 3695 3696 if (atype == BPF_READ && value_regno >= 0) 3697 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id); 3698 3699 return 0; 3700 } 3701 3702 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 3703 struct bpf_reg_state *regs, 3704 int regno, int off, int size, 3705 enum bpf_access_type atype, 3706 int value_regno) 3707 { 3708 struct bpf_reg_state *reg = regs + regno; 3709 struct bpf_map *map = reg->map_ptr; 3710 const struct btf_type *t; 3711 const char *tname; 3712 u32 btf_id; 3713 int ret; 3714 3715 if (!btf_vmlinux) { 3716 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 3717 return -ENOTSUPP; 3718 } 3719 3720 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 3721 verbose(env, "map_ptr access not supported for map type %d\n", 3722 map->map_type); 3723 return -ENOTSUPP; 3724 } 3725 3726 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 3727 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 3728 3729 if (!env->allow_ptr_to_map_access) { 3730 verbose(env, 3731 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 3732 tname); 3733 return -EPERM; 3734 } 3735 3736 if (off < 0) { 3737 verbose(env, "R%d is %s invalid negative access: off=%d\n", 3738 regno, tname, off); 3739 return -EACCES; 3740 } 3741 3742 if (atype != BPF_READ) { 3743 verbose(env, "only read from %s is supported\n", tname); 3744 return -EACCES; 3745 } 3746 3747 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id); 3748 if (ret < 0) 3749 return ret; 3750 3751 if (value_regno >= 0) 3752 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id); 3753 3754 return 0; 3755 } 3756 3757 /* Check that the stack access at the given offset is within bounds. The 3758 * maximum valid offset is -1. 3759 * 3760 * The minimum valid offset is -MAX_BPF_STACK for writes, and 3761 * -state->allocated_stack for reads. 3762 */ 3763 static int check_stack_slot_within_bounds(int off, 3764 struct bpf_func_state *state, 3765 enum bpf_access_type t) 3766 { 3767 int min_valid_off; 3768 3769 if (t == BPF_WRITE) 3770 min_valid_off = -MAX_BPF_STACK; 3771 else 3772 min_valid_off = -state->allocated_stack; 3773 3774 if (off < min_valid_off || off > -1) 3775 return -EACCES; 3776 return 0; 3777 } 3778 3779 /* Check that the stack access at 'regno + off' falls within the maximum stack 3780 * bounds. 3781 * 3782 * 'off' includes `regno->offset`, but not its dynamic part (if any). 3783 */ 3784 static int check_stack_access_within_bounds( 3785 struct bpf_verifier_env *env, 3786 int regno, int off, int access_size, 3787 enum stack_access_src src, enum bpf_access_type type) 3788 { 3789 struct bpf_reg_state *regs = cur_regs(env); 3790 struct bpf_reg_state *reg = regs + regno; 3791 struct bpf_func_state *state = func(env, reg); 3792 int min_off, max_off; 3793 int err; 3794 char *err_extra; 3795 3796 if (src == ACCESS_HELPER) 3797 /* We don't know if helpers are reading or writing (or both). */ 3798 err_extra = " indirect access to"; 3799 else if (type == BPF_READ) 3800 err_extra = " read from"; 3801 else 3802 err_extra = " write to"; 3803 3804 if (tnum_is_const(reg->var_off)) { 3805 min_off = reg->var_off.value + off; 3806 if (access_size > 0) 3807 max_off = min_off + access_size - 1; 3808 else 3809 max_off = min_off; 3810 } else { 3811 if (reg->smax_value >= BPF_MAX_VAR_OFF || 3812 reg->smin_value <= -BPF_MAX_VAR_OFF) { 3813 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 3814 err_extra, regno); 3815 return -EACCES; 3816 } 3817 min_off = reg->smin_value + off; 3818 if (access_size > 0) 3819 max_off = reg->smax_value + off + access_size - 1; 3820 else 3821 max_off = min_off; 3822 } 3823 3824 err = check_stack_slot_within_bounds(min_off, state, type); 3825 if (!err) 3826 err = check_stack_slot_within_bounds(max_off, state, type); 3827 3828 if (err) { 3829 if (tnum_is_const(reg->var_off)) { 3830 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 3831 err_extra, regno, off, access_size); 3832 } else { 3833 char tn_buf[48]; 3834 3835 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3836 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 3837 err_extra, regno, tn_buf, access_size); 3838 } 3839 } 3840 return err; 3841 } 3842 3843 /* check whether memory at (regno + off) is accessible for t = (read | write) 3844 * if t==write, value_regno is a register which value is stored into memory 3845 * if t==read, value_regno is a register which will receive the value from memory 3846 * if t==write && value_regno==-1, some unknown value is stored into memory 3847 * if t==read && value_regno==-1, don't care what we read from memory 3848 */ 3849 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 3850 int off, int bpf_size, enum bpf_access_type t, 3851 int value_regno, bool strict_alignment_once) 3852 { 3853 struct bpf_reg_state *regs = cur_regs(env); 3854 struct bpf_reg_state *reg = regs + regno; 3855 struct bpf_func_state *state; 3856 int size, err = 0; 3857 3858 size = bpf_size_to_bytes(bpf_size); 3859 if (size < 0) 3860 return size; 3861 3862 /* alignment checks will add in reg->off themselves */ 3863 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 3864 if (err) 3865 return err; 3866 3867 /* for access checks, reg->off is just part of off */ 3868 off += reg->off; 3869 3870 if (reg->type == PTR_TO_MAP_KEY) { 3871 if (t == BPF_WRITE) { 3872 verbose(env, "write to change key R%d not allowed\n", regno); 3873 return -EACCES; 3874 } 3875 3876 err = check_mem_region_access(env, regno, off, size, 3877 reg->map_ptr->key_size, false); 3878 if (err) 3879 return err; 3880 if (value_regno >= 0) 3881 mark_reg_unknown(env, regs, value_regno); 3882 } else if (reg->type == PTR_TO_MAP_VALUE) { 3883 if (t == BPF_WRITE && value_regno >= 0 && 3884 is_pointer_value(env, value_regno)) { 3885 verbose(env, "R%d leaks addr into map\n", value_regno); 3886 return -EACCES; 3887 } 3888 err = check_map_access_type(env, regno, off, size, t); 3889 if (err) 3890 return err; 3891 err = check_map_access(env, regno, off, size, false); 3892 if (!err && t == BPF_READ && value_regno >= 0) { 3893 struct bpf_map *map = reg->map_ptr; 3894 3895 /* if map is read-only, track its contents as scalars */ 3896 if (tnum_is_const(reg->var_off) && 3897 bpf_map_is_rdonly(map) && 3898 map->ops->map_direct_value_addr) { 3899 int map_off = off + reg->var_off.value; 3900 u64 val = 0; 3901 3902 err = bpf_map_direct_read(map, map_off, size, 3903 &val); 3904 if (err) 3905 return err; 3906 3907 regs[value_regno].type = SCALAR_VALUE; 3908 __mark_reg_known(®s[value_regno], val); 3909 } else { 3910 mark_reg_unknown(env, regs, value_regno); 3911 } 3912 } 3913 } else if (reg->type == PTR_TO_MEM) { 3914 if (t == BPF_WRITE && value_regno >= 0 && 3915 is_pointer_value(env, value_regno)) { 3916 verbose(env, "R%d leaks addr into mem\n", value_regno); 3917 return -EACCES; 3918 } 3919 err = check_mem_region_access(env, regno, off, size, 3920 reg->mem_size, false); 3921 if (!err && t == BPF_READ && value_regno >= 0) 3922 mark_reg_unknown(env, regs, value_regno); 3923 } else if (reg->type == PTR_TO_CTX) { 3924 enum bpf_reg_type reg_type = SCALAR_VALUE; 3925 struct btf *btf = NULL; 3926 u32 btf_id = 0; 3927 3928 if (t == BPF_WRITE && value_regno >= 0 && 3929 is_pointer_value(env, value_regno)) { 3930 verbose(env, "R%d leaks addr into ctx\n", value_regno); 3931 return -EACCES; 3932 } 3933 3934 err = check_ctx_reg(env, reg, regno); 3935 if (err < 0) 3936 return err; 3937 3938 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, &btf_id); 3939 if (err) 3940 verbose_linfo(env, insn_idx, "; "); 3941 if (!err && t == BPF_READ && value_regno >= 0) { 3942 /* ctx access returns either a scalar, or a 3943 * PTR_TO_PACKET[_META,_END]. In the latter 3944 * case, we know the offset is zero. 3945 */ 3946 if (reg_type == SCALAR_VALUE) { 3947 mark_reg_unknown(env, regs, value_regno); 3948 } else { 3949 mark_reg_known_zero(env, regs, 3950 value_regno); 3951 if (reg_type_may_be_null(reg_type)) 3952 regs[value_regno].id = ++env->id_gen; 3953 /* A load of ctx field could have different 3954 * actual load size with the one encoded in the 3955 * insn. When the dst is PTR, it is for sure not 3956 * a sub-register. 3957 */ 3958 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 3959 if (reg_type == PTR_TO_BTF_ID || 3960 reg_type == PTR_TO_BTF_ID_OR_NULL) { 3961 regs[value_regno].btf = btf; 3962 regs[value_regno].btf_id = btf_id; 3963 } 3964 } 3965 regs[value_regno].type = reg_type; 3966 } 3967 3968 } else if (reg->type == PTR_TO_STACK) { 3969 /* Basic bounds checks. */ 3970 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 3971 if (err) 3972 return err; 3973 3974 state = func(env, reg); 3975 err = update_stack_depth(env, state, off); 3976 if (err) 3977 return err; 3978 3979 if (t == BPF_READ) 3980 err = check_stack_read(env, regno, off, size, 3981 value_regno); 3982 else 3983 err = check_stack_write(env, regno, off, size, 3984 value_regno, insn_idx); 3985 } else if (reg_is_pkt_pointer(reg)) { 3986 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 3987 verbose(env, "cannot write into packet\n"); 3988 return -EACCES; 3989 } 3990 if (t == BPF_WRITE && value_regno >= 0 && 3991 is_pointer_value(env, value_regno)) { 3992 verbose(env, "R%d leaks addr into packet\n", 3993 value_regno); 3994 return -EACCES; 3995 } 3996 err = check_packet_access(env, regno, off, size, false); 3997 if (!err && t == BPF_READ && value_regno >= 0) 3998 mark_reg_unknown(env, regs, value_regno); 3999 } else if (reg->type == PTR_TO_FLOW_KEYS) { 4000 if (t == BPF_WRITE && value_regno >= 0 && 4001 is_pointer_value(env, value_regno)) { 4002 verbose(env, "R%d leaks addr into flow keys\n", 4003 value_regno); 4004 return -EACCES; 4005 } 4006 4007 err = check_flow_keys_access(env, off, size); 4008 if (!err && t == BPF_READ && value_regno >= 0) 4009 mark_reg_unknown(env, regs, value_regno); 4010 } else if (type_is_sk_pointer(reg->type)) { 4011 if (t == BPF_WRITE) { 4012 verbose(env, "R%d cannot write into %s\n", 4013 regno, reg_type_str[reg->type]); 4014 return -EACCES; 4015 } 4016 err = check_sock_access(env, insn_idx, regno, off, size, t); 4017 if (!err && value_regno >= 0) 4018 mark_reg_unknown(env, regs, value_regno); 4019 } else if (reg->type == PTR_TO_TP_BUFFER) { 4020 err = check_tp_buffer_access(env, reg, regno, off, size); 4021 if (!err && t == BPF_READ && value_regno >= 0) 4022 mark_reg_unknown(env, regs, value_regno); 4023 } else if (reg->type == PTR_TO_BTF_ID) { 4024 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 4025 value_regno); 4026 } else if (reg->type == CONST_PTR_TO_MAP) { 4027 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 4028 value_regno); 4029 } else if (reg->type == PTR_TO_RDONLY_BUF) { 4030 if (t == BPF_WRITE) { 4031 verbose(env, "R%d cannot write into %s\n", 4032 regno, reg_type_str[reg->type]); 4033 return -EACCES; 4034 } 4035 err = check_buffer_access(env, reg, regno, off, size, false, 4036 "rdonly", 4037 &env->prog->aux->max_rdonly_access); 4038 if (!err && value_regno >= 0) 4039 mark_reg_unknown(env, regs, value_regno); 4040 } else if (reg->type == PTR_TO_RDWR_BUF) { 4041 err = check_buffer_access(env, reg, regno, off, size, false, 4042 "rdwr", 4043 &env->prog->aux->max_rdwr_access); 4044 if (!err && t == BPF_READ && value_regno >= 0) 4045 mark_reg_unknown(env, regs, value_regno); 4046 } else { 4047 verbose(env, "R%d invalid mem access '%s'\n", regno, 4048 reg_type_str[reg->type]); 4049 return -EACCES; 4050 } 4051 4052 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 4053 regs[value_regno].type == SCALAR_VALUE) { 4054 /* b/h/w load zero-extends, mark upper bits as known 0 */ 4055 coerce_reg_to_size(®s[value_regno], size); 4056 } 4057 return err; 4058 } 4059 4060 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 4061 { 4062 int load_reg; 4063 int err; 4064 4065 switch (insn->imm) { 4066 case BPF_ADD: 4067 case BPF_ADD | BPF_FETCH: 4068 case BPF_AND: 4069 case BPF_AND | BPF_FETCH: 4070 case BPF_OR: 4071 case BPF_OR | BPF_FETCH: 4072 case BPF_XOR: 4073 case BPF_XOR | BPF_FETCH: 4074 case BPF_XCHG: 4075 case BPF_CMPXCHG: 4076 break; 4077 default: 4078 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 4079 return -EINVAL; 4080 } 4081 4082 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 4083 verbose(env, "invalid atomic operand size\n"); 4084 return -EINVAL; 4085 } 4086 4087 /* check src1 operand */ 4088 err = check_reg_arg(env, insn->src_reg, SRC_OP); 4089 if (err) 4090 return err; 4091 4092 /* check src2 operand */ 4093 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 4094 if (err) 4095 return err; 4096 4097 if (insn->imm == BPF_CMPXCHG) { 4098 /* Check comparison of R0 with memory location */ 4099 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 4100 if (err) 4101 return err; 4102 } 4103 4104 if (is_pointer_value(env, insn->src_reg)) { 4105 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 4106 return -EACCES; 4107 } 4108 4109 if (is_ctx_reg(env, insn->dst_reg) || 4110 is_pkt_reg(env, insn->dst_reg) || 4111 is_flow_key_reg(env, insn->dst_reg) || 4112 is_sk_reg(env, insn->dst_reg)) { 4113 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 4114 insn->dst_reg, 4115 reg_type_str[reg_state(env, insn->dst_reg)->type]); 4116 return -EACCES; 4117 } 4118 4119 if (insn->imm & BPF_FETCH) { 4120 if (insn->imm == BPF_CMPXCHG) 4121 load_reg = BPF_REG_0; 4122 else 4123 load_reg = insn->src_reg; 4124 4125 /* check and record load of old value */ 4126 err = check_reg_arg(env, load_reg, DST_OP); 4127 if (err) 4128 return err; 4129 } else { 4130 /* This instruction accesses a memory location but doesn't 4131 * actually load it into a register. 4132 */ 4133 load_reg = -1; 4134 } 4135 4136 /* check whether we can read the memory */ 4137 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 4138 BPF_SIZE(insn->code), BPF_READ, load_reg, true); 4139 if (err) 4140 return err; 4141 4142 /* check whether we can write into the same memory */ 4143 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 4144 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 4145 if (err) 4146 return err; 4147 4148 return 0; 4149 } 4150 4151 /* When register 'regno' is used to read the stack (either directly or through 4152 * a helper function) make sure that it's within stack boundary and, depending 4153 * on the access type, that all elements of the stack are initialized. 4154 * 4155 * 'off' includes 'regno->off', but not its dynamic part (if any). 4156 * 4157 * All registers that have been spilled on the stack in the slots within the 4158 * read offsets are marked as read. 4159 */ 4160 static int check_stack_range_initialized( 4161 struct bpf_verifier_env *env, int regno, int off, 4162 int access_size, bool zero_size_allowed, 4163 enum stack_access_src type, struct bpf_call_arg_meta *meta) 4164 { 4165 struct bpf_reg_state *reg = reg_state(env, regno); 4166 struct bpf_func_state *state = func(env, reg); 4167 int err, min_off, max_off, i, j, slot, spi; 4168 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 4169 enum bpf_access_type bounds_check_type; 4170 /* Some accesses can write anything into the stack, others are 4171 * read-only. 4172 */ 4173 bool clobber = false; 4174 4175 if (access_size == 0 && !zero_size_allowed) { 4176 verbose(env, "invalid zero-sized read\n"); 4177 return -EACCES; 4178 } 4179 4180 if (type == ACCESS_HELPER) { 4181 /* The bounds checks for writes are more permissive than for 4182 * reads. However, if raw_mode is not set, we'll do extra 4183 * checks below. 4184 */ 4185 bounds_check_type = BPF_WRITE; 4186 clobber = true; 4187 } else { 4188 bounds_check_type = BPF_READ; 4189 } 4190 err = check_stack_access_within_bounds(env, regno, off, access_size, 4191 type, bounds_check_type); 4192 if (err) 4193 return err; 4194 4195 4196 if (tnum_is_const(reg->var_off)) { 4197 min_off = max_off = reg->var_off.value + off; 4198 } else { 4199 /* Variable offset is prohibited for unprivileged mode for 4200 * simplicity since it requires corresponding support in 4201 * Spectre masking for stack ALU. 4202 * See also retrieve_ptr_limit(). 4203 */ 4204 if (!env->bypass_spec_v1) { 4205 char tn_buf[48]; 4206 4207 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4208 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 4209 regno, err_extra, tn_buf); 4210 return -EACCES; 4211 } 4212 /* Only initialized buffer on stack is allowed to be accessed 4213 * with variable offset. With uninitialized buffer it's hard to 4214 * guarantee that whole memory is marked as initialized on 4215 * helper return since specific bounds are unknown what may 4216 * cause uninitialized stack leaking. 4217 */ 4218 if (meta && meta->raw_mode) 4219 meta = NULL; 4220 4221 min_off = reg->smin_value + off; 4222 max_off = reg->smax_value + off; 4223 } 4224 4225 if (meta && meta->raw_mode) { 4226 meta->access_size = access_size; 4227 meta->regno = regno; 4228 return 0; 4229 } 4230 4231 for (i = min_off; i < max_off + access_size; i++) { 4232 u8 *stype; 4233 4234 slot = -i - 1; 4235 spi = slot / BPF_REG_SIZE; 4236 if (state->allocated_stack <= slot) 4237 goto err; 4238 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4239 if (*stype == STACK_MISC) 4240 goto mark; 4241 if (*stype == STACK_ZERO) { 4242 if (clobber) { 4243 /* helper can write anything into the stack */ 4244 *stype = STACK_MISC; 4245 } 4246 goto mark; 4247 } 4248 4249 if (state->stack[spi].slot_type[0] == STACK_SPILL && 4250 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID) 4251 goto mark; 4252 4253 if (state->stack[spi].slot_type[0] == STACK_SPILL && 4254 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 4255 env->allow_ptr_leaks)) { 4256 if (clobber) { 4257 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 4258 for (j = 0; j < BPF_REG_SIZE; j++) 4259 state->stack[spi].slot_type[j] = STACK_MISC; 4260 } 4261 goto mark; 4262 } 4263 4264 err: 4265 if (tnum_is_const(reg->var_off)) { 4266 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 4267 err_extra, regno, min_off, i - min_off, access_size); 4268 } else { 4269 char tn_buf[48]; 4270 4271 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4272 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 4273 err_extra, regno, tn_buf, i - min_off, access_size); 4274 } 4275 return -EACCES; 4276 mark: 4277 /* reading any byte out of 8-byte 'spill_slot' will cause 4278 * the whole slot to be marked as 'read' 4279 */ 4280 mark_reg_read(env, &state->stack[spi].spilled_ptr, 4281 state->stack[spi].spilled_ptr.parent, 4282 REG_LIVE_READ64); 4283 } 4284 return update_stack_depth(env, state, min_off); 4285 } 4286 4287 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 4288 int access_size, bool zero_size_allowed, 4289 struct bpf_call_arg_meta *meta) 4290 { 4291 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4292 4293 switch (reg->type) { 4294 case PTR_TO_PACKET: 4295 case PTR_TO_PACKET_META: 4296 return check_packet_access(env, regno, reg->off, access_size, 4297 zero_size_allowed); 4298 case PTR_TO_MAP_KEY: 4299 return check_mem_region_access(env, regno, reg->off, access_size, 4300 reg->map_ptr->key_size, false); 4301 case PTR_TO_MAP_VALUE: 4302 if (check_map_access_type(env, regno, reg->off, access_size, 4303 meta && meta->raw_mode ? BPF_WRITE : 4304 BPF_READ)) 4305 return -EACCES; 4306 return check_map_access(env, regno, reg->off, access_size, 4307 zero_size_allowed); 4308 case PTR_TO_MEM: 4309 return check_mem_region_access(env, regno, reg->off, 4310 access_size, reg->mem_size, 4311 zero_size_allowed); 4312 case PTR_TO_RDONLY_BUF: 4313 if (meta && meta->raw_mode) 4314 return -EACCES; 4315 return check_buffer_access(env, reg, regno, reg->off, 4316 access_size, zero_size_allowed, 4317 "rdonly", 4318 &env->prog->aux->max_rdonly_access); 4319 case PTR_TO_RDWR_BUF: 4320 return check_buffer_access(env, reg, regno, reg->off, 4321 access_size, zero_size_allowed, 4322 "rdwr", 4323 &env->prog->aux->max_rdwr_access); 4324 case PTR_TO_STACK: 4325 return check_stack_range_initialized( 4326 env, 4327 regno, reg->off, access_size, 4328 zero_size_allowed, ACCESS_HELPER, meta); 4329 default: /* scalar_value or invalid ptr */ 4330 /* Allow zero-byte read from NULL, regardless of pointer type */ 4331 if (zero_size_allowed && access_size == 0 && 4332 register_is_null(reg)) 4333 return 0; 4334 4335 verbose(env, "R%d type=%s expected=%s\n", regno, 4336 reg_type_str[reg->type], 4337 reg_type_str[PTR_TO_STACK]); 4338 return -EACCES; 4339 } 4340 } 4341 4342 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4343 u32 regno, u32 mem_size) 4344 { 4345 if (register_is_null(reg)) 4346 return 0; 4347 4348 if (reg_type_may_be_null(reg->type)) { 4349 /* Assuming that the register contains a value check if the memory 4350 * access is safe. Temporarily save and restore the register's state as 4351 * the conversion shouldn't be visible to a caller. 4352 */ 4353 const struct bpf_reg_state saved_reg = *reg; 4354 int rv; 4355 4356 mark_ptr_not_null_reg(reg); 4357 rv = check_helper_mem_access(env, regno, mem_size, true, NULL); 4358 *reg = saved_reg; 4359 return rv; 4360 } 4361 4362 return check_helper_mem_access(env, regno, mem_size, true, NULL); 4363 } 4364 4365 /* Implementation details: 4366 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL 4367 * Two bpf_map_lookups (even with the same key) will have different reg->id. 4368 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after 4369 * value_or_null->value transition, since the verifier only cares about 4370 * the range of access to valid map value pointer and doesn't care about actual 4371 * address of the map element. 4372 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 4373 * reg->id > 0 after value_or_null->value transition. By doing so 4374 * two bpf_map_lookups will be considered two different pointers that 4375 * point to different bpf_spin_locks. 4376 * The verifier allows taking only one bpf_spin_lock at a time to avoid 4377 * dead-locks. 4378 * Since only one bpf_spin_lock is allowed the checks are simpler than 4379 * reg_is_refcounted() logic. The verifier needs to remember only 4380 * one spin_lock instead of array of acquired_refs. 4381 * cur_state->active_spin_lock remembers which map value element got locked 4382 * and clears it after bpf_spin_unlock. 4383 */ 4384 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 4385 bool is_lock) 4386 { 4387 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4388 struct bpf_verifier_state *cur = env->cur_state; 4389 bool is_const = tnum_is_const(reg->var_off); 4390 struct bpf_map *map = reg->map_ptr; 4391 u64 val = reg->var_off.value; 4392 4393 if (!is_const) { 4394 verbose(env, 4395 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 4396 regno); 4397 return -EINVAL; 4398 } 4399 if (!map->btf) { 4400 verbose(env, 4401 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 4402 map->name); 4403 return -EINVAL; 4404 } 4405 if (!map_value_has_spin_lock(map)) { 4406 if (map->spin_lock_off == -E2BIG) 4407 verbose(env, 4408 "map '%s' has more than one 'struct bpf_spin_lock'\n", 4409 map->name); 4410 else if (map->spin_lock_off == -ENOENT) 4411 verbose(env, 4412 "map '%s' doesn't have 'struct bpf_spin_lock'\n", 4413 map->name); 4414 else 4415 verbose(env, 4416 "map '%s' is not a struct type or bpf_spin_lock is mangled\n", 4417 map->name); 4418 return -EINVAL; 4419 } 4420 if (map->spin_lock_off != val + reg->off) { 4421 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n", 4422 val + reg->off); 4423 return -EINVAL; 4424 } 4425 if (is_lock) { 4426 if (cur->active_spin_lock) { 4427 verbose(env, 4428 "Locking two bpf_spin_locks are not allowed\n"); 4429 return -EINVAL; 4430 } 4431 cur->active_spin_lock = reg->id; 4432 } else { 4433 if (!cur->active_spin_lock) { 4434 verbose(env, "bpf_spin_unlock without taking a lock\n"); 4435 return -EINVAL; 4436 } 4437 if (cur->active_spin_lock != reg->id) { 4438 verbose(env, "bpf_spin_unlock of different lock\n"); 4439 return -EINVAL; 4440 } 4441 cur->active_spin_lock = 0; 4442 } 4443 return 0; 4444 } 4445 4446 static bool arg_type_is_mem_ptr(enum bpf_arg_type type) 4447 { 4448 return type == ARG_PTR_TO_MEM || 4449 type == ARG_PTR_TO_MEM_OR_NULL || 4450 type == ARG_PTR_TO_UNINIT_MEM; 4451 } 4452 4453 static bool arg_type_is_mem_size(enum bpf_arg_type type) 4454 { 4455 return type == ARG_CONST_SIZE || 4456 type == ARG_CONST_SIZE_OR_ZERO; 4457 } 4458 4459 static bool arg_type_is_alloc_size(enum bpf_arg_type type) 4460 { 4461 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO; 4462 } 4463 4464 static bool arg_type_is_int_ptr(enum bpf_arg_type type) 4465 { 4466 return type == ARG_PTR_TO_INT || 4467 type == ARG_PTR_TO_LONG; 4468 } 4469 4470 static int int_ptr_type_to_size(enum bpf_arg_type type) 4471 { 4472 if (type == ARG_PTR_TO_INT) 4473 return sizeof(u32); 4474 else if (type == ARG_PTR_TO_LONG) 4475 return sizeof(u64); 4476 4477 return -EINVAL; 4478 } 4479 4480 static int resolve_map_arg_type(struct bpf_verifier_env *env, 4481 const struct bpf_call_arg_meta *meta, 4482 enum bpf_arg_type *arg_type) 4483 { 4484 if (!meta->map_ptr) { 4485 /* kernel subsystem misconfigured verifier */ 4486 verbose(env, "invalid map_ptr to access map->type\n"); 4487 return -EACCES; 4488 } 4489 4490 switch (meta->map_ptr->map_type) { 4491 case BPF_MAP_TYPE_SOCKMAP: 4492 case BPF_MAP_TYPE_SOCKHASH: 4493 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 4494 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 4495 } else { 4496 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 4497 return -EINVAL; 4498 } 4499 break; 4500 4501 default: 4502 break; 4503 } 4504 return 0; 4505 } 4506 4507 struct bpf_reg_types { 4508 const enum bpf_reg_type types[10]; 4509 u32 *btf_id; 4510 }; 4511 4512 static const struct bpf_reg_types map_key_value_types = { 4513 .types = { 4514 PTR_TO_STACK, 4515 PTR_TO_PACKET, 4516 PTR_TO_PACKET_META, 4517 PTR_TO_MAP_KEY, 4518 PTR_TO_MAP_VALUE, 4519 }, 4520 }; 4521 4522 static const struct bpf_reg_types sock_types = { 4523 .types = { 4524 PTR_TO_SOCK_COMMON, 4525 PTR_TO_SOCKET, 4526 PTR_TO_TCP_SOCK, 4527 PTR_TO_XDP_SOCK, 4528 }, 4529 }; 4530 4531 #ifdef CONFIG_NET 4532 static const struct bpf_reg_types btf_id_sock_common_types = { 4533 .types = { 4534 PTR_TO_SOCK_COMMON, 4535 PTR_TO_SOCKET, 4536 PTR_TO_TCP_SOCK, 4537 PTR_TO_XDP_SOCK, 4538 PTR_TO_BTF_ID, 4539 }, 4540 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 4541 }; 4542 #endif 4543 4544 static const struct bpf_reg_types mem_types = { 4545 .types = { 4546 PTR_TO_STACK, 4547 PTR_TO_PACKET, 4548 PTR_TO_PACKET_META, 4549 PTR_TO_MAP_KEY, 4550 PTR_TO_MAP_VALUE, 4551 PTR_TO_MEM, 4552 PTR_TO_RDONLY_BUF, 4553 PTR_TO_RDWR_BUF, 4554 }, 4555 }; 4556 4557 static const struct bpf_reg_types int_ptr_types = { 4558 .types = { 4559 PTR_TO_STACK, 4560 PTR_TO_PACKET, 4561 PTR_TO_PACKET_META, 4562 PTR_TO_MAP_KEY, 4563 PTR_TO_MAP_VALUE, 4564 }, 4565 }; 4566 4567 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 4568 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 4569 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 4570 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } }; 4571 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 4572 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } }; 4573 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } }; 4574 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } }; 4575 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 4576 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 4577 4578 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 4579 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types, 4580 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types, 4581 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types, 4582 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types, 4583 [ARG_CONST_SIZE] = &scalar_types, 4584 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 4585 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 4586 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 4587 [ARG_PTR_TO_CTX] = &context_types, 4588 [ARG_PTR_TO_CTX_OR_NULL] = &context_types, 4589 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 4590 #ifdef CONFIG_NET 4591 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 4592 #endif 4593 [ARG_PTR_TO_SOCKET] = &fullsock_types, 4594 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types, 4595 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 4596 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 4597 [ARG_PTR_TO_MEM] = &mem_types, 4598 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types, 4599 [ARG_PTR_TO_UNINIT_MEM] = &mem_types, 4600 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types, 4601 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types, 4602 [ARG_PTR_TO_INT] = &int_ptr_types, 4603 [ARG_PTR_TO_LONG] = &int_ptr_types, 4604 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 4605 [ARG_PTR_TO_FUNC] = &func_ptr_types, 4606 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types, 4607 }; 4608 4609 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 4610 enum bpf_arg_type arg_type, 4611 const u32 *arg_btf_id) 4612 { 4613 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4614 enum bpf_reg_type expected, type = reg->type; 4615 const struct bpf_reg_types *compatible; 4616 int i, j; 4617 4618 compatible = compatible_reg_types[arg_type]; 4619 if (!compatible) { 4620 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 4621 return -EFAULT; 4622 } 4623 4624 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 4625 expected = compatible->types[i]; 4626 if (expected == NOT_INIT) 4627 break; 4628 4629 if (type == expected) 4630 goto found; 4631 } 4632 4633 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]); 4634 for (j = 0; j + 1 < i; j++) 4635 verbose(env, "%s, ", reg_type_str[compatible->types[j]]); 4636 verbose(env, "%s\n", reg_type_str[compatible->types[j]]); 4637 return -EACCES; 4638 4639 found: 4640 if (type == PTR_TO_BTF_ID) { 4641 if (!arg_btf_id) { 4642 if (!compatible->btf_id) { 4643 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 4644 return -EFAULT; 4645 } 4646 arg_btf_id = compatible->btf_id; 4647 } 4648 4649 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 4650 btf_vmlinux, *arg_btf_id)) { 4651 verbose(env, "R%d is of type %s but %s is expected\n", 4652 regno, kernel_type_name(reg->btf, reg->btf_id), 4653 kernel_type_name(btf_vmlinux, *arg_btf_id)); 4654 return -EACCES; 4655 } 4656 4657 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4658 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n", 4659 regno); 4660 return -EACCES; 4661 } 4662 } 4663 4664 return 0; 4665 } 4666 4667 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 4668 struct bpf_call_arg_meta *meta, 4669 const struct bpf_func_proto *fn) 4670 { 4671 u32 regno = BPF_REG_1 + arg; 4672 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4673 enum bpf_arg_type arg_type = fn->arg_type[arg]; 4674 enum bpf_reg_type type = reg->type; 4675 int err = 0; 4676 4677 if (arg_type == ARG_DONTCARE) 4678 return 0; 4679 4680 err = check_reg_arg(env, regno, SRC_OP); 4681 if (err) 4682 return err; 4683 4684 if (arg_type == ARG_ANYTHING) { 4685 if (is_pointer_value(env, regno)) { 4686 verbose(env, "R%d leaks addr into helper function\n", 4687 regno); 4688 return -EACCES; 4689 } 4690 return 0; 4691 } 4692 4693 if (type_is_pkt_pointer(type) && 4694 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 4695 verbose(env, "helper access to the packet is not allowed\n"); 4696 return -EACCES; 4697 } 4698 4699 if (arg_type == ARG_PTR_TO_MAP_VALUE || 4700 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE || 4701 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) { 4702 err = resolve_map_arg_type(env, meta, &arg_type); 4703 if (err) 4704 return err; 4705 } 4706 4707 if (register_is_null(reg) && arg_type_may_be_null(arg_type)) 4708 /* A NULL register has a SCALAR_VALUE type, so skip 4709 * type checking. 4710 */ 4711 goto skip_type_check; 4712 4713 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]); 4714 if (err) 4715 return err; 4716 4717 if (type == PTR_TO_CTX) { 4718 err = check_ctx_reg(env, reg, regno); 4719 if (err < 0) 4720 return err; 4721 } 4722 4723 skip_type_check: 4724 if (reg->ref_obj_id) { 4725 if (meta->ref_obj_id) { 4726 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 4727 regno, reg->ref_obj_id, 4728 meta->ref_obj_id); 4729 return -EFAULT; 4730 } 4731 meta->ref_obj_id = reg->ref_obj_id; 4732 } 4733 4734 if (arg_type == ARG_CONST_MAP_PTR) { 4735 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 4736 meta->map_ptr = reg->map_ptr; 4737 } else if (arg_type == ARG_PTR_TO_MAP_KEY) { 4738 /* bpf_map_xxx(..., map_ptr, ..., key) call: 4739 * check that [key, key + map->key_size) are within 4740 * stack limits and initialized 4741 */ 4742 if (!meta->map_ptr) { 4743 /* in function declaration map_ptr must come before 4744 * map_key, so that it's verified and known before 4745 * we have to check map_key here. Otherwise it means 4746 * that kernel subsystem misconfigured verifier 4747 */ 4748 verbose(env, "invalid map_ptr to access map->key\n"); 4749 return -EACCES; 4750 } 4751 err = check_helper_mem_access(env, regno, 4752 meta->map_ptr->key_size, false, 4753 NULL); 4754 } else if (arg_type == ARG_PTR_TO_MAP_VALUE || 4755 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL && 4756 !register_is_null(reg)) || 4757 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) { 4758 /* bpf_map_xxx(..., map_ptr, ..., value) call: 4759 * check [value, value + map->value_size) validity 4760 */ 4761 if (!meta->map_ptr) { 4762 /* kernel subsystem misconfigured verifier */ 4763 verbose(env, "invalid map_ptr to access map->value\n"); 4764 return -EACCES; 4765 } 4766 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE); 4767 err = check_helper_mem_access(env, regno, 4768 meta->map_ptr->value_size, false, 4769 meta); 4770 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) { 4771 if (!reg->btf_id) { 4772 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 4773 return -EACCES; 4774 } 4775 meta->ret_btf = reg->btf; 4776 meta->ret_btf_id = reg->btf_id; 4777 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) { 4778 if (meta->func_id == BPF_FUNC_spin_lock) { 4779 if (process_spin_lock(env, regno, true)) 4780 return -EACCES; 4781 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 4782 if (process_spin_lock(env, regno, false)) 4783 return -EACCES; 4784 } else { 4785 verbose(env, "verifier internal error\n"); 4786 return -EFAULT; 4787 } 4788 } else if (arg_type == ARG_PTR_TO_FUNC) { 4789 meta->subprogno = reg->subprogno; 4790 } else if (arg_type_is_mem_ptr(arg_type)) { 4791 /* The access to this pointer is only checked when we hit the 4792 * next is_mem_size argument below. 4793 */ 4794 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM); 4795 } else if (arg_type_is_mem_size(arg_type)) { 4796 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); 4797 4798 /* This is used to refine r0 return value bounds for helpers 4799 * that enforce this value as an upper bound on return values. 4800 * See do_refine_retval_range() for helpers that can refine 4801 * the return value. C type of helper is u32 so we pull register 4802 * bound from umax_value however, if negative verifier errors 4803 * out. Only upper bounds can be learned because retval is an 4804 * int type and negative retvals are allowed. 4805 */ 4806 meta->msize_max_value = reg->umax_value; 4807 4808 /* The register is SCALAR_VALUE; the access check 4809 * happens using its boundaries. 4810 */ 4811 if (!tnum_is_const(reg->var_off)) 4812 /* For unprivileged variable accesses, disable raw 4813 * mode so that the program is required to 4814 * initialize all the memory that the helper could 4815 * just partially fill up. 4816 */ 4817 meta = NULL; 4818 4819 if (reg->smin_value < 0) { 4820 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 4821 regno); 4822 return -EACCES; 4823 } 4824 4825 if (reg->umin_value == 0) { 4826 err = check_helper_mem_access(env, regno - 1, 0, 4827 zero_size_allowed, 4828 meta); 4829 if (err) 4830 return err; 4831 } 4832 4833 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 4834 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 4835 regno); 4836 return -EACCES; 4837 } 4838 err = check_helper_mem_access(env, regno - 1, 4839 reg->umax_value, 4840 zero_size_allowed, meta); 4841 if (!err) 4842 err = mark_chain_precision(env, regno); 4843 } else if (arg_type_is_alloc_size(arg_type)) { 4844 if (!tnum_is_const(reg->var_off)) { 4845 verbose(env, "R%d is not a known constant'\n", 4846 regno); 4847 return -EACCES; 4848 } 4849 meta->mem_size = reg->var_off.value; 4850 } else if (arg_type_is_int_ptr(arg_type)) { 4851 int size = int_ptr_type_to_size(arg_type); 4852 4853 err = check_helper_mem_access(env, regno, size, false, meta); 4854 if (err) 4855 return err; 4856 err = check_ptr_alignment(env, reg, 0, size, true); 4857 } 4858 4859 return err; 4860 } 4861 4862 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 4863 { 4864 enum bpf_attach_type eatype = env->prog->expected_attach_type; 4865 enum bpf_prog_type type = resolve_prog_type(env->prog); 4866 4867 if (func_id != BPF_FUNC_map_update_elem) 4868 return false; 4869 4870 /* It's not possible to get access to a locked struct sock in these 4871 * contexts, so updating is safe. 4872 */ 4873 switch (type) { 4874 case BPF_PROG_TYPE_TRACING: 4875 if (eatype == BPF_TRACE_ITER) 4876 return true; 4877 break; 4878 case BPF_PROG_TYPE_SOCKET_FILTER: 4879 case BPF_PROG_TYPE_SCHED_CLS: 4880 case BPF_PROG_TYPE_SCHED_ACT: 4881 case BPF_PROG_TYPE_XDP: 4882 case BPF_PROG_TYPE_SK_REUSEPORT: 4883 case BPF_PROG_TYPE_FLOW_DISSECTOR: 4884 case BPF_PROG_TYPE_SK_LOOKUP: 4885 return true; 4886 default: 4887 break; 4888 } 4889 4890 verbose(env, "cannot update sockmap in this context\n"); 4891 return false; 4892 } 4893 4894 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 4895 { 4896 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64); 4897 } 4898 4899 static int check_map_func_compatibility(struct bpf_verifier_env *env, 4900 struct bpf_map *map, int func_id) 4901 { 4902 if (!map) 4903 return 0; 4904 4905 /* We need a two way check, first is from map perspective ... */ 4906 switch (map->map_type) { 4907 case BPF_MAP_TYPE_PROG_ARRAY: 4908 if (func_id != BPF_FUNC_tail_call) 4909 goto error; 4910 break; 4911 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 4912 if (func_id != BPF_FUNC_perf_event_read && 4913 func_id != BPF_FUNC_perf_event_output && 4914 func_id != BPF_FUNC_skb_output && 4915 func_id != BPF_FUNC_perf_event_read_value && 4916 func_id != BPF_FUNC_xdp_output) 4917 goto error; 4918 break; 4919 case BPF_MAP_TYPE_RINGBUF: 4920 if (func_id != BPF_FUNC_ringbuf_output && 4921 func_id != BPF_FUNC_ringbuf_reserve && 4922 func_id != BPF_FUNC_ringbuf_submit && 4923 func_id != BPF_FUNC_ringbuf_discard && 4924 func_id != BPF_FUNC_ringbuf_query) 4925 goto error; 4926 break; 4927 case BPF_MAP_TYPE_STACK_TRACE: 4928 if (func_id != BPF_FUNC_get_stackid) 4929 goto error; 4930 break; 4931 case BPF_MAP_TYPE_CGROUP_ARRAY: 4932 if (func_id != BPF_FUNC_skb_under_cgroup && 4933 func_id != BPF_FUNC_current_task_under_cgroup) 4934 goto error; 4935 break; 4936 case BPF_MAP_TYPE_CGROUP_STORAGE: 4937 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 4938 if (func_id != BPF_FUNC_get_local_storage) 4939 goto error; 4940 break; 4941 case BPF_MAP_TYPE_DEVMAP: 4942 case BPF_MAP_TYPE_DEVMAP_HASH: 4943 if (func_id != BPF_FUNC_redirect_map && 4944 func_id != BPF_FUNC_map_lookup_elem) 4945 goto error; 4946 break; 4947 /* Restrict bpf side of cpumap and xskmap, open when use-cases 4948 * appear. 4949 */ 4950 case BPF_MAP_TYPE_CPUMAP: 4951 if (func_id != BPF_FUNC_redirect_map) 4952 goto error; 4953 break; 4954 case BPF_MAP_TYPE_XSKMAP: 4955 if (func_id != BPF_FUNC_redirect_map && 4956 func_id != BPF_FUNC_map_lookup_elem) 4957 goto error; 4958 break; 4959 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 4960 case BPF_MAP_TYPE_HASH_OF_MAPS: 4961 if (func_id != BPF_FUNC_map_lookup_elem) 4962 goto error; 4963 break; 4964 case BPF_MAP_TYPE_SOCKMAP: 4965 if (func_id != BPF_FUNC_sk_redirect_map && 4966 func_id != BPF_FUNC_sock_map_update && 4967 func_id != BPF_FUNC_map_delete_elem && 4968 func_id != BPF_FUNC_msg_redirect_map && 4969 func_id != BPF_FUNC_sk_select_reuseport && 4970 func_id != BPF_FUNC_map_lookup_elem && 4971 !may_update_sockmap(env, func_id)) 4972 goto error; 4973 break; 4974 case BPF_MAP_TYPE_SOCKHASH: 4975 if (func_id != BPF_FUNC_sk_redirect_hash && 4976 func_id != BPF_FUNC_sock_hash_update && 4977 func_id != BPF_FUNC_map_delete_elem && 4978 func_id != BPF_FUNC_msg_redirect_hash && 4979 func_id != BPF_FUNC_sk_select_reuseport && 4980 func_id != BPF_FUNC_map_lookup_elem && 4981 !may_update_sockmap(env, func_id)) 4982 goto error; 4983 break; 4984 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 4985 if (func_id != BPF_FUNC_sk_select_reuseport) 4986 goto error; 4987 break; 4988 case BPF_MAP_TYPE_QUEUE: 4989 case BPF_MAP_TYPE_STACK: 4990 if (func_id != BPF_FUNC_map_peek_elem && 4991 func_id != BPF_FUNC_map_pop_elem && 4992 func_id != BPF_FUNC_map_push_elem) 4993 goto error; 4994 break; 4995 case BPF_MAP_TYPE_SK_STORAGE: 4996 if (func_id != BPF_FUNC_sk_storage_get && 4997 func_id != BPF_FUNC_sk_storage_delete) 4998 goto error; 4999 break; 5000 case BPF_MAP_TYPE_INODE_STORAGE: 5001 if (func_id != BPF_FUNC_inode_storage_get && 5002 func_id != BPF_FUNC_inode_storage_delete) 5003 goto error; 5004 break; 5005 case BPF_MAP_TYPE_TASK_STORAGE: 5006 if (func_id != BPF_FUNC_task_storage_get && 5007 func_id != BPF_FUNC_task_storage_delete) 5008 goto error; 5009 break; 5010 default: 5011 break; 5012 } 5013 5014 /* ... and second from the function itself. */ 5015 switch (func_id) { 5016 case BPF_FUNC_tail_call: 5017 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 5018 goto error; 5019 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 5020 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 5021 return -EINVAL; 5022 } 5023 break; 5024 case BPF_FUNC_perf_event_read: 5025 case BPF_FUNC_perf_event_output: 5026 case BPF_FUNC_perf_event_read_value: 5027 case BPF_FUNC_skb_output: 5028 case BPF_FUNC_xdp_output: 5029 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 5030 goto error; 5031 break; 5032 case BPF_FUNC_get_stackid: 5033 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 5034 goto error; 5035 break; 5036 case BPF_FUNC_current_task_under_cgroup: 5037 case BPF_FUNC_skb_under_cgroup: 5038 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 5039 goto error; 5040 break; 5041 case BPF_FUNC_redirect_map: 5042 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 5043 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 5044 map->map_type != BPF_MAP_TYPE_CPUMAP && 5045 map->map_type != BPF_MAP_TYPE_XSKMAP) 5046 goto error; 5047 break; 5048 case BPF_FUNC_sk_redirect_map: 5049 case BPF_FUNC_msg_redirect_map: 5050 case BPF_FUNC_sock_map_update: 5051 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 5052 goto error; 5053 break; 5054 case BPF_FUNC_sk_redirect_hash: 5055 case BPF_FUNC_msg_redirect_hash: 5056 case BPF_FUNC_sock_hash_update: 5057 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 5058 goto error; 5059 break; 5060 case BPF_FUNC_get_local_storage: 5061 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 5062 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 5063 goto error; 5064 break; 5065 case BPF_FUNC_sk_select_reuseport: 5066 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 5067 map->map_type != BPF_MAP_TYPE_SOCKMAP && 5068 map->map_type != BPF_MAP_TYPE_SOCKHASH) 5069 goto error; 5070 break; 5071 case BPF_FUNC_map_peek_elem: 5072 case BPF_FUNC_map_pop_elem: 5073 case BPF_FUNC_map_push_elem: 5074 if (map->map_type != BPF_MAP_TYPE_QUEUE && 5075 map->map_type != BPF_MAP_TYPE_STACK) 5076 goto error; 5077 break; 5078 case BPF_FUNC_sk_storage_get: 5079 case BPF_FUNC_sk_storage_delete: 5080 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 5081 goto error; 5082 break; 5083 case BPF_FUNC_inode_storage_get: 5084 case BPF_FUNC_inode_storage_delete: 5085 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 5086 goto error; 5087 break; 5088 case BPF_FUNC_task_storage_get: 5089 case BPF_FUNC_task_storage_delete: 5090 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 5091 goto error; 5092 break; 5093 default: 5094 break; 5095 } 5096 5097 return 0; 5098 error: 5099 verbose(env, "cannot pass map_type %d into func %s#%d\n", 5100 map->map_type, func_id_name(func_id), func_id); 5101 return -EINVAL; 5102 } 5103 5104 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 5105 { 5106 int count = 0; 5107 5108 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 5109 count++; 5110 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 5111 count++; 5112 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 5113 count++; 5114 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 5115 count++; 5116 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 5117 count++; 5118 5119 /* We only support one arg being in raw mode at the moment, 5120 * which is sufficient for the helper functions we have 5121 * right now. 5122 */ 5123 return count <= 1; 5124 } 5125 5126 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr, 5127 enum bpf_arg_type arg_next) 5128 { 5129 return (arg_type_is_mem_ptr(arg_curr) && 5130 !arg_type_is_mem_size(arg_next)) || 5131 (!arg_type_is_mem_ptr(arg_curr) && 5132 arg_type_is_mem_size(arg_next)); 5133 } 5134 5135 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 5136 { 5137 /* bpf_xxx(..., buf, len) call will access 'len' 5138 * bytes from memory 'buf'. Both arg types need 5139 * to be paired, so make sure there's no buggy 5140 * helper function specification. 5141 */ 5142 if (arg_type_is_mem_size(fn->arg1_type) || 5143 arg_type_is_mem_ptr(fn->arg5_type) || 5144 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) || 5145 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) || 5146 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) || 5147 check_args_pair_invalid(fn->arg4_type, fn->arg5_type)) 5148 return false; 5149 5150 return true; 5151 } 5152 5153 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id) 5154 { 5155 int count = 0; 5156 5157 if (arg_type_may_be_refcounted(fn->arg1_type)) 5158 count++; 5159 if (arg_type_may_be_refcounted(fn->arg2_type)) 5160 count++; 5161 if (arg_type_may_be_refcounted(fn->arg3_type)) 5162 count++; 5163 if (arg_type_may_be_refcounted(fn->arg4_type)) 5164 count++; 5165 if (arg_type_may_be_refcounted(fn->arg5_type)) 5166 count++; 5167 5168 /* A reference acquiring function cannot acquire 5169 * another refcounted ptr. 5170 */ 5171 if (may_be_acquire_function(func_id) && count) 5172 return false; 5173 5174 /* We only support one arg being unreferenced at the moment, 5175 * which is sufficient for the helper functions we have right now. 5176 */ 5177 return count <= 1; 5178 } 5179 5180 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 5181 { 5182 int i; 5183 5184 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 5185 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i]) 5186 return false; 5187 5188 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i]) 5189 return false; 5190 } 5191 5192 return true; 5193 } 5194 5195 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 5196 { 5197 return check_raw_mode_ok(fn) && 5198 check_arg_pair_ok(fn) && 5199 check_btf_id_ok(fn) && 5200 check_refcount_ok(fn, func_id) ? 0 : -EINVAL; 5201 } 5202 5203 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 5204 * are now invalid, so turn them into unknown SCALAR_VALUE. 5205 */ 5206 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env, 5207 struct bpf_func_state *state) 5208 { 5209 struct bpf_reg_state *regs = state->regs, *reg; 5210 int i; 5211 5212 for (i = 0; i < MAX_BPF_REG; i++) 5213 if (reg_is_pkt_pointer_any(®s[i])) 5214 mark_reg_unknown(env, regs, i); 5215 5216 bpf_for_each_spilled_reg(i, state, reg) { 5217 if (!reg) 5218 continue; 5219 if (reg_is_pkt_pointer_any(reg)) 5220 __mark_reg_unknown(env, reg); 5221 } 5222 } 5223 5224 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 5225 { 5226 struct bpf_verifier_state *vstate = env->cur_state; 5227 int i; 5228 5229 for (i = 0; i <= vstate->curframe; i++) 5230 __clear_all_pkt_pointers(env, vstate->frame[i]); 5231 } 5232 5233 enum { 5234 AT_PKT_END = -1, 5235 BEYOND_PKT_END = -2, 5236 }; 5237 5238 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 5239 { 5240 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5241 struct bpf_reg_state *reg = &state->regs[regn]; 5242 5243 if (reg->type != PTR_TO_PACKET) 5244 /* PTR_TO_PACKET_META is not supported yet */ 5245 return; 5246 5247 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 5248 * How far beyond pkt_end it goes is unknown. 5249 * if (!range_open) it's the case of pkt >= pkt_end 5250 * if (range_open) it's the case of pkt > pkt_end 5251 * hence this pointer is at least 1 byte bigger than pkt_end 5252 */ 5253 if (range_open) 5254 reg->range = BEYOND_PKT_END; 5255 else 5256 reg->range = AT_PKT_END; 5257 } 5258 5259 static void release_reg_references(struct bpf_verifier_env *env, 5260 struct bpf_func_state *state, 5261 int ref_obj_id) 5262 { 5263 struct bpf_reg_state *regs = state->regs, *reg; 5264 int i; 5265 5266 for (i = 0; i < MAX_BPF_REG; i++) 5267 if (regs[i].ref_obj_id == ref_obj_id) 5268 mark_reg_unknown(env, regs, i); 5269 5270 bpf_for_each_spilled_reg(i, state, reg) { 5271 if (!reg) 5272 continue; 5273 if (reg->ref_obj_id == ref_obj_id) 5274 __mark_reg_unknown(env, reg); 5275 } 5276 } 5277 5278 /* The pointer with the specified id has released its reference to kernel 5279 * resources. Identify all copies of the same pointer and clear the reference. 5280 */ 5281 static int release_reference(struct bpf_verifier_env *env, 5282 int ref_obj_id) 5283 { 5284 struct bpf_verifier_state *vstate = env->cur_state; 5285 int err; 5286 int i; 5287 5288 err = release_reference_state(cur_func(env), ref_obj_id); 5289 if (err) 5290 return err; 5291 5292 for (i = 0; i <= vstate->curframe; i++) 5293 release_reg_references(env, vstate->frame[i], ref_obj_id); 5294 5295 return 0; 5296 } 5297 5298 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 5299 struct bpf_reg_state *regs) 5300 { 5301 int i; 5302 5303 /* after the call registers r0 - r5 were scratched */ 5304 for (i = 0; i < CALLER_SAVED_REGS; i++) { 5305 mark_reg_not_init(env, regs, caller_saved[i]); 5306 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 5307 } 5308 } 5309 5310 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 5311 struct bpf_func_state *caller, 5312 struct bpf_func_state *callee, 5313 int insn_idx); 5314 5315 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 5316 int *insn_idx, int subprog, 5317 set_callee_state_fn set_callee_state_cb) 5318 { 5319 struct bpf_verifier_state *state = env->cur_state; 5320 struct bpf_func_info_aux *func_info_aux; 5321 struct bpf_func_state *caller, *callee; 5322 int err; 5323 bool is_global = false; 5324 5325 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 5326 verbose(env, "the call stack of %d frames is too deep\n", 5327 state->curframe + 2); 5328 return -E2BIG; 5329 } 5330 5331 caller = state->frame[state->curframe]; 5332 if (state->frame[state->curframe + 1]) { 5333 verbose(env, "verifier bug. Frame %d already allocated\n", 5334 state->curframe + 1); 5335 return -EFAULT; 5336 } 5337 5338 func_info_aux = env->prog->aux->func_info_aux; 5339 if (func_info_aux) 5340 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 5341 err = btf_check_func_arg_match(env, subprog, caller->regs); 5342 if (err == -EFAULT) 5343 return err; 5344 if (is_global) { 5345 if (err) { 5346 verbose(env, "Caller passes invalid args into func#%d\n", 5347 subprog); 5348 return err; 5349 } else { 5350 if (env->log.level & BPF_LOG_LEVEL) 5351 verbose(env, 5352 "Func#%d is global and valid. Skipping.\n", 5353 subprog); 5354 clear_caller_saved_regs(env, caller->regs); 5355 5356 /* All global functions return a 64-bit SCALAR_VALUE */ 5357 mark_reg_unknown(env, caller->regs, BPF_REG_0); 5358 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 5359 5360 /* continue with next insn after call */ 5361 return 0; 5362 } 5363 } 5364 5365 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 5366 if (!callee) 5367 return -ENOMEM; 5368 state->frame[state->curframe + 1] = callee; 5369 5370 /* callee cannot access r0, r6 - r9 for reading and has to write 5371 * into its own stack before reading from it. 5372 * callee can read/write into caller's stack 5373 */ 5374 init_func_state(env, callee, 5375 /* remember the callsite, it will be used by bpf_exit */ 5376 *insn_idx /* callsite */, 5377 state->curframe + 1 /* frameno within this callchain */, 5378 subprog /* subprog number within this prog */); 5379 5380 /* Transfer references to the callee */ 5381 err = transfer_reference_state(callee, caller); 5382 if (err) 5383 return err; 5384 5385 err = set_callee_state_cb(env, caller, callee, *insn_idx); 5386 if (err) 5387 return err; 5388 5389 clear_caller_saved_regs(env, caller->regs); 5390 5391 /* only increment it after check_reg_arg() finished */ 5392 state->curframe++; 5393 5394 /* and go analyze first insn of the callee */ 5395 *insn_idx = env->subprog_info[subprog].start - 1; 5396 5397 if (env->log.level & BPF_LOG_LEVEL) { 5398 verbose(env, "caller:\n"); 5399 print_verifier_state(env, caller); 5400 verbose(env, "callee:\n"); 5401 print_verifier_state(env, callee); 5402 } 5403 return 0; 5404 } 5405 5406 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 5407 struct bpf_func_state *caller, 5408 struct bpf_func_state *callee) 5409 { 5410 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 5411 * void *callback_ctx, u64 flags); 5412 * callback_fn(struct bpf_map *map, void *key, void *value, 5413 * void *callback_ctx); 5414 */ 5415 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 5416 5417 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 5418 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 5419 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 5420 5421 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 5422 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 5423 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 5424 5425 /* pointer to stack or null */ 5426 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 5427 5428 /* unused */ 5429 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 5430 return 0; 5431 } 5432 5433 static int set_callee_state(struct bpf_verifier_env *env, 5434 struct bpf_func_state *caller, 5435 struct bpf_func_state *callee, int insn_idx) 5436 { 5437 int i; 5438 5439 /* copy r1 - r5 args that callee can access. The copy includes parent 5440 * pointers, which connects us up to the liveness chain 5441 */ 5442 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 5443 callee->regs[i] = caller->regs[i]; 5444 return 0; 5445 } 5446 5447 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 5448 int *insn_idx) 5449 { 5450 int subprog, target_insn; 5451 5452 target_insn = *insn_idx + insn->imm + 1; 5453 subprog = find_subprog(env, target_insn); 5454 if (subprog < 0) { 5455 verbose(env, "verifier bug. No program starts at insn %d\n", 5456 target_insn); 5457 return -EFAULT; 5458 } 5459 5460 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 5461 } 5462 5463 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 5464 struct bpf_func_state *caller, 5465 struct bpf_func_state *callee, 5466 int insn_idx) 5467 { 5468 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 5469 struct bpf_map *map; 5470 int err; 5471 5472 if (bpf_map_ptr_poisoned(insn_aux)) { 5473 verbose(env, "tail_call abusing map_ptr\n"); 5474 return -EINVAL; 5475 } 5476 5477 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 5478 if (!map->ops->map_set_for_each_callback_args || 5479 !map->ops->map_for_each_callback) { 5480 verbose(env, "callback function not allowed for map\n"); 5481 return -ENOTSUPP; 5482 } 5483 5484 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 5485 if (err) 5486 return err; 5487 5488 callee->in_callback_fn = true; 5489 return 0; 5490 } 5491 5492 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 5493 { 5494 struct bpf_verifier_state *state = env->cur_state; 5495 struct bpf_func_state *caller, *callee; 5496 struct bpf_reg_state *r0; 5497 int err; 5498 5499 callee = state->frame[state->curframe]; 5500 r0 = &callee->regs[BPF_REG_0]; 5501 if (r0->type == PTR_TO_STACK) { 5502 /* technically it's ok to return caller's stack pointer 5503 * (or caller's caller's pointer) back to the caller, 5504 * since these pointers are valid. Only current stack 5505 * pointer will be invalid as soon as function exits, 5506 * but let's be conservative 5507 */ 5508 verbose(env, "cannot return stack pointer to the caller\n"); 5509 return -EINVAL; 5510 } 5511 5512 state->curframe--; 5513 caller = state->frame[state->curframe]; 5514 if (callee->in_callback_fn) { 5515 /* enforce R0 return value range [0, 1]. */ 5516 struct tnum range = tnum_range(0, 1); 5517 5518 if (r0->type != SCALAR_VALUE) { 5519 verbose(env, "R0 not a scalar value\n"); 5520 return -EACCES; 5521 } 5522 if (!tnum_in(range, r0->var_off)) { 5523 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 5524 return -EINVAL; 5525 } 5526 } else { 5527 /* return to the caller whatever r0 had in the callee */ 5528 caller->regs[BPF_REG_0] = *r0; 5529 } 5530 5531 /* Transfer references to the caller */ 5532 err = transfer_reference_state(caller, callee); 5533 if (err) 5534 return err; 5535 5536 *insn_idx = callee->callsite + 1; 5537 if (env->log.level & BPF_LOG_LEVEL) { 5538 verbose(env, "returning from callee:\n"); 5539 print_verifier_state(env, callee); 5540 verbose(env, "to caller at %d:\n", *insn_idx); 5541 print_verifier_state(env, caller); 5542 } 5543 /* clear everything in the callee */ 5544 free_func_state(callee); 5545 state->frame[state->curframe + 1] = NULL; 5546 return 0; 5547 } 5548 5549 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 5550 int func_id, 5551 struct bpf_call_arg_meta *meta) 5552 { 5553 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 5554 5555 if (ret_type != RET_INTEGER || 5556 (func_id != BPF_FUNC_get_stack && 5557 func_id != BPF_FUNC_probe_read_str && 5558 func_id != BPF_FUNC_probe_read_kernel_str && 5559 func_id != BPF_FUNC_probe_read_user_str)) 5560 return; 5561 5562 ret_reg->smax_value = meta->msize_max_value; 5563 ret_reg->s32_max_value = meta->msize_max_value; 5564 ret_reg->smin_value = -MAX_ERRNO; 5565 ret_reg->s32_min_value = -MAX_ERRNO; 5566 __reg_deduce_bounds(ret_reg); 5567 __reg_bound_offset(ret_reg); 5568 __update_reg_bounds(ret_reg); 5569 } 5570 5571 static int 5572 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 5573 int func_id, int insn_idx) 5574 { 5575 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 5576 struct bpf_map *map = meta->map_ptr; 5577 5578 if (func_id != BPF_FUNC_tail_call && 5579 func_id != BPF_FUNC_map_lookup_elem && 5580 func_id != BPF_FUNC_map_update_elem && 5581 func_id != BPF_FUNC_map_delete_elem && 5582 func_id != BPF_FUNC_map_push_elem && 5583 func_id != BPF_FUNC_map_pop_elem && 5584 func_id != BPF_FUNC_map_peek_elem && 5585 func_id != BPF_FUNC_for_each_map_elem) 5586 return 0; 5587 5588 if (map == NULL) { 5589 verbose(env, "kernel subsystem misconfigured verifier\n"); 5590 return -EINVAL; 5591 } 5592 5593 /* In case of read-only, some additional restrictions 5594 * need to be applied in order to prevent altering the 5595 * state of the map from program side. 5596 */ 5597 if ((map->map_flags & BPF_F_RDONLY_PROG) && 5598 (func_id == BPF_FUNC_map_delete_elem || 5599 func_id == BPF_FUNC_map_update_elem || 5600 func_id == BPF_FUNC_map_push_elem || 5601 func_id == BPF_FUNC_map_pop_elem)) { 5602 verbose(env, "write into map forbidden\n"); 5603 return -EACCES; 5604 } 5605 5606 if (!BPF_MAP_PTR(aux->map_ptr_state)) 5607 bpf_map_ptr_store(aux, meta->map_ptr, 5608 !meta->map_ptr->bypass_spec_v1); 5609 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 5610 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 5611 !meta->map_ptr->bypass_spec_v1); 5612 return 0; 5613 } 5614 5615 static int 5616 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 5617 int func_id, int insn_idx) 5618 { 5619 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 5620 struct bpf_reg_state *regs = cur_regs(env), *reg; 5621 struct bpf_map *map = meta->map_ptr; 5622 struct tnum range; 5623 u64 val; 5624 int err; 5625 5626 if (func_id != BPF_FUNC_tail_call) 5627 return 0; 5628 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 5629 verbose(env, "kernel subsystem misconfigured verifier\n"); 5630 return -EINVAL; 5631 } 5632 5633 range = tnum_range(0, map->max_entries - 1); 5634 reg = ®s[BPF_REG_3]; 5635 5636 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) { 5637 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 5638 return 0; 5639 } 5640 5641 err = mark_chain_precision(env, BPF_REG_3); 5642 if (err) 5643 return err; 5644 5645 val = reg->var_off.value; 5646 if (bpf_map_key_unseen(aux)) 5647 bpf_map_key_store(aux, val); 5648 else if (!bpf_map_key_poisoned(aux) && 5649 bpf_map_key_immediate(aux) != val) 5650 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 5651 return 0; 5652 } 5653 5654 static int check_reference_leak(struct bpf_verifier_env *env) 5655 { 5656 struct bpf_func_state *state = cur_func(env); 5657 int i; 5658 5659 for (i = 0; i < state->acquired_refs; i++) { 5660 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 5661 state->refs[i].id, state->refs[i].insn_idx); 5662 } 5663 return state->acquired_refs ? -EINVAL : 0; 5664 } 5665 5666 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 5667 int *insn_idx_p) 5668 { 5669 const struct bpf_func_proto *fn = NULL; 5670 struct bpf_reg_state *regs; 5671 struct bpf_call_arg_meta meta; 5672 int insn_idx = *insn_idx_p; 5673 bool changes_data; 5674 int i, err, func_id; 5675 5676 /* find function prototype */ 5677 func_id = insn->imm; 5678 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 5679 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 5680 func_id); 5681 return -EINVAL; 5682 } 5683 5684 if (env->ops->get_func_proto) 5685 fn = env->ops->get_func_proto(func_id, env->prog); 5686 if (!fn) { 5687 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 5688 func_id); 5689 return -EINVAL; 5690 } 5691 5692 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 5693 if (!env->prog->gpl_compatible && fn->gpl_only) { 5694 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 5695 return -EINVAL; 5696 } 5697 5698 if (fn->allowed && !fn->allowed(env->prog)) { 5699 verbose(env, "helper call is not allowed in probe\n"); 5700 return -EINVAL; 5701 } 5702 5703 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 5704 changes_data = bpf_helper_changes_pkt_data(fn->func); 5705 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 5706 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 5707 func_id_name(func_id), func_id); 5708 return -EINVAL; 5709 } 5710 5711 memset(&meta, 0, sizeof(meta)); 5712 meta.pkt_access = fn->pkt_access; 5713 5714 err = check_func_proto(fn, func_id); 5715 if (err) { 5716 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 5717 func_id_name(func_id), func_id); 5718 return err; 5719 } 5720 5721 meta.func_id = func_id; 5722 /* check args */ 5723 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 5724 err = check_func_arg(env, i, &meta, fn); 5725 if (err) 5726 return err; 5727 } 5728 5729 err = record_func_map(env, &meta, func_id, insn_idx); 5730 if (err) 5731 return err; 5732 5733 err = record_func_key(env, &meta, func_id, insn_idx); 5734 if (err) 5735 return err; 5736 5737 /* Mark slots with STACK_MISC in case of raw mode, stack offset 5738 * is inferred from register state. 5739 */ 5740 for (i = 0; i < meta.access_size; i++) { 5741 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 5742 BPF_WRITE, -1, false); 5743 if (err) 5744 return err; 5745 } 5746 5747 if (func_id == BPF_FUNC_tail_call) { 5748 err = check_reference_leak(env); 5749 if (err) { 5750 verbose(env, "tail_call would lead to reference leak\n"); 5751 return err; 5752 } 5753 } else if (is_release_function(func_id)) { 5754 err = release_reference(env, meta.ref_obj_id); 5755 if (err) { 5756 verbose(env, "func %s#%d reference has not been acquired before\n", 5757 func_id_name(func_id), func_id); 5758 return err; 5759 } 5760 } 5761 5762 regs = cur_regs(env); 5763 5764 /* check that flags argument in get_local_storage(map, flags) is 0, 5765 * this is required because get_local_storage() can't return an error. 5766 */ 5767 if (func_id == BPF_FUNC_get_local_storage && 5768 !register_is_null(®s[BPF_REG_2])) { 5769 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 5770 return -EINVAL; 5771 } 5772 5773 if (func_id == BPF_FUNC_for_each_map_elem) { 5774 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 5775 set_map_elem_callback_state); 5776 if (err < 0) 5777 return -EINVAL; 5778 } 5779 5780 /* reset caller saved regs */ 5781 for (i = 0; i < CALLER_SAVED_REGS; i++) { 5782 mark_reg_not_init(env, regs, caller_saved[i]); 5783 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 5784 } 5785 5786 /* helper call returns 64-bit value. */ 5787 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 5788 5789 /* update return register (already marked as written above) */ 5790 if (fn->ret_type == RET_INTEGER) { 5791 /* sets type to SCALAR_VALUE */ 5792 mark_reg_unknown(env, regs, BPF_REG_0); 5793 } else if (fn->ret_type == RET_VOID) { 5794 regs[BPF_REG_0].type = NOT_INIT; 5795 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL || 5796 fn->ret_type == RET_PTR_TO_MAP_VALUE) { 5797 /* There is no offset yet applied, variable or fixed */ 5798 mark_reg_known_zero(env, regs, BPF_REG_0); 5799 /* remember map_ptr, so that check_map_access() 5800 * can check 'value_size' boundary of memory access 5801 * to map element returned from bpf_map_lookup_elem() 5802 */ 5803 if (meta.map_ptr == NULL) { 5804 verbose(env, 5805 "kernel subsystem misconfigured verifier\n"); 5806 return -EINVAL; 5807 } 5808 regs[BPF_REG_0].map_ptr = meta.map_ptr; 5809 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) { 5810 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE; 5811 if (map_value_has_spin_lock(meta.map_ptr)) 5812 regs[BPF_REG_0].id = ++env->id_gen; 5813 } else { 5814 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; 5815 } 5816 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) { 5817 mark_reg_known_zero(env, regs, BPF_REG_0); 5818 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL; 5819 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) { 5820 mark_reg_known_zero(env, regs, BPF_REG_0); 5821 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL; 5822 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) { 5823 mark_reg_known_zero(env, regs, BPF_REG_0); 5824 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL; 5825 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) { 5826 mark_reg_known_zero(env, regs, BPF_REG_0); 5827 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL; 5828 regs[BPF_REG_0].mem_size = meta.mem_size; 5829 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL || 5830 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) { 5831 const struct btf_type *t; 5832 5833 mark_reg_known_zero(env, regs, BPF_REG_0); 5834 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 5835 if (!btf_type_is_struct(t)) { 5836 u32 tsize; 5837 const struct btf_type *ret; 5838 const char *tname; 5839 5840 /* resolve the type size of ksym. */ 5841 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 5842 if (IS_ERR(ret)) { 5843 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 5844 verbose(env, "unable to resolve the size of type '%s': %ld\n", 5845 tname, PTR_ERR(ret)); 5846 return -EINVAL; 5847 } 5848 regs[BPF_REG_0].type = 5849 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ? 5850 PTR_TO_MEM : PTR_TO_MEM_OR_NULL; 5851 regs[BPF_REG_0].mem_size = tsize; 5852 } else { 5853 regs[BPF_REG_0].type = 5854 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ? 5855 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL; 5856 regs[BPF_REG_0].btf = meta.ret_btf; 5857 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 5858 } 5859 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL || 5860 fn->ret_type == RET_PTR_TO_BTF_ID) { 5861 int ret_btf_id; 5862 5863 mark_reg_known_zero(env, regs, BPF_REG_0); 5864 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ? 5865 PTR_TO_BTF_ID : 5866 PTR_TO_BTF_ID_OR_NULL; 5867 ret_btf_id = *fn->ret_btf_id; 5868 if (ret_btf_id == 0) { 5869 verbose(env, "invalid return type %d of func %s#%d\n", 5870 fn->ret_type, func_id_name(func_id), func_id); 5871 return -EINVAL; 5872 } 5873 /* current BPF helper definitions are only coming from 5874 * built-in code with type IDs from vmlinux BTF 5875 */ 5876 regs[BPF_REG_0].btf = btf_vmlinux; 5877 regs[BPF_REG_0].btf_id = ret_btf_id; 5878 } else { 5879 verbose(env, "unknown return type %d of func %s#%d\n", 5880 fn->ret_type, func_id_name(func_id), func_id); 5881 return -EINVAL; 5882 } 5883 5884 if (reg_type_may_be_null(regs[BPF_REG_0].type)) 5885 regs[BPF_REG_0].id = ++env->id_gen; 5886 5887 if (is_ptr_cast_function(func_id)) { 5888 /* For release_reference() */ 5889 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 5890 } else if (is_acquire_function(func_id, meta.map_ptr)) { 5891 int id = acquire_reference_state(env, insn_idx); 5892 5893 if (id < 0) 5894 return id; 5895 /* For mark_ptr_or_null_reg() */ 5896 regs[BPF_REG_0].id = id; 5897 /* For release_reference() */ 5898 regs[BPF_REG_0].ref_obj_id = id; 5899 } 5900 5901 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 5902 5903 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 5904 if (err) 5905 return err; 5906 5907 if ((func_id == BPF_FUNC_get_stack || 5908 func_id == BPF_FUNC_get_task_stack) && 5909 !env->prog->has_callchain_buf) { 5910 const char *err_str; 5911 5912 #ifdef CONFIG_PERF_EVENTS 5913 err = get_callchain_buffers(sysctl_perf_event_max_stack); 5914 err_str = "cannot get callchain buffer for func %s#%d\n"; 5915 #else 5916 err = -ENOTSUPP; 5917 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 5918 #endif 5919 if (err) { 5920 verbose(env, err_str, func_id_name(func_id), func_id); 5921 return err; 5922 } 5923 5924 env->prog->has_callchain_buf = true; 5925 } 5926 5927 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 5928 env->prog->call_get_stack = true; 5929 5930 if (changes_data) 5931 clear_all_pkt_pointers(env); 5932 return 0; 5933 } 5934 5935 static bool signed_add_overflows(s64 a, s64 b) 5936 { 5937 /* Do the add in u64, where overflow is well-defined */ 5938 s64 res = (s64)((u64)a + (u64)b); 5939 5940 if (b < 0) 5941 return res > a; 5942 return res < a; 5943 } 5944 5945 static bool signed_add32_overflows(s32 a, s32 b) 5946 { 5947 /* Do the add in u32, where overflow is well-defined */ 5948 s32 res = (s32)((u32)a + (u32)b); 5949 5950 if (b < 0) 5951 return res > a; 5952 return res < a; 5953 } 5954 5955 static bool signed_sub_overflows(s64 a, s64 b) 5956 { 5957 /* Do the sub in u64, where overflow is well-defined */ 5958 s64 res = (s64)((u64)a - (u64)b); 5959 5960 if (b < 0) 5961 return res < a; 5962 return res > a; 5963 } 5964 5965 static bool signed_sub32_overflows(s32 a, s32 b) 5966 { 5967 /* Do the sub in u32, where overflow is well-defined */ 5968 s32 res = (s32)((u32)a - (u32)b); 5969 5970 if (b < 0) 5971 return res < a; 5972 return res > a; 5973 } 5974 5975 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 5976 const struct bpf_reg_state *reg, 5977 enum bpf_reg_type type) 5978 { 5979 bool known = tnum_is_const(reg->var_off); 5980 s64 val = reg->var_off.value; 5981 s64 smin = reg->smin_value; 5982 5983 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 5984 verbose(env, "math between %s pointer and %lld is not allowed\n", 5985 reg_type_str[type], val); 5986 return false; 5987 } 5988 5989 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 5990 verbose(env, "%s pointer offset %d is not allowed\n", 5991 reg_type_str[type], reg->off); 5992 return false; 5993 } 5994 5995 if (smin == S64_MIN) { 5996 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 5997 reg_type_str[type]); 5998 return false; 5999 } 6000 6001 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 6002 verbose(env, "value %lld makes %s pointer be out of bounds\n", 6003 smin, reg_type_str[type]); 6004 return false; 6005 } 6006 6007 return true; 6008 } 6009 6010 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 6011 { 6012 return &env->insn_aux_data[env->insn_idx]; 6013 } 6014 6015 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 6016 u32 *ptr_limit, u8 opcode, bool off_is_neg) 6017 { 6018 bool mask_to_left = (opcode == BPF_ADD && off_is_neg) || 6019 (opcode == BPF_SUB && !off_is_neg); 6020 u32 off; 6021 6022 switch (ptr_reg->type) { 6023 case PTR_TO_STACK: 6024 /* Indirect variable offset stack access is prohibited in 6025 * unprivileged mode so it's not handled here. 6026 */ 6027 off = ptr_reg->off + ptr_reg->var_off.value; 6028 if (mask_to_left) 6029 *ptr_limit = MAX_BPF_STACK + off; 6030 else 6031 *ptr_limit = -off; 6032 return 0; 6033 case PTR_TO_MAP_KEY: 6034 /* Currently, this code is not exercised as the only use 6035 * is bpf_for_each_map_elem() helper which requires 6036 * bpf_capble. The code has been tested manually for 6037 * future use. 6038 */ 6039 if (mask_to_left) { 6040 *ptr_limit = ptr_reg->umax_value + ptr_reg->off; 6041 } else { 6042 off = ptr_reg->smin_value + ptr_reg->off; 6043 *ptr_limit = ptr_reg->map_ptr->key_size - off; 6044 } 6045 return 0; 6046 case PTR_TO_MAP_VALUE: 6047 if (mask_to_left) { 6048 *ptr_limit = ptr_reg->umax_value + ptr_reg->off; 6049 } else { 6050 off = ptr_reg->smin_value + ptr_reg->off; 6051 *ptr_limit = ptr_reg->map_ptr->value_size - off; 6052 } 6053 return 0; 6054 default: 6055 return -EINVAL; 6056 } 6057 } 6058 6059 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 6060 const struct bpf_insn *insn) 6061 { 6062 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 6063 } 6064 6065 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 6066 u32 alu_state, u32 alu_limit) 6067 { 6068 /* If we arrived here from different branches with different 6069 * state or limits to sanitize, then this won't work. 6070 */ 6071 if (aux->alu_state && 6072 (aux->alu_state != alu_state || 6073 aux->alu_limit != alu_limit)) 6074 return -EACCES; 6075 6076 /* Corresponding fixup done in do_misc_fixups(). */ 6077 aux->alu_state = alu_state; 6078 aux->alu_limit = alu_limit; 6079 return 0; 6080 } 6081 6082 static int sanitize_val_alu(struct bpf_verifier_env *env, 6083 struct bpf_insn *insn) 6084 { 6085 struct bpf_insn_aux_data *aux = cur_aux(env); 6086 6087 if (can_skip_alu_sanitation(env, insn)) 6088 return 0; 6089 6090 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 6091 } 6092 6093 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 6094 struct bpf_insn *insn, 6095 const struct bpf_reg_state *ptr_reg, 6096 struct bpf_reg_state *dst_reg, 6097 bool off_is_neg) 6098 { 6099 struct bpf_verifier_state *vstate = env->cur_state; 6100 struct bpf_insn_aux_data *aux = cur_aux(env); 6101 bool ptr_is_dst_reg = ptr_reg == dst_reg; 6102 u8 opcode = BPF_OP(insn->code); 6103 u32 alu_state, alu_limit; 6104 struct bpf_reg_state tmp; 6105 bool ret; 6106 6107 if (can_skip_alu_sanitation(env, insn)) 6108 return 0; 6109 6110 /* We already marked aux for masking from non-speculative 6111 * paths, thus we got here in the first place. We only care 6112 * to explore bad access from here. 6113 */ 6114 if (vstate->speculative) 6115 goto do_sim; 6116 6117 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 6118 alu_state |= ptr_is_dst_reg ? 6119 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 6120 6121 if (retrieve_ptr_limit(ptr_reg, &alu_limit, opcode, off_is_neg)) 6122 return 0; 6123 if (update_alu_sanitation_state(aux, alu_state, alu_limit)) 6124 return -EACCES; 6125 do_sim: 6126 /* Simulate and find potential out-of-bounds access under 6127 * speculative execution from truncation as a result of 6128 * masking when off was not within expected range. If off 6129 * sits in dst, then we temporarily need to move ptr there 6130 * to simulate dst (== 0) +/-= ptr. Needed, for example, 6131 * for cases where we use K-based arithmetic in one direction 6132 * and truncated reg-based in the other in order to explore 6133 * bad access. 6134 */ 6135 if (!ptr_is_dst_reg) { 6136 tmp = *dst_reg; 6137 *dst_reg = *ptr_reg; 6138 } 6139 ret = push_stack(env, env->insn_idx + 1, env->insn_idx, true); 6140 if (!ptr_is_dst_reg && ret) 6141 *dst_reg = tmp; 6142 return !ret ? -EFAULT : 0; 6143 } 6144 6145 /* check that stack access falls within stack limits and that 'reg' doesn't 6146 * have a variable offset. 6147 * 6148 * Variable offset is prohibited for unprivileged mode for simplicity since it 6149 * requires corresponding support in Spectre masking for stack ALU. See also 6150 * retrieve_ptr_limit(). 6151 * 6152 * 6153 * 'off' includes 'reg->off'. 6154 */ 6155 static int check_stack_access_for_ptr_arithmetic( 6156 struct bpf_verifier_env *env, 6157 int regno, 6158 const struct bpf_reg_state *reg, 6159 int off) 6160 { 6161 if (!tnum_is_const(reg->var_off)) { 6162 char tn_buf[48]; 6163 6164 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 6165 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 6166 regno, tn_buf, off); 6167 return -EACCES; 6168 } 6169 6170 if (off >= 0 || off < -MAX_BPF_STACK) { 6171 verbose(env, "R%d stack pointer arithmetic goes out of range, " 6172 "prohibited for !root; off=%d\n", regno, off); 6173 return -EACCES; 6174 } 6175 6176 return 0; 6177 } 6178 6179 6180 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 6181 * Caller should also handle BPF_MOV case separately. 6182 * If we return -EACCES, caller may want to try again treating pointer as a 6183 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 6184 */ 6185 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 6186 struct bpf_insn *insn, 6187 const struct bpf_reg_state *ptr_reg, 6188 const struct bpf_reg_state *off_reg) 6189 { 6190 struct bpf_verifier_state *vstate = env->cur_state; 6191 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 6192 struct bpf_reg_state *regs = state->regs, *dst_reg; 6193 bool known = tnum_is_const(off_reg->var_off); 6194 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 6195 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 6196 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 6197 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 6198 u32 dst = insn->dst_reg, src = insn->src_reg; 6199 u8 opcode = BPF_OP(insn->code); 6200 int ret; 6201 6202 dst_reg = ®s[dst]; 6203 6204 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 6205 smin_val > smax_val || umin_val > umax_val) { 6206 /* Taint dst register if offset had invalid bounds derived from 6207 * e.g. dead branches. 6208 */ 6209 __mark_reg_unknown(env, dst_reg); 6210 return 0; 6211 } 6212 6213 if (BPF_CLASS(insn->code) != BPF_ALU64) { 6214 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 6215 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 6216 __mark_reg_unknown(env, dst_reg); 6217 return 0; 6218 } 6219 6220 verbose(env, 6221 "R%d 32-bit pointer arithmetic prohibited\n", 6222 dst); 6223 return -EACCES; 6224 } 6225 6226 switch (ptr_reg->type) { 6227 case PTR_TO_MAP_VALUE_OR_NULL: 6228 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 6229 dst, reg_type_str[ptr_reg->type]); 6230 return -EACCES; 6231 case CONST_PTR_TO_MAP: 6232 /* smin_val represents the known value */ 6233 if (known && smin_val == 0 && opcode == BPF_ADD) 6234 break; 6235 fallthrough; 6236 case PTR_TO_PACKET_END: 6237 case PTR_TO_SOCKET: 6238 case PTR_TO_SOCKET_OR_NULL: 6239 case PTR_TO_SOCK_COMMON: 6240 case PTR_TO_SOCK_COMMON_OR_NULL: 6241 case PTR_TO_TCP_SOCK: 6242 case PTR_TO_TCP_SOCK_OR_NULL: 6243 case PTR_TO_XDP_SOCK: 6244 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 6245 dst, reg_type_str[ptr_reg->type]); 6246 return -EACCES; 6247 case PTR_TO_MAP_KEY: 6248 case PTR_TO_MAP_VALUE: 6249 if (!env->allow_ptr_leaks && !known && (smin_val < 0) != (smax_val < 0)) { 6250 verbose(env, "R%d has unknown scalar with mixed signed bounds, pointer arithmetic with it prohibited for !root\n", 6251 off_reg == dst_reg ? dst : src); 6252 return -EACCES; 6253 } 6254 fallthrough; 6255 default: 6256 break; 6257 } 6258 6259 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 6260 * The id may be overwritten later if we create a new variable offset. 6261 */ 6262 dst_reg->type = ptr_reg->type; 6263 dst_reg->id = ptr_reg->id; 6264 6265 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 6266 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 6267 return -EINVAL; 6268 6269 /* pointer types do not carry 32-bit bounds at the moment. */ 6270 __mark_reg32_unbounded(dst_reg); 6271 6272 switch (opcode) { 6273 case BPF_ADD: 6274 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0); 6275 if (ret < 0) { 6276 verbose(env, "R%d tried to add from different maps or paths\n", dst); 6277 return ret; 6278 } 6279 /* We can take a fixed offset as long as it doesn't overflow 6280 * the s32 'off' field 6281 */ 6282 if (known && (ptr_reg->off + smin_val == 6283 (s64)(s32)(ptr_reg->off + smin_val))) { 6284 /* pointer += K. Accumulate it into fixed offset */ 6285 dst_reg->smin_value = smin_ptr; 6286 dst_reg->smax_value = smax_ptr; 6287 dst_reg->umin_value = umin_ptr; 6288 dst_reg->umax_value = umax_ptr; 6289 dst_reg->var_off = ptr_reg->var_off; 6290 dst_reg->off = ptr_reg->off + smin_val; 6291 dst_reg->raw = ptr_reg->raw; 6292 break; 6293 } 6294 /* A new variable offset is created. Note that off_reg->off 6295 * == 0, since it's a scalar. 6296 * dst_reg gets the pointer type and since some positive 6297 * integer value was added to the pointer, give it a new 'id' 6298 * if it's a PTR_TO_PACKET. 6299 * this creates a new 'base' pointer, off_reg (variable) gets 6300 * added into the variable offset, and we copy the fixed offset 6301 * from ptr_reg. 6302 */ 6303 if (signed_add_overflows(smin_ptr, smin_val) || 6304 signed_add_overflows(smax_ptr, smax_val)) { 6305 dst_reg->smin_value = S64_MIN; 6306 dst_reg->smax_value = S64_MAX; 6307 } else { 6308 dst_reg->smin_value = smin_ptr + smin_val; 6309 dst_reg->smax_value = smax_ptr + smax_val; 6310 } 6311 if (umin_ptr + umin_val < umin_ptr || 6312 umax_ptr + umax_val < umax_ptr) { 6313 dst_reg->umin_value = 0; 6314 dst_reg->umax_value = U64_MAX; 6315 } else { 6316 dst_reg->umin_value = umin_ptr + umin_val; 6317 dst_reg->umax_value = umax_ptr + umax_val; 6318 } 6319 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 6320 dst_reg->off = ptr_reg->off; 6321 dst_reg->raw = ptr_reg->raw; 6322 if (reg_is_pkt_pointer(ptr_reg)) { 6323 dst_reg->id = ++env->id_gen; 6324 /* something was added to pkt_ptr, set range to zero */ 6325 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 6326 } 6327 break; 6328 case BPF_SUB: 6329 ret = sanitize_ptr_alu(env, insn, ptr_reg, dst_reg, smin_val < 0); 6330 if (ret < 0) { 6331 verbose(env, "R%d tried to sub from different maps or paths\n", dst); 6332 return ret; 6333 } 6334 if (dst_reg == off_reg) { 6335 /* scalar -= pointer. Creates an unknown scalar */ 6336 verbose(env, "R%d tried to subtract pointer from scalar\n", 6337 dst); 6338 return -EACCES; 6339 } 6340 /* We don't allow subtraction from FP, because (according to 6341 * test_verifier.c test "invalid fp arithmetic", JITs might not 6342 * be able to deal with it. 6343 */ 6344 if (ptr_reg->type == PTR_TO_STACK) { 6345 verbose(env, "R%d subtraction from stack pointer prohibited\n", 6346 dst); 6347 return -EACCES; 6348 } 6349 if (known && (ptr_reg->off - smin_val == 6350 (s64)(s32)(ptr_reg->off - smin_val))) { 6351 /* pointer -= K. Subtract it from fixed offset */ 6352 dst_reg->smin_value = smin_ptr; 6353 dst_reg->smax_value = smax_ptr; 6354 dst_reg->umin_value = umin_ptr; 6355 dst_reg->umax_value = umax_ptr; 6356 dst_reg->var_off = ptr_reg->var_off; 6357 dst_reg->id = ptr_reg->id; 6358 dst_reg->off = ptr_reg->off - smin_val; 6359 dst_reg->raw = ptr_reg->raw; 6360 break; 6361 } 6362 /* A new variable offset is created. If the subtrahend is known 6363 * nonnegative, then any reg->range we had before is still good. 6364 */ 6365 if (signed_sub_overflows(smin_ptr, smax_val) || 6366 signed_sub_overflows(smax_ptr, smin_val)) { 6367 /* Overflow possible, we know nothing */ 6368 dst_reg->smin_value = S64_MIN; 6369 dst_reg->smax_value = S64_MAX; 6370 } else { 6371 dst_reg->smin_value = smin_ptr - smax_val; 6372 dst_reg->smax_value = smax_ptr - smin_val; 6373 } 6374 if (umin_ptr < umax_val) { 6375 /* Overflow possible, we know nothing */ 6376 dst_reg->umin_value = 0; 6377 dst_reg->umax_value = U64_MAX; 6378 } else { 6379 /* Cannot overflow (as long as bounds are consistent) */ 6380 dst_reg->umin_value = umin_ptr - umax_val; 6381 dst_reg->umax_value = umax_ptr - umin_val; 6382 } 6383 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 6384 dst_reg->off = ptr_reg->off; 6385 dst_reg->raw = ptr_reg->raw; 6386 if (reg_is_pkt_pointer(ptr_reg)) { 6387 dst_reg->id = ++env->id_gen; 6388 /* something was added to pkt_ptr, set range to zero */ 6389 if (smin_val < 0) 6390 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 6391 } 6392 break; 6393 case BPF_AND: 6394 case BPF_OR: 6395 case BPF_XOR: 6396 /* bitwise ops on pointers are troublesome, prohibit. */ 6397 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 6398 dst, bpf_alu_string[opcode >> 4]); 6399 return -EACCES; 6400 default: 6401 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 6402 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 6403 dst, bpf_alu_string[opcode >> 4]); 6404 return -EACCES; 6405 } 6406 6407 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 6408 return -EINVAL; 6409 6410 __update_reg_bounds(dst_reg); 6411 __reg_deduce_bounds(dst_reg); 6412 __reg_bound_offset(dst_reg); 6413 6414 /* For unprivileged we require that resulting offset must be in bounds 6415 * in order to be able to sanitize access later on. 6416 */ 6417 if (!env->bypass_spec_v1) { 6418 if (dst_reg->type == PTR_TO_MAP_VALUE && 6419 check_map_access(env, dst, dst_reg->off, 1, false)) { 6420 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 6421 "prohibited for !root\n", dst); 6422 return -EACCES; 6423 } else if (dst_reg->type == PTR_TO_STACK && 6424 check_stack_access_for_ptr_arithmetic( 6425 env, dst, dst_reg, dst_reg->off + 6426 dst_reg->var_off.value)) { 6427 return -EACCES; 6428 } 6429 } 6430 6431 return 0; 6432 } 6433 6434 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 6435 struct bpf_reg_state *src_reg) 6436 { 6437 s32 smin_val = src_reg->s32_min_value; 6438 s32 smax_val = src_reg->s32_max_value; 6439 u32 umin_val = src_reg->u32_min_value; 6440 u32 umax_val = src_reg->u32_max_value; 6441 6442 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 6443 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 6444 dst_reg->s32_min_value = S32_MIN; 6445 dst_reg->s32_max_value = S32_MAX; 6446 } else { 6447 dst_reg->s32_min_value += smin_val; 6448 dst_reg->s32_max_value += smax_val; 6449 } 6450 if (dst_reg->u32_min_value + umin_val < umin_val || 6451 dst_reg->u32_max_value + umax_val < umax_val) { 6452 dst_reg->u32_min_value = 0; 6453 dst_reg->u32_max_value = U32_MAX; 6454 } else { 6455 dst_reg->u32_min_value += umin_val; 6456 dst_reg->u32_max_value += umax_val; 6457 } 6458 } 6459 6460 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 6461 struct bpf_reg_state *src_reg) 6462 { 6463 s64 smin_val = src_reg->smin_value; 6464 s64 smax_val = src_reg->smax_value; 6465 u64 umin_val = src_reg->umin_value; 6466 u64 umax_val = src_reg->umax_value; 6467 6468 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 6469 signed_add_overflows(dst_reg->smax_value, smax_val)) { 6470 dst_reg->smin_value = S64_MIN; 6471 dst_reg->smax_value = S64_MAX; 6472 } else { 6473 dst_reg->smin_value += smin_val; 6474 dst_reg->smax_value += smax_val; 6475 } 6476 if (dst_reg->umin_value + umin_val < umin_val || 6477 dst_reg->umax_value + umax_val < umax_val) { 6478 dst_reg->umin_value = 0; 6479 dst_reg->umax_value = U64_MAX; 6480 } else { 6481 dst_reg->umin_value += umin_val; 6482 dst_reg->umax_value += umax_val; 6483 } 6484 } 6485 6486 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 6487 struct bpf_reg_state *src_reg) 6488 { 6489 s32 smin_val = src_reg->s32_min_value; 6490 s32 smax_val = src_reg->s32_max_value; 6491 u32 umin_val = src_reg->u32_min_value; 6492 u32 umax_val = src_reg->u32_max_value; 6493 6494 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 6495 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 6496 /* Overflow possible, we know nothing */ 6497 dst_reg->s32_min_value = S32_MIN; 6498 dst_reg->s32_max_value = S32_MAX; 6499 } else { 6500 dst_reg->s32_min_value -= smax_val; 6501 dst_reg->s32_max_value -= smin_val; 6502 } 6503 if (dst_reg->u32_min_value < umax_val) { 6504 /* Overflow possible, we know nothing */ 6505 dst_reg->u32_min_value = 0; 6506 dst_reg->u32_max_value = U32_MAX; 6507 } else { 6508 /* Cannot overflow (as long as bounds are consistent) */ 6509 dst_reg->u32_min_value -= umax_val; 6510 dst_reg->u32_max_value -= umin_val; 6511 } 6512 } 6513 6514 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 6515 struct bpf_reg_state *src_reg) 6516 { 6517 s64 smin_val = src_reg->smin_value; 6518 s64 smax_val = src_reg->smax_value; 6519 u64 umin_val = src_reg->umin_value; 6520 u64 umax_val = src_reg->umax_value; 6521 6522 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 6523 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 6524 /* Overflow possible, we know nothing */ 6525 dst_reg->smin_value = S64_MIN; 6526 dst_reg->smax_value = S64_MAX; 6527 } else { 6528 dst_reg->smin_value -= smax_val; 6529 dst_reg->smax_value -= smin_val; 6530 } 6531 if (dst_reg->umin_value < umax_val) { 6532 /* Overflow possible, we know nothing */ 6533 dst_reg->umin_value = 0; 6534 dst_reg->umax_value = U64_MAX; 6535 } else { 6536 /* Cannot overflow (as long as bounds are consistent) */ 6537 dst_reg->umin_value -= umax_val; 6538 dst_reg->umax_value -= umin_val; 6539 } 6540 } 6541 6542 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 6543 struct bpf_reg_state *src_reg) 6544 { 6545 s32 smin_val = src_reg->s32_min_value; 6546 u32 umin_val = src_reg->u32_min_value; 6547 u32 umax_val = src_reg->u32_max_value; 6548 6549 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 6550 /* Ain't nobody got time to multiply that sign */ 6551 __mark_reg32_unbounded(dst_reg); 6552 return; 6553 } 6554 /* Both values are positive, so we can work with unsigned and 6555 * copy the result to signed (unless it exceeds S32_MAX). 6556 */ 6557 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 6558 /* Potential overflow, we know nothing */ 6559 __mark_reg32_unbounded(dst_reg); 6560 return; 6561 } 6562 dst_reg->u32_min_value *= umin_val; 6563 dst_reg->u32_max_value *= umax_val; 6564 if (dst_reg->u32_max_value > S32_MAX) { 6565 /* Overflow possible, we know nothing */ 6566 dst_reg->s32_min_value = S32_MIN; 6567 dst_reg->s32_max_value = S32_MAX; 6568 } else { 6569 dst_reg->s32_min_value = dst_reg->u32_min_value; 6570 dst_reg->s32_max_value = dst_reg->u32_max_value; 6571 } 6572 } 6573 6574 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 6575 struct bpf_reg_state *src_reg) 6576 { 6577 s64 smin_val = src_reg->smin_value; 6578 u64 umin_val = src_reg->umin_value; 6579 u64 umax_val = src_reg->umax_value; 6580 6581 if (smin_val < 0 || dst_reg->smin_value < 0) { 6582 /* Ain't nobody got time to multiply that sign */ 6583 __mark_reg64_unbounded(dst_reg); 6584 return; 6585 } 6586 /* Both values are positive, so we can work with unsigned and 6587 * copy the result to signed (unless it exceeds S64_MAX). 6588 */ 6589 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 6590 /* Potential overflow, we know nothing */ 6591 __mark_reg64_unbounded(dst_reg); 6592 return; 6593 } 6594 dst_reg->umin_value *= umin_val; 6595 dst_reg->umax_value *= umax_val; 6596 if (dst_reg->umax_value > S64_MAX) { 6597 /* Overflow possible, we know nothing */ 6598 dst_reg->smin_value = S64_MIN; 6599 dst_reg->smax_value = S64_MAX; 6600 } else { 6601 dst_reg->smin_value = dst_reg->umin_value; 6602 dst_reg->smax_value = dst_reg->umax_value; 6603 } 6604 } 6605 6606 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 6607 struct bpf_reg_state *src_reg) 6608 { 6609 bool src_known = tnum_subreg_is_const(src_reg->var_off); 6610 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 6611 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 6612 s32 smin_val = src_reg->s32_min_value; 6613 u32 umax_val = src_reg->u32_max_value; 6614 6615 /* Assuming scalar64_min_max_and will be called so its safe 6616 * to skip updating register for known 32-bit case. 6617 */ 6618 if (src_known && dst_known) 6619 return; 6620 6621 /* We get our minimum from the var_off, since that's inherently 6622 * bitwise. Our maximum is the minimum of the operands' maxima. 6623 */ 6624 dst_reg->u32_min_value = var32_off.value; 6625 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 6626 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 6627 /* Lose signed bounds when ANDing negative numbers, 6628 * ain't nobody got time for that. 6629 */ 6630 dst_reg->s32_min_value = S32_MIN; 6631 dst_reg->s32_max_value = S32_MAX; 6632 } else { 6633 /* ANDing two positives gives a positive, so safe to 6634 * cast result into s64. 6635 */ 6636 dst_reg->s32_min_value = dst_reg->u32_min_value; 6637 dst_reg->s32_max_value = dst_reg->u32_max_value; 6638 } 6639 6640 } 6641 6642 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 6643 struct bpf_reg_state *src_reg) 6644 { 6645 bool src_known = tnum_is_const(src_reg->var_off); 6646 bool dst_known = tnum_is_const(dst_reg->var_off); 6647 s64 smin_val = src_reg->smin_value; 6648 u64 umax_val = src_reg->umax_value; 6649 6650 if (src_known && dst_known) { 6651 __mark_reg_known(dst_reg, dst_reg->var_off.value); 6652 return; 6653 } 6654 6655 /* We get our minimum from the var_off, since that's inherently 6656 * bitwise. Our maximum is the minimum of the operands' maxima. 6657 */ 6658 dst_reg->umin_value = dst_reg->var_off.value; 6659 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 6660 if (dst_reg->smin_value < 0 || smin_val < 0) { 6661 /* Lose signed bounds when ANDing negative numbers, 6662 * ain't nobody got time for that. 6663 */ 6664 dst_reg->smin_value = S64_MIN; 6665 dst_reg->smax_value = S64_MAX; 6666 } else { 6667 /* ANDing two positives gives a positive, so safe to 6668 * cast result into s64. 6669 */ 6670 dst_reg->smin_value = dst_reg->umin_value; 6671 dst_reg->smax_value = dst_reg->umax_value; 6672 } 6673 /* We may learn something more from the var_off */ 6674 __update_reg_bounds(dst_reg); 6675 } 6676 6677 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 6678 struct bpf_reg_state *src_reg) 6679 { 6680 bool src_known = tnum_subreg_is_const(src_reg->var_off); 6681 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 6682 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 6683 s32 smin_val = src_reg->s32_min_value; 6684 u32 umin_val = src_reg->u32_min_value; 6685 6686 /* Assuming scalar64_min_max_or will be called so it is safe 6687 * to skip updating register for known case. 6688 */ 6689 if (src_known && dst_known) 6690 return; 6691 6692 /* We get our maximum from the var_off, and our minimum is the 6693 * maximum of the operands' minima 6694 */ 6695 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 6696 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 6697 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 6698 /* Lose signed bounds when ORing negative numbers, 6699 * ain't nobody got time for that. 6700 */ 6701 dst_reg->s32_min_value = S32_MIN; 6702 dst_reg->s32_max_value = S32_MAX; 6703 } else { 6704 /* ORing two positives gives a positive, so safe to 6705 * cast result into s64. 6706 */ 6707 dst_reg->s32_min_value = dst_reg->u32_min_value; 6708 dst_reg->s32_max_value = dst_reg->u32_max_value; 6709 } 6710 } 6711 6712 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 6713 struct bpf_reg_state *src_reg) 6714 { 6715 bool src_known = tnum_is_const(src_reg->var_off); 6716 bool dst_known = tnum_is_const(dst_reg->var_off); 6717 s64 smin_val = src_reg->smin_value; 6718 u64 umin_val = src_reg->umin_value; 6719 6720 if (src_known && dst_known) { 6721 __mark_reg_known(dst_reg, dst_reg->var_off.value); 6722 return; 6723 } 6724 6725 /* We get our maximum from the var_off, and our minimum is the 6726 * maximum of the operands' minima 6727 */ 6728 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 6729 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 6730 if (dst_reg->smin_value < 0 || smin_val < 0) { 6731 /* Lose signed bounds when ORing negative numbers, 6732 * ain't nobody got time for that. 6733 */ 6734 dst_reg->smin_value = S64_MIN; 6735 dst_reg->smax_value = S64_MAX; 6736 } else { 6737 /* ORing two positives gives a positive, so safe to 6738 * cast result into s64. 6739 */ 6740 dst_reg->smin_value = dst_reg->umin_value; 6741 dst_reg->smax_value = dst_reg->umax_value; 6742 } 6743 /* We may learn something more from the var_off */ 6744 __update_reg_bounds(dst_reg); 6745 } 6746 6747 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 6748 struct bpf_reg_state *src_reg) 6749 { 6750 bool src_known = tnum_subreg_is_const(src_reg->var_off); 6751 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 6752 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 6753 s32 smin_val = src_reg->s32_min_value; 6754 6755 /* Assuming scalar64_min_max_xor will be called so it is safe 6756 * to skip updating register for known case. 6757 */ 6758 if (src_known && dst_known) 6759 return; 6760 6761 /* We get both minimum and maximum from the var32_off. */ 6762 dst_reg->u32_min_value = var32_off.value; 6763 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 6764 6765 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 6766 /* XORing two positive sign numbers gives a positive, 6767 * so safe to cast u32 result into s32. 6768 */ 6769 dst_reg->s32_min_value = dst_reg->u32_min_value; 6770 dst_reg->s32_max_value = dst_reg->u32_max_value; 6771 } else { 6772 dst_reg->s32_min_value = S32_MIN; 6773 dst_reg->s32_max_value = S32_MAX; 6774 } 6775 } 6776 6777 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 6778 struct bpf_reg_state *src_reg) 6779 { 6780 bool src_known = tnum_is_const(src_reg->var_off); 6781 bool dst_known = tnum_is_const(dst_reg->var_off); 6782 s64 smin_val = src_reg->smin_value; 6783 6784 if (src_known && dst_known) { 6785 /* dst_reg->var_off.value has been updated earlier */ 6786 __mark_reg_known(dst_reg, dst_reg->var_off.value); 6787 return; 6788 } 6789 6790 /* We get both minimum and maximum from the var_off. */ 6791 dst_reg->umin_value = dst_reg->var_off.value; 6792 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 6793 6794 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 6795 /* XORing two positive sign numbers gives a positive, 6796 * so safe to cast u64 result into s64. 6797 */ 6798 dst_reg->smin_value = dst_reg->umin_value; 6799 dst_reg->smax_value = dst_reg->umax_value; 6800 } else { 6801 dst_reg->smin_value = S64_MIN; 6802 dst_reg->smax_value = S64_MAX; 6803 } 6804 6805 __update_reg_bounds(dst_reg); 6806 } 6807 6808 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 6809 u64 umin_val, u64 umax_val) 6810 { 6811 /* We lose all sign bit information (except what we can pick 6812 * up from var_off) 6813 */ 6814 dst_reg->s32_min_value = S32_MIN; 6815 dst_reg->s32_max_value = S32_MAX; 6816 /* If we might shift our top bit out, then we know nothing */ 6817 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 6818 dst_reg->u32_min_value = 0; 6819 dst_reg->u32_max_value = U32_MAX; 6820 } else { 6821 dst_reg->u32_min_value <<= umin_val; 6822 dst_reg->u32_max_value <<= umax_val; 6823 } 6824 } 6825 6826 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 6827 struct bpf_reg_state *src_reg) 6828 { 6829 u32 umax_val = src_reg->u32_max_value; 6830 u32 umin_val = src_reg->u32_min_value; 6831 /* u32 alu operation will zext upper bits */ 6832 struct tnum subreg = tnum_subreg(dst_reg->var_off); 6833 6834 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 6835 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 6836 /* Not required but being careful mark reg64 bounds as unknown so 6837 * that we are forced to pick them up from tnum and zext later and 6838 * if some path skips this step we are still safe. 6839 */ 6840 __mark_reg64_unbounded(dst_reg); 6841 __update_reg32_bounds(dst_reg); 6842 } 6843 6844 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 6845 u64 umin_val, u64 umax_val) 6846 { 6847 /* Special case <<32 because it is a common compiler pattern to sign 6848 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 6849 * positive we know this shift will also be positive so we can track 6850 * bounds correctly. Otherwise we lose all sign bit information except 6851 * what we can pick up from var_off. Perhaps we can generalize this 6852 * later to shifts of any length. 6853 */ 6854 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 6855 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 6856 else 6857 dst_reg->smax_value = S64_MAX; 6858 6859 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 6860 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 6861 else 6862 dst_reg->smin_value = S64_MIN; 6863 6864 /* If we might shift our top bit out, then we know nothing */ 6865 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 6866 dst_reg->umin_value = 0; 6867 dst_reg->umax_value = U64_MAX; 6868 } else { 6869 dst_reg->umin_value <<= umin_val; 6870 dst_reg->umax_value <<= umax_val; 6871 } 6872 } 6873 6874 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 6875 struct bpf_reg_state *src_reg) 6876 { 6877 u64 umax_val = src_reg->umax_value; 6878 u64 umin_val = src_reg->umin_value; 6879 6880 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 6881 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 6882 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 6883 6884 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 6885 /* We may learn something more from the var_off */ 6886 __update_reg_bounds(dst_reg); 6887 } 6888 6889 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 6890 struct bpf_reg_state *src_reg) 6891 { 6892 struct tnum subreg = tnum_subreg(dst_reg->var_off); 6893 u32 umax_val = src_reg->u32_max_value; 6894 u32 umin_val = src_reg->u32_min_value; 6895 6896 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 6897 * be negative, then either: 6898 * 1) src_reg might be zero, so the sign bit of the result is 6899 * unknown, so we lose our signed bounds 6900 * 2) it's known negative, thus the unsigned bounds capture the 6901 * signed bounds 6902 * 3) the signed bounds cross zero, so they tell us nothing 6903 * about the result 6904 * If the value in dst_reg is known nonnegative, then again the 6905 * unsigned bounds capture the signed bounds. 6906 * Thus, in all cases it suffices to blow away our signed bounds 6907 * and rely on inferring new ones from the unsigned bounds and 6908 * var_off of the result. 6909 */ 6910 dst_reg->s32_min_value = S32_MIN; 6911 dst_reg->s32_max_value = S32_MAX; 6912 6913 dst_reg->var_off = tnum_rshift(subreg, umin_val); 6914 dst_reg->u32_min_value >>= umax_val; 6915 dst_reg->u32_max_value >>= umin_val; 6916 6917 __mark_reg64_unbounded(dst_reg); 6918 __update_reg32_bounds(dst_reg); 6919 } 6920 6921 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 6922 struct bpf_reg_state *src_reg) 6923 { 6924 u64 umax_val = src_reg->umax_value; 6925 u64 umin_val = src_reg->umin_value; 6926 6927 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 6928 * be negative, then either: 6929 * 1) src_reg might be zero, so the sign bit of the result is 6930 * unknown, so we lose our signed bounds 6931 * 2) it's known negative, thus the unsigned bounds capture the 6932 * signed bounds 6933 * 3) the signed bounds cross zero, so they tell us nothing 6934 * about the result 6935 * If the value in dst_reg is known nonnegative, then again the 6936 * unsigned bounds capture the signed bounds. 6937 * Thus, in all cases it suffices to blow away our signed bounds 6938 * and rely on inferring new ones from the unsigned bounds and 6939 * var_off of the result. 6940 */ 6941 dst_reg->smin_value = S64_MIN; 6942 dst_reg->smax_value = S64_MAX; 6943 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 6944 dst_reg->umin_value >>= umax_val; 6945 dst_reg->umax_value >>= umin_val; 6946 6947 /* Its not easy to operate on alu32 bounds here because it depends 6948 * on bits being shifted in. Take easy way out and mark unbounded 6949 * so we can recalculate later from tnum. 6950 */ 6951 __mark_reg32_unbounded(dst_reg); 6952 __update_reg_bounds(dst_reg); 6953 } 6954 6955 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 6956 struct bpf_reg_state *src_reg) 6957 { 6958 u64 umin_val = src_reg->u32_min_value; 6959 6960 /* Upon reaching here, src_known is true and 6961 * umax_val is equal to umin_val. 6962 */ 6963 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 6964 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 6965 6966 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 6967 6968 /* blow away the dst_reg umin_value/umax_value and rely on 6969 * dst_reg var_off to refine the result. 6970 */ 6971 dst_reg->u32_min_value = 0; 6972 dst_reg->u32_max_value = U32_MAX; 6973 6974 __mark_reg64_unbounded(dst_reg); 6975 __update_reg32_bounds(dst_reg); 6976 } 6977 6978 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 6979 struct bpf_reg_state *src_reg) 6980 { 6981 u64 umin_val = src_reg->umin_value; 6982 6983 /* Upon reaching here, src_known is true and umax_val is equal 6984 * to umin_val. 6985 */ 6986 dst_reg->smin_value >>= umin_val; 6987 dst_reg->smax_value >>= umin_val; 6988 6989 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 6990 6991 /* blow away the dst_reg umin_value/umax_value and rely on 6992 * dst_reg var_off to refine the result. 6993 */ 6994 dst_reg->umin_value = 0; 6995 dst_reg->umax_value = U64_MAX; 6996 6997 /* Its not easy to operate on alu32 bounds here because it depends 6998 * on bits being shifted in from upper 32-bits. Take easy way out 6999 * and mark unbounded so we can recalculate later from tnum. 7000 */ 7001 __mark_reg32_unbounded(dst_reg); 7002 __update_reg_bounds(dst_reg); 7003 } 7004 7005 /* WARNING: This function does calculations on 64-bit values, but the actual 7006 * execution may occur on 32-bit values. Therefore, things like bitshifts 7007 * need extra checks in the 32-bit case. 7008 */ 7009 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 7010 struct bpf_insn *insn, 7011 struct bpf_reg_state *dst_reg, 7012 struct bpf_reg_state src_reg) 7013 { 7014 struct bpf_reg_state *regs = cur_regs(env); 7015 u8 opcode = BPF_OP(insn->code); 7016 bool src_known; 7017 s64 smin_val, smax_val; 7018 u64 umin_val, umax_val; 7019 s32 s32_min_val, s32_max_val; 7020 u32 u32_min_val, u32_max_val; 7021 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 7022 u32 dst = insn->dst_reg; 7023 int ret; 7024 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 7025 7026 smin_val = src_reg.smin_value; 7027 smax_val = src_reg.smax_value; 7028 umin_val = src_reg.umin_value; 7029 umax_val = src_reg.umax_value; 7030 7031 s32_min_val = src_reg.s32_min_value; 7032 s32_max_val = src_reg.s32_max_value; 7033 u32_min_val = src_reg.u32_min_value; 7034 u32_max_val = src_reg.u32_max_value; 7035 7036 if (alu32) { 7037 src_known = tnum_subreg_is_const(src_reg.var_off); 7038 if ((src_known && 7039 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 7040 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 7041 /* Taint dst register if offset had invalid bounds 7042 * derived from e.g. dead branches. 7043 */ 7044 __mark_reg_unknown(env, dst_reg); 7045 return 0; 7046 } 7047 } else { 7048 src_known = tnum_is_const(src_reg.var_off); 7049 if ((src_known && 7050 (smin_val != smax_val || umin_val != umax_val)) || 7051 smin_val > smax_val || umin_val > umax_val) { 7052 /* Taint dst register if offset had invalid bounds 7053 * derived from e.g. dead branches. 7054 */ 7055 __mark_reg_unknown(env, dst_reg); 7056 return 0; 7057 } 7058 } 7059 7060 if (!src_known && 7061 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 7062 __mark_reg_unknown(env, dst_reg); 7063 return 0; 7064 } 7065 7066 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 7067 * There are two classes of instructions: The first class we track both 7068 * alu32 and alu64 sign/unsigned bounds independently this provides the 7069 * greatest amount of precision when alu operations are mixed with jmp32 7070 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 7071 * and BPF_OR. This is possible because these ops have fairly easy to 7072 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 7073 * See alu32 verifier tests for examples. The second class of 7074 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 7075 * with regards to tracking sign/unsigned bounds because the bits may 7076 * cross subreg boundaries in the alu64 case. When this happens we mark 7077 * the reg unbounded in the subreg bound space and use the resulting 7078 * tnum to calculate an approximation of the sign/unsigned bounds. 7079 */ 7080 switch (opcode) { 7081 case BPF_ADD: 7082 ret = sanitize_val_alu(env, insn); 7083 if (ret < 0) { 7084 verbose(env, "R%d tried to add from different pointers or scalars\n", dst); 7085 return ret; 7086 } 7087 scalar32_min_max_add(dst_reg, &src_reg); 7088 scalar_min_max_add(dst_reg, &src_reg); 7089 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 7090 break; 7091 case BPF_SUB: 7092 ret = sanitize_val_alu(env, insn); 7093 if (ret < 0) { 7094 verbose(env, "R%d tried to sub from different pointers or scalars\n", dst); 7095 return ret; 7096 } 7097 scalar32_min_max_sub(dst_reg, &src_reg); 7098 scalar_min_max_sub(dst_reg, &src_reg); 7099 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 7100 break; 7101 case BPF_MUL: 7102 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 7103 scalar32_min_max_mul(dst_reg, &src_reg); 7104 scalar_min_max_mul(dst_reg, &src_reg); 7105 break; 7106 case BPF_AND: 7107 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 7108 scalar32_min_max_and(dst_reg, &src_reg); 7109 scalar_min_max_and(dst_reg, &src_reg); 7110 break; 7111 case BPF_OR: 7112 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 7113 scalar32_min_max_or(dst_reg, &src_reg); 7114 scalar_min_max_or(dst_reg, &src_reg); 7115 break; 7116 case BPF_XOR: 7117 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 7118 scalar32_min_max_xor(dst_reg, &src_reg); 7119 scalar_min_max_xor(dst_reg, &src_reg); 7120 break; 7121 case BPF_LSH: 7122 if (umax_val >= insn_bitness) { 7123 /* Shifts greater than 31 or 63 are undefined. 7124 * This includes shifts by a negative number. 7125 */ 7126 mark_reg_unknown(env, regs, insn->dst_reg); 7127 break; 7128 } 7129 if (alu32) 7130 scalar32_min_max_lsh(dst_reg, &src_reg); 7131 else 7132 scalar_min_max_lsh(dst_reg, &src_reg); 7133 break; 7134 case BPF_RSH: 7135 if (umax_val >= insn_bitness) { 7136 /* Shifts greater than 31 or 63 are undefined. 7137 * This includes shifts by a negative number. 7138 */ 7139 mark_reg_unknown(env, regs, insn->dst_reg); 7140 break; 7141 } 7142 if (alu32) 7143 scalar32_min_max_rsh(dst_reg, &src_reg); 7144 else 7145 scalar_min_max_rsh(dst_reg, &src_reg); 7146 break; 7147 case BPF_ARSH: 7148 if (umax_val >= insn_bitness) { 7149 /* Shifts greater than 31 or 63 are undefined. 7150 * This includes shifts by a negative number. 7151 */ 7152 mark_reg_unknown(env, regs, insn->dst_reg); 7153 break; 7154 } 7155 if (alu32) 7156 scalar32_min_max_arsh(dst_reg, &src_reg); 7157 else 7158 scalar_min_max_arsh(dst_reg, &src_reg); 7159 break; 7160 default: 7161 mark_reg_unknown(env, regs, insn->dst_reg); 7162 break; 7163 } 7164 7165 /* ALU32 ops are zero extended into 64bit register */ 7166 if (alu32) 7167 zext_32_to_64(dst_reg); 7168 7169 __update_reg_bounds(dst_reg); 7170 __reg_deduce_bounds(dst_reg); 7171 __reg_bound_offset(dst_reg); 7172 return 0; 7173 } 7174 7175 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 7176 * and var_off. 7177 */ 7178 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 7179 struct bpf_insn *insn) 7180 { 7181 struct bpf_verifier_state *vstate = env->cur_state; 7182 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7183 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 7184 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 7185 u8 opcode = BPF_OP(insn->code); 7186 int err; 7187 7188 dst_reg = ®s[insn->dst_reg]; 7189 src_reg = NULL; 7190 if (dst_reg->type != SCALAR_VALUE) 7191 ptr_reg = dst_reg; 7192 else 7193 /* Make sure ID is cleared otherwise dst_reg min/max could be 7194 * incorrectly propagated into other registers by find_equal_scalars() 7195 */ 7196 dst_reg->id = 0; 7197 if (BPF_SRC(insn->code) == BPF_X) { 7198 src_reg = ®s[insn->src_reg]; 7199 if (src_reg->type != SCALAR_VALUE) { 7200 if (dst_reg->type != SCALAR_VALUE) { 7201 /* Combining two pointers by any ALU op yields 7202 * an arbitrary scalar. Disallow all math except 7203 * pointer subtraction 7204 */ 7205 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 7206 mark_reg_unknown(env, regs, insn->dst_reg); 7207 return 0; 7208 } 7209 verbose(env, "R%d pointer %s pointer prohibited\n", 7210 insn->dst_reg, 7211 bpf_alu_string[opcode >> 4]); 7212 return -EACCES; 7213 } else { 7214 /* scalar += pointer 7215 * This is legal, but we have to reverse our 7216 * src/dest handling in computing the range 7217 */ 7218 err = mark_chain_precision(env, insn->dst_reg); 7219 if (err) 7220 return err; 7221 return adjust_ptr_min_max_vals(env, insn, 7222 src_reg, dst_reg); 7223 } 7224 } else if (ptr_reg) { 7225 /* pointer += scalar */ 7226 err = mark_chain_precision(env, insn->src_reg); 7227 if (err) 7228 return err; 7229 return adjust_ptr_min_max_vals(env, insn, 7230 dst_reg, src_reg); 7231 } 7232 } else { 7233 /* Pretend the src is a reg with a known value, since we only 7234 * need to be able to read from this state. 7235 */ 7236 off_reg.type = SCALAR_VALUE; 7237 __mark_reg_known(&off_reg, insn->imm); 7238 src_reg = &off_reg; 7239 if (ptr_reg) /* pointer += K */ 7240 return adjust_ptr_min_max_vals(env, insn, 7241 ptr_reg, src_reg); 7242 } 7243 7244 /* Got here implies adding two SCALAR_VALUEs */ 7245 if (WARN_ON_ONCE(ptr_reg)) { 7246 print_verifier_state(env, state); 7247 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 7248 return -EINVAL; 7249 } 7250 if (WARN_ON(!src_reg)) { 7251 print_verifier_state(env, state); 7252 verbose(env, "verifier internal error: no src_reg\n"); 7253 return -EINVAL; 7254 } 7255 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 7256 } 7257 7258 /* check validity of 32-bit and 64-bit arithmetic operations */ 7259 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 7260 { 7261 struct bpf_reg_state *regs = cur_regs(env); 7262 u8 opcode = BPF_OP(insn->code); 7263 int err; 7264 7265 if (opcode == BPF_END || opcode == BPF_NEG) { 7266 if (opcode == BPF_NEG) { 7267 if (BPF_SRC(insn->code) != 0 || 7268 insn->src_reg != BPF_REG_0 || 7269 insn->off != 0 || insn->imm != 0) { 7270 verbose(env, "BPF_NEG uses reserved fields\n"); 7271 return -EINVAL; 7272 } 7273 } else { 7274 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 7275 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 7276 BPF_CLASS(insn->code) == BPF_ALU64) { 7277 verbose(env, "BPF_END uses reserved fields\n"); 7278 return -EINVAL; 7279 } 7280 } 7281 7282 /* check src operand */ 7283 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7284 if (err) 7285 return err; 7286 7287 if (is_pointer_value(env, insn->dst_reg)) { 7288 verbose(env, "R%d pointer arithmetic prohibited\n", 7289 insn->dst_reg); 7290 return -EACCES; 7291 } 7292 7293 /* check dest operand */ 7294 err = check_reg_arg(env, insn->dst_reg, DST_OP); 7295 if (err) 7296 return err; 7297 7298 } else if (opcode == BPF_MOV) { 7299 7300 if (BPF_SRC(insn->code) == BPF_X) { 7301 if (insn->imm != 0 || insn->off != 0) { 7302 verbose(env, "BPF_MOV uses reserved fields\n"); 7303 return -EINVAL; 7304 } 7305 7306 /* check src operand */ 7307 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7308 if (err) 7309 return err; 7310 } else { 7311 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 7312 verbose(env, "BPF_MOV uses reserved fields\n"); 7313 return -EINVAL; 7314 } 7315 } 7316 7317 /* check dest operand, mark as required later */ 7318 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 7319 if (err) 7320 return err; 7321 7322 if (BPF_SRC(insn->code) == BPF_X) { 7323 struct bpf_reg_state *src_reg = regs + insn->src_reg; 7324 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 7325 7326 if (BPF_CLASS(insn->code) == BPF_ALU64) { 7327 /* case: R1 = R2 7328 * copy register state to dest reg 7329 */ 7330 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 7331 /* Assign src and dst registers the same ID 7332 * that will be used by find_equal_scalars() 7333 * to propagate min/max range. 7334 */ 7335 src_reg->id = ++env->id_gen; 7336 *dst_reg = *src_reg; 7337 dst_reg->live |= REG_LIVE_WRITTEN; 7338 dst_reg->subreg_def = DEF_NOT_SUBREG; 7339 } else { 7340 /* R1 = (u32) R2 */ 7341 if (is_pointer_value(env, insn->src_reg)) { 7342 verbose(env, 7343 "R%d partial copy of pointer\n", 7344 insn->src_reg); 7345 return -EACCES; 7346 } else if (src_reg->type == SCALAR_VALUE) { 7347 *dst_reg = *src_reg; 7348 /* Make sure ID is cleared otherwise 7349 * dst_reg min/max could be incorrectly 7350 * propagated into src_reg by find_equal_scalars() 7351 */ 7352 dst_reg->id = 0; 7353 dst_reg->live |= REG_LIVE_WRITTEN; 7354 dst_reg->subreg_def = env->insn_idx + 1; 7355 } else { 7356 mark_reg_unknown(env, regs, 7357 insn->dst_reg); 7358 } 7359 zext_32_to_64(dst_reg); 7360 } 7361 } else { 7362 /* case: R = imm 7363 * remember the value we stored into this reg 7364 */ 7365 /* clear any state __mark_reg_known doesn't set */ 7366 mark_reg_unknown(env, regs, insn->dst_reg); 7367 regs[insn->dst_reg].type = SCALAR_VALUE; 7368 if (BPF_CLASS(insn->code) == BPF_ALU64) { 7369 __mark_reg_known(regs + insn->dst_reg, 7370 insn->imm); 7371 } else { 7372 __mark_reg_known(regs + insn->dst_reg, 7373 (u32)insn->imm); 7374 } 7375 } 7376 7377 } else if (opcode > BPF_END) { 7378 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 7379 return -EINVAL; 7380 7381 } else { /* all other ALU ops: and, sub, xor, add, ... */ 7382 7383 if (BPF_SRC(insn->code) == BPF_X) { 7384 if (insn->imm != 0 || insn->off != 0) { 7385 verbose(env, "BPF_ALU uses reserved fields\n"); 7386 return -EINVAL; 7387 } 7388 /* check src1 operand */ 7389 err = check_reg_arg(env, insn->src_reg, SRC_OP); 7390 if (err) 7391 return err; 7392 } else { 7393 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 7394 verbose(env, "BPF_ALU uses reserved fields\n"); 7395 return -EINVAL; 7396 } 7397 } 7398 7399 /* check src2 operand */ 7400 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 7401 if (err) 7402 return err; 7403 7404 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 7405 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 7406 verbose(env, "div by zero\n"); 7407 return -EINVAL; 7408 } 7409 7410 if ((opcode == BPF_LSH || opcode == BPF_RSH || 7411 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 7412 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 7413 7414 if (insn->imm < 0 || insn->imm >= size) { 7415 verbose(env, "invalid shift %d\n", insn->imm); 7416 return -EINVAL; 7417 } 7418 } 7419 7420 /* check dest operand */ 7421 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 7422 if (err) 7423 return err; 7424 7425 return adjust_reg_min_max_vals(env, insn); 7426 } 7427 7428 return 0; 7429 } 7430 7431 static void __find_good_pkt_pointers(struct bpf_func_state *state, 7432 struct bpf_reg_state *dst_reg, 7433 enum bpf_reg_type type, int new_range) 7434 { 7435 struct bpf_reg_state *reg; 7436 int i; 7437 7438 for (i = 0; i < MAX_BPF_REG; i++) { 7439 reg = &state->regs[i]; 7440 if (reg->type == type && reg->id == dst_reg->id) 7441 /* keep the maximum range already checked */ 7442 reg->range = max(reg->range, new_range); 7443 } 7444 7445 bpf_for_each_spilled_reg(i, state, reg) { 7446 if (!reg) 7447 continue; 7448 if (reg->type == type && reg->id == dst_reg->id) 7449 reg->range = max(reg->range, new_range); 7450 } 7451 } 7452 7453 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 7454 struct bpf_reg_state *dst_reg, 7455 enum bpf_reg_type type, 7456 bool range_right_open) 7457 { 7458 int new_range, i; 7459 7460 if (dst_reg->off < 0 || 7461 (dst_reg->off == 0 && range_right_open)) 7462 /* This doesn't give us any range */ 7463 return; 7464 7465 if (dst_reg->umax_value > MAX_PACKET_OFF || 7466 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 7467 /* Risk of overflow. For instance, ptr + (1<<63) may be less 7468 * than pkt_end, but that's because it's also less than pkt. 7469 */ 7470 return; 7471 7472 new_range = dst_reg->off; 7473 if (range_right_open) 7474 new_range--; 7475 7476 /* Examples for register markings: 7477 * 7478 * pkt_data in dst register: 7479 * 7480 * r2 = r3; 7481 * r2 += 8; 7482 * if (r2 > pkt_end) goto <handle exception> 7483 * <access okay> 7484 * 7485 * r2 = r3; 7486 * r2 += 8; 7487 * if (r2 < pkt_end) goto <access okay> 7488 * <handle exception> 7489 * 7490 * Where: 7491 * r2 == dst_reg, pkt_end == src_reg 7492 * r2=pkt(id=n,off=8,r=0) 7493 * r3=pkt(id=n,off=0,r=0) 7494 * 7495 * pkt_data in src register: 7496 * 7497 * r2 = r3; 7498 * r2 += 8; 7499 * if (pkt_end >= r2) goto <access okay> 7500 * <handle exception> 7501 * 7502 * r2 = r3; 7503 * r2 += 8; 7504 * if (pkt_end <= r2) goto <handle exception> 7505 * <access okay> 7506 * 7507 * Where: 7508 * pkt_end == dst_reg, r2 == src_reg 7509 * r2=pkt(id=n,off=8,r=0) 7510 * r3=pkt(id=n,off=0,r=0) 7511 * 7512 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 7513 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 7514 * and [r3, r3 + 8-1) respectively is safe to access depending on 7515 * the check. 7516 */ 7517 7518 /* If our ids match, then we must have the same max_value. And we 7519 * don't care about the other reg's fixed offset, since if it's too big 7520 * the range won't allow anything. 7521 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 7522 */ 7523 for (i = 0; i <= vstate->curframe; i++) 7524 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type, 7525 new_range); 7526 } 7527 7528 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 7529 { 7530 struct tnum subreg = tnum_subreg(reg->var_off); 7531 s32 sval = (s32)val; 7532 7533 switch (opcode) { 7534 case BPF_JEQ: 7535 if (tnum_is_const(subreg)) 7536 return !!tnum_equals_const(subreg, val); 7537 break; 7538 case BPF_JNE: 7539 if (tnum_is_const(subreg)) 7540 return !tnum_equals_const(subreg, val); 7541 break; 7542 case BPF_JSET: 7543 if ((~subreg.mask & subreg.value) & val) 7544 return 1; 7545 if (!((subreg.mask | subreg.value) & val)) 7546 return 0; 7547 break; 7548 case BPF_JGT: 7549 if (reg->u32_min_value > val) 7550 return 1; 7551 else if (reg->u32_max_value <= val) 7552 return 0; 7553 break; 7554 case BPF_JSGT: 7555 if (reg->s32_min_value > sval) 7556 return 1; 7557 else if (reg->s32_max_value <= sval) 7558 return 0; 7559 break; 7560 case BPF_JLT: 7561 if (reg->u32_max_value < val) 7562 return 1; 7563 else if (reg->u32_min_value >= val) 7564 return 0; 7565 break; 7566 case BPF_JSLT: 7567 if (reg->s32_max_value < sval) 7568 return 1; 7569 else if (reg->s32_min_value >= sval) 7570 return 0; 7571 break; 7572 case BPF_JGE: 7573 if (reg->u32_min_value >= val) 7574 return 1; 7575 else if (reg->u32_max_value < val) 7576 return 0; 7577 break; 7578 case BPF_JSGE: 7579 if (reg->s32_min_value >= sval) 7580 return 1; 7581 else if (reg->s32_max_value < sval) 7582 return 0; 7583 break; 7584 case BPF_JLE: 7585 if (reg->u32_max_value <= val) 7586 return 1; 7587 else if (reg->u32_min_value > val) 7588 return 0; 7589 break; 7590 case BPF_JSLE: 7591 if (reg->s32_max_value <= sval) 7592 return 1; 7593 else if (reg->s32_min_value > sval) 7594 return 0; 7595 break; 7596 } 7597 7598 return -1; 7599 } 7600 7601 7602 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 7603 { 7604 s64 sval = (s64)val; 7605 7606 switch (opcode) { 7607 case BPF_JEQ: 7608 if (tnum_is_const(reg->var_off)) 7609 return !!tnum_equals_const(reg->var_off, val); 7610 break; 7611 case BPF_JNE: 7612 if (tnum_is_const(reg->var_off)) 7613 return !tnum_equals_const(reg->var_off, val); 7614 break; 7615 case BPF_JSET: 7616 if ((~reg->var_off.mask & reg->var_off.value) & val) 7617 return 1; 7618 if (!((reg->var_off.mask | reg->var_off.value) & val)) 7619 return 0; 7620 break; 7621 case BPF_JGT: 7622 if (reg->umin_value > val) 7623 return 1; 7624 else if (reg->umax_value <= val) 7625 return 0; 7626 break; 7627 case BPF_JSGT: 7628 if (reg->smin_value > sval) 7629 return 1; 7630 else if (reg->smax_value <= sval) 7631 return 0; 7632 break; 7633 case BPF_JLT: 7634 if (reg->umax_value < val) 7635 return 1; 7636 else if (reg->umin_value >= val) 7637 return 0; 7638 break; 7639 case BPF_JSLT: 7640 if (reg->smax_value < sval) 7641 return 1; 7642 else if (reg->smin_value >= sval) 7643 return 0; 7644 break; 7645 case BPF_JGE: 7646 if (reg->umin_value >= val) 7647 return 1; 7648 else if (reg->umax_value < val) 7649 return 0; 7650 break; 7651 case BPF_JSGE: 7652 if (reg->smin_value >= sval) 7653 return 1; 7654 else if (reg->smax_value < sval) 7655 return 0; 7656 break; 7657 case BPF_JLE: 7658 if (reg->umax_value <= val) 7659 return 1; 7660 else if (reg->umin_value > val) 7661 return 0; 7662 break; 7663 case BPF_JSLE: 7664 if (reg->smax_value <= sval) 7665 return 1; 7666 else if (reg->smin_value > sval) 7667 return 0; 7668 break; 7669 } 7670 7671 return -1; 7672 } 7673 7674 /* compute branch direction of the expression "if (reg opcode val) goto target;" 7675 * and return: 7676 * 1 - branch will be taken and "goto target" will be executed 7677 * 0 - branch will not be taken and fall-through to next insn 7678 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 7679 * range [0,10] 7680 */ 7681 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 7682 bool is_jmp32) 7683 { 7684 if (__is_pointer_value(false, reg)) { 7685 if (!reg_type_not_null(reg->type)) 7686 return -1; 7687 7688 /* If pointer is valid tests against zero will fail so we can 7689 * use this to direct branch taken. 7690 */ 7691 if (val != 0) 7692 return -1; 7693 7694 switch (opcode) { 7695 case BPF_JEQ: 7696 return 0; 7697 case BPF_JNE: 7698 return 1; 7699 default: 7700 return -1; 7701 } 7702 } 7703 7704 if (is_jmp32) 7705 return is_branch32_taken(reg, val, opcode); 7706 return is_branch64_taken(reg, val, opcode); 7707 } 7708 7709 static int flip_opcode(u32 opcode) 7710 { 7711 /* How can we transform "a <op> b" into "b <op> a"? */ 7712 static const u8 opcode_flip[16] = { 7713 /* these stay the same */ 7714 [BPF_JEQ >> 4] = BPF_JEQ, 7715 [BPF_JNE >> 4] = BPF_JNE, 7716 [BPF_JSET >> 4] = BPF_JSET, 7717 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 7718 [BPF_JGE >> 4] = BPF_JLE, 7719 [BPF_JGT >> 4] = BPF_JLT, 7720 [BPF_JLE >> 4] = BPF_JGE, 7721 [BPF_JLT >> 4] = BPF_JGT, 7722 [BPF_JSGE >> 4] = BPF_JSLE, 7723 [BPF_JSGT >> 4] = BPF_JSLT, 7724 [BPF_JSLE >> 4] = BPF_JSGE, 7725 [BPF_JSLT >> 4] = BPF_JSGT 7726 }; 7727 return opcode_flip[opcode >> 4]; 7728 } 7729 7730 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 7731 struct bpf_reg_state *src_reg, 7732 u8 opcode) 7733 { 7734 struct bpf_reg_state *pkt; 7735 7736 if (src_reg->type == PTR_TO_PACKET_END) { 7737 pkt = dst_reg; 7738 } else if (dst_reg->type == PTR_TO_PACKET_END) { 7739 pkt = src_reg; 7740 opcode = flip_opcode(opcode); 7741 } else { 7742 return -1; 7743 } 7744 7745 if (pkt->range >= 0) 7746 return -1; 7747 7748 switch (opcode) { 7749 case BPF_JLE: 7750 /* pkt <= pkt_end */ 7751 fallthrough; 7752 case BPF_JGT: 7753 /* pkt > pkt_end */ 7754 if (pkt->range == BEYOND_PKT_END) 7755 /* pkt has at last one extra byte beyond pkt_end */ 7756 return opcode == BPF_JGT; 7757 break; 7758 case BPF_JLT: 7759 /* pkt < pkt_end */ 7760 fallthrough; 7761 case BPF_JGE: 7762 /* pkt >= pkt_end */ 7763 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 7764 return opcode == BPF_JGE; 7765 break; 7766 } 7767 return -1; 7768 } 7769 7770 /* Adjusts the register min/max values in the case that the dst_reg is the 7771 * variable register that we are working on, and src_reg is a constant or we're 7772 * simply doing a BPF_K check. 7773 * In JEQ/JNE cases we also adjust the var_off values. 7774 */ 7775 static void reg_set_min_max(struct bpf_reg_state *true_reg, 7776 struct bpf_reg_state *false_reg, 7777 u64 val, u32 val32, 7778 u8 opcode, bool is_jmp32) 7779 { 7780 struct tnum false_32off = tnum_subreg(false_reg->var_off); 7781 struct tnum false_64off = false_reg->var_off; 7782 struct tnum true_32off = tnum_subreg(true_reg->var_off); 7783 struct tnum true_64off = true_reg->var_off; 7784 s64 sval = (s64)val; 7785 s32 sval32 = (s32)val32; 7786 7787 /* If the dst_reg is a pointer, we can't learn anything about its 7788 * variable offset from the compare (unless src_reg were a pointer into 7789 * the same object, but we don't bother with that. 7790 * Since false_reg and true_reg have the same type by construction, we 7791 * only need to check one of them for pointerness. 7792 */ 7793 if (__is_pointer_value(false, false_reg)) 7794 return; 7795 7796 switch (opcode) { 7797 case BPF_JEQ: 7798 case BPF_JNE: 7799 { 7800 struct bpf_reg_state *reg = 7801 opcode == BPF_JEQ ? true_reg : false_reg; 7802 7803 /* JEQ/JNE comparison doesn't change the register equivalence. 7804 * r1 = r2; 7805 * if (r1 == 42) goto label; 7806 * ... 7807 * label: // here both r1 and r2 are known to be 42. 7808 * 7809 * Hence when marking register as known preserve it's ID. 7810 */ 7811 if (is_jmp32) 7812 __mark_reg32_known(reg, val32); 7813 else 7814 ___mark_reg_known(reg, val); 7815 break; 7816 } 7817 case BPF_JSET: 7818 if (is_jmp32) { 7819 false_32off = tnum_and(false_32off, tnum_const(~val32)); 7820 if (is_power_of_2(val32)) 7821 true_32off = tnum_or(true_32off, 7822 tnum_const(val32)); 7823 } else { 7824 false_64off = tnum_and(false_64off, tnum_const(~val)); 7825 if (is_power_of_2(val)) 7826 true_64off = tnum_or(true_64off, 7827 tnum_const(val)); 7828 } 7829 break; 7830 case BPF_JGE: 7831 case BPF_JGT: 7832 { 7833 if (is_jmp32) { 7834 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 7835 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 7836 7837 false_reg->u32_max_value = min(false_reg->u32_max_value, 7838 false_umax); 7839 true_reg->u32_min_value = max(true_reg->u32_min_value, 7840 true_umin); 7841 } else { 7842 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 7843 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 7844 7845 false_reg->umax_value = min(false_reg->umax_value, false_umax); 7846 true_reg->umin_value = max(true_reg->umin_value, true_umin); 7847 } 7848 break; 7849 } 7850 case BPF_JSGE: 7851 case BPF_JSGT: 7852 { 7853 if (is_jmp32) { 7854 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 7855 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 7856 7857 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 7858 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 7859 } else { 7860 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 7861 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 7862 7863 false_reg->smax_value = min(false_reg->smax_value, false_smax); 7864 true_reg->smin_value = max(true_reg->smin_value, true_smin); 7865 } 7866 break; 7867 } 7868 case BPF_JLE: 7869 case BPF_JLT: 7870 { 7871 if (is_jmp32) { 7872 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 7873 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 7874 7875 false_reg->u32_min_value = max(false_reg->u32_min_value, 7876 false_umin); 7877 true_reg->u32_max_value = min(true_reg->u32_max_value, 7878 true_umax); 7879 } else { 7880 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 7881 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 7882 7883 false_reg->umin_value = max(false_reg->umin_value, false_umin); 7884 true_reg->umax_value = min(true_reg->umax_value, true_umax); 7885 } 7886 break; 7887 } 7888 case BPF_JSLE: 7889 case BPF_JSLT: 7890 { 7891 if (is_jmp32) { 7892 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 7893 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 7894 7895 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 7896 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 7897 } else { 7898 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 7899 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 7900 7901 false_reg->smin_value = max(false_reg->smin_value, false_smin); 7902 true_reg->smax_value = min(true_reg->smax_value, true_smax); 7903 } 7904 break; 7905 } 7906 default: 7907 return; 7908 } 7909 7910 if (is_jmp32) { 7911 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 7912 tnum_subreg(false_32off)); 7913 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 7914 tnum_subreg(true_32off)); 7915 __reg_combine_32_into_64(false_reg); 7916 __reg_combine_32_into_64(true_reg); 7917 } else { 7918 false_reg->var_off = false_64off; 7919 true_reg->var_off = true_64off; 7920 __reg_combine_64_into_32(false_reg); 7921 __reg_combine_64_into_32(true_reg); 7922 } 7923 } 7924 7925 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 7926 * the variable reg. 7927 */ 7928 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 7929 struct bpf_reg_state *false_reg, 7930 u64 val, u32 val32, 7931 u8 opcode, bool is_jmp32) 7932 { 7933 opcode = flip_opcode(opcode); 7934 /* This uses zero as "not present in table"; luckily the zero opcode, 7935 * BPF_JA, can't get here. 7936 */ 7937 if (opcode) 7938 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 7939 } 7940 7941 /* Regs are known to be equal, so intersect their min/max/var_off */ 7942 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 7943 struct bpf_reg_state *dst_reg) 7944 { 7945 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 7946 dst_reg->umin_value); 7947 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 7948 dst_reg->umax_value); 7949 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 7950 dst_reg->smin_value); 7951 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 7952 dst_reg->smax_value); 7953 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 7954 dst_reg->var_off); 7955 /* We might have learned new bounds from the var_off. */ 7956 __update_reg_bounds(src_reg); 7957 __update_reg_bounds(dst_reg); 7958 /* We might have learned something about the sign bit. */ 7959 __reg_deduce_bounds(src_reg); 7960 __reg_deduce_bounds(dst_reg); 7961 /* We might have learned some bits from the bounds. */ 7962 __reg_bound_offset(src_reg); 7963 __reg_bound_offset(dst_reg); 7964 /* Intersecting with the old var_off might have improved our bounds 7965 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 7966 * then new var_off is (0; 0x7f...fc) which improves our umax. 7967 */ 7968 __update_reg_bounds(src_reg); 7969 __update_reg_bounds(dst_reg); 7970 } 7971 7972 static void reg_combine_min_max(struct bpf_reg_state *true_src, 7973 struct bpf_reg_state *true_dst, 7974 struct bpf_reg_state *false_src, 7975 struct bpf_reg_state *false_dst, 7976 u8 opcode) 7977 { 7978 switch (opcode) { 7979 case BPF_JEQ: 7980 __reg_combine_min_max(true_src, true_dst); 7981 break; 7982 case BPF_JNE: 7983 __reg_combine_min_max(false_src, false_dst); 7984 break; 7985 } 7986 } 7987 7988 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 7989 struct bpf_reg_state *reg, u32 id, 7990 bool is_null) 7991 { 7992 if (reg_type_may_be_null(reg->type) && reg->id == id && 7993 !WARN_ON_ONCE(!reg->id)) { 7994 /* Old offset (both fixed and variable parts) should 7995 * have been known-zero, because we don't allow pointer 7996 * arithmetic on pointers that might be NULL. 7997 */ 7998 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || 7999 !tnum_equals_const(reg->var_off, 0) || 8000 reg->off)) { 8001 __mark_reg_known_zero(reg); 8002 reg->off = 0; 8003 } 8004 if (is_null) { 8005 reg->type = SCALAR_VALUE; 8006 /* We don't need id and ref_obj_id from this point 8007 * onwards anymore, thus we should better reset it, 8008 * so that state pruning has chances to take effect. 8009 */ 8010 reg->id = 0; 8011 reg->ref_obj_id = 0; 8012 8013 return; 8014 } 8015 8016 mark_ptr_not_null_reg(reg); 8017 8018 if (!reg_may_point_to_spin_lock(reg)) { 8019 /* For not-NULL ptr, reg->ref_obj_id will be reset 8020 * in release_reg_references(). 8021 * 8022 * reg->id is still used by spin_lock ptr. Other 8023 * than spin_lock ptr type, reg->id can be reset. 8024 */ 8025 reg->id = 0; 8026 } 8027 } 8028 } 8029 8030 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id, 8031 bool is_null) 8032 { 8033 struct bpf_reg_state *reg; 8034 int i; 8035 8036 for (i = 0; i < MAX_BPF_REG; i++) 8037 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null); 8038 8039 bpf_for_each_spilled_reg(i, state, reg) { 8040 if (!reg) 8041 continue; 8042 mark_ptr_or_null_reg(state, reg, id, is_null); 8043 } 8044 } 8045 8046 /* The logic is similar to find_good_pkt_pointers(), both could eventually 8047 * be folded together at some point. 8048 */ 8049 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 8050 bool is_null) 8051 { 8052 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8053 struct bpf_reg_state *regs = state->regs; 8054 u32 ref_obj_id = regs[regno].ref_obj_id; 8055 u32 id = regs[regno].id; 8056 int i; 8057 8058 if (ref_obj_id && ref_obj_id == id && is_null) 8059 /* regs[regno] is in the " == NULL" branch. 8060 * No one could have freed the reference state before 8061 * doing the NULL check. 8062 */ 8063 WARN_ON_ONCE(release_reference_state(state, id)); 8064 8065 for (i = 0; i <= vstate->curframe; i++) 8066 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null); 8067 } 8068 8069 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 8070 struct bpf_reg_state *dst_reg, 8071 struct bpf_reg_state *src_reg, 8072 struct bpf_verifier_state *this_branch, 8073 struct bpf_verifier_state *other_branch) 8074 { 8075 if (BPF_SRC(insn->code) != BPF_X) 8076 return false; 8077 8078 /* Pointers are always 64-bit. */ 8079 if (BPF_CLASS(insn->code) == BPF_JMP32) 8080 return false; 8081 8082 switch (BPF_OP(insn->code)) { 8083 case BPF_JGT: 8084 if ((dst_reg->type == PTR_TO_PACKET && 8085 src_reg->type == PTR_TO_PACKET_END) || 8086 (dst_reg->type == PTR_TO_PACKET_META && 8087 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8088 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 8089 find_good_pkt_pointers(this_branch, dst_reg, 8090 dst_reg->type, false); 8091 mark_pkt_end(other_branch, insn->dst_reg, true); 8092 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8093 src_reg->type == PTR_TO_PACKET) || 8094 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8095 src_reg->type == PTR_TO_PACKET_META)) { 8096 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 8097 find_good_pkt_pointers(other_branch, src_reg, 8098 src_reg->type, true); 8099 mark_pkt_end(this_branch, insn->src_reg, false); 8100 } else { 8101 return false; 8102 } 8103 break; 8104 case BPF_JLT: 8105 if ((dst_reg->type == PTR_TO_PACKET && 8106 src_reg->type == PTR_TO_PACKET_END) || 8107 (dst_reg->type == PTR_TO_PACKET_META && 8108 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8109 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 8110 find_good_pkt_pointers(other_branch, dst_reg, 8111 dst_reg->type, true); 8112 mark_pkt_end(this_branch, insn->dst_reg, false); 8113 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8114 src_reg->type == PTR_TO_PACKET) || 8115 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8116 src_reg->type == PTR_TO_PACKET_META)) { 8117 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 8118 find_good_pkt_pointers(this_branch, src_reg, 8119 src_reg->type, false); 8120 mark_pkt_end(other_branch, insn->src_reg, true); 8121 } else { 8122 return false; 8123 } 8124 break; 8125 case BPF_JGE: 8126 if ((dst_reg->type == PTR_TO_PACKET && 8127 src_reg->type == PTR_TO_PACKET_END) || 8128 (dst_reg->type == PTR_TO_PACKET_META && 8129 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8130 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 8131 find_good_pkt_pointers(this_branch, dst_reg, 8132 dst_reg->type, true); 8133 mark_pkt_end(other_branch, insn->dst_reg, false); 8134 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8135 src_reg->type == PTR_TO_PACKET) || 8136 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8137 src_reg->type == PTR_TO_PACKET_META)) { 8138 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 8139 find_good_pkt_pointers(other_branch, src_reg, 8140 src_reg->type, false); 8141 mark_pkt_end(this_branch, insn->src_reg, true); 8142 } else { 8143 return false; 8144 } 8145 break; 8146 case BPF_JLE: 8147 if ((dst_reg->type == PTR_TO_PACKET && 8148 src_reg->type == PTR_TO_PACKET_END) || 8149 (dst_reg->type == PTR_TO_PACKET_META && 8150 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 8151 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 8152 find_good_pkt_pointers(other_branch, dst_reg, 8153 dst_reg->type, false); 8154 mark_pkt_end(this_branch, insn->dst_reg, true); 8155 } else if ((dst_reg->type == PTR_TO_PACKET_END && 8156 src_reg->type == PTR_TO_PACKET) || 8157 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 8158 src_reg->type == PTR_TO_PACKET_META)) { 8159 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 8160 find_good_pkt_pointers(this_branch, src_reg, 8161 src_reg->type, true); 8162 mark_pkt_end(other_branch, insn->src_reg, false); 8163 } else { 8164 return false; 8165 } 8166 break; 8167 default: 8168 return false; 8169 } 8170 8171 return true; 8172 } 8173 8174 static void find_equal_scalars(struct bpf_verifier_state *vstate, 8175 struct bpf_reg_state *known_reg) 8176 { 8177 struct bpf_func_state *state; 8178 struct bpf_reg_state *reg; 8179 int i, j; 8180 8181 for (i = 0; i <= vstate->curframe; i++) { 8182 state = vstate->frame[i]; 8183 for (j = 0; j < MAX_BPF_REG; j++) { 8184 reg = &state->regs[j]; 8185 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 8186 *reg = *known_reg; 8187 } 8188 8189 bpf_for_each_spilled_reg(j, state, reg) { 8190 if (!reg) 8191 continue; 8192 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 8193 *reg = *known_reg; 8194 } 8195 } 8196 } 8197 8198 static int check_cond_jmp_op(struct bpf_verifier_env *env, 8199 struct bpf_insn *insn, int *insn_idx) 8200 { 8201 struct bpf_verifier_state *this_branch = env->cur_state; 8202 struct bpf_verifier_state *other_branch; 8203 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 8204 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 8205 u8 opcode = BPF_OP(insn->code); 8206 bool is_jmp32; 8207 int pred = -1; 8208 int err; 8209 8210 /* Only conditional jumps are expected to reach here. */ 8211 if (opcode == BPF_JA || opcode > BPF_JSLE) { 8212 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 8213 return -EINVAL; 8214 } 8215 8216 if (BPF_SRC(insn->code) == BPF_X) { 8217 if (insn->imm != 0) { 8218 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 8219 return -EINVAL; 8220 } 8221 8222 /* check src1 operand */ 8223 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8224 if (err) 8225 return err; 8226 8227 if (is_pointer_value(env, insn->src_reg)) { 8228 verbose(env, "R%d pointer comparison prohibited\n", 8229 insn->src_reg); 8230 return -EACCES; 8231 } 8232 src_reg = ®s[insn->src_reg]; 8233 } else { 8234 if (insn->src_reg != BPF_REG_0) { 8235 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 8236 return -EINVAL; 8237 } 8238 } 8239 8240 /* check src2 operand */ 8241 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8242 if (err) 8243 return err; 8244 8245 dst_reg = ®s[insn->dst_reg]; 8246 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 8247 8248 if (BPF_SRC(insn->code) == BPF_K) { 8249 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 8250 } else if (src_reg->type == SCALAR_VALUE && 8251 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 8252 pred = is_branch_taken(dst_reg, 8253 tnum_subreg(src_reg->var_off).value, 8254 opcode, 8255 is_jmp32); 8256 } else if (src_reg->type == SCALAR_VALUE && 8257 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 8258 pred = is_branch_taken(dst_reg, 8259 src_reg->var_off.value, 8260 opcode, 8261 is_jmp32); 8262 } else if (reg_is_pkt_pointer_any(dst_reg) && 8263 reg_is_pkt_pointer_any(src_reg) && 8264 !is_jmp32) { 8265 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 8266 } 8267 8268 if (pred >= 0) { 8269 /* If we get here with a dst_reg pointer type it is because 8270 * above is_branch_taken() special cased the 0 comparison. 8271 */ 8272 if (!__is_pointer_value(false, dst_reg)) 8273 err = mark_chain_precision(env, insn->dst_reg); 8274 if (BPF_SRC(insn->code) == BPF_X && !err && 8275 !__is_pointer_value(false, src_reg)) 8276 err = mark_chain_precision(env, insn->src_reg); 8277 if (err) 8278 return err; 8279 } 8280 if (pred == 1) { 8281 /* only follow the goto, ignore fall-through */ 8282 *insn_idx += insn->off; 8283 return 0; 8284 } else if (pred == 0) { 8285 /* only follow fall-through branch, since 8286 * that's where the program will go 8287 */ 8288 return 0; 8289 } 8290 8291 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 8292 false); 8293 if (!other_branch) 8294 return -EFAULT; 8295 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 8296 8297 /* detect if we are comparing against a constant value so we can adjust 8298 * our min/max values for our dst register. 8299 * this is only legit if both are scalars (or pointers to the same 8300 * object, I suppose, but we don't support that right now), because 8301 * otherwise the different base pointers mean the offsets aren't 8302 * comparable. 8303 */ 8304 if (BPF_SRC(insn->code) == BPF_X) { 8305 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 8306 8307 if (dst_reg->type == SCALAR_VALUE && 8308 src_reg->type == SCALAR_VALUE) { 8309 if (tnum_is_const(src_reg->var_off) || 8310 (is_jmp32 && 8311 tnum_is_const(tnum_subreg(src_reg->var_off)))) 8312 reg_set_min_max(&other_branch_regs[insn->dst_reg], 8313 dst_reg, 8314 src_reg->var_off.value, 8315 tnum_subreg(src_reg->var_off).value, 8316 opcode, is_jmp32); 8317 else if (tnum_is_const(dst_reg->var_off) || 8318 (is_jmp32 && 8319 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 8320 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 8321 src_reg, 8322 dst_reg->var_off.value, 8323 tnum_subreg(dst_reg->var_off).value, 8324 opcode, is_jmp32); 8325 else if (!is_jmp32 && 8326 (opcode == BPF_JEQ || opcode == BPF_JNE)) 8327 /* Comparing for equality, we can combine knowledge */ 8328 reg_combine_min_max(&other_branch_regs[insn->src_reg], 8329 &other_branch_regs[insn->dst_reg], 8330 src_reg, dst_reg, opcode); 8331 if (src_reg->id && 8332 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 8333 find_equal_scalars(this_branch, src_reg); 8334 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 8335 } 8336 8337 } 8338 } else if (dst_reg->type == SCALAR_VALUE) { 8339 reg_set_min_max(&other_branch_regs[insn->dst_reg], 8340 dst_reg, insn->imm, (u32)insn->imm, 8341 opcode, is_jmp32); 8342 } 8343 8344 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 8345 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 8346 find_equal_scalars(this_branch, dst_reg); 8347 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 8348 } 8349 8350 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 8351 * NOTE: these optimizations below are related with pointer comparison 8352 * which will never be JMP32. 8353 */ 8354 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 8355 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 8356 reg_type_may_be_null(dst_reg->type)) { 8357 /* Mark all identical registers in each branch as either 8358 * safe or unknown depending R == 0 or R != 0 conditional. 8359 */ 8360 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 8361 opcode == BPF_JNE); 8362 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 8363 opcode == BPF_JEQ); 8364 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 8365 this_branch, other_branch) && 8366 is_pointer_value(env, insn->dst_reg)) { 8367 verbose(env, "R%d pointer comparison prohibited\n", 8368 insn->dst_reg); 8369 return -EACCES; 8370 } 8371 if (env->log.level & BPF_LOG_LEVEL) 8372 print_verifier_state(env, this_branch->frame[this_branch->curframe]); 8373 return 0; 8374 } 8375 8376 /* verify BPF_LD_IMM64 instruction */ 8377 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 8378 { 8379 struct bpf_insn_aux_data *aux = cur_aux(env); 8380 struct bpf_reg_state *regs = cur_regs(env); 8381 struct bpf_reg_state *dst_reg; 8382 struct bpf_map *map; 8383 int err; 8384 8385 if (BPF_SIZE(insn->code) != BPF_DW) { 8386 verbose(env, "invalid BPF_LD_IMM insn\n"); 8387 return -EINVAL; 8388 } 8389 if (insn->off != 0) { 8390 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 8391 return -EINVAL; 8392 } 8393 8394 err = check_reg_arg(env, insn->dst_reg, DST_OP); 8395 if (err) 8396 return err; 8397 8398 dst_reg = ®s[insn->dst_reg]; 8399 if (insn->src_reg == 0) { 8400 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 8401 8402 dst_reg->type = SCALAR_VALUE; 8403 __mark_reg_known(®s[insn->dst_reg], imm); 8404 return 0; 8405 } 8406 8407 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 8408 mark_reg_known_zero(env, regs, insn->dst_reg); 8409 8410 dst_reg->type = aux->btf_var.reg_type; 8411 switch (dst_reg->type) { 8412 case PTR_TO_MEM: 8413 dst_reg->mem_size = aux->btf_var.mem_size; 8414 break; 8415 case PTR_TO_BTF_ID: 8416 case PTR_TO_PERCPU_BTF_ID: 8417 dst_reg->btf = aux->btf_var.btf; 8418 dst_reg->btf_id = aux->btf_var.btf_id; 8419 break; 8420 default: 8421 verbose(env, "bpf verifier is misconfigured\n"); 8422 return -EFAULT; 8423 } 8424 return 0; 8425 } 8426 8427 if (insn->src_reg == BPF_PSEUDO_FUNC) { 8428 struct bpf_prog_aux *aux = env->prog->aux; 8429 u32 subprogno = insn[1].imm; 8430 8431 if (!aux->func_info) { 8432 verbose(env, "missing btf func_info\n"); 8433 return -EINVAL; 8434 } 8435 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 8436 verbose(env, "callback function not static\n"); 8437 return -EINVAL; 8438 } 8439 8440 dst_reg->type = PTR_TO_FUNC; 8441 dst_reg->subprogno = subprogno; 8442 return 0; 8443 } 8444 8445 map = env->used_maps[aux->map_index]; 8446 mark_reg_known_zero(env, regs, insn->dst_reg); 8447 dst_reg->map_ptr = map; 8448 8449 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE) { 8450 dst_reg->type = PTR_TO_MAP_VALUE; 8451 dst_reg->off = aux->map_off; 8452 if (map_value_has_spin_lock(map)) 8453 dst_reg->id = ++env->id_gen; 8454 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD) { 8455 dst_reg->type = CONST_PTR_TO_MAP; 8456 } else { 8457 verbose(env, "bpf verifier is misconfigured\n"); 8458 return -EINVAL; 8459 } 8460 8461 return 0; 8462 } 8463 8464 static bool may_access_skb(enum bpf_prog_type type) 8465 { 8466 switch (type) { 8467 case BPF_PROG_TYPE_SOCKET_FILTER: 8468 case BPF_PROG_TYPE_SCHED_CLS: 8469 case BPF_PROG_TYPE_SCHED_ACT: 8470 return true; 8471 default: 8472 return false; 8473 } 8474 } 8475 8476 /* verify safety of LD_ABS|LD_IND instructions: 8477 * - they can only appear in the programs where ctx == skb 8478 * - since they are wrappers of function calls, they scratch R1-R5 registers, 8479 * preserve R6-R9, and store return value into R0 8480 * 8481 * Implicit input: 8482 * ctx == skb == R6 == CTX 8483 * 8484 * Explicit input: 8485 * SRC == any register 8486 * IMM == 32-bit immediate 8487 * 8488 * Output: 8489 * R0 - 8/16/32-bit skb data converted to cpu endianness 8490 */ 8491 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 8492 { 8493 struct bpf_reg_state *regs = cur_regs(env); 8494 static const int ctx_reg = BPF_REG_6; 8495 u8 mode = BPF_MODE(insn->code); 8496 int i, err; 8497 8498 if (!may_access_skb(resolve_prog_type(env->prog))) { 8499 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 8500 return -EINVAL; 8501 } 8502 8503 if (!env->ops->gen_ld_abs) { 8504 verbose(env, "bpf verifier is misconfigured\n"); 8505 return -EINVAL; 8506 } 8507 8508 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 8509 BPF_SIZE(insn->code) == BPF_DW || 8510 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 8511 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 8512 return -EINVAL; 8513 } 8514 8515 /* check whether implicit source operand (register R6) is readable */ 8516 err = check_reg_arg(env, ctx_reg, SRC_OP); 8517 if (err) 8518 return err; 8519 8520 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 8521 * gen_ld_abs() may terminate the program at runtime, leading to 8522 * reference leak. 8523 */ 8524 err = check_reference_leak(env); 8525 if (err) { 8526 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 8527 return err; 8528 } 8529 8530 if (env->cur_state->active_spin_lock) { 8531 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 8532 return -EINVAL; 8533 } 8534 8535 if (regs[ctx_reg].type != PTR_TO_CTX) { 8536 verbose(env, 8537 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 8538 return -EINVAL; 8539 } 8540 8541 if (mode == BPF_IND) { 8542 /* check explicit source operand */ 8543 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8544 if (err) 8545 return err; 8546 } 8547 8548 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg); 8549 if (err < 0) 8550 return err; 8551 8552 /* reset caller saved regs to unreadable */ 8553 for (i = 0; i < CALLER_SAVED_REGS; i++) { 8554 mark_reg_not_init(env, regs, caller_saved[i]); 8555 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 8556 } 8557 8558 /* mark destination R0 register as readable, since it contains 8559 * the value fetched from the packet. 8560 * Already marked as written above. 8561 */ 8562 mark_reg_unknown(env, regs, BPF_REG_0); 8563 /* ld_abs load up to 32-bit skb data. */ 8564 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 8565 return 0; 8566 } 8567 8568 static int check_return_code(struct bpf_verifier_env *env) 8569 { 8570 struct tnum enforce_attach_type_range = tnum_unknown; 8571 const struct bpf_prog *prog = env->prog; 8572 struct bpf_reg_state *reg; 8573 struct tnum range = tnum_range(0, 1); 8574 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 8575 int err; 8576 const bool is_subprog = env->cur_state->frame[0]->subprogno; 8577 8578 /* LSM and struct_ops func-ptr's return type could be "void" */ 8579 if (!is_subprog && 8580 (prog_type == BPF_PROG_TYPE_STRUCT_OPS || 8581 prog_type == BPF_PROG_TYPE_LSM) && 8582 !prog->aux->attach_func_proto->type) 8583 return 0; 8584 8585 /* eBPF calling convetion is such that R0 is used 8586 * to return the value from eBPF program. 8587 * Make sure that it's readable at this time 8588 * of bpf_exit, which means that program wrote 8589 * something into it earlier 8590 */ 8591 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 8592 if (err) 8593 return err; 8594 8595 if (is_pointer_value(env, BPF_REG_0)) { 8596 verbose(env, "R0 leaks addr as return value\n"); 8597 return -EACCES; 8598 } 8599 8600 reg = cur_regs(env) + BPF_REG_0; 8601 if (is_subprog) { 8602 if (reg->type != SCALAR_VALUE) { 8603 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 8604 reg_type_str[reg->type]); 8605 return -EINVAL; 8606 } 8607 return 0; 8608 } 8609 8610 switch (prog_type) { 8611 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 8612 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 8613 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 8614 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 8615 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 8616 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 8617 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 8618 range = tnum_range(1, 1); 8619 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 8620 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 8621 range = tnum_range(0, 3); 8622 break; 8623 case BPF_PROG_TYPE_CGROUP_SKB: 8624 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 8625 range = tnum_range(0, 3); 8626 enforce_attach_type_range = tnum_range(2, 3); 8627 } 8628 break; 8629 case BPF_PROG_TYPE_CGROUP_SOCK: 8630 case BPF_PROG_TYPE_SOCK_OPS: 8631 case BPF_PROG_TYPE_CGROUP_DEVICE: 8632 case BPF_PROG_TYPE_CGROUP_SYSCTL: 8633 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 8634 break; 8635 case BPF_PROG_TYPE_RAW_TRACEPOINT: 8636 if (!env->prog->aux->attach_btf_id) 8637 return 0; 8638 range = tnum_const(0); 8639 break; 8640 case BPF_PROG_TYPE_TRACING: 8641 switch (env->prog->expected_attach_type) { 8642 case BPF_TRACE_FENTRY: 8643 case BPF_TRACE_FEXIT: 8644 range = tnum_const(0); 8645 break; 8646 case BPF_TRACE_RAW_TP: 8647 case BPF_MODIFY_RETURN: 8648 return 0; 8649 case BPF_TRACE_ITER: 8650 break; 8651 default: 8652 return -ENOTSUPP; 8653 } 8654 break; 8655 case BPF_PROG_TYPE_SK_LOOKUP: 8656 range = tnum_range(SK_DROP, SK_PASS); 8657 break; 8658 case BPF_PROG_TYPE_EXT: 8659 /* freplace program can return anything as its return value 8660 * depends on the to-be-replaced kernel func or bpf program. 8661 */ 8662 default: 8663 return 0; 8664 } 8665 8666 if (reg->type != SCALAR_VALUE) { 8667 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 8668 reg_type_str[reg->type]); 8669 return -EINVAL; 8670 } 8671 8672 if (!tnum_in(range, reg->var_off)) { 8673 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 8674 return -EINVAL; 8675 } 8676 8677 if (!tnum_is_unknown(enforce_attach_type_range) && 8678 tnum_in(enforce_attach_type_range, reg->var_off)) 8679 env->prog->enforce_expected_attach_type = 1; 8680 return 0; 8681 } 8682 8683 /* non-recursive DFS pseudo code 8684 * 1 procedure DFS-iterative(G,v): 8685 * 2 label v as discovered 8686 * 3 let S be a stack 8687 * 4 S.push(v) 8688 * 5 while S is not empty 8689 * 6 t <- S.pop() 8690 * 7 if t is what we're looking for: 8691 * 8 return t 8692 * 9 for all edges e in G.adjacentEdges(t) do 8693 * 10 if edge e is already labelled 8694 * 11 continue with the next edge 8695 * 12 w <- G.adjacentVertex(t,e) 8696 * 13 if vertex w is not discovered and not explored 8697 * 14 label e as tree-edge 8698 * 15 label w as discovered 8699 * 16 S.push(w) 8700 * 17 continue at 5 8701 * 18 else if vertex w is discovered 8702 * 19 label e as back-edge 8703 * 20 else 8704 * 21 // vertex w is explored 8705 * 22 label e as forward- or cross-edge 8706 * 23 label t as explored 8707 * 24 S.pop() 8708 * 8709 * convention: 8710 * 0x10 - discovered 8711 * 0x11 - discovered and fall-through edge labelled 8712 * 0x12 - discovered and fall-through and branch edges labelled 8713 * 0x20 - explored 8714 */ 8715 8716 enum { 8717 DISCOVERED = 0x10, 8718 EXPLORED = 0x20, 8719 FALLTHROUGH = 1, 8720 BRANCH = 2, 8721 }; 8722 8723 static u32 state_htab_size(struct bpf_verifier_env *env) 8724 { 8725 return env->prog->len; 8726 } 8727 8728 static struct bpf_verifier_state_list **explored_state( 8729 struct bpf_verifier_env *env, 8730 int idx) 8731 { 8732 struct bpf_verifier_state *cur = env->cur_state; 8733 struct bpf_func_state *state = cur->frame[cur->curframe]; 8734 8735 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 8736 } 8737 8738 static void init_explored_state(struct bpf_verifier_env *env, int idx) 8739 { 8740 env->insn_aux_data[idx].prune_point = true; 8741 } 8742 8743 enum { 8744 DONE_EXPLORING = 0, 8745 KEEP_EXPLORING = 1, 8746 }; 8747 8748 /* t, w, e - match pseudo-code above: 8749 * t - index of current instruction 8750 * w - next instruction 8751 * e - edge 8752 */ 8753 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 8754 bool loop_ok) 8755 { 8756 int *insn_stack = env->cfg.insn_stack; 8757 int *insn_state = env->cfg.insn_state; 8758 8759 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 8760 return DONE_EXPLORING; 8761 8762 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 8763 return DONE_EXPLORING; 8764 8765 if (w < 0 || w >= env->prog->len) { 8766 verbose_linfo(env, t, "%d: ", t); 8767 verbose(env, "jump out of range from insn %d to %d\n", t, w); 8768 return -EINVAL; 8769 } 8770 8771 if (e == BRANCH) 8772 /* mark branch target for state pruning */ 8773 init_explored_state(env, w); 8774 8775 if (insn_state[w] == 0) { 8776 /* tree-edge */ 8777 insn_state[t] = DISCOVERED | e; 8778 insn_state[w] = DISCOVERED; 8779 if (env->cfg.cur_stack >= env->prog->len) 8780 return -E2BIG; 8781 insn_stack[env->cfg.cur_stack++] = w; 8782 return KEEP_EXPLORING; 8783 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 8784 if (loop_ok && env->bpf_capable) 8785 return DONE_EXPLORING; 8786 verbose_linfo(env, t, "%d: ", t); 8787 verbose_linfo(env, w, "%d: ", w); 8788 verbose(env, "back-edge from insn %d to %d\n", t, w); 8789 return -EINVAL; 8790 } else if (insn_state[w] == EXPLORED) { 8791 /* forward- or cross-edge */ 8792 insn_state[t] = DISCOVERED | e; 8793 } else { 8794 verbose(env, "insn state internal bug\n"); 8795 return -EFAULT; 8796 } 8797 return DONE_EXPLORING; 8798 } 8799 8800 static int visit_func_call_insn(int t, int insn_cnt, 8801 struct bpf_insn *insns, 8802 struct bpf_verifier_env *env, 8803 bool visit_callee) 8804 { 8805 int ret; 8806 8807 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 8808 if (ret) 8809 return ret; 8810 8811 if (t + 1 < insn_cnt) 8812 init_explored_state(env, t + 1); 8813 if (visit_callee) { 8814 init_explored_state(env, t); 8815 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, 8816 env, false); 8817 } 8818 return ret; 8819 } 8820 8821 /* Visits the instruction at index t and returns one of the following: 8822 * < 0 - an error occurred 8823 * DONE_EXPLORING - the instruction was fully explored 8824 * KEEP_EXPLORING - there is still work to be done before it is fully explored 8825 */ 8826 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env) 8827 { 8828 struct bpf_insn *insns = env->prog->insnsi; 8829 int ret; 8830 8831 if (bpf_pseudo_func(insns + t)) 8832 return visit_func_call_insn(t, insn_cnt, insns, env, true); 8833 8834 /* All non-branch instructions have a single fall-through edge. */ 8835 if (BPF_CLASS(insns[t].code) != BPF_JMP && 8836 BPF_CLASS(insns[t].code) != BPF_JMP32) 8837 return push_insn(t, t + 1, FALLTHROUGH, env, false); 8838 8839 switch (BPF_OP(insns[t].code)) { 8840 case BPF_EXIT: 8841 return DONE_EXPLORING; 8842 8843 case BPF_CALL: 8844 return visit_func_call_insn(t, insn_cnt, insns, env, 8845 insns[t].src_reg == BPF_PSEUDO_CALL); 8846 8847 case BPF_JA: 8848 if (BPF_SRC(insns[t].code) != BPF_K) 8849 return -EINVAL; 8850 8851 /* unconditional jump with single edge */ 8852 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env, 8853 true); 8854 if (ret) 8855 return ret; 8856 8857 /* unconditional jmp is not a good pruning point, 8858 * but it's marked, since backtracking needs 8859 * to record jmp history in is_state_visited(). 8860 */ 8861 init_explored_state(env, t + insns[t].off + 1); 8862 /* tell verifier to check for equivalent states 8863 * after every call and jump 8864 */ 8865 if (t + 1 < insn_cnt) 8866 init_explored_state(env, t + 1); 8867 8868 return ret; 8869 8870 default: 8871 /* conditional jump with two edges */ 8872 init_explored_state(env, t); 8873 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 8874 if (ret) 8875 return ret; 8876 8877 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true); 8878 } 8879 } 8880 8881 /* non-recursive depth-first-search to detect loops in BPF program 8882 * loop == back-edge in directed graph 8883 */ 8884 static int check_cfg(struct bpf_verifier_env *env) 8885 { 8886 int insn_cnt = env->prog->len; 8887 int *insn_stack, *insn_state; 8888 int ret = 0; 8889 int i; 8890 8891 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 8892 if (!insn_state) 8893 return -ENOMEM; 8894 8895 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 8896 if (!insn_stack) { 8897 kvfree(insn_state); 8898 return -ENOMEM; 8899 } 8900 8901 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 8902 insn_stack[0] = 0; /* 0 is the first instruction */ 8903 env->cfg.cur_stack = 1; 8904 8905 while (env->cfg.cur_stack > 0) { 8906 int t = insn_stack[env->cfg.cur_stack - 1]; 8907 8908 ret = visit_insn(t, insn_cnt, env); 8909 switch (ret) { 8910 case DONE_EXPLORING: 8911 insn_state[t] = EXPLORED; 8912 env->cfg.cur_stack--; 8913 break; 8914 case KEEP_EXPLORING: 8915 break; 8916 default: 8917 if (ret > 0) { 8918 verbose(env, "visit_insn internal bug\n"); 8919 ret = -EFAULT; 8920 } 8921 goto err_free; 8922 } 8923 } 8924 8925 if (env->cfg.cur_stack < 0) { 8926 verbose(env, "pop stack internal bug\n"); 8927 ret = -EFAULT; 8928 goto err_free; 8929 } 8930 8931 for (i = 0; i < insn_cnt; i++) { 8932 if (insn_state[i] != EXPLORED) { 8933 verbose(env, "unreachable insn %d\n", i); 8934 ret = -EINVAL; 8935 goto err_free; 8936 } 8937 } 8938 ret = 0; /* cfg looks good */ 8939 8940 err_free: 8941 kvfree(insn_state); 8942 kvfree(insn_stack); 8943 env->cfg.insn_state = env->cfg.insn_stack = NULL; 8944 return ret; 8945 } 8946 8947 static int check_abnormal_return(struct bpf_verifier_env *env) 8948 { 8949 int i; 8950 8951 for (i = 1; i < env->subprog_cnt; i++) { 8952 if (env->subprog_info[i].has_ld_abs) { 8953 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 8954 return -EINVAL; 8955 } 8956 if (env->subprog_info[i].has_tail_call) { 8957 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 8958 return -EINVAL; 8959 } 8960 } 8961 return 0; 8962 } 8963 8964 /* The minimum supported BTF func info size */ 8965 #define MIN_BPF_FUNCINFO_SIZE 8 8966 #define MAX_FUNCINFO_REC_SIZE 252 8967 8968 static int check_btf_func(struct bpf_verifier_env *env, 8969 const union bpf_attr *attr, 8970 union bpf_attr __user *uattr) 8971 { 8972 const struct btf_type *type, *func_proto, *ret_type; 8973 u32 i, nfuncs, urec_size, min_size; 8974 u32 krec_size = sizeof(struct bpf_func_info); 8975 struct bpf_func_info *krecord; 8976 struct bpf_func_info_aux *info_aux = NULL; 8977 struct bpf_prog *prog; 8978 const struct btf *btf; 8979 void __user *urecord; 8980 u32 prev_offset = 0; 8981 bool scalar_return; 8982 int ret = -ENOMEM; 8983 8984 nfuncs = attr->func_info_cnt; 8985 if (!nfuncs) { 8986 if (check_abnormal_return(env)) 8987 return -EINVAL; 8988 return 0; 8989 } 8990 8991 if (nfuncs != env->subprog_cnt) { 8992 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 8993 return -EINVAL; 8994 } 8995 8996 urec_size = attr->func_info_rec_size; 8997 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 8998 urec_size > MAX_FUNCINFO_REC_SIZE || 8999 urec_size % sizeof(u32)) { 9000 verbose(env, "invalid func info rec size %u\n", urec_size); 9001 return -EINVAL; 9002 } 9003 9004 prog = env->prog; 9005 btf = prog->aux->btf; 9006 9007 urecord = u64_to_user_ptr(attr->func_info); 9008 min_size = min_t(u32, krec_size, urec_size); 9009 9010 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 9011 if (!krecord) 9012 return -ENOMEM; 9013 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 9014 if (!info_aux) 9015 goto err_free; 9016 9017 for (i = 0; i < nfuncs; i++) { 9018 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 9019 if (ret) { 9020 if (ret == -E2BIG) { 9021 verbose(env, "nonzero tailing record in func info"); 9022 /* set the size kernel expects so loader can zero 9023 * out the rest of the record. 9024 */ 9025 if (put_user(min_size, &uattr->func_info_rec_size)) 9026 ret = -EFAULT; 9027 } 9028 goto err_free; 9029 } 9030 9031 if (copy_from_user(&krecord[i], urecord, min_size)) { 9032 ret = -EFAULT; 9033 goto err_free; 9034 } 9035 9036 /* check insn_off */ 9037 ret = -EINVAL; 9038 if (i == 0) { 9039 if (krecord[i].insn_off) { 9040 verbose(env, 9041 "nonzero insn_off %u for the first func info record", 9042 krecord[i].insn_off); 9043 goto err_free; 9044 } 9045 } else if (krecord[i].insn_off <= prev_offset) { 9046 verbose(env, 9047 "same or smaller insn offset (%u) than previous func info record (%u)", 9048 krecord[i].insn_off, prev_offset); 9049 goto err_free; 9050 } 9051 9052 if (env->subprog_info[i].start != krecord[i].insn_off) { 9053 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 9054 goto err_free; 9055 } 9056 9057 /* check type_id */ 9058 type = btf_type_by_id(btf, krecord[i].type_id); 9059 if (!type || !btf_type_is_func(type)) { 9060 verbose(env, "invalid type id %d in func info", 9061 krecord[i].type_id); 9062 goto err_free; 9063 } 9064 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 9065 9066 func_proto = btf_type_by_id(btf, type->type); 9067 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 9068 /* btf_func_check() already verified it during BTF load */ 9069 goto err_free; 9070 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 9071 scalar_return = 9072 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type); 9073 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 9074 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 9075 goto err_free; 9076 } 9077 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 9078 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 9079 goto err_free; 9080 } 9081 9082 prev_offset = krecord[i].insn_off; 9083 urecord += urec_size; 9084 } 9085 9086 prog->aux->func_info = krecord; 9087 prog->aux->func_info_cnt = nfuncs; 9088 prog->aux->func_info_aux = info_aux; 9089 return 0; 9090 9091 err_free: 9092 kvfree(krecord); 9093 kfree(info_aux); 9094 return ret; 9095 } 9096 9097 static void adjust_btf_func(struct bpf_verifier_env *env) 9098 { 9099 struct bpf_prog_aux *aux = env->prog->aux; 9100 int i; 9101 9102 if (!aux->func_info) 9103 return; 9104 9105 for (i = 0; i < env->subprog_cnt; i++) 9106 aux->func_info[i].insn_off = env->subprog_info[i].start; 9107 } 9108 9109 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \ 9110 sizeof(((struct bpf_line_info *)(0))->line_col)) 9111 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 9112 9113 static int check_btf_line(struct bpf_verifier_env *env, 9114 const union bpf_attr *attr, 9115 union bpf_attr __user *uattr) 9116 { 9117 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 9118 struct bpf_subprog_info *sub; 9119 struct bpf_line_info *linfo; 9120 struct bpf_prog *prog; 9121 const struct btf *btf; 9122 void __user *ulinfo; 9123 int err; 9124 9125 nr_linfo = attr->line_info_cnt; 9126 if (!nr_linfo) 9127 return 0; 9128 9129 rec_size = attr->line_info_rec_size; 9130 if (rec_size < MIN_BPF_LINEINFO_SIZE || 9131 rec_size > MAX_LINEINFO_REC_SIZE || 9132 rec_size & (sizeof(u32) - 1)) 9133 return -EINVAL; 9134 9135 /* Need to zero it in case the userspace may 9136 * pass in a smaller bpf_line_info object. 9137 */ 9138 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 9139 GFP_KERNEL | __GFP_NOWARN); 9140 if (!linfo) 9141 return -ENOMEM; 9142 9143 prog = env->prog; 9144 btf = prog->aux->btf; 9145 9146 s = 0; 9147 sub = env->subprog_info; 9148 ulinfo = u64_to_user_ptr(attr->line_info); 9149 expected_size = sizeof(struct bpf_line_info); 9150 ncopy = min_t(u32, expected_size, rec_size); 9151 for (i = 0; i < nr_linfo; i++) { 9152 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 9153 if (err) { 9154 if (err == -E2BIG) { 9155 verbose(env, "nonzero tailing record in line_info"); 9156 if (put_user(expected_size, 9157 &uattr->line_info_rec_size)) 9158 err = -EFAULT; 9159 } 9160 goto err_free; 9161 } 9162 9163 if (copy_from_user(&linfo[i], ulinfo, ncopy)) { 9164 err = -EFAULT; 9165 goto err_free; 9166 } 9167 9168 /* 9169 * Check insn_off to ensure 9170 * 1) strictly increasing AND 9171 * 2) bounded by prog->len 9172 * 9173 * The linfo[0].insn_off == 0 check logically falls into 9174 * the later "missing bpf_line_info for func..." case 9175 * because the first linfo[0].insn_off must be the 9176 * first sub also and the first sub must have 9177 * subprog_info[0].start == 0. 9178 */ 9179 if ((i && linfo[i].insn_off <= prev_offset) || 9180 linfo[i].insn_off >= prog->len) { 9181 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 9182 i, linfo[i].insn_off, prev_offset, 9183 prog->len); 9184 err = -EINVAL; 9185 goto err_free; 9186 } 9187 9188 if (!prog->insnsi[linfo[i].insn_off].code) { 9189 verbose(env, 9190 "Invalid insn code at line_info[%u].insn_off\n", 9191 i); 9192 err = -EINVAL; 9193 goto err_free; 9194 } 9195 9196 if (!btf_name_by_offset(btf, linfo[i].line_off) || 9197 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 9198 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 9199 err = -EINVAL; 9200 goto err_free; 9201 } 9202 9203 if (s != env->subprog_cnt) { 9204 if (linfo[i].insn_off == sub[s].start) { 9205 sub[s].linfo_idx = i; 9206 s++; 9207 } else if (sub[s].start < linfo[i].insn_off) { 9208 verbose(env, "missing bpf_line_info for func#%u\n", s); 9209 err = -EINVAL; 9210 goto err_free; 9211 } 9212 } 9213 9214 prev_offset = linfo[i].insn_off; 9215 ulinfo += rec_size; 9216 } 9217 9218 if (s != env->subprog_cnt) { 9219 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 9220 env->subprog_cnt - s, s); 9221 err = -EINVAL; 9222 goto err_free; 9223 } 9224 9225 prog->aux->linfo = linfo; 9226 prog->aux->nr_linfo = nr_linfo; 9227 9228 return 0; 9229 9230 err_free: 9231 kvfree(linfo); 9232 return err; 9233 } 9234 9235 static int check_btf_info(struct bpf_verifier_env *env, 9236 const union bpf_attr *attr, 9237 union bpf_attr __user *uattr) 9238 { 9239 struct btf *btf; 9240 int err; 9241 9242 if (!attr->func_info_cnt && !attr->line_info_cnt) { 9243 if (check_abnormal_return(env)) 9244 return -EINVAL; 9245 return 0; 9246 } 9247 9248 btf = btf_get_by_fd(attr->prog_btf_fd); 9249 if (IS_ERR(btf)) 9250 return PTR_ERR(btf); 9251 env->prog->aux->btf = btf; 9252 9253 err = check_btf_func(env, attr, uattr); 9254 if (err) 9255 return err; 9256 9257 err = check_btf_line(env, attr, uattr); 9258 if (err) 9259 return err; 9260 9261 return 0; 9262 } 9263 9264 /* check %cur's range satisfies %old's */ 9265 static bool range_within(struct bpf_reg_state *old, 9266 struct bpf_reg_state *cur) 9267 { 9268 return old->umin_value <= cur->umin_value && 9269 old->umax_value >= cur->umax_value && 9270 old->smin_value <= cur->smin_value && 9271 old->smax_value >= cur->smax_value && 9272 old->u32_min_value <= cur->u32_min_value && 9273 old->u32_max_value >= cur->u32_max_value && 9274 old->s32_min_value <= cur->s32_min_value && 9275 old->s32_max_value >= cur->s32_max_value; 9276 } 9277 9278 /* Maximum number of register states that can exist at once */ 9279 #define ID_MAP_SIZE (MAX_BPF_REG + MAX_BPF_STACK / BPF_REG_SIZE) 9280 struct idpair { 9281 u32 old; 9282 u32 cur; 9283 }; 9284 9285 /* If in the old state two registers had the same id, then they need to have 9286 * the same id in the new state as well. But that id could be different from 9287 * the old state, so we need to track the mapping from old to new ids. 9288 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 9289 * regs with old id 5 must also have new id 9 for the new state to be safe. But 9290 * regs with a different old id could still have new id 9, we don't care about 9291 * that. 9292 * So we look through our idmap to see if this old id has been seen before. If 9293 * so, we require the new id to match; otherwise, we add the id pair to the map. 9294 */ 9295 static bool check_ids(u32 old_id, u32 cur_id, struct idpair *idmap) 9296 { 9297 unsigned int i; 9298 9299 for (i = 0; i < ID_MAP_SIZE; i++) { 9300 if (!idmap[i].old) { 9301 /* Reached an empty slot; haven't seen this id before */ 9302 idmap[i].old = old_id; 9303 idmap[i].cur = cur_id; 9304 return true; 9305 } 9306 if (idmap[i].old == old_id) 9307 return idmap[i].cur == cur_id; 9308 } 9309 /* We ran out of idmap slots, which should be impossible */ 9310 WARN_ON_ONCE(1); 9311 return false; 9312 } 9313 9314 static void clean_func_state(struct bpf_verifier_env *env, 9315 struct bpf_func_state *st) 9316 { 9317 enum bpf_reg_liveness live; 9318 int i, j; 9319 9320 for (i = 0; i < BPF_REG_FP; i++) { 9321 live = st->regs[i].live; 9322 /* liveness must not touch this register anymore */ 9323 st->regs[i].live |= REG_LIVE_DONE; 9324 if (!(live & REG_LIVE_READ)) 9325 /* since the register is unused, clear its state 9326 * to make further comparison simpler 9327 */ 9328 __mark_reg_not_init(env, &st->regs[i]); 9329 } 9330 9331 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 9332 live = st->stack[i].spilled_ptr.live; 9333 /* liveness must not touch this stack slot anymore */ 9334 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 9335 if (!(live & REG_LIVE_READ)) { 9336 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 9337 for (j = 0; j < BPF_REG_SIZE; j++) 9338 st->stack[i].slot_type[j] = STACK_INVALID; 9339 } 9340 } 9341 } 9342 9343 static void clean_verifier_state(struct bpf_verifier_env *env, 9344 struct bpf_verifier_state *st) 9345 { 9346 int i; 9347 9348 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 9349 /* all regs in this state in all frames were already marked */ 9350 return; 9351 9352 for (i = 0; i <= st->curframe; i++) 9353 clean_func_state(env, st->frame[i]); 9354 } 9355 9356 /* the parentage chains form a tree. 9357 * the verifier states are added to state lists at given insn and 9358 * pushed into state stack for future exploration. 9359 * when the verifier reaches bpf_exit insn some of the verifer states 9360 * stored in the state lists have their final liveness state already, 9361 * but a lot of states will get revised from liveness point of view when 9362 * the verifier explores other branches. 9363 * Example: 9364 * 1: r0 = 1 9365 * 2: if r1 == 100 goto pc+1 9366 * 3: r0 = 2 9367 * 4: exit 9368 * when the verifier reaches exit insn the register r0 in the state list of 9369 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 9370 * of insn 2 and goes exploring further. At the insn 4 it will walk the 9371 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 9372 * 9373 * Since the verifier pushes the branch states as it sees them while exploring 9374 * the program the condition of walking the branch instruction for the second 9375 * time means that all states below this branch were already explored and 9376 * their final liveness markes are already propagated. 9377 * Hence when the verifier completes the search of state list in is_state_visited() 9378 * we can call this clean_live_states() function to mark all liveness states 9379 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 9380 * will not be used. 9381 * This function also clears the registers and stack for states that !READ 9382 * to simplify state merging. 9383 * 9384 * Important note here that walking the same branch instruction in the callee 9385 * doesn't meant that the states are DONE. The verifier has to compare 9386 * the callsites 9387 */ 9388 static void clean_live_states(struct bpf_verifier_env *env, int insn, 9389 struct bpf_verifier_state *cur) 9390 { 9391 struct bpf_verifier_state_list *sl; 9392 int i; 9393 9394 sl = *explored_state(env, insn); 9395 while (sl) { 9396 if (sl->state.branches) 9397 goto next; 9398 if (sl->state.insn_idx != insn || 9399 sl->state.curframe != cur->curframe) 9400 goto next; 9401 for (i = 0; i <= cur->curframe; i++) 9402 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 9403 goto next; 9404 clean_verifier_state(env, &sl->state); 9405 next: 9406 sl = sl->next; 9407 } 9408 } 9409 9410 /* Returns true if (rold safe implies rcur safe) */ 9411 static bool regsafe(struct bpf_reg_state *rold, struct bpf_reg_state *rcur, 9412 struct idpair *idmap) 9413 { 9414 bool equal; 9415 9416 if (!(rold->live & REG_LIVE_READ)) 9417 /* explored state didn't use this */ 9418 return true; 9419 9420 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0; 9421 9422 if (rold->type == PTR_TO_STACK) 9423 /* two stack pointers are equal only if they're pointing to 9424 * the same stack frame, since fp-8 in foo != fp-8 in bar 9425 */ 9426 return equal && rold->frameno == rcur->frameno; 9427 9428 if (equal) 9429 return true; 9430 9431 if (rold->type == NOT_INIT) 9432 /* explored state can't have used this */ 9433 return true; 9434 if (rcur->type == NOT_INIT) 9435 return false; 9436 switch (rold->type) { 9437 case SCALAR_VALUE: 9438 if (rcur->type == SCALAR_VALUE) { 9439 if (!rold->precise && !rcur->precise) 9440 return true; 9441 /* new val must satisfy old val knowledge */ 9442 return range_within(rold, rcur) && 9443 tnum_in(rold->var_off, rcur->var_off); 9444 } else { 9445 /* We're trying to use a pointer in place of a scalar. 9446 * Even if the scalar was unbounded, this could lead to 9447 * pointer leaks because scalars are allowed to leak 9448 * while pointers are not. We could make this safe in 9449 * special cases if root is calling us, but it's 9450 * probably not worth the hassle. 9451 */ 9452 return false; 9453 } 9454 case PTR_TO_MAP_KEY: 9455 case PTR_TO_MAP_VALUE: 9456 /* If the new min/max/var_off satisfy the old ones and 9457 * everything else matches, we are OK. 9458 * 'id' is not compared, since it's only used for maps with 9459 * bpf_spin_lock inside map element and in such cases if 9460 * the rest of the prog is valid for one map element then 9461 * it's valid for all map elements regardless of the key 9462 * used in bpf_map_lookup() 9463 */ 9464 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 9465 range_within(rold, rcur) && 9466 tnum_in(rold->var_off, rcur->var_off); 9467 case PTR_TO_MAP_VALUE_OR_NULL: 9468 /* a PTR_TO_MAP_VALUE could be safe to use as a 9469 * PTR_TO_MAP_VALUE_OR_NULL into the same map. 9470 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- 9471 * checked, doing so could have affected others with the same 9472 * id, and we can't check for that because we lost the id when 9473 * we converted to a PTR_TO_MAP_VALUE. 9474 */ 9475 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) 9476 return false; 9477 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) 9478 return false; 9479 /* Check our ids match any regs they're supposed to */ 9480 return check_ids(rold->id, rcur->id, idmap); 9481 case PTR_TO_PACKET_META: 9482 case PTR_TO_PACKET: 9483 if (rcur->type != rold->type) 9484 return false; 9485 /* We must have at least as much range as the old ptr 9486 * did, so that any accesses which were safe before are 9487 * still safe. This is true even if old range < old off, 9488 * since someone could have accessed through (ptr - k), or 9489 * even done ptr -= k in a register, to get a safe access. 9490 */ 9491 if (rold->range > rcur->range) 9492 return false; 9493 /* If the offsets don't match, we can't trust our alignment; 9494 * nor can we be sure that we won't fall out of range. 9495 */ 9496 if (rold->off != rcur->off) 9497 return false; 9498 /* id relations must be preserved */ 9499 if (rold->id && !check_ids(rold->id, rcur->id, idmap)) 9500 return false; 9501 /* new val must satisfy old val knowledge */ 9502 return range_within(rold, rcur) && 9503 tnum_in(rold->var_off, rcur->var_off); 9504 case PTR_TO_CTX: 9505 case CONST_PTR_TO_MAP: 9506 case PTR_TO_PACKET_END: 9507 case PTR_TO_FLOW_KEYS: 9508 case PTR_TO_SOCKET: 9509 case PTR_TO_SOCKET_OR_NULL: 9510 case PTR_TO_SOCK_COMMON: 9511 case PTR_TO_SOCK_COMMON_OR_NULL: 9512 case PTR_TO_TCP_SOCK: 9513 case PTR_TO_TCP_SOCK_OR_NULL: 9514 case PTR_TO_XDP_SOCK: 9515 /* Only valid matches are exact, which memcmp() above 9516 * would have accepted 9517 */ 9518 default: 9519 /* Don't know what's going on, just say it's not safe */ 9520 return false; 9521 } 9522 9523 /* Shouldn't get here; if we do, say it's not safe */ 9524 WARN_ON_ONCE(1); 9525 return false; 9526 } 9527 9528 static bool stacksafe(struct bpf_func_state *old, 9529 struct bpf_func_state *cur, 9530 struct idpair *idmap) 9531 { 9532 int i, spi; 9533 9534 /* walk slots of the explored stack and ignore any additional 9535 * slots in the current stack, since explored(safe) state 9536 * didn't use them 9537 */ 9538 for (i = 0; i < old->allocated_stack; i++) { 9539 spi = i / BPF_REG_SIZE; 9540 9541 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 9542 i += BPF_REG_SIZE - 1; 9543 /* explored state didn't use this */ 9544 continue; 9545 } 9546 9547 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 9548 continue; 9549 9550 /* explored stack has more populated slots than current stack 9551 * and these slots were used 9552 */ 9553 if (i >= cur->allocated_stack) 9554 return false; 9555 9556 /* if old state was safe with misc data in the stack 9557 * it will be safe with zero-initialized stack. 9558 * The opposite is not true 9559 */ 9560 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 9561 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 9562 continue; 9563 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 9564 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 9565 /* Ex: old explored (safe) state has STACK_SPILL in 9566 * this stack slot, but current has STACK_MISC -> 9567 * this verifier states are not equivalent, 9568 * return false to continue verification of this path 9569 */ 9570 return false; 9571 if (i % BPF_REG_SIZE) 9572 continue; 9573 if (old->stack[spi].slot_type[0] != STACK_SPILL) 9574 continue; 9575 if (!regsafe(&old->stack[spi].spilled_ptr, 9576 &cur->stack[spi].spilled_ptr, 9577 idmap)) 9578 /* when explored and current stack slot are both storing 9579 * spilled registers, check that stored pointers types 9580 * are the same as well. 9581 * Ex: explored safe path could have stored 9582 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 9583 * but current path has stored: 9584 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 9585 * such verifier states are not equivalent. 9586 * return false to continue verification of this path 9587 */ 9588 return false; 9589 } 9590 return true; 9591 } 9592 9593 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur) 9594 { 9595 if (old->acquired_refs != cur->acquired_refs) 9596 return false; 9597 return !memcmp(old->refs, cur->refs, 9598 sizeof(*old->refs) * old->acquired_refs); 9599 } 9600 9601 /* compare two verifier states 9602 * 9603 * all states stored in state_list are known to be valid, since 9604 * verifier reached 'bpf_exit' instruction through them 9605 * 9606 * this function is called when verifier exploring different branches of 9607 * execution popped from the state stack. If it sees an old state that has 9608 * more strict register state and more strict stack state then this execution 9609 * branch doesn't need to be explored further, since verifier already 9610 * concluded that more strict state leads to valid finish. 9611 * 9612 * Therefore two states are equivalent if register state is more conservative 9613 * and explored stack state is more conservative than the current one. 9614 * Example: 9615 * explored current 9616 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 9617 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 9618 * 9619 * In other words if current stack state (one being explored) has more 9620 * valid slots than old one that already passed validation, it means 9621 * the verifier can stop exploring and conclude that current state is valid too 9622 * 9623 * Similarly with registers. If explored state has register type as invalid 9624 * whereas register type in current state is meaningful, it means that 9625 * the current state will reach 'bpf_exit' instruction safely 9626 */ 9627 static bool func_states_equal(struct bpf_func_state *old, 9628 struct bpf_func_state *cur) 9629 { 9630 struct idpair *idmap; 9631 bool ret = false; 9632 int i; 9633 9634 idmap = kcalloc(ID_MAP_SIZE, sizeof(struct idpair), GFP_KERNEL); 9635 /* If we failed to allocate the idmap, just say it's not safe */ 9636 if (!idmap) 9637 return false; 9638 9639 for (i = 0; i < MAX_BPF_REG; i++) { 9640 if (!regsafe(&old->regs[i], &cur->regs[i], idmap)) 9641 goto out_free; 9642 } 9643 9644 if (!stacksafe(old, cur, idmap)) 9645 goto out_free; 9646 9647 if (!refsafe(old, cur)) 9648 goto out_free; 9649 ret = true; 9650 out_free: 9651 kfree(idmap); 9652 return ret; 9653 } 9654 9655 static bool states_equal(struct bpf_verifier_env *env, 9656 struct bpf_verifier_state *old, 9657 struct bpf_verifier_state *cur) 9658 { 9659 int i; 9660 9661 if (old->curframe != cur->curframe) 9662 return false; 9663 9664 /* Verification state from speculative execution simulation 9665 * must never prune a non-speculative execution one. 9666 */ 9667 if (old->speculative && !cur->speculative) 9668 return false; 9669 9670 if (old->active_spin_lock != cur->active_spin_lock) 9671 return false; 9672 9673 /* for states to be equal callsites have to be the same 9674 * and all frame states need to be equivalent 9675 */ 9676 for (i = 0; i <= old->curframe; i++) { 9677 if (old->frame[i]->callsite != cur->frame[i]->callsite) 9678 return false; 9679 if (!func_states_equal(old->frame[i], cur->frame[i])) 9680 return false; 9681 } 9682 return true; 9683 } 9684 9685 /* Return 0 if no propagation happened. Return negative error code if error 9686 * happened. Otherwise, return the propagated bit. 9687 */ 9688 static int propagate_liveness_reg(struct bpf_verifier_env *env, 9689 struct bpf_reg_state *reg, 9690 struct bpf_reg_state *parent_reg) 9691 { 9692 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 9693 u8 flag = reg->live & REG_LIVE_READ; 9694 int err; 9695 9696 /* When comes here, read flags of PARENT_REG or REG could be any of 9697 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 9698 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 9699 */ 9700 if (parent_flag == REG_LIVE_READ64 || 9701 /* Or if there is no read flag from REG. */ 9702 !flag || 9703 /* Or if the read flag from REG is the same as PARENT_REG. */ 9704 parent_flag == flag) 9705 return 0; 9706 9707 err = mark_reg_read(env, reg, parent_reg, flag); 9708 if (err) 9709 return err; 9710 9711 return flag; 9712 } 9713 9714 /* A write screens off any subsequent reads; but write marks come from the 9715 * straight-line code between a state and its parent. When we arrive at an 9716 * equivalent state (jump target or such) we didn't arrive by the straight-line 9717 * code, so read marks in the state must propagate to the parent regardless 9718 * of the state's write marks. That's what 'parent == state->parent' comparison 9719 * in mark_reg_read() is for. 9720 */ 9721 static int propagate_liveness(struct bpf_verifier_env *env, 9722 const struct bpf_verifier_state *vstate, 9723 struct bpf_verifier_state *vparent) 9724 { 9725 struct bpf_reg_state *state_reg, *parent_reg; 9726 struct bpf_func_state *state, *parent; 9727 int i, frame, err = 0; 9728 9729 if (vparent->curframe != vstate->curframe) { 9730 WARN(1, "propagate_live: parent frame %d current frame %d\n", 9731 vparent->curframe, vstate->curframe); 9732 return -EFAULT; 9733 } 9734 /* Propagate read liveness of registers... */ 9735 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 9736 for (frame = 0; frame <= vstate->curframe; frame++) { 9737 parent = vparent->frame[frame]; 9738 state = vstate->frame[frame]; 9739 parent_reg = parent->regs; 9740 state_reg = state->regs; 9741 /* We don't need to worry about FP liveness, it's read-only */ 9742 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 9743 err = propagate_liveness_reg(env, &state_reg[i], 9744 &parent_reg[i]); 9745 if (err < 0) 9746 return err; 9747 if (err == REG_LIVE_READ64) 9748 mark_insn_zext(env, &parent_reg[i]); 9749 } 9750 9751 /* Propagate stack slots. */ 9752 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 9753 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 9754 parent_reg = &parent->stack[i].spilled_ptr; 9755 state_reg = &state->stack[i].spilled_ptr; 9756 err = propagate_liveness_reg(env, state_reg, 9757 parent_reg); 9758 if (err < 0) 9759 return err; 9760 } 9761 } 9762 return 0; 9763 } 9764 9765 /* find precise scalars in the previous equivalent state and 9766 * propagate them into the current state 9767 */ 9768 static int propagate_precision(struct bpf_verifier_env *env, 9769 const struct bpf_verifier_state *old) 9770 { 9771 struct bpf_reg_state *state_reg; 9772 struct bpf_func_state *state; 9773 int i, err = 0; 9774 9775 state = old->frame[old->curframe]; 9776 state_reg = state->regs; 9777 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 9778 if (state_reg->type != SCALAR_VALUE || 9779 !state_reg->precise) 9780 continue; 9781 if (env->log.level & BPF_LOG_LEVEL2) 9782 verbose(env, "propagating r%d\n", i); 9783 err = mark_chain_precision(env, i); 9784 if (err < 0) 9785 return err; 9786 } 9787 9788 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 9789 if (state->stack[i].slot_type[0] != STACK_SPILL) 9790 continue; 9791 state_reg = &state->stack[i].spilled_ptr; 9792 if (state_reg->type != SCALAR_VALUE || 9793 !state_reg->precise) 9794 continue; 9795 if (env->log.level & BPF_LOG_LEVEL2) 9796 verbose(env, "propagating fp%d\n", 9797 (-i - 1) * BPF_REG_SIZE); 9798 err = mark_chain_precision_stack(env, i); 9799 if (err < 0) 9800 return err; 9801 } 9802 return 0; 9803 } 9804 9805 static bool states_maybe_looping(struct bpf_verifier_state *old, 9806 struct bpf_verifier_state *cur) 9807 { 9808 struct bpf_func_state *fold, *fcur; 9809 int i, fr = cur->curframe; 9810 9811 if (old->curframe != fr) 9812 return false; 9813 9814 fold = old->frame[fr]; 9815 fcur = cur->frame[fr]; 9816 for (i = 0; i < MAX_BPF_REG; i++) 9817 if (memcmp(&fold->regs[i], &fcur->regs[i], 9818 offsetof(struct bpf_reg_state, parent))) 9819 return false; 9820 return true; 9821 } 9822 9823 9824 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 9825 { 9826 struct bpf_verifier_state_list *new_sl; 9827 struct bpf_verifier_state_list *sl, **pprev; 9828 struct bpf_verifier_state *cur = env->cur_state, *new; 9829 int i, j, err, states_cnt = 0; 9830 bool add_new_state = env->test_state_freq ? true : false; 9831 9832 cur->last_insn_idx = env->prev_insn_idx; 9833 if (!env->insn_aux_data[insn_idx].prune_point) 9834 /* this 'insn_idx' instruction wasn't marked, so we will not 9835 * be doing state search here 9836 */ 9837 return 0; 9838 9839 /* bpf progs typically have pruning point every 4 instructions 9840 * http://vger.kernel.org/bpfconf2019.html#session-1 9841 * Do not add new state for future pruning if the verifier hasn't seen 9842 * at least 2 jumps and at least 8 instructions. 9843 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 9844 * In tests that amounts to up to 50% reduction into total verifier 9845 * memory consumption and 20% verifier time speedup. 9846 */ 9847 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 9848 env->insn_processed - env->prev_insn_processed >= 8) 9849 add_new_state = true; 9850 9851 pprev = explored_state(env, insn_idx); 9852 sl = *pprev; 9853 9854 clean_live_states(env, insn_idx, cur); 9855 9856 while (sl) { 9857 states_cnt++; 9858 if (sl->state.insn_idx != insn_idx) 9859 goto next; 9860 if (sl->state.branches) { 9861 if (states_maybe_looping(&sl->state, cur) && 9862 states_equal(env, &sl->state, cur)) { 9863 verbose_linfo(env, insn_idx, "; "); 9864 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 9865 return -EINVAL; 9866 } 9867 /* if the verifier is processing a loop, avoid adding new state 9868 * too often, since different loop iterations have distinct 9869 * states and may not help future pruning. 9870 * This threshold shouldn't be too low to make sure that 9871 * a loop with large bound will be rejected quickly. 9872 * The most abusive loop will be: 9873 * r1 += 1 9874 * if r1 < 1000000 goto pc-2 9875 * 1M insn_procssed limit / 100 == 10k peak states. 9876 * This threshold shouldn't be too high either, since states 9877 * at the end of the loop are likely to be useful in pruning. 9878 */ 9879 if (env->jmps_processed - env->prev_jmps_processed < 20 && 9880 env->insn_processed - env->prev_insn_processed < 100) 9881 add_new_state = false; 9882 goto miss; 9883 } 9884 if (states_equal(env, &sl->state, cur)) { 9885 sl->hit_cnt++; 9886 /* reached equivalent register/stack state, 9887 * prune the search. 9888 * Registers read by the continuation are read by us. 9889 * If we have any write marks in env->cur_state, they 9890 * will prevent corresponding reads in the continuation 9891 * from reaching our parent (an explored_state). Our 9892 * own state will get the read marks recorded, but 9893 * they'll be immediately forgotten as we're pruning 9894 * this state and will pop a new one. 9895 */ 9896 err = propagate_liveness(env, &sl->state, cur); 9897 9898 /* if previous state reached the exit with precision and 9899 * current state is equivalent to it (except precsion marks) 9900 * the precision needs to be propagated back in 9901 * the current state. 9902 */ 9903 err = err ? : push_jmp_history(env, cur); 9904 err = err ? : propagate_precision(env, &sl->state); 9905 if (err) 9906 return err; 9907 return 1; 9908 } 9909 miss: 9910 /* when new state is not going to be added do not increase miss count. 9911 * Otherwise several loop iterations will remove the state 9912 * recorded earlier. The goal of these heuristics is to have 9913 * states from some iterations of the loop (some in the beginning 9914 * and some at the end) to help pruning. 9915 */ 9916 if (add_new_state) 9917 sl->miss_cnt++; 9918 /* heuristic to determine whether this state is beneficial 9919 * to keep checking from state equivalence point of view. 9920 * Higher numbers increase max_states_per_insn and verification time, 9921 * but do not meaningfully decrease insn_processed. 9922 */ 9923 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 9924 /* the state is unlikely to be useful. Remove it to 9925 * speed up verification 9926 */ 9927 *pprev = sl->next; 9928 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 9929 u32 br = sl->state.branches; 9930 9931 WARN_ONCE(br, 9932 "BUG live_done but branches_to_explore %d\n", 9933 br); 9934 free_verifier_state(&sl->state, false); 9935 kfree(sl); 9936 env->peak_states--; 9937 } else { 9938 /* cannot free this state, since parentage chain may 9939 * walk it later. Add it for free_list instead to 9940 * be freed at the end of verification 9941 */ 9942 sl->next = env->free_list; 9943 env->free_list = sl; 9944 } 9945 sl = *pprev; 9946 continue; 9947 } 9948 next: 9949 pprev = &sl->next; 9950 sl = *pprev; 9951 } 9952 9953 if (env->max_states_per_insn < states_cnt) 9954 env->max_states_per_insn = states_cnt; 9955 9956 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 9957 return push_jmp_history(env, cur); 9958 9959 if (!add_new_state) 9960 return push_jmp_history(env, cur); 9961 9962 /* There were no equivalent states, remember the current one. 9963 * Technically the current state is not proven to be safe yet, 9964 * but it will either reach outer most bpf_exit (which means it's safe) 9965 * or it will be rejected. When there are no loops the verifier won't be 9966 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 9967 * again on the way to bpf_exit. 9968 * When looping the sl->state.branches will be > 0 and this state 9969 * will not be considered for equivalence until branches == 0. 9970 */ 9971 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 9972 if (!new_sl) 9973 return -ENOMEM; 9974 env->total_states++; 9975 env->peak_states++; 9976 env->prev_jmps_processed = env->jmps_processed; 9977 env->prev_insn_processed = env->insn_processed; 9978 9979 /* add new state to the head of linked list */ 9980 new = &new_sl->state; 9981 err = copy_verifier_state(new, cur); 9982 if (err) { 9983 free_verifier_state(new, false); 9984 kfree(new_sl); 9985 return err; 9986 } 9987 new->insn_idx = insn_idx; 9988 WARN_ONCE(new->branches != 1, 9989 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 9990 9991 cur->parent = new; 9992 cur->first_insn_idx = insn_idx; 9993 clear_jmp_history(cur); 9994 new_sl->next = *explored_state(env, insn_idx); 9995 *explored_state(env, insn_idx) = new_sl; 9996 /* connect new state to parentage chain. Current frame needs all 9997 * registers connected. Only r6 - r9 of the callers are alive (pushed 9998 * to the stack implicitly by JITs) so in callers' frames connect just 9999 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 10000 * the state of the call instruction (with WRITTEN set), and r0 comes 10001 * from callee with its full parentage chain, anyway. 10002 */ 10003 /* clear write marks in current state: the writes we did are not writes 10004 * our child did, so they don't screen off its reads from us. 10005 * (There are no read marks in current state, because reads always mark 10006 * their parent and current state never has children yet. Only 10007 * explored_states can get read marks.) 10008 */ 10009 for (j = 0; j <= cur->curframe; j++) { 10010 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 10011 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 10012 for (i = 0; i < BPF_REG_FP; i++) 10013 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 10014 } 10015 10016 /* all stack frames are accessible from callee, clear them all */ 10017 for (j = 0; j <= cur->curframe; j++) { 10018 struct bpf_func_state *frame = cur->frame[j]; 10019 struct bpf_func_state *newframe = new->frame[j]; 10020 10021 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 10022 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 10023 frame->stack[i].spilled_ptr.parent = 10024 &newframe->stack[i].spilled_ptr; 10025 } 10026 } 10027 return 0; 10028 } 10029 10030 /* Return true if it's OK to have the same insn return a different type. */ 10031 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 10032 { 10033 switch (type) { 10034 case PTR_TO_CTX: 10035 case PTR_TO_SOCKET: 10036 case PTR_TO_SOCKET_OR_NULL: 10037 case PTR_TO_SOCK_COMMON: 10038 case PTR_TO_SOCK_COMMON_OR_NULL: 10039 case PTR_TO_TCP_SOCK: 10040 case PTR_TO_TCP_SOCK_OR_NULL: 10041 case PTR_TO_XDP_SOCK: 10042 case PTR_TO_BTF_ID: 10043 case PTR_TO_BTF_ID_OR_NULL: 10044 return false; 10045 default: 10046 return true; 10047 } 10048 } 10049 10050 /* If an instruction was previously used with particular pointer types, then we 10051 * need to be careful to avoid cases such as the below, where it may be ok 10052 * for one branch accessing the pointer, but not ok for the other branch: 10053 * 10054 * R1 = sock_ptr 10055 * goto X; 10056 * ... 10057 * R1 = some_other_valid_ptr; 10058 * goto X; 10059 * ... 10060 * R2 = *(u32 *)(R1 + 0); 10061 */ 10062 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 10063 { 10064 return src != prev && (!reg_type_mismatch_ok(src) || 10065 !reg_type_mismatch_ok(prev)); 10066 } 10067 10068 static int do_check(struct bpf_verifier_env *env) 10069 { 10070 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 10071 struct bpf_verifier_state *state = env->cur_state; 10072 struct bpf_insn *insns = env->prog->insnsi; 10073 struct bpf_reg_state *regs; 10074 int insn_cnt = env->prog->len; 10075 bool do_print_state = false; 10076 int prev_insn_idx = -1; 10077 10078 for (;;) { 10079 struct bpf_insn *insn; 10080 u8 class; 10081 int err; 10082 10083 env->prev_insn_idx = prev_insn_idx; 10084 if (env->insn_idx >= insn_cnt) { 10085 verbose(env, "invalid insn idx %d insn_cnt %d\n", 10086 env->insn_idx, insn_cnt); 10087 return -EFAULT; 10088 } 10089 10090 insn = &insns[env->insn_idx]; 10091 class = BPF_CLASS(insn->code); 10092 10093 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 10094 verbose(env, 10095 "BPF program is too large. Processed %d insn\n", 10096 env->insn_processed); 10097 return -E2BIG; 10098 } 10099 10100 err = is_state_visited(env, env->insn_idx); 10101 if (err < 0) 10102 return err; 10103 if (err == 1) { 10104 /* found equivalent state, can prune the search */ 10105 if (env->log.level & BPF_LOG_LEVEL) { 10106 if (do_print_state) 10107 verbose(env, "\nfrom %d to %d%s: safe\n", 10108 env->prev_insn_idx, env->insn_idx, 10109 env->cur_state->speculative ? 10110 " (speculative execution)" : ""); 10111 else 10112 verbose(env, "%d: safe\n", env->insn_idx); 10113 } 10114 goto process_bpf_exit; 10115 } 10116 10117 if (signal_pending(current)) 10118 return -EAGAIN; 10119 10120 if (need_resched()) 10121 cond_resched(); 10122 10123 if (env->log.level & BPF_LOG_LEVEL2 || 10124 (env->log.level & BPF_LOG_LEVEL && do_print_state)) { 10125 if (env->log.level & BPF_LOG_LEVEL2) 10126 verbose(env, "%d:", env->insn_idx); 10127 else 10128 verbose(env, "\nfrom %d to %d%s:", 10129 env->prev_insn_idx, env->insn_idx, 10130 env->cur_state->speculative ? 10131 " (speculative execution)" : ""); 10132 print_verifier_state(env, state->frame[state->curframe]); 10133 do_print_state = false; 10134 } 10135 10136 if (env->log.level & BPF_LOG_LEVEL) { 10137 const struct bpf_insn_cbs cbs = { 10138 .cb_print = verbose, 10139 .private_data = env, 10140 }; 10141 10142 verbose_linfo(env, env->insn_idx, "; "); 10143 verbose(env, "%d: ", env->insn_idx); 10144 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 10145 } 10146 10147 if (bpf_prog_is_dev_bound(env->prog->aux)) { 10148 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 10149 env->prev_insn_idx); 10150 if (err) 10151 return err; 10152 } 10153 10154 regs = cur_regs(env); 10155 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 10156 prev_insn_idx = env->insn_idx; 10157 10158 if (class == BPF_ALU || class == BPF_ALU64) { 10159 err = check_alu_op(env, insn); 10160 if (err) 10161 return err; 10162 10163 } else if (class == BPF_LDX) { 10164 enum bpf_reg_type *prev_src_type, src_reg_type; 10165 10166 /* check for reserved fields is already done */ 10167 10168 /* check src operand */ 10169 err = check_reg_arg(env, insn->src_reg, SRC_OP); 10170 if (err) 10171 return err; 10172 10173 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 10174 if (err) 10175 return err; 10176 10177 src_reg_type = regs[insn->src_reg].type; 10178 10179 /* check that memory (src_reg + off) is readable, 10180 * the state of dst_reg will be updated by this func 10181 */ 10182 err = check_mem_access(env, env->insn_idx, insn->src_reg, 10183 insn->off, BPF_SIZE(insn->code), 10184 BPF_READ, insn->dst_reg, false); 10185 if (err) 10186 return err; 10187 10188 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 10189 10190 if (*prev_src_type == NOT_INIT) { 10191 /* saw a valid insn 10192 * dst_reg = *(u32 *)(src_reg + off) 10193 * save type to validate intersecting paths 10194 */ 10195 *prev_src_type = src_reg_type; 10196 10197 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 10198 /* ABuser program is trying to use the same insn 10199 * dst_reg = *(u32*) (src_reg + off) 10200 * with different pointer types: 10201 * src_reg == ctx in one branch and 10202 * src_reg == stack|map in some other branch. 10203 * Reject it. 10204 */ 10205 verbose(env, "same insn cannot be used with different pointers\n"); 10206 return -EINVAL; 10207 } 10208 10209 } else if (class == BPF_STX) { 10210 enum bpf_reg_type *prev_dst_type, dst_reg_type; 10211 10212 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 10213 err = check_atomic(env, env->insn_idx, insn); 10214 if (err) 10215 return err; 10216 env->insn_idx++; 10217 continue; 10218 } 10219 10220 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 10221 verbose(env, "BPF_STX uses reserved fields\n"); 10222 return -EINVAL; 10223 } 10224 10225 /* check src1 operand */ 10226 err = check_reg_arg(env, insn->src_reg, SRC_OP); 10227 if (err) 10228 return err; 10229 /* check src2 operand */ 10230 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 10231 if (err) 10232 return err; 10233 10234 dst_reg_type = regs[insn->dst_reg].type; 10235 10236 /* check that memory (dst_reg + off) is writeable */ 10237 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 10238 insn->off, BPF_SIZE(insn->code), 10239 BPF_WRITE, insn->src_reg, false); 10240 if (err) 10241 return err; 10242 10243 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 10244 10245 if (*prev_dst_type == NOT_INIT) { 10246 *prev_dst_type = dst_reg_type; 10247 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 10248 verbose(env, "same insn cannot be used with different pointers\n"); 10249 return -EINVAL; 10250 } 10251 10252 } else if (class == BPF_ST) { 10253 if (BPF_MODE(insn->code) != BPF_MEM || 10254 insn->src_reg != BPF_REG_0) { 10255 verbose(env, "BPF_ST uses reserved fields\n"); 10256 return -EINVAL; 10257 } 10258 /* check src operand */ 10259 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 10260 if (err) 10261 return err; 10262 10263 if (is_ctx_reg(env, insn->dst_reg)) { 10264 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 10265 insn->dst_reg, 10266 reg_type_str[reg_state(env, insn->dst_reg)->type]); 10267 return -EACCES; 10268 } 10269 10270 /* check that memory (dst_reg + off) is writeable */ 10271 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 10272 insn->off, BPF_SIZE(insn->code), 10273 BPF_WRITE, -1, false); 10274 if (err) 10275 return err; 10276 10277 } else if (class == BPF_JMP || class == BPF_JMP32) { 10278 u8 opcode = BPF_OP(insn->code); 10279 10280 env->jmps_processed++; 10281 if (opcode == BPF_CALL) { 10282 if (BPF_SRC(insn->code) != BPF_K || 10283 insn->off != 0 || 10284 (insn->src_reg != BPF_REG_0 && 10285 insn->src_reg != BPF_PSEUDO_CALL) || 10286 insn->dst_reg != BPF_REG_0 || 10287 class == BPF_JMP32) { 10288 verbose(env, "BPF_CALL uses reserved fields\n"); 10289 return -EINVAL; 10290 } 10291 10292 if (env->cur_state->active_spin_lock && 10293 (insn->src_reg == BPF_PSEUDO_CALL || 10294 insn->imm != BPF_FUNC_spin_unlock)) { 10295 verbose(env, "function calls are not allowed while holding a lock\n"); 10296 return -EINVAL; 10297 } 10298 if (insn->src_reg == BPF_PSEUDO_CALL) 10299 err = check_func_call(env, insn, &env->insn_idx); 10300 else 10301 err = check_helper_call(env, insn, &env->insn_idx); 10302 if (err) 10303 return err; 10304 } else if (opcode == BPF_JA) { 10305 if (BPF_SRC(insn->code) != BPF_K || 10306 insn->imm != 0 || 10307 insn->src_reg != BPF_REG_0 || 10308 insn->dst_reg != BPF_REG_0 || 10309 class == BPF_JMP32) { 10310 verbose(env, "BPF_JA uses reserved fields\n"); 10311 return -EINVAL; 10312 } 10313 10314 env->insn_idx += insn->off + 1; 10315 continue; 10316 10317 } else if (opcode == BPF_EXIT) { 10318 if (BPF_SRC(insn->code) != BPF_K || 10319 insn->imm != 0 || 10320 insn->src_reg != BPF_REG_0 || 10321 insn->dst_reg != BPF_REG_0 || 10322 class == BPF_JMP32) { 10323 verbose(env, "BPF_EXIT uses reserved fields\n"); 10324 return -EINVAL; 10325 } 10326 10327 if (env->cur_state->active_spin_lock) { 10328 verbose(env, "bpf_spin_unlock is missing\n"); 10329 return -EINVAL; 10330 } 10331 10332 if (state->curframe) { 10333 /* exit from nested function */ 10334 err = prepare_func_exit(env, &env->insn_idx); 10335 if (err) 10336 return err; 10337 do_print_state = true; 10338 continue; 10339 } 10340 10341 err = check_reference_leak(env); 10342 if (err) 10343 return err; 10344 10345 err = check_return_code(env); 10346 if (err) 10347 return err; 10348 process_bpf_exit: 10349 update_branch_counts(env, env->cur_state); 10350 err = pop_stack(env, &prev_insn_idx, 10351 &env->insn_idx, pop_log); 10352 if (err < 0) { 10353 if (err != -ENOENT) 10354 return err; 10355 break; 10356 } else { 10357 do_print_state = true; 10358 continue; 10359 } 10360 } else { 10361 err = check_cond_jmp_op(env, insn, &env->insn_idx); 10362 if (err) 10363 return err; 10364 } 10365 } else if (class == BPF_LD) { 10366 u8 mode = BPF_MODE(insn->code); 10367 10368 if (mode == BPF_ABS || mode == BPF_IND) { 10369 err = check_ld_abs(env, insn); 10370 if (err) 10371 return err; 10372 10373 } else if (mode == BPF_IMM) { 10374 err = check_ld_imm(env, insn); 10375 if (err) 10376 return err; 10377 10378 env->insn_idx++; 10379 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 10380 } else { 10381 verbose(env, "invalid BPF_LD mode\n"); 10382 return -EINVAL; 10383 } 10384 } else { 10385 verbose(env, "unknown insn class %d\n", class); 10386 return -EINVAL; 10387 } 10388 10389 env->insn_idx++; 10390 } 10391 10392 return 0; 10393 } 10394 10395 static int find_btf_percpu_datasec(struct btf *btf) 10396 { 10397 const struct btf_type *t; 10398 const char *tname; 10399 int i, n; 10400 10401 /* 10402 * Both vmlinux and module each have their own ".data..percpu" 10403 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 10404 * types to look at only module's own BTF types. 10405 */ 10406 n = btf_nr_types(btf); 10407 if (btf_is_module(btf)) 10408 i = btf_nr_types(btf_vmlinux); 10409 else 10410 i = 1; 10411 10412 for(; i < n; i++) { 10413 t = btf_type_by_id(btf, i); 10414 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 10415 continue; 10416 10417 tname = btf_name_by_offset(btf, t->name_off); 10418 if (!strcmp(tname, ".data..percpu")) 10419 return i; 10420 } 10421 10422 return -ENOENT; 10423 } 10424 10425 /* replace pseudo btf_id with kernel symbol address */ 10426 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 10427 struct bpf_insn *insn, 10428 struct bpf_insn_aux_data *aux) 10429 { 10430 const struct btf_var_secinfo *vsi; 10431 const struct btf_type *datasec; 10432 struct btf_mod_pair *btf_mod; 10433 const struct btf_type *t; 10434 const char *sym_name; 10435 bool percpu = false; 10436 u32 type, id = insn->imm; 10437 struct btf *btf; 10438 s32 datasec_id; 10439 u64 addr; 10440 int i, btf_fd, err; 10441 10442 btf_fd = insn[1].imm; 10443 if (btf_fd) { 10444 btf = btf_get_by_fd(btf_fd); 10445 if (IS_ERR(btf)) { 10446 verbose(env, "invalid module BTF object FD specified.\n"); 10447 return -EINVAL; 10448 } 10449 } else { 10450 if (!btf_vmlinux) { 10451 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 10452 return -EINVAL; 10453 } 10454 btf = btf_vmlinux; 10455 btf_get(btf); 10456 } 10457 10458 t = btf_type_by_id(btf, id); 10459 if (!t) { 10460 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 10461 err = -ENOENT; 10462 goto err_put; 10463 } 10464 10465 if (!btf_type_is_var(t)) { 10466 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id); 10467 err = -EINVAL; 10468 goto err_put; 10469 } 10470 10471 sym_name = btf_name_by_offset(btf, t->name_off); 10472 addr = kallsyms_lookup_name(sym_name); 10473 if (!addr) { 10474 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 10475 sym_name); 10476 err = -ENOENT; 10477 goto err_put; 10478 } 10479 10480 datasec_id = find_btf_percpu_datasec(btf); 10481 if (datasec_id > 0) { 10482 datasec = btf_type_by_id(btf, datasec_id); 10483 for_each_vsi(i, datasec, vsi) { 10484 if (vsi->type == id) { 10485 percpu = true; 10486 break; 10487 } 10488 } 10489 } 10490 10491 insn[0].imm = (u32)addr; 10492 insn[1].imm = addr >> 32; 10493 10494 type = t->type; 10495 t = btf_type_skip_modifiers(btf, type, NULL); 10496 if (percpu) { 10497 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID; 10498 aux->btf_var.btf = btf; 10499 aux->btf_var.btf_id = type; 10500 } else if (!btf_type_is_struct(t)) { 10501 const struct btf_type *ret; 10502 const char *tname; 10503 u32 tsize; 10504 10505 /* resolve the type size of ksym. */ 10506 ret = btf_resolve_size(btf, t, &tsize); 10507 if (IS_ERR(ret)) { 10508 tname = btf_name_by_offset(btf, t->name_off); 10509 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 10510 tname, PTR_ERR(ret)); 10511 err = -EINVAL; 10512 goto err_put; 10513 } 10514 aux->btf_var.reg_type = PTR_TO_MEM; 10515 aux->btf_var.mem_size = tsize; 10516 } else { 10517 aux->btf_var.reg_type = PTR_TO_BTF_ID; 10518 aux->btf_var.btf = btf; 10519 aux->btf_var.btf_id = type; 10520 } 10521 10522 /* check whether we recorded this BTF (and maybe module) already */ 10523 for (i = 0; i < env->used_btf_cnt; i++) { 10524 if (env->used_btfs[i].btf == btf) { 10525 btf_put(btf); 10526 return 0; 10527 } 10528 } 10529 10530 if (env->used_btf_cnt >= MAX_USED_BTFS) { 10531 err = -E2BIG; 10532 goto err_put; 10533 } 10534 10535 btf_mod = &env->used_btfs[env->used_btf_cnt]; 10536 btf_mod->btf = btf; 10537 btf_mod->module = NULL; 10538 10539 /* if we reference variables from kernel module, bump its refcount */ 10540 if (btf_is_module(btf)) { 10541 btf_mod->module = btf_try_get_module(btf); 10542 if (!btf_mod->module) { 10543 err = -ENXIO; 10544 goto err_put; 10545 } 10546 } 10547 10548 env->used_btf_cnt++; 10549 10550 return 0; 10551 err_put: 10552 btf_put(btf); 10553 return err; 10554 } 10555 10556 static int check_map_prealloc(struct bpf_map *map) 10557 { 10558 return (map->map_type != BPF_MAP_TYPE_HASH && 10559 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 10560 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || 10561 !(map->map_flags & BPF_F_NO_PREALLOC); 10562 } 10563 10564 static bool is_tracing_prog_type(enum bpf_prog_type type) 10565 { 10566 switch (type) { 10567 case BPF_PROG_TYPE_KPROBE: 10568 case BPF_PROG_TYPE_TRACEPOINT: 10569 case BPF_PROG_TYPE_PERF_EVENT: 10570 case BPF_PROG_TYPE_RAW_TRACEPOINT: 10571 return true; 10572 default: 10573 return false; 10574 } 10575 } 10576 10577 static bool is_preallocated_map(struct bpf_map *map) 10578 { 10579 if (!check_map_prealloc(map)) 10580 return false; 10581 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) 10582 return false; 10583 return true; 10584 } 10585 10586 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 10587 struct bpf_map *map, 10588 struct bpf_prog *prog) 10589 10590 { 10591 enum bpf_prog_type prog_type = resolve_prog_type(prog); 10592 /* 10593 * Validate that trace type programs use preallocated hash maps. 10594 * 10595 * For programs attached to PERF events this is mandatory as the 10596 * perf NMI can hit any arbitrary code sequence. 10597 * 10598 * All other trace types using preallocated hash maps are unsafe as 10599 * well because tracepoint or kprobes can be inside locked regions 10600 * of the memory allocator or at a place where a recursion into the 10601 * memory allocator would see inconsistent state. 10602 * 10603 * On RT enabled kernels run-time allocation of all trace type 10604 * programs is strictly prohibited due to lock type constraints. On 10605 * !RT kernels it is allowed for backwards compatibility reasons for 10606 * now, but warnings are emitted so developers are made aware of 10607 * the unsafety and can fix their programs before this is enforced. 10608 */ 10609 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) { 10610 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) { 10611 verbose(env, "perf_event programs can only use preallocated hash map\n"); 10612 return -EINVAL; 10613 } 10614 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 10615 verbose(env, "trace type programs can only use preallocated hash map\n"); 10616 return -EINVAL; 10617 } 10618 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n"); 10619 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n"); 10620 } 10621 10622 if (map_value_has_spin_lock(map)) { 10623 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 10624 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 10625 return -EINVAL; 10626 } 10627 10628 if (is_tracing_prog_type(prog_type)) { 10629 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 10630 return -EINVAL; 10631 } 10632 10633 if (prog->aux->sleepable) { 10634 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 10635 return -EINVAL; 10636 } 10637 } 10638 10639 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) && 10640 !bpf_offload_prog_map_match(prog, map)) { 10641 verbose(env, "offload device mismatch between prog and map\n"); 10642 return -EINVAL; 10643 } 10644 10645 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 10646 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 10647 return -EINVAL; 10648 } 10649 10650 if (prog->aux->sleepable) 10651 switch (map->map_type) { 10652 case BPF_MAP_TYPE_HASH: 10653 case BPF_MAP_TYPE_LRU_HASH: 10654 case BPF_MAP_TYPE_ARRAY: 10655 case BPF_MAP_TYPE_PERCPU_HASH: 10656 case BPF_MAP_TYPE_PERCPU_ARRAY: 10657 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 10658 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 10659 case BPF_MAP_TYPE_HASH_OF_MAPS: 10660 if (!is_preallocated_map(map)) { 10661 verbose(env, 10662 "Sleepable programs can only use preallocated maps\n"); 10663 return -EINVAL; 10664 } 10665 break; 10666 case BPF_MAP_TYPE_RINGBUF: 10667 break; 10668 default: 10669 verbose(env, 10670 "Sleepable programs can only use array, hash, and ringbuf maps\n"); 10671 return -EINVAL; 10672 } 10673 10674 return 0; 10675 } 10676 10677 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 10678 { 10679 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 10680 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 10681 } 10682 10683 /* find and rewrite pseudo imm in ld_imm64 instructions: 10684 * 10685 * 1. if it accesses map FD, replace it with actual map pointer. 10686 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 10687 * 10688 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 10689 */ 10690 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 10691 { 10692 struct bpf_insn *insn = env->prog->insnsi; 10693 int insn_cnt = env->prog->len; 10694 int i, j, err; 10695 10696 err = bpf_prog_calc_tag(env->prog); 10697 if (err) 10698 return err; 10699 10700 for (i = 0; i < insn_cnt; i++, insn++) { 10701 if (BPF_CLASS(insn->code) == BPF_LDX && 10702 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 10703 verbose(env, "BPF_LDX uses reserved fields\n"); 10704 return -EINVAL; 10705 } 10706 10707 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 10708 struct bpf_insn_aux_data *aux; 10709 struct bpf_map *map; 10710 struct fd f; 10711 u64 addr; 10712 10713 if (i == insn_cnt - 1 || insn[1].code != 0 || 10714 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 10715 insn[1].off != 0) { 10716 verbose(env, "invalid bpf_ld_imm64 insn\n"); 10717 return -EINVAL; 10718 } 10719 10720 if (insn[0].src_reg == 0) 10721 /* valid generic load 64-bit imm */ 10722 goto next_insn; 10723 10724 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 10725 aux = &env->insn_aux_data[i]; 10726 err = check_pseudo_btf_id(env, insn, aux); 10727 if (err) 10728 return err; 10729 goto next_insn; 10730 } 10731 10732 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 10733 aux = &env->insn_aux_data[i]; 10734 aux->ptr_type = PTR_TO_FUNC; 10735 goto next_insn; 10736 } 10737 10738 /* In final convert_pseudo_ld_imm64() step, this is 10739 * converted into regular 64-bit imm load insn. 10740 */ 10741 if ((insn[0].src_reg != BPF_PSEUDO_MAP_FD && 10742 insn[0].src_reg != BPF_PSEUDO_MAP_VALUE) || 10743 (insn[0].src_reg == BPF_PSEUDO_MAP_FD && 10744 insn[1].imm != 0)) { 10745 verbose(env, 10746 "unrecognized bpf_ld_imm64 insn\n"); 10747 return -EINVAL; 10748 } 10749 10750 f = fdget(insn[0].imm); 10751 map = __bpf_map_get(f); 10752 if (IS_ERR(map)) { 10753 verbose(env, "fd %d is not pointing to valid bpf_map\n", 10754 insn[0].imm); 10755 return PTR_ERR(map); 10756 } 10757 10758 err = check_map_prog_compatibility(env, map, env->prog); 10759 if (err) { 10760 fdput(f); 10761 return err; 10762 } 10763 10764 aux = &env->insn_aux_data[i]; 10765 if (insn->src_reg == BPF_PSEUDO_MAP_FD) { 10766 addr = (unsigned long)map; 10767 } else { 10768 u32 off = insn[1].imm; 10769 10770 if (off >= BPF_MAX_VAR_OFF) { 10771 verbose(env, "direct value offset of %u is not allowed\n", off); 10772 fdput(f); 10773 return -EINVAL; 10774 } 10775 10776 if (!map->ops->map_direct_value_addr) { 10777 verbose(env, "no direct value access support for this map type\n"); 10778 fdput(f); 10779 return -EINVAL; 10780 } 10781 10782 err = map->ops->map_direct_value_addr(map, &addr, off); 10783 if (err) { 10784 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 10785 map->value_size, off); 10786 fdput(f); 10787 return err; 10788 } 10789 10790 aux->map_off = off; 10791 addr += off; 10792 } 10793 10794 insn[0].imm = (u32)addr; 10795 insn[1].imm = addr >> 32; 10796 10797 /* check whether we recorded this map already */ 10798 for (j = 0; j < env->used_map_cnt; j++) { 10799 if (env->used_maps[j] == map) { 10800 aux->map_index = j; 10801 fdput(f); 10802 goto next_insn; 10803 } 10804 } 10805 10806 if (env->used_map_cnt >= MAX_USED_MAPS) { 10807 fdput(f); 10808 return -E2BIG; 10809 } 10810 10811 /* hold the map. If the program is rejected by verifier, 10812 * the map will be released by release_maps() or it 10813 * will be used by the valid program until it's unloaded 10814 * and all maps are released in free_used_maps() 10815 */ 10816 bpf_map_inc(map); 10817 10818 aux->map_index = env->used_map_cnt; 10819 env->used_maps[env->used_map_cnt++] = map; 10820 10821 if (bpf_map_is_cgroup_storage(map) && 10822 bpf_cgroup_storage_assign(env->prog->aux, map)) { 10823 verbose(env, "only one cgroup storage of each type is allowed\n"); 10824 fdput(f); 10825 return -EBUSY; 10826 } 10827 10828 fdput(f); 10829 next_insn: 10830 insn++; 10831 i++; 10832 continue; 10833 } 10834 10835 /* Basic sanity check before we invest more work here. */ 10836 if (!bpf_opcode_in_insntable(insn->code)) { 10837 verbose(env, "unknown opcode %02x\n", insn->code); 10838 return -EINVAL; 10839 } 10840 } 10841 10842 /* now all pseudo BPF_LD_IMM64 instructions load valid 10843 * 'struct bpf_map *' into a register instead of user map_fd. 10844 * These pointers will be used later by verifier to validate map access. 10845 */ 10846 return 0; 10847 } 10848 10849 /* drop refcnt of maps used by the rejected program */ 10850 static void release_maps(struct bpf_verifier_env *env) 10851 { 10852 __bpf_free_used_maps(env->prog->aux, env->used_maps, 10853 env->used_map_cnt); 10854 } 10855 10856 /* drop refcnt of maps used by the rejected program */ 10857 static void release_btfs(struct bpf_verifier_env *env) 10858 { 10859 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 10860 env->used_btf_cnt); 10861 } 10862 10863 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 10864 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 10865 { 10866 struct bpf_insn *insn = env->prog->insnsi; 10867 int insn_cnt = env->prog->len; 10868 int i; 10869 10870 for (i = 0; i < insn_cnt; i++, insn++) { 10871 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 10872 continue; 10873 if (insn->src_reg == BPF_PSEUDO_FUNC) 10874 continue; 10875 insn->src_reg = 0; 10876 } 10877 } 10878 10879 /* single env->prog->insni[off] instruction was replaced with the range 10880 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 10881 * [0, off) and [off, end) to new locations, so the patched range stays zero 10882 */ 10883 static int adjust_insn_aux_data(struct bpf_verifier_env *env, 10884 struct bpf_prog *new_prog, u32 off, u32 cnt) 10885 { 10886 struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; 10887 struct bpf_insn *insn = new_prog->insnsi; 10888 u32 prog_len; 10889 int i; 10890 10891 /* aux info at OFF always needs adjustment, no matter fast path 10892 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 10893 * original insn at old prog. 10894 */ 10895 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 10896 10897 if (cnt == 1) 10898 return 0; 10899 prog_len = new_prog->len; 10900 new_data = vzalloc(array_size(prog_len, 10901 sizeof(struct bpf_insn_aux_data))); 10902 if (!new_data) 10903 return -ENOMEM; 10904 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 10905 memcpy(new_data + off + cnt - 1, old_data + off, 10906 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 10907 for (i = off; i < off + cnt - 1; i++) { 10908 new_data[i].seen = env->pass_cnt; 10909 new_data[i].zext_dst = insn_has_def32(env, insn + i); 10910 } 10911 env->insn_aux_data = new_data; 10912 vfree(old_data); 10913 return 0; 10914 } 10915 10916 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 10917 { 10918 int i; 10919 10920 if (len == 1) 10921 return; 10922 /* NOTE: fake 'exit' subprog should be updated as well. */ 10923 for (i = 0; i <= env->subprog_cnt; i++) { 10924 if (env->subprog_info[i].start <= off) 10925 continue; 10926 env->subprog_info[i].start += len - 1; 10927 } 10928 } 10929 10930 static void adjust_poke_descs(struct bpf_prog *prog, u32 len) 10931 { 10932 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 10933 int i, sz = prog->aux->size_poke_tab; 10934 struct bpf_jit_poke_descriptor *desc; 10935 10936 for (i = 0; i < sz; i++) { 10937 desc = &tab[i]; 10938 desc->insn_idx += len - 1; 10939 } 10940 } 10941 10942 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 10943 const struct bpf_insn *patch, u32 len) 10944 { 10945 struct bpf_prog *new_prog; 10946 10947 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 10948 if (IS_ERR(new_prog)) { 10949 if (PTR_ERR(new_prog) == -ERANGE) 10950 verbose(env, 10951 "insn %d cannot be patched due to 16-bit range\n", 10952 env->insn_aux_data[off].orig_idx); 10953 return NULL; 10954 } 10955 if (adjust_insn_aux_data(env, new_prog, off, len)) 10956 return NULL; 10957 adjust_subprog_starts(env, off, len); 10958 adjust_poke_descs(new_prog, len); 10959 return new_prog; 10960 } 10961 10962 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 10963 u32 off, u32 cnt) 10964 { 10965 int i, j; 10966 10967 /* find first prog starting at or after off (first to remove) */ 10968 for (i = 0; i < env->subprog_cnt; i++) 10969 if (env->subprog_info[i].start >= off) 10970 break; 10971 /* find first prog starting at or after off + cnt (first to stay) */ 10972 for (j = i; j < env->subprog_cnt; j++) 10973 if (env->subprog_info[j].start >= off + cnt) 10974 break; 10975 /* if j doesn't start exactly at off + cnt, we are just removing 10976 * the front of previous prog 10977 */ 10978 if (env->subprog_info[j].start != off + cnt) 10979 j--; 10980 10981 if (j > i) { 10982 struct bpf_prog_aux *aux = env->prog->aux; 10983 int move; 10984 10985 /* move fake 'exit' subprog as well */ 10986 move = env->subprog_cnt + 1 - j; 10987 10988 memmove(env->subprog_info + i, 10989 env->subprog_info + j, 10990 sizeof(*env->subprog_info) * move); 10991 env->subprog_cnt -= j - i; 10992 10993 /* remove func_info */ 10994 if (aux->func_info) { 10995 move = aux->func_info_cnt - j; 10996 10997 memmove(aux->func_info + i, 10998 aux->func_info + j, 10999 sizeof(*aux->func_info) * move); 11000 aux->func_info_cnt -= j - i; 11001 /* func_info->insn_off is set after all code rewrites, 11002 * in adjust_btf_func() - no need to adjust 11003 */ 11004 } 11005 } else { 11006 /* convert i from "first prog to remove" to "first to adjust" */ 11007 if (env->subprog_info[i].start == off) 11008 i++; 11009 } 11010 11011 /* update fake 'exit' subprog as well */ 11012 for (; i <= env->subprog_cnt; i++) 11013 env->subprog_info[i].start -= cnt; 11014 11015 return 0; 11016 } 11017 11018 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 11019 u32 cnt) 11020 { 11021 struct bpf_prog *prog = env->prog; 11022 u32 i, l_off, l_cnt, nr_linfo; 11023 struct bpf_line_info *linfo; 11024 11025 nr_linfo = prog->aux->nr_linfo; 11026 if (!nr_linfo) 11027 return 0; 11028 11029 linfo = prog->aux->linfo; 11030 11031 /* find first line info to remove, count lines to be removed */ 11032 for (i = 0; i < nr_linfo; i++) 11033 if (linfo[i].insn_off >= off) 11034 break; 11035 11036 l_off = i; 11037 l_cnt = 0; 11038 for (; i < nr_linfo; i++) 11039 if (linfo[i].insn_off < off + cnt) 11040 l_cnt++; 11041 else 11042 break; 11043 11044 /* First live insn doesn't match first live linfo, it needs to "inherit" 11045 * last removed linfo. prog is already modified, so prog->len == off 11046 * means no live instructions after (tail of the program was removed). 11047 */ 11048 if (prog->len != off && l_cnt && 11049 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 11050 l_cnt--; 11051 linfo[--i].insn_off = off + cnt; 11052 } 11053 11054 /* remove the line info which refer to the removed instructions */ 11055 if (l_cnt) { 11056 memmove(linfo + l_off, linfo + i, 11057 sizeof(*linfo) * (nr_linfo - i)); 11058 11059 prog->aux->nr_linfo -= l_cnt; 11060 nr_linfo = prog->aux->nr_linfo; 11061 } 11062 11063 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 11064 for (i = l_off; i < nr_linfo; i++) 11065 linfo[i].insn_off -= cnt; 11066 11067 /* fix up all subprogs (incl. 'exit') which start >= off */ 11068 for (i = 0; i <= env->subprog_cnt; i++) 11069 if (env->subprog_info[i].linfo_idx > l_off) { 11070 /* program may have started in the removed region but 11071 * may not be fully removed 11072 */ 11073 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 11074 env->subprog_info[i].linfo_idx -= l_cnt; 11075 else 11076 env->subprog_info[i].linfo_idx = l_off; 11077 } 11078 11079 return 0; 11080 } 11081 11082 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 11083 { 11084 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11085 unsigned int orig_prog_len = env->prog->len; 11086 int err; 11087 11088 if (bpf_prog_is_dev_bound(env->prog->aux)) 11089 bpf_prog_offload_remove_insns(env, off, cnt); 11090 11091 err = bpf_remove_insns(env->prog, off, cnt); 11092 if (err) 11093 return err; 11094 11095 err = adjust_subprog_starts_after_remove(env, off, cnt); 11096 if (err) 11097 return err; 11098 11099 err = bpf_adj_linfo_after_remove(env, off, cnt); 11100 if (err) 11101 return err; 11102 11103 memmove(aux_data + off, aux_data + off + cnt, 11104 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 11105 11106 return 0; 11107 } 11108 11109 /* The verifier does more data flow analysis than llvm and will not 11110 * explore branches that are dead at run time. Malicious programs can 11111 * have dead code too. Therefore replace all dead at-run-time code 11112 * with 'ja -1'. 11113 * 11114 * Just nops are not optimal, e.g. if they would sit at the end of the 11115 * program and through another bug we would manage to jump there, then 11116 * we'd execute beyond program memory otherwise. Returning exception 11117 * code also wouldn't work since we can have subprogs where the dead 11118 * code could be located. 11119 */ 11120 static void sanitize_dead_code(struct bpf_verifier_env *env) 11121 { 11122 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11123 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 11124 struct bpf_insn *insn = env->prog->insnsi; 11125 const int insn_cnt = env->prog->len; 11126 int i; 11127 11128 for (i = 0; i < insn_cnt; i++) { 11129 if (aux_data[i].seen) 11130 continue; 11131 memcpy(insn + i, &trap, sizeof(trap)); 11132 } 11133 } 11134 11135 static bool insn_is_cond_jump(u8 code) 11136 { 11137 u8 op; 11138 11139 if (BPF_CLASS(code) == BPF_JMP32) 11140 return true; 11141 11142 if (BPF_CLASS(code) != BPF_JMP) 11143 return false; 11144 11145 op = BPF_OP(code); 11146 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 11147 } 11148 11149 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 11150 { 11151 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11152 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 11153 struct bpf_insn *insn = env->prog->insnsi; 11154 const int insn_cnt = env->prog->len; 11155 int i; 11156 11157 for (i = 0; i < insn_cnt; i++, insn++) { 11158 if (!insn_is_cond_jump(insn->code)) 11159 continue; 11160 11161 if (!aux_data[i + 1].seen) 11162 ja.off = insn->off; 11163 else if (!aux_data[i + 1 + insn->off].seen) 11164 ja.off = 0; 11165 else 11166 continue; 11167 11168 if (bpf_prog_is_dev_bound(env->prog->aux)) 11169 bpf_prog_offload_replace_insn(env, i, &ja); 11170 11171 memcpy(insn, &ja, sizeof(ja)); 11172 } 11173 } 11174 11175 static int opt_remove_dead_code(struct bpf_verifier_env *env) 11176 { 11177 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 11178 int insn_cnt = env->prog->len; 11179 int i, err; 11180 11181 for (i = 0; i < insn_cnt; i++) { 11182 int j; 11183 11184 j = 0; 11185 while (i + j < insn_cnt && !aux_data[i + j].seen) 11186 j++; 11187 if (!j) 11188 continue; 11189 11190 err = verifier_remove_insns(env, i, j); 11191 if (err) 11192 return err; 11193 insn_cnt = env->prog->len; 11194 } 11195 11196 return 0; 11197 } 11198 11199 static int opt_remove_nops(struct bpf_verifier_env *env) 11200 { 11201 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 11202 struct bpf_insn *insn = env->prog->insnsi; 11203 int insn_cnt = env->prog->len; 11204 int i, err; 11205 11206 for (i = 0; i < insn_cnt; i++) { 11207 if (memcmp(&insn[i], &ja, sizeof(ja))) 11208 continue; 11209 11210 err = verifier_remove_insns(env, i, 1); 11211 if (err) 11212 return err; 11213 insn_cnt--; 11214 i--; 11215 } 11216 11217 return 0; 11218 } 11219 11220 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 11221 const union bpf_attr *attr) 11222 { 11223 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 11224 struct bpf_insn_aux_data *aux = env->insn_aux_data; 11225 int i, patch_len, delta = 0, len = env->prog->len; 11226 struct bpf_insn *insns = env->prog->insnsi; 11227 struct bpf_prog *new_prog; 11228 bool rnd_hi32; 11229 11230 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 11231 zext_patch[1] = BPF_ZEXT_REG(0); 11232 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 11233 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 11234 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 11235 for (i = 0; i < len; i++) { 11236 int adj_idx = i + delta; 11237 struct bpf_insn insn; 11238 u8 load_reg; 11239 11240 insn = insns[adj_idx]; 11241 if (!aux[adj_idx].zext_dst) { 11242 u8 code, class; 11243 u32 imm_rnd; 11244 11245 if (!rnd_hi32) 11246 continue; 11247 11248 code = insn.code; 11249 class = BPF_CLASS(code); 11250 if (insn_no_def(&insn)) 11251 continue; 11252 11253 /* NOTE: arg "reg" (the fourth one) is only used for 11254 * BPF_STX which has been ruled out in above 11255 * check, it is safe to pass NULL here. 11256 */ 11257 if (is_reg64(env, &insn, insn.dst_reg, NULL, DST_OP)) { 11258 if (class == BPF_LD && 11259 BPF_MODE(code) == BPF_IMM) 11260 i++; 11261 continue; 11262 } 11263 11264 /* ctx load could be transformed into wider load. */ 11265 if (class == BPF_LDX && 11266 aux[adj_idx].ptr_type == PTR_TO_CTX) 11267 continue; 11268 11269 imm_rnd = get_random_int(); 11270 rnd_hi32_patch[0] = insn; 11271 rnd_hi32_patch[1].imm = imm_rnd; 11272 rnd_hi32_patch[3].dst_reg = insn.dst_reg; 11273 patch = rnd_hi32_patch; 11274 patch_len = 4; 11275 goto apply_patch_buffer; 11276 } 11277 11278 if (!bpf_jit_needs_zext()) 11279 continue; 11280 11281 /* zext_dst means that we want to zero-extend whatever register 11282 * the insn defines, which is dst_reg most of the time, with 11283 * the notable exception of BPF_STX + BPF_ATOMIC + BPF_FETCH. 11284 */ 11285 if (BPF_CLASS(insn.code) == BPF_STX && 11286 BPF_MODE(insn.code) == BPF_ATOMIC) { 11287 /* BPF_STX + BPF_ATOMIC insns without BPF_FETCH do not 11288 * define any registers, therefore zext_dst cannot be 11289 * set. 11290 */ 11291 if (WARN_ON(!(insn.imm & BPF_FETCH))) 11292 return -EINVAL; 11293 load_reg = insn.imm == BPF_CMPXCHG ? BPF_REG_0 11294 : insn.src_reg; 11295 } else { 11296 load_reg = insn.dst_reg; 11297 } 11298 11299 zext_patch[0] = insn; 11300 zext_patch[1].dst_reg = load_reg; 11301 zext_patch[1].src_reg = load_reg; 11302 patch = zext_patch; 11303 patch_len = 2; 11304 apply_patch_buffer: 11305 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 11306 if (!new_prog) 11307 return -ENOMEM; 11308 env->prog = new_prog; 11309 insns = new_prog->insnsi; 11310 aux = env->insn_aux_data; 11311 delta += patch_len - 1; 11312 } 11313 11314 return 0; 11315 } 11316 11317 /* convert load instructions that access fields of a context type into a 11318 * sequence of instructions that access fields of the underlying structure: 11319 * struct __sk_buff -> struct sk_buff 11320 * struct bpf_sock_ops -> struct sock 11321 */ 11322 static int convert_ctx_accesses(struct bpf_verifier_env *env) 11323 { 11324 const struct bpf_verifier_ops *ops = env->ops; 11325 int i, cnt, size, ctx_field_size, delta = 0; 11326 const int insn_cnt = env->prog->len; 11327 struct bpf_insn insn_buf[16], *insn; 11328 u32 target_size, size_default, off; 11329 struct bpf_prog *new_prog; 11330 enum bpf_access_type type; 11331 bool is_narrower_load; 11332 11333 if (ops->gen_prologue || env->seen_direct_write) { 11334 if (!ops->gen_prologue) { 11335 verbose(env, "bpf verifier is misconfigured\n"); 11336 return -EINVAL; 11337 } 11338 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 11339 env->prog); 11340 if (cnt >= ARRAY_SIZE(insn_buf)) { 11341 verbose(env, "bpf verifier is misconfigured\n"); 11342 return -EINVAL; 11343 } else if (cnt) { 11344 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 11345 if (!new_prog) 11346 return -ENOMEM; 11347 11348 env->prog = new_prog; 11349 delta += cnt - 1; 11350 } 11351 } 11352 11353 if (bpf_prog_is_dev_bound(env->prog->aux)) 11354 return 0; 11355 11356 insn = env->prog->insnsi + delta; 11357 11358 for (i = 0; i < insn_cnt; i++, insn++) { 11359 bpf_convert_ctx_access_t convert_ctx_access; 11360 11361 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 11362 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 11363 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 11364 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) 11365 type = BPF_READ; 11366 else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 11367 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 11368 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 11369 insn->code == (BPF_STX | BPF_MEM | BPF_DW)) 11370 type = BPF_WRITE; 11371 else 11372 continue; 11373 11374 if (type == BPF_WRITE && 11375 env->insn_aux_data[i + delta].sanitize_stack_off) { 11376 struct bpf_insn patch[] = { 11377 /* Sanitize suspicious stack slot with zero. 11378 * There are no memory dependencies for this store, 11379 * since it's only using frame pointer and immediate 11380 * constant of zero 11381 */ 11382 BPF_ST_MEM(BPF_DW, BPF_REG_FP, 11383 env->insn_aux_data[i + delta].sanitize_stack_off, 11384 0), 11385 /* the original STX instruction will immediately 11386 * overwrite the same stack slot with appropriate value 11387 */ 11388 *insn, 11389 }; 11390 11391 cnt = ARRAY_SIZE(patch); 11392 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 11393 if (!new_prog) 11394 return -ENOMEM; 11395 11396 delta += cnt - 1; 11397 env->prog = new_prog; 11398 insn = new_prog->insnsi + i + delta; 11399 continue; 11400 } 11401 11402 switch (env->insn_aux_data[i + delta].ptr_type) { 11403 case PTR_TO_CTX: 11404 if (!ops->convert_ctx_access) 11405 continue; 11406 convert_ctx_access = ops->convert_ctx_access; 11407 break; 11408 case PTR_TO_SOCKET: 11409 case PTR_TO_SOCK_COMMON: 11410 convert_ctx_access = bpf_sock_convert_ctx_access; 11411 break; 11412 case PTR_TO_TCP_SOCK: 11413 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 11414 break; 11415 case PTR_TO_XDP_SOCK: 11416 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 11417 break; 11418 case PTR_TO_BTF_ID: 11419 if (type == BPF_READ) { 11420 insn->code = BPF_LDX | BPF_PROBE_MEM | 11421 BPF_SIZE((insn)->code); 11422 env->prog->aux->num_exentries++; 11423 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) { 11424 verbose(env, "Writes through BTF pointers are not allowed\n"); 11425 return -EINVAL; 11426 } 11427 continue; 11428 default: 11429 continue; 11430 } 11431 11432 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 11433 size = BPF_LDST_BYTES(insn); 11434 11435 /* If the read access is a narrower load of the field, 11436 * convert to a 4/8-byte load, to minimum program type specific 11437 * convert_ctx_access changes. If conversion is successful, 11438 * we will apply proper mask to the result. 11439 */ 11440 is_narrower_load = size < ctx_field_size; 11441 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 11442 off = insn->off; 11443 if (is_narrower_load) { 11444 u8 size_code; 11445 11446 if (type == BPF_WRITE) { 11447 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 11448 return -EINVAL; 11449 } 11450 11451 size_code = BPF_H; 11452 if (ctx_field_size == 4) 11453 size_code = BPF_W; 11454 else if (ctx_field_size == 8) 11455 size_code = BPF_DW; 11456 11457 insn->off = off & ~(size_default - 1); 11458 insn->code = BPF_LDX | BPF_MEM | size_code; 11459 } 11460 11461 target_size = 0; 11462 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 11463 &target_size); 11464 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 11465 (ctx_field_size && !target_size)) { 11466 verbose(env, "bpf verifier is misconfigured\n"); 11467 return -EINVAL; 11468 } 11469 11470 if (is_narrower_load && size < target_size) { 11471 u8 shift = bpf_ctx_narrow_access_offset( 11472 off, size, size_default) * 8; 11473 if (ctx_field_size <= 4) { 11474 if (shift) 11475 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 11476 insn->dst_reg, 11477 shift); 11478 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 11479 (1 << size * 8) - 1); 11480 } else { 11481 if (shift) 11482 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 11483 insn->dst_reg, 11484 shift); 11485 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 11486 (1ULL << size * 8) - 1); 11487 } 11488 } 11489 11490 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 11491 if (!new_prog) 11492 return -ENOMEM; 11493 11494 delta += cnt - 1; 11495 11496 /* keep walking new program and skip insns we just inserted */ 11497 env->prog = new_prog; 11498 insn = new_prog->insnsi + i + delta; 11499 } 11500 11501 return 0; 11502 } 11503 11504 static int jit_subprogs(struct bpf_verifier_env *env) 11505 { 11506 struct bpf_prog *prog = env->prog, **func, *tmp; 11507 int i, j, subprog_start, subprog_end = 0, len, subprog; 11508 struct bpf_map *map_ptr; 11509 struct bpf_insn *insn; 11510 void *old_bpf_func; 11511 int err, num_exentries; 11512 11513 if (env->subprog_cnt <= 1) 11514 return 0; 11515 11516 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 11517 if (bpf_pseudo_func(insn)) { 11518 env->insn_aux_data[i].call_imm = insn->imm; 11519 /* subprog is encoded in insn[1].imm */ 11520 continue; 11521 } 11522 11523 if (!bpf_pseudo_call(insn)) 11524 continue; 11525 /* Upon error here we cannot fall back to interpreter but 11526 * need a hard reject of the program. Thus -EFAULT is 11527 * propagated in any case. 11528 */ 11529 subprog = find_subprog(env, i + insn->imm + 1); 11530 if (subprog < 0) { 11531 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 11532 i + insn->imm + 1); 11533 return -EFAULT; 11534 } 11535 /* temporarily remember subprog id inside insn instead of 11536 * aux_data, since next loop will split up all insns into funcs 11537 */ 11538 insn->off = subprog; 11539 /* remember original imm in case JIT fails and fallback 11540 * to interpreter will be needed 11541 */ 11542 env->insn_aux_data[i].call_imm = insn->imm; 11543 /* point imm to __bpf_call_base+1 from JITs point of view */ 11544 insn->imm = 1; 11545 } 11546 11547 err = bpf_prog_alloc_jited_linfo(prog); 11548 if (err) 11549 goto out_undo_insn; 11550 11551 err = -ENOMEM; 11552 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 11553 if (!func) 11554 goto out_undo_insn; 11555 11556 for (i = 0; i < env->subprog_cnt; i++) { 11557 subprog_start = subprog_end; 11558 subprog_end = env->subprog_info[i + 1].start; 11559 11560 len = subprog_end - subprog_start; 11561 /* BPF_PROG_RUN doesn't call subprogs directly, 11562 * hence main prog stats include the runtime of subprogs. 11563 * subprogs don't have IDs and not reachable via prog_get_next_id 11564 * func[i]->stats will never be accessed and stays NULL 11565 */ 11566 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 11567 if (!func[i]) 11568 goto out_free; 11569 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 11570 len * sizeof(struct bpf_insn)); 11571 func[i]->type = prog->type; 11572 func[i]->len = len; 11573 if (bpf_prog_calc_tag(func[i])) 11574 goto out_free; 11575 func[i]->is_func = 1; 11576 func[i]->aux->func_idx = i; 11577 /* the btf and func_info will be freed only at prog->aux */ 11578 func[i]->aux->btf = prog->aux->btf; 11579 func[i]->aux->func_info = prog->aux->func_info; 11580 11581 for (j = 0; j < prog->aux->size_poke_tab; j++) { 11582 u32 insn_idx = prog->aux->poke_tab[j].insn_idx; 11583 int ret; 11584 11585 if (!(insn_idx >= subprog_start && 11586 insn_idx <= subprog_end)) 11587 continue; 11588 11589 ret = bpf_jit_add_poke_descriptor(func[i], 11590 &prog->aux->poke_tab[j]); 11591 if (ret < 0) { 11592 verbose(env, "adding tail call poke descriptor failed\n"); 11593 goto out_free; 11594 } 11595 11596 func[i]->insnsi[insn_idx - subprog_start].imm = ret + 1; 11597 11598 map_ptr = func[i]->aux->poke_tab[ret].tail_call.map; 11599 ret = map_ptr->ops->map_poke_track(map_ptr, func[i]->aux); 11600 if (ret < 0) { 11601 verbose(env, "tracking tail call prog failed\n"); 11602 goto out_free; 11603 } 11604 } 11605 11606 /* Use bpf_prog_F_tag to indicate functions in stack traces. 11607 * Long term would need debug info to populate names 11608 */ 11609 func[i]->aux->name[0] = 'F'; 11610 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 11611 func[i]->jit_requested = 1; 11612 func[i]->aux->linfo = prog->aux->linfo; 11613 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 11614 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 11615 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 11616 num_exentries = 0; 11617 insn = func[i]->insnsi; 11618 for (j = 0; j < func[i]->len; j++, insn++) { 11619 if (BPF_CLASS(insn->code) == BPF_LDX && 11620 BPF_MODE(insn->code) == BPF_PROBE_MEM) 11621 num_exentries++; 11622 } 11623 func[i]->aux->num_exentries = num_exentries; 11624 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 11625 func[i] = bpf_int_jit_compile(func[i]); 11626 if (!func[i]->jited) { 11627 err = -ENOTSUPP; 11628 goto out_free; 11629 } 11630 cond_resched(); 11631 } 11632 11633 /* Untrack main program's aux structs so that during map_poke_run() 11634 * we will not stumble upon the unfilled poke descriptors; each 11635 * of the main program's poke descs got distributed across subprogs 11636 * and got tracked onto map, so we are sure that none of them will 11637 * be missed after the operation below 11638 */ 11639 for (i = 0; i < prog->aux->size_poke_tab; i++) { 11640 map_ptr = prog->aux->poke_tab[i].tail_call.map; 11641 11642 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 11643 } 11644 11645 /* at this point all bpf functions were successfully JITed 11646 * now populate all bpf_calls with correct addresses and 11647 * run last pass of JIT 11648 */ 11649 for (i = 0; i < env->subprog_cnt; i++) { 11650 insn = func[i]->insnsi; 11651 for (j = 0; j < func[i]->len; j++, insn++) { 11652 if (bpf_pseudo_func(insn)) { 11653 subprog = insn[1].imm; 11654 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 11655 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 11656 continue; 11657 } 11658 if (!bpf_pseudo_call(insn)) 11659 continue; 11660 subprog = insn->off; 11661 insn->imm = BPF_CAST_CALL(func[subprog]->bpf_func) - 11662 __bpf_call_base; 11663 } 11664 11665 /* we use the aux data to keep a list of the start addresses 11666 * of the JITed images for each function in the program 11667 * 11668 * for some architectures, such as powerpc64, the imm field 11669 * might not be large enough to hold the offset of the start 11670 * address of the callee's JITed image from __bpf_call_base 11671 * 11672 * in such cases, we can lookup the start address of a callee 11673 * by using its subprog id, available from the off field of 11674 * the call instruction, as an index for this list 11675 */ 11676 func[i]->aux->func = func; 11677 func[i]->aux->func_cnt = env->subprog_cnt; 11678 } 11679 for (i = 0; i < env->subprog_cnt; i++) { 11680 old_bpf_func = func[i]->bpf_func; 11681 tmp = bpf_int_jit_compile(func[i]); 11682 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 11683 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 11684 err = -ENOTSUPP; 11685 goto out_free; 11686 } 11687 cond_resched(); 11688 } 11689 11690 /* finally lock prog and jit images for all functions and 11691 * populate kallsysm 11692 */ 11693 for (i = 0; i < env->subprog_cnt; i++) { 11694 bpf_prog_lock_ro(func[i]); 11695 bpf_prog_kallsyms_add(func[i]); 11696 } 11697 11698 /* Last step: make now unused interpreter insns from main 11699 * prog consistent for later dump requests, so they can 11700 * later look the same as if they were interpreted only. 11701 */ 11702 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 11703 if (bpf_pseudo_func(insn)) { 11704 insn[0].imm = env->insn_aux_data[i].call_imm; 11705 insn[1].imm = find_subprog(env, i + insn[0].imm + 1); 11706 continue; 11707 } 11708 if (!bpf_pseudo_call(insn)) 11709 continue; 11710 insn->off = env->insn_aux_data[i].call_imm; 11711 subprog = find_subprog(env, i + insn->off + 1); 11712 insn->imm = subprog; 11713 } 11714 11715 prog->jited = 1; 11716 prog->bpf_func = func[0]->bpf_func; 11717 prog->aux->func = func; 11718 prog->aux->func_cnt = env->subprog_cnt; 11719 bpf_prog_free_unused_jited_linfo(prog); 11720 return 0; 11721 out_free: 11722 for (i = 0; i < env->subprog_cnt; i++) { 11723 if (!func[i]) 11724 continue; 11725 11726 for (j = 0; j < func[i]->aux->size_poke_tab; j++) { 11727 map_ptr = func[i]->aux->poke_tab[j].tail_call.map; 11728 map_ptr->ops->map_poke_untrack(map_ptr, func[i]->aux); 11729 } 11730 bpf_jit_free(func[i]); 11731 } 11732 kfree(func); 11733 out_undo_insn: 11734 /* cleanup main prog to be interpreted */ 11735 prog->jit_requested = 0; 11736 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 11737 if (!bpf_pseudo_call(insn)) 11738 continue; 11739 insn->off = 0; 11740 insn->imm = env->insn_aux_data[i].call_imm; 11741 } 11742 bpf_prog_free_jited_linfo(prog); 11743 return err; 11744 } 11745 11746 static int fixup_call_args(struct bpf_verifier_env *env) 11747 { 11748 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 11749 struct bpf_prog *prog = env->prog; 11750 struct bpf_insn *insn = prog->insnsi; 11751 int i, depth; 11752 #endif 11753 int err = 0; 11754 11755 if (env->prog->jit_requested && 11756 !bpf_prog_is_dev_bound(env->prog->aux)) { 11757 err = jit_subprogs(env); 11758 if (err == 0) 11759 return 0; 11760 if (err == -EFAULT) 11761 return err; 11762 } 11763 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 11764 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 11765 /* When JIT fails the progs with bpf2bpf calls and tail_calls 11766 * have to be rejected, since interpreter doesn't support them yet. 11767 */ 11768 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 11769 return -EINVAL; 11770 } 11771 for (i = 0; i < prog->len; i++, insn++) { 11772 if (bpf_pseudo_func(insn)) { 11773 /* When JIT fails the progs with callback calls 11774 * have to be rejected, since interpreter doesn't support them yet. 11775 */ 11776 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 11777 return -EINVAL; 11778 } 11779 11780 if (!bpf_pseudo_call(insn)) 11781 continue; 11782 depth = get_callee_stack_depth(env, insn, i); 11783 if (depth < 0) 11784 return depth; 11785 bpf_patch_call_args(insn, depth); 11786 } 11787 err = 0; 11788 #endif 11789 return err; 11790 } 11791 11792 /* Do various post-verification rewrites in a single program pass. 11793 * These rewrites simplify JIT and interpreter implementations. 11794 */ 11795 static int do_misc_fixups(struct bpf_verifier_env *env) 11796 { 11797 struct bpf_prog *prog = env->prog; 11798 bool expect_blinding = bpf_jit_blinding_enabled(prog); 11799 struct bpf_insn *insn = prog->insnsi; 11800 const struct bpf_func_proto *fn; 11801 const int insn_cnt = prog->len; 11802 const struct bpf_map_ops *ops; 11803 struct bpf_insn_aux_data *aux; 11804 struct bpf_insn insn_buf[16]; 11805 struct bpf_prog *new_prog; 11806 struct bpf_map *map_ptr; 11807 int i, ret, cnt, delta = 0; 11808 11809 for (i = 0; i < insn_cnt; i++, insn++) { 11810 /* Make divide-by-zero exceptions impossible. */ 11811 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 11812 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 11813 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 11814 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 11815 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 11816 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 11817 struct bpf_insn *patchlet; 11818 struct bpf_insn chk_and_div[] = { 11819 /* [R,W]x div 0 -> 0 */ 11820 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 11821 BPF_JNE | BPF_K, insn->src_reg, 11822 0, 2, 0), 11823 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 11824 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 11825 *insn, 11826 }; 11827 struct bpf_insn chk_and_mod[] = { 11828 /* [R,W]x mod 0 -> [R,W]x */ 11829 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 11830 BPF_JEQ | BPF_K, insn->src_reg, 11831 0, 1 + (is64 ? 0 : 1), 0), 11832 *insn, 11833 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 11834 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 11835 }; 11836 11837 patchlet = isdiv ? chk_and_div : chk_and_mod; 11838 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 11839 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 11840 11841 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 11842 if (!new_prog) 11843 return -ENOMEM; 11844 11845 delta += cnt - 1; 11846 env->prog = prog = new_prog; 11847 insn = new_prog->insnsi + i + delta; 11848 continue; 11849 } 11850 11851 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 11852 if (BPF_CLASS(insn->code) == BPF_LD && 11853 (BPF_MODE(insn->code) == BPF_ABS || 11854 BPF_MODE(insn->code) == BPF_IND)) { 11855 cnt = env->ops->gen_ld_abs(insn, insn_buf); 11856 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 11857 verbose(env, "bpf verifier is misconfigured\n"); 11858 return -EINVAL; 11859 } 11860 11861 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 11862 if (!new_prog) 11863 return -ENOMEM; 11864 11865 delta += cnt - 1; 11866 env->prog = prog = new_prog; 11867 insn = new_prog->insnsi + i + delta; 11868 continue; 11869 } 11870 11871 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 11872 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 11873 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 11874 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 11875 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 11876 struct bpf_insn insn_buf[16]; 11877 struct bpf_insn *patch = &insn_buf[0]; 11878 bool issrc, isneg; 11879 u32 off_reg; 11880 11881 aux = &env->insn_aux_data[i + delta]; 11882 if (!aux->alu_state || 11883 aux->alu_state == BPF_ALU_NON_POINTER) 11884 continue; 11885 11886 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 11887 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 11888 BPF_ALU_SANITIZE_SRC; 11889 11890 off_reg = issrc ? insn->src_reg : insn->dst_reg; 11891 if (isneg) 11892 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 11893 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit - 1); 11894 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 11895 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 11896 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 11897 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 11898 if (issrc) { 11899 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, 11900 off_reg); 11901 insn->src_reg = BPF_REG_AX; 11902 } else { 11903 *patch++ = BPF_ALU64_REG(BPF_AND, off_reg, 11904 BPF_REG_AX); 11905 } 11906 if (isneg) 11907 insn->code = insn->code == code_add ? 11908 code_sub : code_add; 11909 *patch++ = *insn; 11910 if (issrc && isneg) 11911 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 11912 cnt = patch - insn_buf; 11913 11914 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 11915 if (!new_prog) 11916 return -ENOMEM; 11917 11918 delta += cnt - 1; 11919 env->prog = prog = new_prog; 11920 insn = new_prog->insnsi + i + delta; 11921 continue; 11922 } 11923 11924 if (insn->code != (BPF_JMP | BPF_CALL)) 11925 continue; 11926 if (insn->src_reg == BPF_PSEUDO_CALL) 11927 continue; 11928 11929 if (insn->imm == BPF_FUNC_get_route_realm) 11930 prog->dst_needed = 1; 11931 if (insn->imm == BPF_FUNC_get_prandom_u32) 11932 bpf_user_rnd_init_once(); 11933 if (insn->imm == BPF_FUNC_override_return) 11934 prog->kprobe_override = 1; 11935 if (insn->imm == BPF_FUNC_tail_call) { 11936 /* If we tail call into other programs, we 11937 * cannot make any assumptions since they can 11938 * be replaced dynamically during runtime in 11939 * the program array. 11940 */ 11941 prog->cb_access = 1; 11942 if (!allow_tail_call_in_subprogs(env)) 11943 prog->aux->stack_depth = MAX_BPF_STACK; 11944 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 11945 11946 /* mark bpf_tail_call as different opcode to avoid 11947 * conditional branch in the interpeter for every normal 11948 * call and to prevent accidental JITing by JIT compiler 11949 * that doesn't support bpf_tail_call yet 11950 */ 11951 insn->imm = 0; 11952 insn->code = BPF_JMP | BPF_TAIL_CALL; 11953 11954 aux = &env->insn_aux_data[i + delta]; 11955 if (env->bpf_capable && !expect_blinding && 11956 prog->jit_requested && 11957 !bpf_map_key_poisoned(aux) && 11958 !bpf_map_ptr_poisoned(aux) && 11959 !bpf_map_ptr_unpriv(aux)) { 11960 struct bpf_jit_poke_descriptor desc = { 11961 .reason = BPF_POKE_REASON_TAIL_CALL, 11962 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 11963 .tail_call.key = bpf_map_key_immediate(aux), 11964 .insn_idx = i + delta, 11965 }; 11966 11967 ret = bpf_jit_add_poke_descriptor(prog, &desc); 11968 if (ret < 0) { 11969 verbose(env, "adding tail call poke descriptor failed\n"); 11970 return ret; 11971 } 11972 11973 insn->imm = ret + 1; 11974 continue; 11975 } 11976 11977 if (!bpf_map_ptr_unpriv(aux)) 11978 continue; 11979 11980 /* instead of changing every JIT dealing with tail_call 11981 * emit two extra insns: 11982 * if (index >= max_entries) goto out; 11983 * index &= array->index_mask; 11984 * to avoid out-of-bounds cpu speculation 11985 */ 11986 if (bpf_map_ptr_poisoned(aux)) { 11987 verbose(env, "tail_call abusing map_ptr\n"); 11988 return -EINVAL; 11989 } 11990 11991 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 11992 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 11993 map_ptr->max_entries, 2); 11994 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 11995 container_of(map_ptr, 11996 struct bpf_array, 11997 map)->index_mask); 11998 insn_buf[2] = *insn; 11999 cnt = 3; 12000 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12001 if (!new_prog) 12002 return -ENOMEM; 12003 12004 delta += cnt - 1; 12005 env->prog = prog = new_prog; 12006 insn = new_prog->insnsi + i + delta; 12007 continue; 12008 } 12009 12010 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 12011 * and other inlining handlers are currently limited to 64 bit 12012 * only. 12013 */ 12014 if (prog->jit_requested && BITS_PER_LONG == 64 && 12015 (insn->imm == BPF_FUNC_map_lookup_elem || 12016 insn->imm == BPF_FUNC_map_update_elem || 12017 insn->imm == BPF_FUNC_map_delete_elem || 12018 insn->imm == BPF_FUNC_map_push_elem || 12019 insn->imm == BPF_FUNC_map_pop_elem || 12020 insn->imm == BPF_FUNC_map_peek_elem)) { 12021 aux = &env->insn_aux_data[i + delta]; 12022 if (bpf_map_ptr_poisoned(aux)) 12023 goto patch_call_imm; 12024 12025 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 12026 ops = map_ptr->ops; 12027 if (insn->imm == BPF_FUNC_map_lookup_elem && 12028 ops->map_gen_lookup) { 12029 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 12030 if (cnt == -EOPNOTSUPP) 12031 goto patch_map_ops_generic; 12032 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 12033 verbose(env, "bpf verifier is misconfigured\n"); 12034 return -EINVAL; 12035 } 12036 12037 new_prog = bpf_patch_insn_data(env, i + delta, 12038 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 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 12049 (void *(*)(struct bpf_map *map, void *key))NULL)); 12050 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 12051 (int (*)(struct bpf_map *map, void *key))NULL)); 12052 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 12053 (int (*)(struct bpf_map *map, void *key, void *value, 12054 u64 flags))NULL)); 12055 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 12056 (int (*)(struct bpf_map *map, void *value, 12057 u64 flags))NULL)); 12058 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 12059 (int (*)(struct bpf_map *map, void *value))NULL)); 12060 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 12061 (int (*)(struct bpf_map *map, void *value))NULL)); 12062 patch_map_ops_generic: 12063 switch (insn->imm) { 12064 case BPF_FUNC_map_lookup_elem: 12065 insn->imm = BPF_CAST_CALL(ops->map_lookup_elem) - 12066 __bpf_call_base; 12067 continue; 12068 case BPF_FUNC_map_update_elem: 12069 insn->imm = BPF_CAST_CALL(ops->map_update_elem) - 12070 __bpf_call_base; 12071 continue; 12072 case BPF_FUNC_map_delete_elem: 12073 insn->imm = BPF_CAST_CALL(ops->map_delete_elem) - 12074 __bpf_call_base; 12075 continue; 12076 case BPF_FUNC_map_push_elem: 12077 insn->imm = BPF_CAST_CALL(ops->map_push_elem) - 12078 __bpf_call_base; 12079 continue; 12080 case BPF_FUNC_map_pop_elem: 12081 insn->imm = BPF_CAST_CALL(ops->map_pop_elem) - 12082 __bpf_call_base; 12083 continue; 12084 case BPF_FUNC_map_peek_elem: 12085 insn->imm = BPF_CAST_CALL(ops->map_peek_elem) - 12086 __bpf_call_base; 12087 continue; 12088 } 12089 12090 goto patch_call_imm; 12091 } 12092 12093 /* Implement bpf_jiffies64 inline. */ 12094 if (prog->jit_requested && BITS_PER_LONG == 64 && 12095 insn->imm == BPF_FUNC_jiffies64) { 12096 struct bpf_insn ld_jiffies_addr[2] = { 12097 BPF_LD_IMM64(BPF_REG_0, 12098 (unsigned long)&jiffies), 12099 }; 12100 12101 insn_buf[0] = ld_jiffies_addr[0]; 12102 insn_buf[1] = ld_jiffies_addr[1]; 12103 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 12104 BPF_REG_0, 0); 12105 cnt = 3; 12106 12107 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 12108 cnt); 12109 if (!new_prog) 12110 return -ENOMEM; 12111 12112 delta += cnt - 1; 12113 env->prog = prog = new_prog; 12114 insn = new_prog->insnsi + i + delta; 12115 continue; 12116 } 12117 12118 patch_call_imm: 12119 fn = env->ops->get_func_proto(insn->imm, env->prog); 12120 /* all functions that have prototype and verifier allowed 12121 * programs to call them, must be real in-kernel functions 12122 */ 12123 if (!fn->func) { 12124 verbose(env, 12125 "kernel subsystem misconfigured func %s#%d\n", 12126 func_id_name(insn->imm), insn->imm); 12127 return -EFAULT; 12128 } 12129 insn->imm = fn->func - __bpf_call_base; 12130 } 12131 12132 /* Since poke tab is now finalized, publish aux to tracker. */ 12133 for (i = 0; i < prog->aux->size_poke_tab; i++) { 12134 map_ptr = prog->aux->poke_tab[i].tail_call.map; 12135 if (!map_ptr->ops->map_poke_track || 12136 !map_ptr->ops->map_poke_untrack || 12137 !map_ptr->ops->map_poke_run) { 12138 verbose(env, "bpf verifier is misconfigured\n"); 12139 return -EINVAL; 12140 } 12141 12142 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 12143 if (ret < 0) { 12144 verbose(env, "tracking tail call prog failed\n"); 12145 return ret; 12146 } 12147 } 12148 12149 return 0; 12150 } 12151 12152 static void free_states(struct bpf_verifier_env *env) 12153 { 12154 struct bpf_verifier_state_list *sl, *sln; 12155 int i; 12156 12157 sl = env->free_list; 12158 while (sl) { 12159 sln = sl->next; 12160 free_verifier_state(&sl->state, false); 12161 kfree(sl); 12162 sl = sln; 12163 } 12164 env->free_list = NULL; 12165 12166 if (!env->explored_states) 12167 return; 12168 12169 for (i = 0; i < state_htab_size(env); i++) { 12170 sl = env->explored_states[i]; 12171 12172 while (sl) { 12173 sln = sl->next; 12174 free_verifier_state(&sl->state, false); 12175 kfree(sl); 12176 sl = sln; 12177 } 12178 env->explored_states[i] = NULL; 12179 } 12180 } 12181 12182 /* The verifier is using insn_aux_data[] to store temporary data during 12183 * verification and to store information for passes that run after the 12184 * verification like dead code sanitization. do_check_common() for subprogram N 12185 * may analyze many other subprograms. sanitize_insn_aux_data() clears all 12186 * temporary data after do_check_common() finds that subprogram N cannot be 12187 * verified independently. pass_cnt counts the number of times 12188 * do_check_common() was run and insn->aux->seen tells the pass number 12189 * insn_aux_data was touched. These variables are compared to clear temporary 12190 * data from failed pass. For testing and experiments do_check_common() can be 12191 * run multiple times even when prior attempt to verify is unsuccessful. 12192 */ 12193 static void sanitize_insn_aux_data(struct bpf_verifier_env *env) 12194 { 12195 struct bpf_insn *insn = env->prog->insnsi; 12196 struct bpf_insn_aux_data *aux; 12197 int i, class; 12198 12199 for (i = 0; i < env->prog->len; i++) { 12200 class = BPF_CLASS(insn[i].code); 12201 if (class != BPF_LDX && class != BPF_STX) 12202 continue; 12203 aux = &env->insn_aux_data[i]; 12204 if (aux->seen != env->pass_cnt) 12205 continue; 12206 memset(aux, 0, offsetof(typeof(*aux), orig_idx)); 12207 } 12208 } 12209 12210 static int do_check_common(struct bpf_verifier_env *env, int subprog) 12211 { 12212 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 12213 struct bpf_verifier_state *state; 12214 struct bpf_reg_state *regs; 12215 int ret, i; 12216 12217 env->prev_linfo = NULL; 12218 env->pass_cnt++; 12219 12220 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 12221 if (!state) 12222 return -ENOMEM; 12223 state->curframe = 0; 12224 state->speculative = false; 12225 state->branches = 1; 12226 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 12227 if (!state->frame[0]) { 12228 kfree(state); 12229 return -ENOMEM; 12230 } 12231 env->cur_state = state; 12232 init_func_state(env, state->frame[0], 12233 BPF_MAIN_FUNC /* callsite */, 12234 0 /* frameno */, 12235 subprog); 12236 12237 regs = state->frame[state->curframe]->regs; 12238 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 12239 ret = btf_prepare_func_args(env, subprog, regs); 12240 if (ret) 12241 goto out; 12242 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 12243 if (regs[i].type == PTR_TO_CTX) 12244 mark_reg_known_zero(env, regs, i); 12245 else if (regs[i].type == SCALAR_VALUE) 12246 mark_reg_unknown(env, regs, i); 12247 else if (regs[i].type == PTR_TO_MEM_OR_NULL) { 12248 const u32 mem_size = regs[i].mem_size; 12249 12250 mark_reg_known_zero(env, regs, i); 12251 regs[i].mem_size = mem_size; 12252 regs[i].id = ++env->id_gen; 12253 } 12254 } 12255 } else { 12256 /* 1st arg to a function */ 12257 regs[BPF_REG_1].type = PTR_TO_CTX; 12258 mark_reg_known_zero(env, regs, BPF_REG_1); 12259 ret = btf_check_func_arg_match(env, subprog, regs); 12260 if (ret == -EFAULT) 12261 /* unlikely verifier bug. abort. 12262 * ret == 0 and ret < 0 are sadly acceptable for 12263 * main() function due to backward compatibility. 12264 * Like socket filter program may be written as: 12265 * int bpf_prog(struct pt_regs *ctx) 12266 * and never dereference that ctx in the program. 12267 * 'struct pt_regs' is a type mismatch for socket 12268 * filter that should be using 'struct __sk_buff'. 12269 */ 12270 goto out; 12271 } 12272 12273 ret = do_check(env); 12274 out: 12275 /* check for NULL is necessary, since cur_state can be freed inside 12276 * do_check() under memory pressure. 12277 */ 12278 if (env->cur_state) { 12279 free_verifier_state(env->cur_state, true); 12280 env->cur_state = NULL; 12281 } 12282 while (!pop_stack(env, NULL, NULL, false)); 12283 if (!ret && pop_log) 12284 bpf_vlog_reset(&env->log, 0); 12285 free_states(env); 12286 if (ret) 12287 /* clean aux data in case subprog was rejected */ 12288 sanitize_insn_aux_data(env); 12289 return ret; 12290 } 12291 12292 /* Verify all global functions in a BPF program one by one based on their BTF. 12293 * All global functions must pass verification. Otherwise the whole program is rejected. 12294 * Consider: 12295 * int bar(int); 12296 * int foo(int f) 12297 * { 12298 * return bar(f); 12299 * } 12300 * int bar(int b) 12301 * { 12302 * ... 12303 * } 12304 * foo() will be verified first for R1=any_scalar_value. During verification it 12305 * will be assumed that bar() already verified successfully and call to bar() 12306 * from foo() will be checked for type match only. Later bar() will be verified 12307 * independently to check that it's safe for R1=any_scalar_value. 12308 */ 12309 static int do_check_subprogs(struct bpf_verifier_env *env) 12310 { 12311 struct bpf_prog_aux *aux = env->prog->aux; 12312 int i, ret; 12313 12314 if (!aux->func_info) 12315 return 0; 12316 12317 for (i = 1; i < env->subprog_cnt; i++) { 12318 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 12319 continue; 12320 env->insn_idx = env->subprog_info[i].start; 12321 WARN_ON_ONCE(env->insn_idx == 0); 12322 ret = do_check_common(env, i); 12323 if (ret) { 12324 return ret; 12325 } else if (env->log.level & BPF_LOG_LEVEL) { 12326 verbose(env, 12327 "Func#%d is safe for any args that match its prototype\n", 12328 i); 12329 } 12330 } 12331 return 0; 12332 } 12333 12334 static int do_check_main(struct bpf_verifier_env *env) 12335 { 12336 int ret; 12337 12338 env->insn_idx = 0; 12339 ret = do_check_common(env, 0); 12340 if (!ret) 12341 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 12342 return ret; 12343 } 12344 12345 12346 static void print_verification_stats(struct bpf_verifier_env *env) 12347 { 12348 int i; 12349 12350 if (env->log.level & BPF_LOG_STATS) { 12351 verbose(env, "verification time %lld usec\n", 12352 div_u64(env->verification_time, 1000)); 12353 verbose(env, "stack depth "); 12354 for (i = 0; i < env->subprog_cnt; i++) { 12355 u32 depth = env->subprog_info[i].stack_depth; 12356 12357 verbose(env, "%d", depth); 12358 if (i + 1 < env->subprog_cnt) 12359 verbose(env, "+"); 12360 } 12361 verbose(env, "\n"); 12362 } 12363 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 12364 "total_states %d peak_states %d mark_read %d\n", 12365 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 12366 env->max_states_per_insn, env->total_states, 12367 env->peak_states, env->longest_mark_read_walk); 12368 } 12369 12370 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 12371 { 12372 const struct btf_type *t, *func_proto; 12373 const struct bpf_struct_ops *st_ops; 12374 const struct btf_member *member; 12375 struct bpf_prog *prog = env->prog; 12376 u32 btf_id, member_idx; 12377 const char *mname; 12378 12379 btf_id = prog->aux->attach_btf_id; 12380 st_ops = bpf_struct_ops_find(btf_id); 12381 if (!st_ops) { 12382 verbose(env, "attach_btf_id %u is not a supported struct\n", 12383 btf_id); 12384 return -ENOTSUPP; 12385 } 12386 12387 t = st_ops->type; 12388 member_idx = prog->expected_attach_type; 12389 if (member_idx >= btf_type_vlen(t)) { 12390 verbose(env, "attach to invalid member idx %u of struct %s\n", 12391 member_idx, st_ops->name); 12392 return -EINVAL; 12393 } 12394 12395 member = &btf_type_member(t)[member_idx]; 12396 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 12397 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 12398 NULL); 12399 if (!func_proto) { 12400 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 12401 mname, member_idx, st_ops->name); 12402 return -EINVAL; 12403 } 12404 12405 if (st_ops->check_member) { 12406 int err = st_ops->check_member(t, member); 12407 12408 if (err) { 12409 verbose(env, "attach to unsupported member %s of struct %s\n", 12410 mname, st_ops->name); 12411 return err; 12412 } 12413 } 12414 12415 prog->aux->attach_func_proto = func_proto; 12416 prog->aux->attach_func_name = mname; 12417 env->ops = st_ops->verifier_ops; 12418 12419 return 0; 12420 } 12421 #define SECURITY_PREFIX "security_" 12422 12423 static int check_attach_modify_return(unsigned long addr, const char *func_name) 12424 { 12425 if (within_error_injection_list(addr) || 12426 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 12427 return 0; 12428 12429 return -EINVAL; 12430 } 12431 12432 /* list of non-sleepable functions that are otherwise on 12433 * ALLOW_ERROR_INJECTION list 12434 */ 12435 BTF_SET_START(btf_non_sleepable_error_inject) 12436 /* Three functions below can be called from sleepable and non-sleepable context. 12437 * Assume non-sleepable from bpf safety point of view. 12438 */ 12439 BTF_ID(func, __add_to_page_cache_locked) 12440 BTF_ID(func, should_fail_alloc_page) 12441 BTF_ID(func, should_failslab) 12442 BTF_SET_END(btf_non_sleepable_error_inject) 12443 12444 static int check_non_sleepable_error_inject(u32 btf_id) 12445 { 12446 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 12447 } 12448 12449 int bpf_check_attach_target(struct bpf_verifier_log *log, 12450 const struct bpf_prog *prog, 12451 const struct bpf_prog *tgt_prog, 12452 u32 btf_id, 12453 struct bpf_attach_target_info *tgt_info) 12454 { 12455 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 12456 const char prefix[] = "btf_trace_"; 12457 int ret = 0, subprog = -1, i; 12458 const struct btf_type *t; 12459 bool conservative = true; 12460 const char *tname; 12461 struct btf *btf; 12462 long addr = 0; 12463 12464 if (!btf_id) { 12465 bpf_log(log, "Tracing programs must provide btf_id\n"); 12466 return -EINVAL; 12467 } 12468 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 12469 if (!btf) { 12470 bpf_log(log, 12471 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 12472 return -EINVAL; 12473 } 12474 t = btf_type_by_id(btf, btf_id); 12475 if (!t) { 12476 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 12477 return -EINVAL; 12478 } 12479 tname = btf_name_by_offset(btf, t->name_off); 12480 if (!tname) { 12481 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 12482 return -EINVAL; 12483 } 12484 if (tgt_prog) { 12485 struct bpf_prog_aux *aux = tgt_prog->aux; 12486 12487 for (i = 0; i < aux->func_info_cnt; i++) 12488 if (aux->func_info[i].type_id == btf_id) { 12489 subprog = i; 12490 break; 12491 } 12492 if (subprog == -1) { 12493 bpf_log(log, "Subprog %s doesn't exist\n", tname); 12494 return -EINVAL; 12495 } 12496 conservative = aux->func_info_aux[subprog].unreliable; 12497 if (prog_extension) { 12498 if (conservative) { 12499 bpf_log(log, 12500 "Cannot replace static functions\n"); 12501 return -EINVAL; 12502 } 12503 if (!prog->jit_requested) { 12504 bpf_log(log, 12505 "Extension programs should be JITed\n"); 12506 return -EINVAL; 12507 } 12508 } 12509 if (!tgt_prog->jited) { 12510 bpf_log(log, "Can attach to only JITed progs\n"); 12511 return -EINVAL; 12512 } 12513 if (tgt_prog->type == prog->type) { 12514 /* Cannot fentry/fexit another fentry/fexit program. 12515 * Cannot attach program extension to another extension. 12516 * It's ok to attach fentry/fexit to extension program. 12517 */ 12518 bpf_log(log, "Cannot recursively attach\n"); 12519 return -EINVAL; 12520 } 12521 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 12522 prog_extension && 12523 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 12524 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 12525 /* Program extensions can extend all program types 12526 * except fentry/fexit. The reason is the following. 12527 * The fentry/fexit programs are used for performance 12528 * analysis, stats and can be attached to any program 12529 * type except themselves. When extension program is 12530 * replacing XDP function it is necessary to allow 12531 * performance analysis of all functions. Both original 12532 * XDP program and its program extension. Hence 12533 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 12534 * allowed. If extending of fentry/fexit was allowed it 12535 * would be possible to create long call chain 12536 * fentry->extension->fentry->extension beyond 12537 * reasonable stack size. Hence extending fentry is not 12538 * allowed. 12539 */ 12540 bpf_log(log, "Cannot extend fentry/fexit\n"); 12541 return -EINVAL; 12542 } 12543 } else { 12544 if (prog_extension) { 12545 bpf_log(log, "Cannot replace kernel functions\n"); 12546 return -EINVAL; 12547 } 12548 } 12549 12550 switch (prog->expected_attach_type) { 12551 case BPF_TRACE_RAW_TP: 12552 if (tgt_prog) { 12553 bpf_log(log, 12554 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 12555 return -EINVAL; 12556 } 12557 if (!btf_type_is_typedef(t)) { 12558 bpf_log(log, "attach_btf_id %u is not a typedef\n", 12559 btf_id); 12560 return -EINVAL; 12561 } 12562 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 12563 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 12564 btf_id, tname); 12565 return -EINVAL; 12566 } 12567 tname += sizeof(prefix) - 1; 12568 t = btf_type_by_id(btf, t->type); 12569 if (!btf_type_is_ptr(t)) 12570 /* should never happen in valid vmlinux build */ 12571 return -EINVAL; 12572 t = btf_type_by_id(btf, t->type); 12573 if (!btf_type_is_func_proto(t)) 12574 /* should never happen in valid vmlinux build */ 12575 return -EINVAL; 12576 12577 break; 12578 case BPF_TRACE_ITER: 12579 if (!btf_type_is_func(t)) { 12580 bpf_log(log, "attach_btf_id %u is not a function\n", 12581 btf_id); 12582 return -EINVAL; 12583 } 12584 t = btf_type_by_id(btf, t->type); 12585 if (!btf_type_is_func_proto(t)) 12586 return -EINVAL; 12587 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 12588 if (ret) 12589 return ret; 12590 break; 12591 default: 12592 if (!prog_extension) 12593 return -EINVAL; 12594 fallthrough; 12595 case BPF_MODIFY_RETURN: 12596 case BPF_LSM_MAC: 12597 case BPF_TRACE_FENTRY: 12598 case BPF_TRACE_FEXIT: 12599 if (!btf_type_is_func(t)) { 12600 bpf_log(log, "attach_btf_id %u is not a function\n", 12601 btf_id); 12602 return -EINVAL; 12603 } 12604 if (prog_extension && 12605 btf_check_type_match(log, prog, btf, t)) 12606 return -EINVAL; 12607 t = btf_type_by_id(btf, t->type); 12608 if (!btf_type_is_func_proto(t)) 12609 return -EINVAL; 12610 12611 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 12612 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 12613 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 12614 return -EINVAL; 12615 12616 if (tgt_prog && conservative) 12617 t = NULL; 12618 12619 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 12620 if (ret < 0) 12621 return ret; 12622 12623 if (tgt_prog) { 12624 if (subprog == 0) 12625 addr = (long) tgt_prog->bpf_func; 12626 else 12627 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 12628 } else { 12629 addr = kallsyms_lookup_name(tname); 12630 if (!addr) { 12631 bpf_log(log, 12632 "The address of function %s cannot be found\n", 12633 tname); 12634 return -ENOENT; 12635 } 12636 } 12637 12638 if (prog->aux->sleepable) { 12639 ret = -EINVAL; 12640 switch (prog->type) { 12641 case BPF_PROG_TYPE_TRACING: 12642 /* fentry/fexit/fmod_ret progs can be sleepable only if they are 12643 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 12644 */ 12645 if (!check_non_sleepable_error_inject(btf_id) && 12646 within_error_injection_list(addr)) 12647 ret = 0; 12648 break; 12649 case BPF_PROG_TYPE_LSM: 12650 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 12651 * Only some of them are sleepable. 12652 */ 12653 if (bpf_lsm_is_sleepable_hook(btf_id)) 12654 ret = 0; 12655 break; 12656 default: 12657 break; 12658 } 12659 if (ret) { 12660 bpf_log(log, "%s is not sleepable\n", tname); 12661 return ret; 12662 } 12663 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 12664 if (tgt_prog) { 12665 bpf_log(log, "can't modify return codes of BPF programs\n"); 12666 return -EINVAL; 12667 } 12668 ret = check_attach_modify_return(addr, tname); 12669 if (ret) { 12670 bpf_log(log, "%s() is not modifiable\n", tname); 12671 return ret; 12672 } 12673 } 12674 12675 break; 12676 } 12677 tgt_info->tgt_addr = addr; 12678 tgt_info->tgt_name = tname; 12679 tgt_info->tgt_type = t; 12680 return 0; 12681 } 12682 12683 static int check_attach_btf_id(struct bpf_verifier_env *env) 12684 { 12685 struct bpf_prog *prog = env->prog; 12686 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 12687 struct bpf_attach_target_info tgt_info = {}; 12688 u32 btf_id = prog->aux->attach_btf_id; 12689 struct bpf_trampoline *tr; 12690 int ret; 12691 u64 key; 12692 12693 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING && 12694 prog->type != BPF_PROG_TYPE_LSM) { 12695 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n"); 12696 return -EINVAL; 12697 } 12698 12699 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 12700 return check_struct_ops_btf_id(env); 12701 12702 if (prog->type != BPF_PROG_TYPE_TRACING && 12703 prog->type != BPF_PROG_TYPE_LSM && 12704 prog->type != BPF_PROG_TYPE_EXT) 12705 return 0; 12706 12707 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 12708 if (ret) 12709 return ret; 12710 12711 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 12712 /* to make freplace equivalent to their targets, they need to 12713 * inherit env->ops and expected_attach_type for the rest of the 12714 * verification 12715 */ 12716 env->ops = bpf_verifier_ops[tgt_prog->type]; 12717 prog->expected_attach_type = tgt_prog->expected_attach_type; 12718 } 12719 12720 /* store info about the attachment target that will be used later */ 12721 prog->aux->attach_func_proto = tgt_info.tgt_type; 12722 prog->aux->attach_func_name = tgt_info.tgt_name; 12723 12724 if (tgt_prog) { 12725 prog->aux->saved_dst_prog_type = tgt_prog->type; 12726 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 12727 } 12728 12729 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 12730 prog->aux->attach_btf_trace = true; 12731 return 0; 12732 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 12733 if (!bpf_iter_prog_supported(prog)) 12734 return -EINVAL; 12735 return 0; 12736 } 12737 12738 if (prog->type == BPF_PROG_TYPE_LSM) { 12739 ret = bpf_lsm_verify_prog(&env->log, prog); 12740 if (ret < 0) 12741 return ret; 12742 } 12743 12744 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 12745 tr = bpf_trampoline_get(key, &tgt_info); 12746 if (!tr) 12747 return -ENOMEM; 12748 12749 prog->aux->dst_trampoline = tr; 12750 return 0; 12751 } 12752 12753 struct btf *bpf_get_btf_vmlinux(void) 12754 { 12755 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 12756 mutex_lock(&bpf_verifier_lock); 12757 if (!btf_vmlinux) 12758 btf_vmlinux = btf_parse_vmlinux(); 12759 mutex_unlock(&bpf_verifier_lock); 12760 } 12761 return btf_vmlinux; 12762 } 12763 12764 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, 12765 union bpf_attr __user *uattr) 12766 { 12767 u64 start_time = ktime_get_ns(); 12768 struct bpf_verifier_env *env; 12769 struct bpf_verifier_log *log; 12770 int i, len, ret = -EINVAL; 12771 bool is_priv; 12772 12773 /* no program is valid */ 12774 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 12775 return -EINVAL; 12776 12777 /* 'struct bpf_verifier_env' can be global, but since it's not small, 12778 * allocate/free it every time bpf_check() is called 12779 */ 12780 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 12781 if (!env) 12782 return -ENOMEM; 12783 log = &env->log; 12784 12785 len = (*prog)->len; 12786 env->insn_aux_data = 12787 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 12788 ret = -ENOMEM; 12789 if (!env->insn_aux_data) 12790 goto err_free_env; 12791 for (i = 0; i < len; i++) 12792 env->insn_aux_data[i].orig_idx = i; 12793 env->prog = *prog; 12794 env->ops = bpf_verifier_ops[env->prog->type]; 12795 is_priv = bpf_capable(); 12796 12797 bpf_get_btf_vmlinux(); 12798 12799 /* grab the mutex to protect few globals used by verifier */ 12800 if (!is_priv) 12801 mutex_lock(&bpf_verifier_lock); 12802 12803 if (attr->log_level || attr->log_buf || attr->log_size) { 12804 /* user requested verbose verifier output 12805 * and supplied buffer to store the verification trace 12806 */ 12807 log->level = attr->log_level; 12808 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 12809 log->len_total = attr->log_size; 12810 12811 ret = -EINVAL; 12812 /* log attributes have to be sane */ 12813 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 || 12814 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK) 12815 goto err_unlock; 12816 } 12817 12818 if (IS_ERR(btf_vmlinux)) { 12819 /* Either gcc or pahole or kernel are broken. */ 12820 verbose(env, "in-kernel BTF is malformed\n"); 12821 ret = PTR_ERR(btf_vmlinux); 12822 goto skip_full_check; 12823 } 12824 12825 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 12826 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 12827 env->strict_alignment = true; 12828 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 12829 env->strict_alignment = false; 12830 12831 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 12832 env->allow_uninit_stack = bpf_allow_uninit_stack(); 12833 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access(); 12834 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 12835 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 12836 env->bpf_capable = bpf_capable(); 12837 12838 if (is_priv) 12839 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 12840 12841 if (bpf_prog_is_dev_bound(env->prog->aux)) { 12842 ret = bpf_prog_offload_verifier_prep(env->prog); 12843 if (ret) 12844 goto skip_full_check; 12845 } 12846 12847 env->explored_states = kvcalloc(state_htab_size(env), 12848 sizeof(struct bpf_verifier_state_list *), 12849 GFP_USER); 12850 ret = -ENOMEM; 12851 if (!env->explored_states) 12852 goto skip_full_check; 12853 12854 ret = check_subprogs(env); 12855 if (ret < 0) 12856 goto skip_full_check; 12857 12858 ret = check_btf_info(env, attr, uattr); 12859 if (ret < 0) 12860 goto skip_full_check; 12861 12862 ret = check_attach_btf_id(env); 12863 if (ret) 12864 goto skip_full_check; 12865 12866 ret = resolve_pseudo_ldimm64(env); 12867 if (ret < 0) 12868 goto skip_full_check; 12869 12870 ret = check_cfg(env); 12871 if (ret < 0) 12872 goto skip_full_check; 12873 12874 ret = do_check_subprogs(env); 12875 ret = ret ?: do_check_main(env); 12876 12877 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux)) 12878 ret = bpf_prog_offload_finalize(env); 12879 12880 skip_full_check: 12881 kvfree(env->explored_states); 12882 12883 if (ret == 0) 12884 ret = check_max_stack_depth(env); 12885 12886 /* instruction rewrites happen after this point */ 12887 if (is_priv) { 12888 if (ret == 0) 12889 opt_hard_wire_dead_code_branches(env); 12890 if (ret == 0) 12891 ret = opt_remove_dead_code(env); 12892 if (ret == 0) 12893 ret = opt_remove_nops(env); 12894 } else { 12895 if (ret == 0) 12896 sanitize_dead_code(env); 12897 } 12898 12899 if (ret == 0) 12900 /* program is valid, convert *(u32*)(ctx + off) accesses */ 12901 ret = convert_ctx_accesses(env); 12902 12903 if (ret == 0) 12904 ret = do_misc_fixups(env); 12905 12906 /* do 32-bit optimization after insn patching has done so those patched 12907 * insns could be handled correctly. 12908 */ 12909 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) { 12910 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 12911 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 12912 : false; 12913 } 12914 12915 if (ret == 0) 12916 ret = fixup_call_args(env); 12917 12918 env->verification_time = ktime_get_ns() - start_time; 12919 print_verification_stats(env); 12920 12921 if (log->level && bpf_verifier_log_full(log)) 12922 ret = -ENOSPC; 12923 if (log->level && !log->ubuf) { 12924 ret = -EFAULT; 12925 goto err_release_maps; 12926 } 12927 12928 if (ret) 12929 goto err_release_maps; 12930 12931 if (env->used_map_cnt) { 12932 /* if program passed verifier, update used_maps in bpf_prog_info */ 12933 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 12934 sizeof(env->used_maps[0]), 12935 GFP_KERNEL); 12936 12937 if (!env->prog->aux->used_maps) { 12938 ret = -ENOMEM; 12939 goto err_release_maps; 12940 } 12941 12942 memcpy(env->prog->aux->used_maps, env->used_maps, 12943 sizeof(env->used_maps[0]) * env->used_map_cnt); 12944 env->prog->aux->used_map_cnt = env->used_map_cnt; 12945 } 12946 if (env->used_btf_cnt) { 12947 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 12948 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 12949 sizeof(env->used_btfs[0]), 12950 GFP_KERNEL); 12951 if (!env->prog->aux->used_btfs) { 12952 ret = -ENOMEM; 12953 goto err_release_maps; 12954 } 12955 12956 memcpy(env->prog->aux->used_btfs, env->used_btfs, 12957 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 12958 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 12959 } 12960 if (env->used_map_cnt || env->used_btf_cnt) { 12961 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 12962 * bpf_ld_imm64 instructions 12963 */ 12964 convert_pseudo_ld_imm64(env); 12965 } 12966 12967 adjust_btf_func(env); 12968 12969 err_release_maps: 12970 if (!env->prog->aux->used_maps) 12971 /* if we didn't copy map pointers into bpf_prog_info, release 12972 * them now. Otherwise free_used_maps() will release them. 12973 */ 12974 release_maps(env); 12975 if (!env->prog->aux->used_btfs) 12976 release_btfs(env); 12977 12978 /* extension progs temporarily inherit the attach_type of their targets 12979 for verification purposes, so set it back to zero before returning 12980 */ 12981 if (env->prog->type == BPF_PROG_TYPE_EXT) 12982 env->prog->expected_attach_type = 0; 12983 12984 *prog = env->prog; 12985 err_unlock: 12986 if (!is_priv) 12987 mutex_unlock(&bpf_verifier_lock); 12988 vfree(env->insn_aux_data); 12989 err_free_env: 12990 kfree(env); 12991 return ret; 12992 } 12993