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 paths 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 either 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_kfunc_call(const struct bpf_insn *insn) 238 { 239 return insn->code == (BPF_JMP | BPF_CALL) && 240 insn->src_reg == BPF_PSEUDO_KFUNC_CALL; 241 } 242 243 static bool bpf_pseudo_func(const struct bpf_insn *insn) 244 { 245 return insn->code == (BPF_LD | BPF_IMM | BPF_DW) && 246 insn->src_reg == BPF_PSEUDO_FUNC; 247 } 248 249 struct bpf_call_arg_meta { 250 struct bpf_map *map_ptr; 251 bool raw_mode; 252 bool pkt_access; 253 int regno; 254 int access_size; 255 int mem_size; 256 u64 msize_max_value; 257 int ref_obj_id; 258 int map_uid; 259 int func_id; 260 struct btf *btf; 261 u32 btf_id; 262 struct btf *ret_btf; 263 u32 ret_btf_id; 264 u32 subprogno; 265 }; 266 267 struct btf *btf_vmlinux; 268 269 static DEFINE_MUTEX(bpf_verifier_lock); 270 271 static const struct bpf_line_info * 272 find_linfo(const struct bpf_verifier_env *env, u32 insn_off) 273 { 274 const struct bpf_line_info *linfo; 275 const struct bpf_prog *prog; 276 u32 i, nr_linfo; 277 278 prog = env->prog; 279 nr_linfo = prog->aux->nr_linfo; 280 281 if (!nr_linfo || insn_off >= prog->len) 282 return NULL; 283 284 linfo = prog->aux->linfo; 285 for (i = 1; i < nr_linfo; i++) 286 if (insn_off < linfo[i].insn_off) 287 break; 288 289 return &linfo[i - 1]; 290 } 291 292 void bpf_verifier_vlog(struct bpf_verifier_log *log, const char *fmt, 293 va_list args) 294 { 295 unsigned int n; 296 297 n = vscnprintf(log->kbuf, BPF_VERIFIER_TMP_LOG_SIZE, fmt, args); 298 299 WARN_ONCE(n >= BPF_VERIFIER_TMP_LOG_SIZE - 1, 300 "verifier log line truncated - local buffer too short\n"); 301 302 n = min(log->len_total - log->len_used - 1, n); 303 log->kbuf[n] = '\0'; 304 305 if (log->level == BPF_LOG_KERNEL) { 306 pr_err("BPF:%s\n", log->kbuf); 307 return; 308 } 309 if (!copy_to_user(log->ubuf + log->len_used, log->kbuf, n + 1)) 310 log->len_used += n; 311 else 312 log->ubuf = NULL; 313 } 314 315 static void bpf_vlog_reset(struct bpf_verifier_log *log, u32 new_pos) 316 { 317 char zero = 0; 318 319 if (!bpf_verifier_log_needed(log)) 320 return; 321 322 log->len_used = new_pos; 323 if (put_user(zero, log->ubuf + new_pos)) 324 log->ubuf = NULL; 325 } 326 327 /* log_level controls verbosity level of eBPF verifier. 328 * bpf_verifier_log_write() is used to dump the verification trace to the log, 329 * so the user can figure out what's wrong with the program 330 */ 331 __printf(2, 3) void bpf_verifier_log_write(struct bpf_verifier_env *env, 332 const char *fmt, ...) 333 { 334 va_list args; 335 336 if (!bpf_verifier_log_needed(&env->log)) 337 return; 338 339 va_start(args, fmt); 340 bpf_verifier_vlog(&env->log, fmt, args); 341 va_end(args); 342 } 343 EXPORT_SYMBOL_GPL(bpf_verifier_log_write); 344 345 __printf(2, 3) static void verbose(void *private_data, const char *fmt, ...) 346 { 347 struct bpf_verifier_env *env = private_data; 348 va_list args; 349 350 if (!bpf_verifier_log_needed(&env->log)) 351 return; 352 353 va_start(args, fmt); 354 bpf_verifier_vlog(&env->log, fmt, args); 355 va_end(args); 356 } 357 358 __printf(2, 3) void bpf_log(struct bpf_verifier_log *log, 359 const char *fmt, ...) 360 { 361 va_list args; 362 363 if (!bpf_verifier_log_needed(log)) 364 return; 365 366 va_start(args, fmt); 367 bpf_verifier_vlog(log, fmt, args); 368 va_end(args); 369 } 370 371 static const char *ltrim(const char *s) 372 { 373 while (isspace(*s)) 374 s++; 375 376 return s; 377 } 378 379 __printf(3, 4) static void verbose_linfo(struct bpf_verifier_env *env, 380 u32 insn_off, 381 const char *prefix_fmt, ...) 382 { 383 const struct bpf_line_info *linfo; 384 385 if (!bpf_verifier_log_needed(&env->log)) 386 return; 387 388 linfo = find_linfo(env, insn_off); 389 if (!linfo || linfo == env->prev_linfo) 390 return; 391 392 if (prefix_fmt) { 393 va_list args; 394 395 va_start(args, prefix_fmt); 396 bpf_verifier_vlog(&env->log, prefix_fmt, args); 397 va_end(args); 398 } 399 400 verbose(env, "%s\n", 401 ltrim(btf_name_by_offset(env->prog->aux->btf, 402 linfo->line_off))); 403 404 env->prev_linfo = linfo; 405 } 406 407 static void verbose_invalid_scalar(struct bpf_verifier_env *env, 408 struct bpf_reg_state *reg, 409 struct tnum *range, const char *ctx, 410 const char *reg_name) 411 { 412 char tn_buf[48]; 413 414 verbose(env, "At %s the register %s ", ctx, reg_name); 415 if (!tnum_is_unknown(reg->var_off)) { 416 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 417 verbose(env, "has value %s", tn_buf); 418 } else { 419 verbose(env, "has unknown scalar value"); 420 } 421 tnum_strn(tn_buf, sizeof(tn_buf), *range); 422 verbose(env, " should have been in %s\n", tn_buf); 423 } 424 425 static bool type_is_pkt_pointer(enum bpf_reg_type type) 426 { 427 return type == PTR_TO_PACKET || 428 type == PTR_TO_PACKET_META; 429 } 430 431 static bool type_is_sk_pointer(enum bpf_reg_type type) 432 { 433 return type == PTR_TO_SOCKET || 434 type == PTR_TO_SOCK_COMMON || 435 type == PTR_TO_TCP_SOCK || 436 type == PTR_TO_XDP_SOCK; 437 } 438 439 static bool reg_type_not_null(enum bpf_reg_type type) 440 { 441 return type == PTR_TO_SOCKET || 442 type == PTR_TO_TCP_SOCK || 443 type == PTR_TO_MAP_VALUE || 444 type == PTR_TO_MAP_KEY || 445 type == PTR_TO_SOCK_COMMON; 446 } 447 448 static bool reg_type_may_be_null(enum bpf_reg_type type) 449 { 450 return type == PTR_TO_MAP_VALUE_OR_NULL || 451 type == PTR_TO_SOCKET_OR_NULL || 452 type == PTR_TO_SOCK_COMMON_OR_NULL || 453 type == PTR_TO_TCP_SOCK_OR_NULL || 454 type == PTR_TO_BTF_ID_OR_NULL || 455 type == PTR_TO_MEM_OR_NULL || 456 type == PTR_TO_RDONLY_BUF_OR_NULL || 457 type == PTR_TO_RDWR_BUF_OR_NULL; 458 } 459 460 static bool reg_may_point_to_spin_lock(const struct bpf_reg_state *reg) 461 { 462 return reg->type == PTR_TO_MAP_VALUE && 463 map_value_has_spin_lock(reg->map_ptr); 464 } 465 466 static bool reg_type_may_be_refcounted_or_null(enum bpf_reg_type type) 467 { 468 return type == PTR_TO_SOCKET || 469 type == PTR_TO_SOCKET_OR_NULL || 470 type == PTR_TO_TCP_SOCK || 471 type == PTR_TO_TCP_SOCK_OR_NULL || 472 type == PTR_TO_MEM || 473 type == PTR_TO_MEM_OR_NULL; 474 } 475 476 static bool arg_type_may_be_refcounted(enum bpf_arg_type type) 477 { 478 return type == ARG_PTR_TO_SOCK_COMMON; 479 } 480 481 static bool arg_type_may_be_null(enum bpf_arg_type type) 482 { 483 return type == ARG_PTR_TO_MAP_VALUE_OR_NULL || 484 type == ARG_PTR_TO_MEM_OR_NULL || 485 type == ARG_PTR_TO_CTX_OR_NULL || 486 type == ARG_PTR_TO_SOCKET_OR_NULL || 487 type == ARG_PTR_TO_ALLOC_MEM_OR_NULL || 488 type == ARG_PTR_TO_STACK_OR_NULL; 489 } 490 491 /* Determine whether the function releases some resources allocated by another 492 * function call. The first reference type argument will be assumed to be 493 * released by release_reference(). 494 */ 495 static bool is_release_function(enum bpf_func_id func_id) 496 { 497 return func_id == BPF_FUNC_sk_release || 498 func_id == BPF_FUNC_ringbuf_submit || 499 func_id == BPF_FUNC_ringbuf_discard; 500 } 501 502 static bool may_be_acquire_function(enum bpf_func_id func_id) 503 { 504 return func_id == BPF_FUNC_sk_lookup_tcp || 505 func_id == BPF_FUNC_sk_lookup_udp || 506 func_id == BPF_FUNC_skc_lookup_tcp || 507 func_id == BPF_FUNC_map_lookup_elem || 508 func_id == BPF_FUNC_ringbuf_reserve; 509 } 510 511 static bool is_acquire_function(enum bpf_func_id func_id, 512 const struct bpf_map *map) 513 { 514 enum bpf_map_type map_type = map ? map->map_type : BPF_MAP_TYPE_UNSPEC; 515 516 if (func_id == BPF_FUNC_sk_lookup_tcp || 517 func_id == BPF_FUNC_sk_lookup_udp || 518 func_id == BPF_FUNC_skc_lookup_tcp || 519 func_id == BPF_FUNC_ringbuf_reserve) 520 return true; 521 522 if (func_id == BPF_FUNC_map_lookup_elem && 523 (map_type == BPF_MAP_TYPE_SOCKMAP || 524 map_type == BPF_MAP_TYPE_SOCKHASH)) 525 return true; 526 527 return false; 528 } 529 530 static bool is_ptr_cast_function(enum bpf_func_id func_id) 531 { 532 return func_id == BPF_FUNC_tcp_sock || 533 func_id == BPF_FUNC_sk_fullsock || 534 func_id == BPF_FUNC_skc_to_tcp_sock || 535 func_id == BPF_FUNC_skc_to_tcp6_sock || 536 func_id == BPF_FUNC_skc_to_udp6_sock || 537 func_id == BPF_FUNC_skc_to_tcp_timewait_sock || 538 func_id == BPF_FUNC_skc_to_tcp_request_sock; 539 } 540 541 static bool is_cmpxchg_insn(const struct bpf_insn *insn) 542 { 543 return BPF_CLASS(insn->code) == BPF_STX && 544 BPF_MODE(insn->code) == BPF_ATOMIC && 545 insn->imm == BPF_CMPXCHG; 546 } 547 548 /* string representation of 'enum bpf_reg_type' */ 549 static const char * const reg_type_str[] = { 550 [NOT_INIT] = "?", 551 [SCALAR_VALUE] = "inv", 552 [PTR_TO_CTX] = "ctx", 553 [CONST_PTR_TO_MAP] = "map_ptr", 554 [PTR_TO_MAP_VALUE] = "map_value", 555 [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", 556 [PTR_TO_STACK] = "fp", 557 [PTR_TO_PACKET] = "pkt", 558 [PTR_TO_PACKET_META] = "pkt_meta", 559 [PTR_TO_PACKET_END] = "pkt_end", 560 [PTR_TO_FLOW_KEYS] = "flow_keys", 561 [PTR_TO_SOCKET] = "sock", 562 [PTR_TO_SOCKET_OR_NULL] = "sock_or_null", 563 [PTR_TO_SOCK_COMMON] = "sock_common", 564 [PTR_TO_SOCK_COMMON_OR_NULL] = "sock_common_or_null", 565 [PTR_TO_TCP_SOCK] = "tcp_sock", 566 [PTR_TO_TCP_SOCK_OR_NULL] = "tcp_sock_or_null", 567 [PTR_TO_TP_BUFFER] = "tp_buffer", 568 [PTR_TO_XDP_SOCK] = "xdp_sock", 569 [PTR_TO_BTF_ID] = "ptr_", 570 [PTR_TO_BTF_ID_OR_NULL] = "ptr_or_null_", 571 [PTR_TO_PERCPU_BTF_ID] = "percpu_ptr_", 572 [PTR_TO_MEM] = "mem", 573 [PTR_TO_MEM_OR_NULL] = "mem_or_null", 574 [PTR_TO_RDONLY_BUF] = "rdonly_buf", 575 [PTR_TO_RDONLY_BUF_OR_NULL] = "rdonly_buf_or_null", 576 [PTR_TO_RDWR_BUF] = "rdwr_buf", 577 [PTR_TO_RDWR_BUF_OR_NULL] = "rdwr_buf_or_null", 578 [PTR_TO_FUNC] = "func", 579 [PTR_TO_MAP_KEY] = "map_key", 580 }; 581 582 static char slot_type_char[] = { 583 [STACK_INVALID] = '?', 584 [STACK_SPILL] = 'r', 585 [STACK_MISC] = 'm', 586 [STACK_ZERO] = '0', 587 }; 588 589 static void print_liveness(struct bpf_verifier_env *env, 590 enum bpf_reg_liveness live) 591 { 592 if (live & (REG_LIVE_READ | REG_LIVE_WRITTEN | REG_LIVE_DONE)) 593 verbose(env, "_"); 594 if (live & REG_LIVE_READ) 595 verbose(env, "r"); 596 if (live & REG_LIVE_WRITTEN) 597 verbose(env, "w"); 598 if (live & REG_LIVE_DONE) 599 verbose(env, "D"); 600 } 601 602 static struct bpf_func_state *func(struct bpf_verifier_env *env, 603 const struct bpf_reg_state *reg) 604 { 605 struct bpf_verifier_state *cur = env->cur_state; 606 607 return cur->frame[reg->frameno]; 608 } 609 610 static const char *kernel_type_name(const struct btf* btf, u32 id) 611 { 612 return btf_name_by_offset(btf, btf_type_by_id(btf, id)->name_off); 613 } 614 615 /* The reg state of a pointer or a bounded scalar was saved when 616 * it was spilled to the stack. 617 */ 618 static bool is_spilled_reg(const struct bpf_stack_state *stack) 619 { 620 return stack->slot_type[BPF_REG_SIZE - 1] == STACK_SPILL; 621 } 622 623 static void scrub_spilled_slot(u8 *stype) 624 { 625 if (*stype != STACK_INVALID) 626 *stype = STACK_MISC; 627 } 628 629 static void print_verifier_state(struct bpf_verifier_env *env, 630 const struct bpf_func_state *state) 631 { 632 const struct bpf_reg_state *reg; 633 enum bpf_reg_type t; 634 int i; 635 636 if (state->frameno) 637 verbose(env, " frame%d:", state->frameno); 638 for (i = 0; i < MAX_BPF_REG; i++) { 639 reg = &state->regs[i]; 640 t = reg->type; 641 if (t == NOT_INIT) 642 continue; 643 verbose(env, " R%d", i); 644 print_liveness(env, reg->live); 645 verbose(env, "=%s", reg_type_str[t]); 646 if (t == SCALAR_VALUE && reg->precise) 647 verbose(env, "P"); 648 if ((t == SCALAR_VALUE || t == PTR_TO_STACK) && 649 tnum_is_const(reg->var_off)) { 650 /* reg->off should be 0 for SCALAR_VALUE */ 651 verbose(env, "%lld", reg->var_off.value + reg->off); 652 } else { 653 if (t == PTR_TO_BTF_ID || 654 t == PTR_TO_BTF_ID_OR_NULL || 655 t == PTR_TO_PERCPU_BTF_ID) 656 verbose(env, "%s", kernel_type_name(reg->btf, reg->btf_id)); 657 verbose(env, "(id=%d", reg->id); 658 if (reg_type_may_be_refcounted_or_null(t)) 659 verbose(env, ",ref_obj_id=%d", reg->ref_obj_id); 660 if (t != SCALAR_VALUE) 661 verbose(env, ",off=%d", reg->off); 662 if (type_is_pkt_pointer(t)) 663 verbose(env, ",r=%d", reg->range); 664 else if (t == CONST_PTR_TO_MAP || 665 t == PTR_TO_MAP_KEY || 666 t == PTR_TO_MAP_VALUE || 667 t == PTR_TO_MAP_VALUE_OR_NULL) 668 verbose(env, ",ks=%d,vs=%d", 669 reg->map_ptr->key_size, 670 reg->map_ptr->value_size); 671 if (tnum_is_const(reg->var_off)) { 672 /* Typically an immediate SCALAR_VALUE, but 673 * could be a pointer whose offset is too big 674 * for reg->off 675 */ 676 verbose(env, ",imm=%llx", reg->var_off.value); 677 } else { 678 if (reg->smin_value != reg->umin_value && 679 reg->smin_value != S64_MIN) 680 verbose(env, ",smin_value=%lld", 681 (long long)reg->smin_value); 682 if (reg->smax_value != reg->umax_value && 683 reg->smax_value != S64_MAX) 684 verbose(env, ",smax_value=%lld", 685 (long long)reg->smax_value); 686 if (reg->umin_value != 0) 687 verbose(env, ",umin_value=%llu", 688 (unsigned long long)reg->umin_value); 689 if (reg->umax_value != U64_MAX) 690 verbose(env, ",umax_value=%llu", 691 (unsigned long long)reg->umax_value); 692 if (!tnum_is_unknown(reg->var_off)) { 693 char tn_buf[48]; 694 695 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 696 verbose(env, ",var_off=%s", tn_buf); 697 } 698 if (reg->s32_min_value != reg->smin_value && 699 reg->s32_min_value != S32_MIN) 700 verbose(env, ",s32_min_value=%d", 701 (int)(reg->s32_min_value)); 702 if (reg->s32_max_value != reg->smax_value && 703 reg->s32_max_value != S32_MAX) 704 verbose(env, ",s32_max_value=%d", 705 (int)(reg->s32_max_value)); 706 if (reg->u32_min_value != reg->umin_value && 707 reg->u32_min_value != U32_MIN) 708 verbose(env, ",u32_min_value=%d", 709 (int)(reg->u32_min_value)); 710 if (reg->u32_max_value != reg->umax_value && 711 reg->u32_max_value != U32_MAX) 712 verbose(env, ",u32_max_value=%d", 713 (int)(reg->u32_max_value)); 714 } 715 verbose(env, ")"); 716 } 717 } 718 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 719 char types_buf[BPF_REG_SIZE + 1]; 720 bool valid = false; 721 int j; 722 723 for (j = 0; j < BPF_REG_SIZE; j++) { 724 if (state->stack[i].slot_type[j] != STACK_INVALID) 725 valid = true; 726 types_buf[j] = slot_type_char[ 727 state->stack[i].slot_type[j]]; 728 } 729 types_buf[BPF_REG_SIZE] = 0; 730 if (!valid) 731 continue; 732 verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE); 733 print_liveness(env, state->stack[i].spilled_ptr.live); 734 if (is_spilled_reg(&state->stack[i])) { 735 reg = &state->stack[i].spilled_ptr; 736 t = reg->type; 737 verbose(env, "=%s", reg_type_str[t]); 738 if (t == SCALAR_VALUE && reg->precise) 739 verbose(env, "P"); 740 if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) 741 verbose(env, "%lld", reg->var_off.value + reg->off); 742 } else { 743 verbose(env, "=%s", types_buf); 744 } 745 } 746 if (state->acquired_refs && state->refs[0].id) { 747 verbose(env, " refs=%d", state->refs[0].id); 748 for (i = 1; i < state->acquired_refs; i++) 749 if (state->refs[i].id) 750 verbose(env, ",%d", state->refs[i].id); 751 } 752 if (state->in_callback_fn) 753 verbose(env, " cb"); 754 if (state->in_async_callback_fn) 755 verbose(env, " async_cb"); 756 verbose(env, "\n"); 757 } 758 759 /* copy array src of length n * size bytes to dst. dst is reallocated if it's too 760 * small to hold src. This is different from krealloc since we don't want to preserve 761 * the contents of dst. 762 * 763 * Leaves dst untouched if src is NULL or length is zero. Returns NULL if memory could 764 * not be allocated. 765 */ 766 static void *copy_array(void *dst, const void *src, size_t n, size_t size, gfp_t flags) 767 { 768 size_t bytes; 769 770 if (ZERO_OR_NULL_PTR(src)) 771 goto out; 772 773 if (unlikely(check_mul_overflow(n, size, &bytes))) 774 return NULL; 775 776 if (ksize(dst) < bytes) { 777 kfree(dst); 778 dst = kmalloc_track_caller(bytes, flags); 779 if (!dst) 780 return NULL; 781 } 782 783 memcpy(dst, src, bytes); 784 out: 785 return dst ? dst : ZERO_SIZE_PTR; 786 } 787 788 /* resize an array from old_n items to new_n items. the array is reallocated if it's too 789 * small to hold new_n items. new items are zeroed out if the array grows. 790 * 791 * Contrary to krealloc_array, does not free arr if new_n is zero. 792 */ 793 static void *realloc_array(void *arr, size_t old_n, size_t new_n, size_t size) 794 { 795 if (!new_n || old_n == new_n) 796 goto out; 797 798 arr = krealloc_array(arr, new_n, size, GFP_KERNEL); 799 if (!arr) 800 return NULL; 801 802 if (new_n > old_n) 803 memset(arr + old_n * size, 0, (new_n - old_n) * size); 804 805 out: 806 return arr ? arr : ZERO_SIZE_PTR; 807 } 808 809 static int copy_reference_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 810 { 811 dst->refs = copy_array(dst->refs, src->refs, src->acquired_refs, 812 sizeof(struct bpf_reference_state), GFP_KERNEL); 813 if (!dst->refs) 814 return -ENOMEM; 815 816 dst->acquired_refs = src->acquired_refs; 817 return 0; 818 } 819 820 static int copy_stack_state(struct bpf_func_state *dst, const struct bpf_func_state *src) 821 { 822 size_t n = src->allocated_stack / BPF_REG_SIZE; 823 824 dst->stack = copy_array(dst->stack, src->stack, n, sizeof(struct bpf_stack_state), 825 GFP_KERNEL); 826 if (!dst->stack) 827 return -ENOMEM; 828 829 dst->allocated_stack = src->allocated_stack; 830 return 0; 831 } 832 833 static int resize_reference_state(struct bpf_func_state *state, size_t n) 834 { 835 state->refs = realloc_array(state->refs, state->acquired_refs, n, 836 sizeof(struct bpf_reference_state)); 837 if (!state->refs) 838 return -ENOMEM; 839 840 state->acquired_refs = n; 841 return 0; 842 } 843 844 static int grow_stack_state(struct bpf_func_state *state, int size) 845 { 846 size_t old_n = state->allocated_stack / BPF_REG_SIZE, n = size / BPF_REG_SIZE; 847 848 if (old_n >= n) 849 return 0; 850 851 state->stack = realloc_array(state->stack, old_n, n, sizeof(struct bpf_stack_state)); 852 if (!state->stack) 853 return -ENOMEM; 854 855 state->allocated_stack = size; 856 return 0; 857 } 858 859 /* Acquire a pointer id from the env and update the state->refs to include 860 * this new pointer reference. 861 * On success, returns a valid pointer id to associate with the register 862 * On failure, returns a negative errno. 863 */ 864 static int acquire_reference_state(struct bpf_verifier_env *env, int insn_idx) 865 { 866 struct bpf_func_state *state = cur_func(env); 867 int new_ofs = state->acquired_refs; 868 int id, err; 869 870 err = resize_reference_state(state, state->acquired_refs + 1); 871 if (err) 872 return err; 873 id = ++env->id_gen; 874 state->refs[new_ofs].id = id; 875 state->refs[new_ofs].insn_idx = insn_idx; 876 877 return id; 878 } 879 880 /* release function corresponding to acquire_reference_state(). Idempotent. */ 881 static int release_reference_state(struct bpf_func_state *state, int ptr_id) 882 { 883 int i, last_idx; 884 885 last_idx = state->acquired_refs - 1; 886 for (i = 0; i < state->acquired_refs; i++) { 887 if (state->refs[i].id == ptr_id) { 888 if (last_idx && i != last_idx) 889 memcpy(&state->refs[i], &state->refs[last_idx], 890 sizeof(*state->refs)); 891 memset(&state->refs[last_idx], 0, sizeof(*state->refs)); 892 state->acquired_refs--; 893 return 0; 894 } 895 } 896 return -EINVAL; 897 } 898 899 static void free_func_state(struct bpf_func_state *state) 900 { 901 if (!state) 902 return; 903 kfree(state->refs); 904 kfree(state->stack); 905 kfree(state); 906 } 907 908 static void clear_jmp_history(struct bpf_verifier_state *state) 909 { 910 kfree(state->jmp_history); 911 state->jmp_history = NULL; 912 state->jmp_history_cnt = 0; 913 } 914 915 static void free_verifier_state(struct bpf_verifier_state *state, 916 bool free_self) 917 { 918 int i; 919 920 for (i = 0; i <= state->curframe; i++) { 921 free_func_state(state->frame[i]); 922 state->frame[i] = NULL; 923 } 924 clear_jmp_history(state); 925 if (free_self) 926 kfree(state); 927 } 928 929 /* copy verifier state from src to dst growing dst stack space 930 * when necessary to accommodate larger src stack 931 */ 932 static int copy_func_state(struct bpf_func_state *dst, 933 const struct bpf_func_state *src) 934 { 935 int err; 936 937 memcpy(dst, src, offsetof(struct bpf_func_state, acquired_refs)); 938 err = copy_reference_state(dst, src); 939 if (err) 940 return err; 941 return copy_stack_state(dst, src); 942 } 943 944 static int copy_verifier_state(struct bpf_verifier_state *dst_state, 945 const struct bpf_verifier_state *src) 946 { 947 struct bpf_func_state *dst; 948 int i, err; 949 950 dst_state->jmp_history = copy_array(dst_state->jmp_history, src->jmp_history, 951 src->jmp_history_cnt, sizeof(struct bpf_idx_pair), 952 GFP_USER); 953 if (!dst_state->jmp_history) 954 return -ENOMEM; 955 dst_state->jmp_history_cnt = src->jmp_history_cnt; 956 957 /* if dst has more stack frames then src frame, free them */ 958 for (i = src->curframe + 1; i <= dst_state->curframe; i++) { 959 free_func_state(dst_state->frame[i]); 960 dst_state->frame[i] = NULL; 961 } 962 dst_state->speculative = src->speculative; 963 dst_state->curframe = src->curframe; 964 dst_state->active_spin_lock = src->active_spin_lock; 965 dst_state->branches = src->branches; 966 dst_state->parent = src->parent; 967 dst_state->first_insn_idx = src->first_insn_idx; 968 dst_state->last_insn_idx = src->last_insn_idx; 969 for (i = 0; i <= src->curframe; i++) { 970 dst = dst_state->frame[i]; 971 if (!dst) { 972 dst = kzalloc(sizeof(*dst), GFP_KERNEL); 973 if (!dst) 974 return -ENOMEM; 975 dst_state->frame[i] = dst; 976 } 977 err = copy_func_state(dst, src->frame[i]); 978 if (err) 979 return err; 980 } 981 return 0; 982 } 983 984 static void update_branch_counts(struct bpf_verifier_env *env, struct bpf_verifier_state *st) 985 { 986 while (st) { 987 u32 br = --st->branches; 988 989 /* WARN_ON(br > 1) technically makes sense here, 990 * but see comment in push_stack(), hence: 991 */ 992 WARN_ONCE((int)br < 0, 993 "BUG update_branch_counts:branches_to_explore=%d\n", 994 br); 995 if (br) 996 break; 997 st = st->parent; 998 } 999 } 1000 1001 static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx, 1002 int *insn_idx, bool pop_log) 1003 { 1004 struct bpf_verifier_state *cur = env->cur_state; 1005 struct bpf_verifier_stack_elem *elem, *head = env->head; 1006 int err; 1007 1008 if (env->head == NULL) 1009 return -ENOENT; 1010 1011 if (cur) { 1012 err = copy_verifier_state(cur, &head->st); 1013 if (err) 1014 return err; 1015 } 1016 if (pop_log) 1017 bpf_vlog_reset(&env->log, head->log_pos); 1018 if (insn_idx) 1019 *insn_idx = head->insn_idx; 1020 if (prev_insn_idx) 1021 *prev_insn_idx = head->prev_insn_idx; 1022 elem = head->next; 1023 free_verifier_state(&head->st, false); 1024 kfree(head); 1025 env->head = elem; 1026 env->stack_size--; 1027 return 0; 1028 } 1029 1030 static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, 1031 int insn_idx, int prev_insn_idx, 1032 bool speculative) 1033 { 1034 struct bpf_verifier_state *cur = env->cur_state; 1035 struct bpf_verifier_stack_elem *elem; 1036 int err; 1037 1038 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1039 if (!elem) 1040 goto err; 1041 1042 elem->insn_idx = insn_idx; 1043 elem->prev_insn_idx = prev_insn_idx; 1044 elem->next = env->head; 1045 elem->log_pos = env->log.len_used; 1046 env->head = elem; 1047 env->stack_size++; 1048 err = copy_verifier_state(&elem->st, cur); 1049 if (err) 1050 goto err; 1051 elem->st.speculative |= speculative; 1052 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1053 verbose(env, "The sequence of %d jumps is too complex.\n", 1054 env->stack_size); 1055 goto err; 1056 } 1057 if (elem->st.parent) { 1058 ++elem->st.parent->branches; 1059 /* WARN_ON(branches > 2) technically makes sense here, 1060 * but 1061 * 1. speculative states will bump 'branches' for non-branch 1062 * instructions 1063 * 2. is_state_visited() heuristics may decide not to create 1064 * a new state for a sequence of branches and all such current 1065 * and cloned states will be pointing to a single parent state 1066 * which might have large 'branches' count. 1067 */ 1068 } 1069 return &elem->st; 1070 err: 1071 free_verifier_state(env->cur_state, true); 1072 env->cur_state = NULL; 1073 /* pop all elements and return */ 1074 while (!pop_stack(env, NULL, NULL, false)); 1075 return NULL; 1076 } 1077 1078 #define CALLER_SAVED_REGS 6 1079 static const int caller_saved[CALLER_SAVED_REGS] = { 1080 BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 1081 }; 1082 1083 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1084 struct bpf_reg_state *reg); 1085 1086 /* This helper doesn't clear reg->id */ 1087 static void ___mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1088 { 1089 reg->var_off = tnum_const(imm); 1090 reg->smin_value = (s64)imm; 1091 reg->smax_value = (s64)imm; 1092 reg->umin_value = imm; 1093 reg->umax_value = imm; 1094 1095 reg->s32_min_value = (s32)imm; 1096 reg->s32_max_value = (s32)imm; 1097 reg->u32_min_value = (u32)imm; 1098 reg->u32_max_value = (u32)imm; 1099 } 1100 1101 /* Mark the unknown part of a register (variable offset or scalar value) as 1102 * known to have the value @imm. 1103 */ 1104 static void __mark_reg_known(struct bpf_reg_state *reg, u64 imm) 1105 { 1106 /* Clear id, off, and union(map_ptr, range) */ 1107 memset(((u8 *)reg) + sizeof(reg->type), 0, 1108 offsetof(struct bpf_reg_state, var_off) - sizeof(reg->type)); 1109 ___mark_reg_known(reg, imm); 1110 } 1111 1112 static void __mark_reg32_known(struct bpf_reg_state *reg, u64 imm) 1113 { 1114 reg->var_off = tnum_const_subreg(reg->var_off, imm); 1115 reg->s32_min_value = (s32)imm; 1116 reg->s32_max_value = (s32)imm; 1117 reg->u32_min_value = (u32)imm; 1118 reg->u32_max_value = (u32)imm; 1119 } 1120 1121 /* Mark the 'variable offset' part of a register as zero. This should be 1122 * used only on registers holding a pointer type. 1123 */ 1124 static void __mark_reg_known_zero(struct bpf_reg_state *reg) 1125 { 1126 __mark_reg_known(reg, 0); 1127 } 1128 1129 static void __mark_reg_const_zero(struct bpf_reg_state *reg) 1130 { 1131 __mark_reg_known(reg, 0); 1132 reg->type = SCALAR_VALUE; 1133 } 1134 1135 static void mark_reg_known_zero(struct bpf_verifier_env *env, 1136 struct bpf_reg_state *regs, u32 regno) 1137 { 1138 if (WARN_ON(regno >= MAX_BPF_REG)) { 1139 verbose(env, "mark_reg_known_zero(regs, %u)\n", regno); 1140 /* Something bad happened, let's kill all regs */ 1141 for (regno = 0; regno < MAX_BPF_REG; regno++) 1142 __mark_reg_not_init(env, regs + regno); 1143 return; 1144 } 1145 __mark_reg_known_zero(regs + regno); 1146 } 1147 1148 static void mark_ptr_not_null_reg(struct bpf_reg_state *reg) 1149 { 1150 switch (reg->type) { 1151 case PTR_TO_MAP_VALUE_OR_NULL: { 1152 const struct bpf_map *map = reg->map_ptr; 1153 1154 if (map->inner_map_meta) { 1155 reg->type = CONST_PTR_TO_MAP; 1156 reg->map_ptr = map->inner_map_meta; 1157 /* transfer reg's id which is unique for every map_lookup_elem 1158 * as UID of the inner map. 1159 */ 1160 reg->map_uid = reg->id; 1161 } else if (map->map_type == BPF_MAP_TYPE_XSKMAP) { 1162 reg->type = PTR_TO_XDP_SOCK; 1163 } else if (map->map_type == BPF_MAP_TYPE_SOCKMAP || 1164 map->map_type == BPF_MAP_TYPE_SOCKHASH) { 1165 reg->type = PTR_TO_SOCKET; 1166 } else { 1167 reg->type = PTR_TO_MAP_VALUE; 1168 } 1169 break; 1170 } 1171 case PTR_TO_SOCKET_OR_NULL: 1172 reg->type = PTR_TO_SOCKET; 1173 break; 1174 case PTR_TO_SOCK_COMMON_OR_NULL: 1175 reg->type = PTR_TO_SOCK_COMMON; 1176 break; 1177 case PTR_TO_TCP_SOCK_OR_NULL: 1178 reg->type = PTR_TO_TCP_SOCK; 1179 break; 1180 case PTR_TO_BTF_ID_OR_NULL: 1181 reg->type = PTR_TO_BTF_ID; 1182 break; 1183 case PTR_TO_MEM_OR_NULL: 1184 reg->type = PTR_TO_MEM; 1185 break; 1186 case PTR_TO_RDONLY_BUF_OR_NULL: 1187 reg->type = PTR_TO_RDONLY_BUF; 1188 break; 1189 case PTR_TO_RDWR_BUF_OR_NULL: 1190 reg->type = PTR_TO_RDWR_BUF; 1191 break; 1192 default: 1193 WARN_ONCE(1, "unknown nullable register type"); 1194 } 1195 } 1196 1197 static bool reg_is_pkt_pointer(const struct bpf_reg_state *reg) 1198 { 1199 return type_is_pkt_pointer(reg->type); 1200 } 1201 1202 static bool reg_is_pkt_pointer_any(const struct bpf_reg_state *reg) 1203 { 1204 return reg_is_pkt_pointer(reg) || 1205 reg->type == PTR_TO_PACKET_END; 1206 } 1207 1208 /* Unmodified PTR_TO_PACKET[_META,_END] register from ctx access. */ 1209 static bool reg_is_init_pkt_pointer(const struct bpf_reg_state *reg, 1210 enum bpf_reg_type which) 1211 { 1212 /* The register can already have a range from prior markings. 1213 * This is fine as long as it hasn't been advanced from its 1214 * origin. 1215 */ 1216 return reg->type == which && 1217 reg->id == 0 && 1218 reg->off == 0 && 1219 tnum_equals_const(reg->var_off, 0); 1220 } 1221 1222 /* Reset the min/max bounds of a register */ 1223 static void __mark_reg_unbounded(struct bpf_reg_state *reg) 1224 { 1225 reg->smin_value = S64_MIN; 1226 reg->smax_value = S64_MAX; 1227 reg->umin_value = 0; 1228 reg->umax_value = U64_MAX; 1229 1230 reg->s32_min_value = S32_MIN; 1231 reg->s32_max_value = S32_MAX; 1232 reg->u32_min_value = 0; 1233 reg->u32_max_value = U32_MAX; 1234 } 1235 1236 static void __mark_reg64_unbounded(struct bpf_reg_state *reg) 1237 { 1238 reg->smin_value = S64_MIN; 1239 reg->smax_value = S64_MAX; 1240 reg->umin_value = 0; 1241 reg->umax_value = U64_MAX; 1242 } 1243 1244 static void __mark_reg32_unbounded(struct bpf_reg_state *reg) 1245 { 1246 reg->s32_min_value = S32_MIN; 1247 reg->s32_max_value = S32_MAX; 1248 reg->u32_min_value = 0; 1249 reg->u32_max_value = U32_MAX; 1250 } 1251 1252 static void __update_reg32_bounds(struct bpf_reg_state *reg) 1253 { 1254 struct tnum var32_off = tnum_subreg(reg->var_off); 1255 1256 /* min signed is max(sign bit) | min(other bits) */ 1257 reg->s32_min_value = max_t(s32, reg->s32_min_value, 1258 var32_off.value | (var32_off.mask & S32_MIN)); 1259 /* max signed is min(sign bit) | max(other bits) */ 1260 reg->s32_max_value = min_t(s32, reg->s32_max_value, 1261 var32_off.value | (var32_off.mask & S32_MAX)); 1262 reg->u32_min_value = max_t(u32, reg->u32_min_value, (u32)var32_off.value); 1263 reg->u32_max_value = min(reg->u32_max_value, 1264 (u32)(var32_off.value | var32_off.mask)); 1265 } 1266 1267 static void __update_reg64_bounds(struct bpf_reg_state *reg) 1268 { 1269 /* min signed is max(sign bit) | min(other bits) */ 1270 reg->smin_value = max_t(s64, reg->smin_value, 1271 reg->var_off.value | (reg->var_off.mask & S64_MIN)); 1272 /* max signed is min(sign bit) | max(other bits) */ 1273 reg->smax_value = min_t(s64, reg->smax_value, 1274 reg->var_off.value | (reg->var_off.mask & S64_MAX)); 1275 reg->umin_value = max(reg->umin_value, reg->var_off.value); 1276 reg->umax_value = min(reg->umax_value, 1277 reg->var_off.value | reg->var_off.mask); 1278 } 1279 1280 static void __update_reg_bounds(struct bpf_reg_state *reg) 1281 { 1282 __update_reg32_bounds(reg); 1283 __update_reg64_bounds(reg); 1284 } 1285 1286 /* Uses signed min/max values to inform unsigned, and vice-versa */ 1287 static void __reg32_deduce_bounds(struct bpf_reg_state *reg) 1288 { 1289 /* Learn sign from signed bounds. 1290 * If we cannot cross the sign boundary, then signed and unsigned bounds 1291 * are the same, so combine. This works even in the negative case, e.g. 1292 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1293 */ 1294 if (reg->s32_min_value >= 0 || reg->s32_max_value < 0) { 1295 reg->s32_min_value = reg->u32_min_value = 1296 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1297 reg->s32_max_value = reg->u32_max_value = 1298 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1299 return; 1300 } 1301 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1302 * boundary, so we must be careful. 1303 */ 1304 if ((s32)reg->u32_max_value >= 0) { 1305 /* Positive. We can't learn anything from the smin, but smax 1306 * is positive, hence safe. 1307 */ 1308 reg->s32_min_value = reg->u32_min_value; 1309 reg->s32_max_value = reg->u32_max_value = 1310 min_t(u32, reg->s32_max_value, reg->u32_max_value); 1311 } else if ((s32)reg->u32_min_value < 0) { 1312 /* Negative. We can't learn anything from the smax, but smin 1313 * is negative, hence safe. 1314 */ 1315 reg->s32_min_value = reg->u32_min_value = 1316 max_t(u32, reg->s32_min_value, reg->u32_min_value); 1317 reg->s32_max_value = reg->u32_max_value; 1318 } 1319 } 1320 1321 static void __reg64_deduce_bounds(struct bpf_reg_state *reg) 1322 { 1323 /* Learn sign from signed bounds. 1324 * If we cannot cross the sign boundary, then signed and unsigned bounds 1325 * are the same, so combine. This works even in the negative case, e.g. 1326 * -3 s<= x s<= -1 implies 0xf...fd u<= x u<= 0xf...ff. 1327 */ 1328 if (reg->smin_value >= 0 || reg->smax_value < 0) { 1329 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1330 reg->umin_value); 1331 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1332 reg->umax_value); 1333 return; 1334 } 1335 /* Learn sign from unsigned bounds. Signed bounds cross the sign 1336 * boundary, so we must be careful. 1337 */ 1338 if ((s64)reg->umax_value >= 0) { 1339 /* Positive. We can't learn anything from the smin, but smax 1340 * is positive, hence safe. 1341 */ 1342 reg->smin_value = reg->umin_value; 1343 reg->smax_value = reg->umax_value = min_t(u64, reg->smax_value, 1344 reg->umax_value); 1345 } else if ((s64)reg->umin_value < 0) { 1346 /* Negative. We can't learn anything from the smax, but smin 1347 * is negative, hence safe. 1348 */ 1349 reg->smin_value = reg->umin_value = max_t(u64, reg->smin_value, 1350 reg->umin_value); 1351 reg->smax_value = reg->umax_value; 1352 } 1353 } 1354 1355 static void __reg_deduce_bounds(struct bpf_reg_state *reg) 1356 { 1357 __reg32_deduce_bounds(reg); 1358 __reg64_deduce_bounds(reg); 1359 } 1360 1361 /* Attempts to improve var_off based on unsigned min/max information */ 1362 static void __reg_bound_offset(struct bpf_reg_state *reg) 1363 { 1364 struct tnum var64_off = tnum_intersect(reg->var_off, 1365 tnum_range(reg->umin_value, 1366 reg->umax_value)); 1367 struct tnum var32_off = tnum_intersect(tnum_subreg(reg->var_off), 1368 tnum_range(reg->u32_min_value, 1369 reg->u32_max_value)); 1370 1371 reg->var_off = tnum_or(tnum_clear_subreg(var64_off), var32_off); 1372 } 1373 1374 static void __reg_assign_32_into_64(struct bpf_reg_state *reg) 1375 { 1376 reg->umin_value = reg->u32_min_value; 1377 reg->umax_value = reg->u32_max_value; 1378 /* Attempt to pull 32-bit signed bounds into 64-bit bounds 1379 * but must be positive otherwise set to worse case bounds 1380 * and refine later from tnum. 1381 */ 1382 if (reg->s32_min_value >= 0 && reg->s32_max_value >= 0) 1383 reg->smax_value = reg->s32_max_value; 1384 else 1385 reg->smax_value = U32_MAX; 1386 if (reg->s32_min_value >= 0) 1387 reg->smin_value = reg->s32_min_value; 1388 else 1389 reg->smin_value = 0; 1390 } 1391 1392 static void __reg_combine_32_into_64(struct bpf_reg_state *reg) 1393 { 1394 /* special case when 64-bit register has upper 32-bit register 1395 * zeroed. Typically happens after zext or <<32, >>32 sequence 1396 * allowing us to use 32-bit bounds directly, 1397 */ 1398 if (tnum_equals_const(tnum_clear_subreg(reg->var_off), 0)) { 1399 __reg_assign_32_into_64(reg); 1400 } else { 1401 /* Otherwise the best we can do is push lower 32bit known and 1402 * unknown bits into register (var_off set from jmp logic) 1403 * then learn as much as possible from the 64-bit tnum 1404 * known and unknown bits. The previous smin/smax bounds are 1405 * invalid here because of jmp32 compare so mark them unknown 1406 * so they do not impact tnum bounds calculation. 1407 */ 1408 __mark_reg64_unbounded(reg); 1409 __update_reg_bounds(reg); 1410 } 1411 1412 /* Intersecting with the old var_off might have improved our bounds 1413 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1414 * then new var_off is (0; 0x7f...fc) which improves our umax. 1415 */ 1416 __reg_deduce_bounds(reg); 1417 __reg_bound_offset(reg); 1418 __update_reg_bounds(reg); 1419 } 1420 1421 static bool __reg64_bound_s32(s64 a) 1422 { 1423 return a >= S32_MIN && a <= S32_MAX; 1424 } 1425 1426 static bool __reg64_bound_u32(u64 a) 1427 { 1428 return a >= U32_MIN && a <= U32_MAX; 1429 } 1430 1431 static void __reg_combine_64_into_32(struct bpf_reg_state *reg) 1432 { 1433 __mark_reg32_unbounded(reg); 1434 1435 if (__reg64_bound_s32(reg->smin_value) && __reg64_bound_s32(reg->smax_value)) { 1436 reg->s32_min_value = (s32)reg->smin_value; 1437 reg->s32_max_value = (s32)reg->smax_value; 1438 } 1439 if (__reg64_bound_u32(reg->umin_value) && __reg64_bound_u32(reg->umax_value)) { 1440 reg->u32_min_value = (u32)reg->umin_value; 1441 reg->u32_max_value = (u32)reg->umax_value; 1442 } 1443 1444 /* Intersecting with the old var_off might have improved our bounds 1445 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 1446 * then new var_off is (0; 0x7f...fc) which improves our umax. 1447 */ 1448 __reg_deduce_bounds(reg); 1449 __reg_bound_offset(reg); 1450 __update_reg_bounds(reg); 1451 } 1452 1453 /* Mark a register as having a completely unknown (scalar) value. */ 1454 static void __mark_reg_unknown(const struct bpf_verifier_env *env, 1455 struct bpf_reg_state *reg) 1456 { 1457 /* 1458 * Clear type, id, off, and union(map_ptr, range) and 1459 * padding between 'type' and union 1460 */ 1461 memset(reg, 0, offsetof(struct bpf_reg_state, var_off)); 1462 reg->type = SCALAR_VALUE; 1463 reg->var_off = tnum_unknown; 1464 reg->frameno = 0; 1465 reg->precise = env->subprog_cnt > 1 || !env->bpf_capable; 1466 __mark_reg_unbounded(reg); 1467 } 1468 1469 static void mark_reg_unknown(struct bpf_verifier_env *env, 1470 struct bpf_reg_state *regs, u32 regno) 1471 { 1472 if (WARN_ON(regno >= MAX_BPF_REG)) { 1473 verbose(env, "mark_reg_unknown(regs, %u)\n", regno); 1474 /* Something bad happened, let's kill all regs except FP */ 1475 for (regno = 0; regno < BPF_REG_FP; regno++) 1476 __mark_reg_not_init(env, regs + regno); 1477 return; 1478 } 1479 __mark_reg_unknown(env, regs + regno); 1480 } 1481 1482 static void __mark_reg_not_init(const struct bpf_verifier_env *env, 1483 struct bpf_reg_state *reg) 1484 { 1485 __mark_reg_unknown(env, reg); 1486 reg->type = NOT_INIT; 1487 } 1488 1489 static void mark_reg_not_init(struct bpf_verifier_env *env, 1490 struct bpf_reg_state *regs, u32 regno) 1491 { 1492 if (WARN_ON(regno >= MAX_BPF_REG)) { 1493 verbose(env, "mark_reg_not_init(regs, %u)\n", regno); 1494 /* Something bad happened, let's kill all regs except FP */ 1495 for (regno = 0; regno < BPF_REG_FP; regno++) 1496 __mark_reg_not_init(env, regs + regno); 1497 return; 1498 } 1499 __mark_reg_not_init(env, regs + regno); 1500 } 1501 1502 static void mark_btf_ld_reg(struct bpf_verifier_env *env, 1503 struct bpf_reg_state *regs, u32 regno, 1504 enum bpf_reg_type reg_type, 1505 struct btf *btf, u32 btf_id) 1506 { 1507 if (reg_type == SCALAR_VALUE) { 1508 mark_reg_unknown(env, regs, regno); 1509 return; 1510 } 1511 mark_reg_known_zero(env, regs, regno); 1512 regs[regno].type = PTR_TO_BTF_ID; 1513 regs[regno].btf = btf; 1514 regs[regno].btf_id = btf_id; 1515 } 1516 1517 #define DEF_NOT_SUBREG (0) 1518 static void init_reg_state(struct bpf_verifier_env *env, 1519 struct bpf_func_state *state) 1520 { 1521 struct bpf_reg_state *regs = state->regs; 1522 int i; 1523 1524 for (i = 0; i < MAX_BPF_REG; i++) { 1525 mark_reg_not_init(env, regs, i); 1526 regs[i].live = REG_LIVE_NONE; 1527 regs[i].parent = NULL; 1528 regs[i].subreg_def = DEF_NOT_SUBREG; 1529 } 1530 1531 /* frame pointer */ 1532 regs[BPF_REG_FP].type = PTR_TO_STACK; 1533 mark_reg_known_zero(env, regs, BPF_REG_FP); 1534 regs[BPF_REG_FP].frameno = state->frameno; 1535 } 1536 1537 #define BPF_MAIN_FUNC (-1) 1538 static void init_func_state(struct bpf_verifier_env *env, 1539 struct bpf_func_state *state, 1540 int callsite, int frameno, int subprogno) 1541 { 1542 state->callsite = callsite; 1543 state->frameno = frameno; 1544 state->subprogno = subprogno; 1545 init_reg_state(env, state); 1546 } 1547 1548 /* Similar to push_stack(), but for async callbacks */ 1549 static struct bpf_verifier_state *push_async_cb(struct bpf_verifier_env *env, 1550 int insn_idx, int prev_insn_idx, 1551 int subprog) 1552 { 1553 struct bpf_verifier_stack_elem *elem; 1554 struct bpf_func_state *frame; 1555 1556 elem = kzalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); 1557 if (!elem) 1558 goto err; 1559 1560 elem->insn_idx = insn_idx; 1561 elem->prev_insn_idx = prev_insn_idx; 1562 elem->next = env->head; 1563 elem->log_pos = env->log.len_used; 1564 env->head = elem; 1565 env->stack_size++; 1566 if (env->stack_size > BPF_COMPLEXITY_LIMIT_JMP_SEQ) { 1567 verbose(env, 1568 "The sequence of %d jumps is too complex for async cb.\n", 1569 env->stack_size); 1570 goto err; 1571 } 1572 /* Unlike push_stack() do not copy_verifier_state(). 1573 * The caller state doesn't matter. 1574 * This is async callback. It starts in a fresh stack. 1575 * Initialize it similar to do_check_common(). 1576 */ 1577 elem->st.branches = 1; 1578 frame = kzalloc(sizeof(*frame), GFP_KERNEL); 1579 if (!frame) 1580 goto err; 1581 init_func_state(env, frame, 1582 BPF_MAIN_FUNC /* callsite */, 1583 0 /* frameno within this callchain */, 1584 subprog /* subprog number within this prog */); 1585 elem->st.frame[0] = frame; 1586 return &elem->st; 1587 err: 1588 free_verifier_state(env->cur_state, true); 1589 env->cur_state = NULL; 1590 /* pop all elements and return */ 1591 while (!pop_stack(env, NULL, NULL, false)); 1592 return NULL; 1593 } 1594 1595 1596 enum reg_arg_type { 1597 SRC_OP, /* register is used as source operand */ 1598 DST_OP, /* register is used as destination operand */ 1599 DST_OP_NO_MARK /* same as above, check only, don't mark */ 1600 }; 1601 1602 static int cmp_subprogs(const void *a, const void *b) 1603 { 1604 return ((struct bpf_subprog_info *)a)->start - 1605 ((struct bpf_subprog_info *)b)->start; 1606 } 1607 1608 static int find_subprog(struct bpf_verifier_env *env, int off) 1609 { 1610 struct bpf_subprog_info *p; 1611 1612 p = bsearch(&off, env->subprog_info, env->subprog_cnt, 1613 sizeof(env->subprog_info[0]), cmp_subprogs); 1614 if (!p) 1615 return -ENOENT; 1616 return p - env->subprog_info; 1617 1618 } 1619 1620 static int add_subprog(struct bpf_verifier_env *env, int off) 1621 { 1622 int insn_cnt = env->prog->len; 1623 int ret; 1624 1625 if (off >= insn_cnt || off < 0) { 1626 verbose(env, "call to invalid destination\n"); 1627 return -EINVAL; 1628 } 1629 ret = find_subprog(env, off); 1630 if (ret >= 0) 1631 return ret; 1632 if (env->subprog_cnt >= BPF_MAX_SUBPROGS) { 1633 verbose(env, "too many subprograms\n"); 1634 return -E2BIG; 1635 } 1636 /* determine subprog starts. The end is one before the next starts */ 1637 env->subprog_info[env->subprog_cnt++].start = off; 1638 sort(env->subprog_info, env->subprog_cnt, 1639 sizeof(env->subprog_info[0]), cmp_subprogs, NULL); 1640 return env->subprog_cnt - 1; 1641 } 1642 1643 #define MAX_KFUNC_DESCS 256 1644 #define MAX_KFUNC_BTFS 256 1645 1646 struct bpf_kfunc_desc { 1647 struct btf_func_model func_model; 1648 u32 func_id; 1649 s32 imm; 1650 u16 offset; 1651 }; 1652 1653 struct bpf_kfunc_btf { 1654 struct btf *btf; 1655 struct module *module; 1656 u16 offset; 1657 }; 1658 1659 struct bpf_kfunc_desc_tab { 1660 struct bpf_kfunc_desc descs[MAX_KFUNC_DESCS]; 1661 u32 nr_descs; 1662 }; 1663 1664 struct bpf_kfunc_btf_tab { 1665 struct bpf_kfunc_btf descs[MAX_KFUNC_BTFS]; 1666 u32 nr_descs; 1667 }; 1668 1669 static int kfunc_desc_cmp_by_id_off(const void *a, const void *b) 1670 { 1671 const struct bpf_kfunc_desc *d0 = a; 1672 const struct bpf_kfunc_desc *d1 = b; 1673 1674 /* func_id is not greater than BTF_MAX_TYPE */ 1675 return d0->func_id - d1->func_id ?: d0->offset - d1->offset; 1676 } 1677 1678 static int kfunc_btf_cmp_by_off(const void *a, const void *b) 1679 { 1680 const struct bpf_kfunc_btf *d0 = a; 1681 const struct bpf_kfunc_btf *d1 = b; 1682 1683 return d0->offset - d1->offset; 1684 } 1685 1686 static const struct bpf_kfunc_desc * 1687 find_kfunc_desc(const struct bpf_prog *prog, u32 func_id, u16 offset) 1688 { 1689 struct bpf_kfunc_desc desc = { 1690 .func_id = func_id, 1691 .offset = offset, 1692 }; 1693 struct bpf_kfunc_desc_tab *tab; 1694 1695 tab = prog->aux->kfunc_tab; 1696 return bsearch(&desc, tab->descs, tab->nr_descs, 1697 sizeof(tab->descs[0]), kfunc_desc_cmp_by_id_off); 1698 } 1699 1700 static struct btf *__find_kfunc_desc_btf(struct bpf_verifier_env *env, 1701 s16 offset, struct module **btf_modp) 1702 { 1703 struct bpf_kfunc_btf kf_btf = { .offset = offset }; 1704 struct bpf_kfunc_btf_tab *tab; 1705 struct bpf_kfunc_btf *b; 1706 struct module *mod; 1707 struct btf *btf; 1708 int btf_fd; 1709 1710 tab = env->prog->aux->kfunc_btf_tab; 1711 b = bsearch(&kf_btf, tab->descs, tab->nr_descs, 1712 sizeof(tab->descs[0]), kfunc_btf_cmp_by_off); 1713 if (!b) { 1714 if (tab->nr_descs == MAX_KFUNC_BTFS) { 1715 verbose(env, "too many different module BTFs\n"); 1716 return ERR_PTR(-E2BIG); 1717 } 1718 1719 if (bpfptr_is_null(env->fd_array)) { 1720 verbose(env, "kfunc offset > 0 without fd_array is invalid\n"); 1721 return ERR_PTR(-EPROTO); 1722 } 1723 1724 if (copy_from_bpfptr_offset(&btf_fd, env->fd_array, 1725 offset * sizeof(btf_fd), 1726 sizeof(btf_fd))) 1727 return ERR_PTR(-EFAULT); 1728 1729 btf = btf_get_by_fd(btf_fd); 1730 if (IS_ERR(btf)) { 1731 verbose(env, "invalid module BTF fd specified\n"); 1732 return btf; 1733 } 1734 1735 if (!btf_is_module(btf)) { 1736 verbose(env, "BTF fd for kfunc is not a module BTF\n"); 1737 btf_put(btf); 1738 return ERR_PTR(-EINVAL); 1739 } 1740 1741 mod = btf_try_get_module(btf); 1742 if (!mod) { 1743 btf_put(btf); 1744 return ERR_PTR(-ENXIO); 1745 } 1746 1747 b = &tab->descs[tab->nr_descs++]; 1748 b->btf = btf; 1749 b->module = mod; 1750 b->offset = offset; 1751 1752 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 1753 kfunc_btf_cmp_by_off, NULL); 1754 } 1755 if (btf_modp) 1756 *btf_modp = b->module; 1757 return b->btf; 1758 } 1759 1760 void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab) 1761 { 1762 if (!tab) 1763 return; 1764 1765 while (tab->nr_descs--) { 1766 module_put(tab->descs[tab->nr_descs].module); 1767 btf_put(tab->descs[tab->nr_descs].btf); 1768 } 1769 kfree(tab); 1770 } 1771 1772 static struct btf *find_kfunc_desc_btf(struct bpf_verifier_env *env, 1773 u32 func_id, s16 offset, 1774 struct module **btf_modp) 1775 { 1776 if (offset) { 1777 if (offset < 0) { 1778 /* In the future, this can be allowed to increase limit 1779 * of fd index into fd_array, interpreted as u16. 1780 */ 1781 verbose(env, "negative offset disallowed for kernel module function call\n"); 1782 return ERR_PTR(-EINVAL); 1783 } 1784 1785 return __find_kfunc_desc_btf(env, offset, btf_modp); 1786 } 1787 return btf_vmlinux ?: ERR_PTR(-ENOENT); 1788 } 1789 1790 static int add_kfunc_call(struct bpf_verifier_env *env, u32 func_id, s16 offset) 1791 { 1792 const struct btf_type *func, *func_proto; 1793 struct bpf_kfunc_btf_tab *btf_tab; 1794 struct bpf_kfunc_desc_tab *tab; 1795 struct bpf_prog_aux *prog_aux; 1796 struct bpf_kfunc_desc *desc; 1797 const char *func_name; 1798 struct btf *desc_btf; 1799 unsigned long addr; 1800 int err; 1801 1802 prog_aux = env->prog->aux; 1803 tab = prog_aux->kfunc_tab; 1804 btf_tab = prog_aux->kfunc_btf_tab; 1805 if (!tab) { 1806 if (!btf_vmlinux) { 1807 verbose(env, "calling kernel function is not supported without CONFIG_DEBUG_INFO_BTF\n"); 1808 return -ENOTSUPP; 1809 } 1810 1811 if (!env->prog->jit_requested) { 1812 verbose(env, "JIT is required for calling kernel function\n"); 1813 return -ENOTSUPP; 1814 } 1815 1816 if (!bpf_jit_supports_kfunc_call()) { 1817 verbose(env, "JIT does not support calling kernel function\n"); 1818 return -ENOTSUPP; 1819 } 1820 1821 if (!env->prog->gpl_compatible) { 1822 verbose(env, "cannot call kernel function from non-GPL compatible program\n"); 1823 return -EINVAL; 1824 } 1825 1826 tab = kzalloc(sizeof(*tab), GFP_KERNEL); 1827 if (!tab) 1828 return -ENOMEM; 1829 prog_aux->kfunc_tab = tab; 1830 } 1831 1832 /* func_id == 0 is always invalid, but instead of returning an error, be 1833 * conservative and wait until the code elimination pass before returning 1834 * error, so that invalid calls that get pruned out can be in BPF programs 1835 * loaded from userspace. It is also required that offset be untouched 1836 * for such calls. 1837 */ 1838 if (!func_id && !offset) 1839 return 0; 1840 1841 if (!btf_tab && offset) { 1842 btf_tab = kzalloc(sizeof(*btf_tab), GFP_KERNEL); 1843 if (!btf_tab) 1844 return -ENOMEM; 1845 prog_aux->kfunc_btf_tab = btf_tab; 1846 } 1847 1848 desc_btf = find_kfunc_desc_btf(env, func_id, offset, NULL); 1849 if (IS_ERR(desc_btf)) { 1850 verbose(env, "failed to find BTF for kernel function\n"); 1851 return PTR_ERR(desc_btf); 1852 } 1853 1854 if (find_kfunc_desc(env->prog, func_id, offset)) 1855 return 0; 1856 1857 if (tab->nr_descs == MAX_KFUNC_DESCS) { 1858 verbose(env, "too many different kernel function calls\n"); 1859 return -E2BIG; 1860 } 1861 1862 func = btf_type_by_id(desc_btf, func_id); 1863 if (!func || !btf_type_is_func(func)) { 1864 verbose(env, "kernel btf_id %u is not a function\n", 1865 func_id); 1866 return -EINVAL; 1867 } 1868 func_proto = btf_type_by_id(desc_btf, func->type); 1869 if (!func_proto || !btf_type_is_func_proto(func_proto)) { 1870 verbose(env, "kernel function btf_id %u does not have a valid func_proto\n", 1871 func_id); 1872 return -EINVAL; 1873 } 1874 1875 func_name = btf_name_by_offset(desc_btf, func->name_off); 1876 addr = kallsyms_lookup_name(func_name); 1877 if (!addr) { 1878 verbose(env, "cannot find address for kernel function %s\n", 1879 func_name); 1880 return -EINVAL; 1881 } 1882 1883 desc = &tab->descs[tab->nr_descs++]; 1884 desc->func_id = func_id; 1885 desc->imm = BPF_CALL_IMM(addr); 1886 desc->offset = offset; 1887 err = btf_distill_func_proto(&env->log, desc_btf, 1888 func_proto, func_name, 1889 &desc->func_model); 1890 if (!err) 1891 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 1892 kfunc_desc_cmp_by_id_off, NULL); 1893 return err; 1894 } 1895 1896 static int kfunc_desc_cmp_by_imm(const void *a, const void *b) 1897 { 1898 const struct bpf_kfunc_desc *d0 = a; 1899 const struct bpf_kfunc_desc *d1 = b; 1900 1901 if (d0->imm > d1->imm) 1902 return 1; 1903 else if (d0->imm < d1->imm) 1904 return -1; 1905 return 0; 1906 } 1907 1908 static void sort_kfunc_descs_by_imm(struct bpf_prog *prog) 1909 { 1910 struct bpf_kfunc_desc_tab *tab; 1911 1912 tab = prog->aux->kfunc_tab; 1913 if (!tab) 1914 return; 1915 1916 sort(tab->descs, tab->nr_descs, sizeof(tab->descs[0]), 1917 kfunc_desc_cmp_by_imm, NULL); 1918 } 1919 1920 bool bpf_prog_has_kfunc_call(const struct bpf_prog *prog) 1921 { 1922 return !!prog->aux->kfunc_tab; 1923 } 1924 1925 const struct btf_func_model * 1926 bpf_jit_find_kfunc_model(const struct bpf_prog *prog, 1927 const struct bpf_insn *insn) 1928 { 1929 const struct bpf_kfunc_desc desc = { 1930 .imm = insn->imm, 1931 }; 1932 const struct bpf_kfunc_desc *res; 1933 struct bpf_kfunc_desc_tab *tab; 1934 1935 tab = prog->aux->kfunc_tab; 1936 res = bsearch(&desc, tab->descs, tab->nr_descs, 1937 sizeof(tab->descs[0]), kfunc_desc_cmp_by_imm); 1938 1939 return res ? &res->func_model : NULL; 1940 } 1941 1942 static int add_subprog_and_kfunc(struct bpf_verifier_env *env) 1943 { 1944 struct bpf_subprog_info *subprog = env->subprog_info; 1945 struct bpf_insn *insn = env->prog->insnsi; 1946 int i, ret, insn_cnt = env->prog->len; 1947 1948 /* Add entry function. */ 1949 ret = add_subprog(env, 0); 1950 if (ret) 1951 return ret; 1952 1953 for (i = 0; i < insn_cnt; i++, insn++) { 1954 if (!bpf_pseudo_func(insn) && !bpf_pseudo_call(insn) && 1955 !bpf_pseudo_kfunc_call(insn)) 1956 continue; 1957 1958 if (!env->bpf_capable) { 1959 verbose(env, "loading/calling other bpf or kernel functions are allowed for CAP_BPF and CAP_SYS_ADMIN\n"); 1960 return -EPERM; 1961 } 1962 1963 if (bpf_pseudo_func(insn)) { 1964 ret = add_subprog(env, i + insn->imm + 1); 1965 if (ret >= 0) 1966 /* remember subprog */ 1967 insn[1].imm = ret; 1968 } else if (bpf_pseudo_call(insn)) { 1969 ret = add_subprog(env, i + insn->imm + 1); 1970 } else { 1971 ret = add_kfunc_call(env, insn->imm, insn->off); 1972 } 1973 1974 if (ret < 0) 1975 return ret; 1976 } 1977 1978 /* Add a fake 'exit' subprog which could simplify subprog iteration 1979 * logic. 'subprog_cnt' should not be increased. 1980 */ 1981 subprog[env->subprog_cnt].start = insn_cnt; 1982 1983 if (env->log.level & BPF_LOG_LEVEL2) 1984 for (i = 0; i < env->subprog_cnt; i++) 1985 verbose(env, "func#%d @%d\n", i, subprog[i].start); 1986 1987 return 0; 1988 } 1989 1990 static int check_subprogs(struct bpf_verifier_env *env) 1991 { 1992 int i, subprog_start, subprog_end, off, cur_subprog = 0; 1993 struct bpf_subprog_info *subprog = env->subprog_info; 1994 struct bpf_insn *insn = env->prog->insnsi; 1995 int insn_cnt = env->prog->len; 1996 1997 /* now check that all jumps are within the same subprog */ 1998 subprog_start = subprog[cur_subprog].start; 1999 subprog_end = subprog[cur_subprog + 1].start; 2000 for (i = 0; i < insn_cnt; i++) { 2001 u8 code = insn[i].code; 2002 2003 if (code == (BPF_JMP | BPF_CALL) && 2004 insn[i].imm == BPF_FUNC_tail_call && 2005 insn[i].src_reg != BPF_PSEUDO_CALL) 2006 subprog[cur_subprog].has_tail_call = true; 2007 if (BPF_CLASS(code) == BPF_LD && 2008 (BPF_MODE(code) == BPF_ABS || BPF_MODE(code) == BPF_IND)) 2009 subprog[cur_subprog].has_ld_abs = true; 2010 if (BPF_CLASS(code) != BPF_JMP && BPF_CLASS(code) != BPF_JMP32) 2011 goto next; 2012 if (BPF_OP(code) == BPF_EXIT || BPF_OP(code) == BPF_CALL) 2013 goto next; 2014 off = i + insn[i].off + 1; 2015 if (off < subprog_start || off >= subprog_end) { 2016 verbose(env, "jump out of range from insn %d to %d\n", i, off); 2017 return -EINVAL; 2018 } 2019 next: 2020 if (i == subprog_end - 1) { 2021 /* to avoid fall-through from one subprog into another 2022 * the last insn of the subprog should be either exit 2023 * or unconditional jump back 2024 */ 2025 if (code != (BPF_JMP | BPF_EXIT) && 2026 code != (BPF_JMP | BPF_JA)) { 2027 verbose(env, "last insn is not an exit or jmp\n"); 2028 return -EINVAL; 2029 } 2030 subprog_start = subprog_end; 2031 cur_subprog++; 2032 if (cur_subprog < env->subprog_cnt) 2033 subprog_end = subprog[cur_subprog + 1].start; 2034 } 2035 } 2036 return 0; 2037 } 2038 2039 /* Parentage chain of this register (or stack slot) should take care of all 2040 * issues like callee-saved registers, stack slot allocation time, etc. 2041 */ 2042 static int mark_reg_read(struct bpf_verifier_env *env, 2043 const struct bpf_reg_state *state, 2044 struct bpf_reg_state *parent, u8 flag) 2045 { 2046 bool writes = parent == state->parent; /* Observe write marks */ 2047 int cnt = 0; 2048 2049 while (parent) { 2050 /* if read wasn't screened by an earlier write ... */ 2051 if (writes && state->live & REG_LIVE_WRITTEN) 2052 break; 2053 if (parent->live & REG_LIVE_DONE) { 2054 verbose(env, "verifier BUG type %s var_off %lld off %d\n", 2055 reg_type_str[parent->type], 2056 parent->var_off.value, parent->off); 2057 return -EFAULT; 2058 } 2059 /* The first condition is more likely to be true than the 2060 * second, checked it first. 2061 */ 2062 if ((parent->live & REG_LIVE_READ) == flag || 2063 parent->live & REG_LIVE_READ64) 2064 /* The parentage chain never changes and 2065 * this parent was already marked as LIVE_READ. 2066 * There is no need to keep walking the chain again and 2067 * keep re-marking all parents as LIVE_READ. 2068 * This case happens when the same register is read 2069 * multiple times without writes into it in-between. 2070 * Also, if parent has the stronger REG_LIVE_READ64 set, 2071 * then no need to set the weak REG_LIVE_READ32. 2072 */ 2073 break; 2074 /* ... then we depend on parent's value */ 2075 parent->live |= flag; 2076 /* REG_LIVE_READ64 overrides REG_LIVE_READ32. */ 2077 if (flag == REG_LIVE_READ64) 2078 parent->live &= ~REG_LIVE_READ32; 2079 state = parent; 2080 parent = state->parent; 2081 writes = true; 2082 cnt++; 2083 } 2084 2085 if (env->longest_mark_read_walk < cnt) 2086 env->longest_mark_read_walk = cnt; 2087 return 0; 2088 } 2089 2090 /* This function is supposed to be used by the following 32-bit optimization 2091 * code only. It returns TRUE if the source or destination register operates 2092 * on 64-bit, otherwise return FALSE. 2093 */ 2094 static bool is_reg64(struct bpf_verifier_env *env, struct bpf_insn *insn, 2095 u32 regno, struct bpf_reg_state *reg, enum reg_arg_type t) 2096 { 2097 u8 code, class, op; 2098 2099 code = insn->code; 2100 class = BPF_CLASS(code); 2101 op = BPF_OP(code); 2102 if (class == BPF_JMP) { 2103 /* BPF_EXIT for "main" will reach here. Return TRUE 2104 * conservatively. 2105 */ 2106 if (op == BPF_EXIT) 2107 return true; 2108 if (op == BPF_CALL) { 2109 /* BPF to BPF call will reach here because of marking 2110 * caller saved clobber with DST_OP_NO_MARK for which we 2111 * don't care the register def because they are anyway 2112 * marked as NOT_INIT already. 2113 */ 2114 if (insn->src_reg == BPF_PSEUDO_CALL) 2115 return false; 2116 /* Helper call will reach here because of arg type 2117 * check, conservatively return TRUE. 2118 */ 2119 if (t == SRC_OP) 2120 return true; 2121 2122 return false; 2123 } 2124 } 2125 2126 if (class == BPF_ALU64 || class == BPF_JMP || 2127 /* BPF_END always use BPF_ALU class. */ 2128 (class == BPF_ALU && op == BPF_END && insn->imm == 64)) 2129 return true; 2130 2131 if (class == BPF_ALU || class == BPF_JMP32) 2132 return false; 2133 2134 if (class == BPF_LDX) { 2135 if (t != SRC_OP) 2136 return BPF_SIZE(code) == BPF_DW; 2137 /* LDX source must be ptr. */ 2138 return true; 2139 } 2140 2141 if (class == BPF_STX) { 2142 /* BPF_STX (including atomic variants) has multiple source 2143 * operands, one of which is a ptr. Check whether the caller is 2144 * asking about it. 2145 */ 2146 if (t == SRC_OP && reg->type != SCALAR_VALUE) 2147 return true; 2148 return BPF_SIZE(code) == BPF_DW; 2149 } 2150 2151 if (class == BPF_LD) { 2152 u8 mode = BPF_MODE(code); 2153 2154 /* LD_IMM64 */ 2155 if (mode == BPF_IMM) 2156 return true; 2157 2158 /* Both LD_IND and LD_ABS return 32-bit data. */ 2159 if (t != SRC_OP) 2160 return false; 2161 2162 /* Implicit ctx ptr. */ 2163 if (regno == BPF_REG_6) 2164 return true; 2165 2166 /* Explicit source could be any width. */ 2167 return true; 2168 } 2169 2170 if (class == BPF_ST) 2171 /* The only source register for BPF_ST is a ptr. */ 2172 return true; 2173 2174 /* Conservatively return true at default. */ 2175 return true; 2176 } 2177 2178 /* Return the regno defined by the insn, or -1. */ 2179 static int insn_def_regno(const struct bpf_insn *insn) 2180 { 2181 switch (BPF_CLASS(insn->code)) { 2182 case BPF_JMP: 2183 case BPF_JMP32: 2184 case BPF_ST: 2185 return -1; 2186 case BPF_STX: 2187 if (BPF_MODE(insn->code) == BPF_ATOMIC && 2188 (insn->imm & BPF_FETCH)) { 2189 if (insn->imm == BPF_CMPXCHG) 2190 return BPF_REG_0; 2191 else 2192 return insn->src_reg; 2193 } else { 2194 return -1; 2195 } 2196 default: 2197 return insn->dst_reg; 2198 } 2199 } 2200 2201 /* Return TRUE if INSN has defined any 32-bit value explicitly. */ 2202 static bool insn_has_def32(struct bpf_verifier_env *env, struct bpf_insn *insn) 2203 { 2204 int dst_reg = insn_def_regno(insn); 2205 2206 if (dst_reg == -1) 2207 return false; 2208 2209 return !is_reg64(env, insn, dst_reg, NULL, DST_OP); 2210 } 2211 2212 static void mark_insn_zext(struct bpf_verifier_env *env, 2213 struct bpf_reg_state *reg) 2214 { 2215 s32 def_idx = reg->subreg_def; 2216 2217 if (def_idx == DEF_NOT_SUBREG) 2218 return; 2219 2220 env->insn_aux_data[def_idx - 1].zext_dst = true; 2221 /* The dst will be zero extended, so won't be sub-register anymore. */ 2222 reg->subreg_def = DEF_NOT_SUBREG; 2223 } 2224 2225 static int check_reg_arg(struct bpf_verifier_env *env, u32 regno, 2226 enum reg_arg_type t) 2227 { 2228 struct bpf_verifier_state *vstate = env->cur_state; 2229 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 2230 struct bpf_insn *insn = env->prog->insnsi + env->insn_idx; 2231 struct bpf_reg_state *reg, *regs = state->regs; 2232 bool rw64; 2233 2234 if (regno >= MAX_BPF_REG) { 2235 verbose(env, "R%d is invalid\n", regno); 2236 return -EINVAL; 2237 } 2238 2239 reg = ®s[regno]; 2240 rw64 = is_reg64(env, insn, regno, reg, t); 2241 if (t == SRC_OP) { 2242 /* check whether register used as source operand can be read */ 2243 if (reg->type == NOT_INIT) { 2244 verbose(env, "R%d !read_ok\n", regno); 2245 return -EACCES; 2246 } 2247 /* We don't need to worry about FP liveness because it's read-only */ 2248 if (regno == BPF_REG_FP) 2249 return 0; 2250 2251 if (rw64) 2252 mark_insn_zext(env, reg); 2253 2254 return mark_reg_read(env, reg, reg->parent, 2255 rw64 ? REG_LIVE_READ64 : REG_LIVE_READ32); 2256 } else { 2257 /* check whether register used as dest operand can be written to */ 2258 if (regno == BPF_REG_FP) { 2259 verbose(env, "frame pointer is read only\n"); 2260 return -EACCES; 2261 } 2262 reg->live |= REG_LIVE_WRITTEN; 2263 reg->subreg_def = rw64 ? DEF_NOT_SUBREG : env->insn_idx + 1; 2264 if (t == DST_OP) 2265 mark_reg_unknown(env, regs, regno); 2266 } 2267 return 0; 2268 } 2269 2270 /* for any branch, call, exit record the history of jmps in the given state */ 2271 static int push_jmp_history(struct bpf_verifier_env *env, 2272 struct bpf_verifier_state *cur) 2273 { 2274 u32 cnt = cur->jmp_history_cnt; 2275 struct bpf_idx_pair *p; 2276 2277 cnt++; 2278 p = krealloc(cur->jmp_history, cnt * sizeof(*p), GFP_USER); 2279 if (!p) 2280 return -ENOMEM; 2281 p[cnt - 1].idx = env->insn_idx; 2282 p[cnt - 1].prev_idx = env->prev_insn_idx; 2283 cur->jmp_history = p; 2284 cur->jmp_history_cnt = cnt; 2285 return 0; 2286 } 2287 2288 /* Backtrack one insn at a time. If idx is not at the top of recorded 2289 * history then previous instruction came from straight line execution. 2290 */ 2291 static int get_prev_insn_idx(struct bpf_verifier_state *st, int i, 2292 u32 *history) 2293 { 2294 u32 cnt = *history; 2295 2296 if (cnt && st->jmp_history[cnt - 1].idx == i) { 2297 i = st->jmp_history[cnt - 1].prev_idx; 2298 (*history)--; 2299 } else { 2300 i--; 2301 } 2302 return i; 2303 } 2304 2305 static const char *disasm_kfunc_name(void *data, const struct bpf_insn *insn) 2306 { 2307 const struct btf_type *func; 2308 struct btf *desc_btf; 2309 2310 if (insn->src_reg != BPF_PSEUDO_KFUNC_CALL) 2311 return NULL; 2312 2313 desc_btf = find_kfunc_desc_btf(data, insn->imm, insn->off, NULL); 2314 if (IS_ERR(desc_btf)) 2315 return "<error>"; 2316 2317 func = btf_type_by_id(desc_btf, insn->imm); 2318 return btf_name_by_offset(desc_btf, func->name_off); 2319 } 2320 2321 /* For given verifier state backtrack_insn() is called from the last insn to 2322 * the first insn. Its purpose is to compute a bitmask of registers and 2323 * stack slots that needs precision in the parent verifier state. 2324 */ 2325 static int backtrack_insn(struct bpf_verifier_env *env, int idx, 2326 u32 *reg_mask, u64 *stack_mask) 2327 { 2328 const struct bpf_insn_cbs cbs = { 2329 .cb_call = disasm_kfunc_name, 2330 .cb_print = verbose, 2331 .private_data = env, 2332 }; 2333 struct bpf_insn *insn = env->prog->insnsi + idx; 2334 u8 class = BPF_CLASS(insn->code); 2335 u8 opcode = BPF_OP(insn->code); 2336 u8 mode = BPF_MODE(insn->code); 2337 u32 dreg = 1u << insn->dst_reg; 2338 u32 sreg = 1u << insn->src_reg; 2339 u32 spi; 2340 2341 if (insn->code == 0) 2342 return 0; 2343 if (env->log.level & BPF_LOG_LEVEL) { 2344 verbose(env, "regs=%x stack=%llx before ", *reg_mask, *stack_mask); 2345 verbose(env, "%d: ", idx); 2346 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 2347 } 2348 2349 if (class == BPF_ALU || class == BPF_ALU64) { 2350 if (!(*reg_mask & dreg)) 2351 return 0; 2352 if (opcode == BPF_MOV) { 2353 if (BPF_SRC(insn->code) == BPF_X) { 2354 /* dreg = sreg 2355 * dreg needs precision after this insn 2356 * sreg needs precision before this insn 2357 */ 2358 *reg_mask &= ~dreg; 2359 *reg_mask |= sreg; 2360 } else { 2361 /* dreg = K 2362 * dreg needs precision after this insn. 2363 * Corresponding register is already marked 2364 * as precise=true in this verifier state. 2365 * No further markings in parent are necessary 2366 */ 2367 *reg_mask &= ~dreg; 2368 } 2369 } else { 2370 if (BPF_SRC(insn->code) == BPF_X) { 2371 /* dreg += sreg 2372 * both dreg and sreg need precision 2373 * before this insn 2374 */ 2375 *reg_mask |= sreg; 2376 } /* else dreg += K 2377 * dreg still needs precision before this insn 2378 */ 2379 } 2380 } else if (class == BPF_LDX) { 2381 if (!(*reg_mask & dreg)) 2382 return 0; 2383 *reg_mask &= ~dreg; 2384 2385 /* scalars can only be spilled into stack w/o losing precision. 2386 * Load from any other memory can be zero extended. 2387 * The desire to keep that precision is already indicated 2388 * by 'precise' mark in corresponding register of this state. 2389 * No further tracking necessary. 2390 */ 2391 if (insn->src_reg != BPF_REG_FP) 2392 return 0; 2393 if (BPF_SIZE(insn->code) != BPF_DW) 2394 return 0; 2395 2396 /* dreg = *(u64 *)[fp - off] was a fill from the stack. 2397 * that [fp - off] slot contains scalar that needs to be 2398 * tracked with precision 2399 */ 2400 spi = (-insn->off - 1) / BPF_REG_SIZE; 2401 if (spi >= 64) { 2402 verbose(env, "BUG spi %d\n", spi); 2403 WARN_ONCE(1, "verifier backtracking bug"); 2404 return -EFAULT; 2405 } 2406 *stack_mask |= 1ull << spi; 2407 } else if (class == BPF_STX || class == BPF_ST) { 2408 if (*reg_mask & dreg) 2409 /* stx & st shouldn't be using _scalar_ dst_reg 2410 * to access memory. It means backtracking 2411 * encountered a case of pointer subtraction. 2412 */ 2413 return -ENOTSUPP; 2414 /* scalars can only be spilled into stack */ 2415 if (insn->dst_reg != BPF_REG_FP) 2416 return 0; 2417 if (BPF_SIZE(insn->code) != BPF_DW) 2418 return 0; 2419 spi = (-insn->off - 1) / BPF_REG_SIZE; 2420 if (spi >= 64) { 2421 verbose(env, "BUG spi %d\n", spi); 2422 WARN_ONCE(1, "verifier backtracking bug"); 2423 return -EFAULT; 2424 } 2425 if (!(*stack_mask & (1ull << spi))) 2426 return 0; 2427 *stack_mask &= ~(1ull << spi); 2428 if (class == BPF_STX) 2429 *reg_mask |= sreg; 2430 } else if (class == BPF_JMP || class == BPF_JMP32) { 2431 if (opcode == BPF_CALL) { 2432 if (insn->src_reg == BPF_PSEUDO_CALL) 2433 return -ENOTSUPP; 2434 /* regular helper call sets R0 */ 2435 *reg_mask &= ~1; 2436 if (*reg_mask & 0x3f) { 2437 /* if backtracing was looking for registers R1-R5 2438 * they should have been found already. 2439 */ 2440 verbose(env, "BUG regs %x\n", *reg_mask); 2441 WARN_ONCE(1, "verifier backtracking bug"); 2442 return -EFAULT; 2443 } 2444 } else if (opcode == BPF_EXIT) { 2445 return -ENOTSUPP; 2446 } 2447 } else if (class == BPF_LD) { 2448 if (!(*reg_mask & dreg)) 2449 return 0; 2450 *reg_mask &= ~dreg; 2451 /* It's ld_imm64 or ld_abs or ld_ind. 2452 * For ld_imm64 no further tracking of precision 2453 * into parent is necessary 2454 */ 2455 if (mode == BPF_IND || mode == BPF_ABS) 2456 /* to be analyzed */ 2457 return -ENOTSUPP; 2458 } 2459 return 0; 2460 } 2461 2462 /* the scalar precision tracking algorithm: 2463 * . at the start all registers have precise=false. 2464 * . scalar ranges are tracked as normal through alu and jmp insns. 2465 * . once precise value of the scalar register is used in: 2466 * . ptr + scalar alu 2467 * . if (scalar cond K|scalar) 2468 * . helper_call(.., scalar, ...) where ARG_CONST is expected 2469 * backtrack through the verifier states and mark all registers and 2470 * stack slots with spilled constants that these scalar regisers 2471 * should be precise. 2472 * . during state pruning two registers (or spilled stack slots) 2473 * are equivalent if both are not precise. 2474 * 2475 * Note the verifier cannot simply walk register parentage chain, 2476 * since many different registers and stack slots could have been 2477 * used to compute single precise scalar. 2478 * 2479 * The approach of starting with precise=true for all registers and then 2480 * backtrack to mark a register as not precise when the verifier detects 2481 * that program doesn't care about specific value (e.g., when helper 2482 * takes register as ARG_ANYTHING parameter) is not safe. 2483 * 2484 * It's ok to walk single parentage chain of the verifier states. 2485 * It's possible that this backtracking will go all the way till 1st insn. 2486 * All other branches will be explored for needing precision later. 2487 * 2488 * The backtracking needs to deal with cases like: 2489 * 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) 2490 * r9 -= r8 2491 * r5 = r9 2492 * if r5 > 0x79f goto pc+7 2493 * R5_w=inv(id=0,umax_value=1951,var_off=(0x0; 0x7ff)) 2494 * r5 += 1 2495 * ... 2496 * call bpf_perf_event_output#25 2497 * where .arg5_type = ARG_CONST_SIZE_OR_ZERO 2498 * 2499 * and this case: 2500 * r6 = 1 2501 * call foo // uses callee's r6 inside to compute r0 2502 * r0 += r6 2503 * if r0 == 0 goto 2504 * 2505 * to track above reg_mask/stack_mask needs to be independent for each frame. 2506 * 2507 * Also if parent's curframe > frame where backtracking started, 2508 * the verifier need to mark registers in both frames, otherwise callees 2509 * may incorrectly prune callers. This is similar to 2510 * commit 7640ead93924 ("bpf: verifier: make sure callees don't prune with caller differences") 2511 * 2512 * For now backtracking falls back into conservative marking. 2513 */ 2514 static void mark_all_scalars_precise(struct bpf_verifier_env *env, 2515 struct bpf_verifier_state *st) 2516 { 2517 struct bpf_func_state *func; 2518 struct bpf_reg_state *reg; 2519 int i, j; 2520 2521 /* big hammer: mark all scalars precise in this path. 2522 * pop_stack may still get !precise scalars. 2523 */ 2524 for (; st; st = st->parent) 2525 for (i = 0; i <= st->curframe; i++) { 2526 func = st->frame[i]; 2527 for (j = 0; j < BPF_REG_FP; j++) { 2528 reg = &func->regs[j]; 2529 if (reg->type != SCALAR_VALUE) 2530 continue; 2531 reg->precise = true; 2532 } 2533 for (j = 0; j < func->allocated_stack / BPF_REG_SIZE; j++) { 2534 if (!is_spilled_reg(&func->stack[j])) 2535 continue; 2536 reg = &func->stack[j].spilled_ptr; 2537 if (reg->type != SCALAR_VALUE) 2538 continue; 2539 reg->precise = true; 2540 } 2541 } 2542 } 2543 2544 static int __mark_chain_precision(struct bpf_verifier_env *env, int regno, 2545 int spi) 2546 { 2547 struct bpf_verifier_state *st = env->cur_state; 2548 int first_idx = st->first_insn_idx; 2549 int last_idx = env->insn_idx; 2550 struct bpf_func_state *func; 2551 struct bpf_reg_state *reg; 2552 u32 reg_mask = regno >= 0 ? 1u << regno : 0; 2553 u64 stack_mask = spi >= 0 ? 1ull << spi : 0; 2554 bool skip_first = true; 2555 bool new_marks = false; 2556 int i, err; 2557 2558 if (!env->bpf_capable) 2559 return 0; 2560 2561 func = st->frame[st->curframe]; 2562 if (regno >= 0) { 2563 reg = &func->regs[regno]; 2564 if (reg->type != SCALAR_VALUE) { 2565 WARN_ONCE(1, "backtracing misuse"); 2566 return -EFAULT; 2567 } 2568 if (!reg->precise) 2569 new_marks = true; 2570 else 2571 reg_mask = 0; 2572 reg->precise = true; 2573 } 2574 2575 while (spi >= 0) { 2576 if (!is_spilled_reg(&func->stack[spi])) { 2577 stack_mask = 0; 2578 break; 2579 } 2580 reg = &func->stack[spi].spilled_ptr; 2581 if (reg->type != SCALAR_VALUE) { 2582 stack_mask = 0; 2583 break; 2584 } 2585 if (!reg->precise) 2586 new_marks = true; 2587 else 2588 stack_mask = 0; 2589 reg->precise = true; 2590 break; 2591 } 2592 2593 if (!new_marks) 2594 return 0; 2595 if (!reg_mask && !stack_mask) 2596 return 0; 2597 for (;;) { 2598 DECLARE_BITMAP(mask, 64); 2599 u32 history = st->jmp_history_cnt; 2600 2601 if (env->log.level & BPF_LOG_LEVEL) 2602 verbose(env, "last_idx %d first_idx %d\n", last_idx, first_idx); 2603 for (i = last_idx;;) { 2604 if (skip_first) { 2605 err = 0; 2606 skip_first = false; 2607 } else { 2608 err = backtrack_insn(env, i, ®_mask, &stack_mask); 2609 } 2610 if (err == -ENOTSUPP) { 2611 mark_all_scalars_precise(env, st); 2612 return 0; 2613 } else if (err) { 2614 return err; 2615 } 2616 if (!reg_mask && !stack_mask) 2617 /* Found assignment(s) into tracked register in this state. 2618 * Since this state is already marked, just return. 2619 * Nothing to be tracked further in the parent state. 2620 */ 2621 return 0; 2622 if (i == first_idx) 2623 break; 2624 i = get_prev_insn_idx(st, i, &history); 2625 if (i >= env->prog->len) { 2626 /* This can happen if backtracking reached insn 0 2627 * and there are still reg_mask or stack_mask 2628 * to backtrack. 2629 * It means the backtracking missed the spot where 2630 * particular register was initialized with a constant. 2631 */ 2632 verbose(env, "BUG backtracking idx %d\n", i); 2633 WARN_ONCE(1, "verifier backtracking bug"); 2634 return -EFAULT; 2635 } 2636 } 2637 st = st->parent; 2638 if (!st) 2639 break; 2640 2641 new_marks = false; 2642 func = st->frame[st->curframe]; 2643 bitmap_from_u64(mask, reg_mask); 2644 for_each_set_bit(i, mask, 32) { 2645 reg = &func->regs[i]; 2646 if (reg->type != SCALAR_VALUE) { 2647 reg_mask &= ~(1u << i); 2648 continue; 2649 } 2650 if (!reg->precise) 2651 new_marks = true; 2652 reg->precise = true; 2653 } 2654 2655 bitmap_from_u64(mask, stack_mask); 2656 for_each_set_bit(i, mask, 64) { 2657 if (i >= func->allocated_stack / BPF_REG_SIZE) { 2658 /* the sequence of instructions: 2659 * 2: (bf) r3 = r10 2660 * 3: (7b) *(u64 *)(r3 -8) = r0 2661 * 4: (79) r4 = *(u64 *)(r10 -8) 2662 * doesn't contain jmps. It's backtracked 2663 * as a single block. 2664 * During backtracking insn 3 is not recognized as 2665 * stack access, so at the end of backtracking 2666 * stack slot fp-8 is still marked in stack_mask. 2667 * However the parent state may not have accessed 2668 * fp-8 and it's "unallocated" stack space. 2669 * In such case fallback to conservative. 2670 */ 2671 mark_all_scalars_precise(env, st); 2672 return 0; 2673 } 2674 2675 if (!is_spilled_reg(&func->stack[i])) { 2676 stack_mask &= ~(1ull << i); 2677 continue; 2678 } 2679 reg = &func->stack[i].spilled_ptr; 2680 if (reg->type != SCALAR_VALUE) { 2681 stack_mask &= ~(1ull << i); 2682 continue; 2683 } 2684 if (!reg->precise) 2685 new_marks = true; 2686 reg->precise = true; 2687 } 2688 if (env->log.level & BPF_LOG_LEVEL) { 2689 print_verifier_state(env, func); 2690 verbose(env, "parent %s regs=%x stack=%llx marks\n", 2691 new_marks ? "didn't have" : "already had", 2692 reg_mask, stack_mask); 2693 } 2694 2695 if (!reg_mask && !stack_mask) 2696 break; 2697 if (!new_marks) 2698 break; 2699 2700 last_idx = st->last_insn_idx; 2701 first_idx = st->first_insn_idx; 2702 } 2703 return 0; 2704 } 2705 2706 static int mark_chain_precision(struct bpf_verifier_env *env, int regno) 2707 { 2708 return __mark_chain_precision(env, regno, -1); 2709 } 2710 2711 static int mark_chain_precision_stack(struct bpf_verifier_env *env, int spi) 2712 { 2713 return __mark_chain_precision(env, -1, spi); 2714 } 2715 2716 static bool is_spillable_regtype(enum bpf_reg_type type) 2717 { 2718 switch (type) { 2719 case PTR_TO_MAP_VALUE: 2720 case PTR_TO_MAP_VALUE_OR_NULL: 2721 case PTR_TO_STACK: 2722 case PTR_TO_CTX: 2723 case PTR_TO_PACKET: 2724 case PTR_TO_PACKET_META: 2725 case PTR_TO_PACKET_END: 2726 case PTR_TO_FLOW_KEYS: 2727 case CONST_PTR_TO_MAP: 2728 case PTR_TO_SOCKET: 2729 case PTR_TO_SOCKET_OR_NULL: 2730 case PTR_TO_SOCK_COMMON: 2731 case PTR_TO_SOCK_COMMON_OR_NULL: 2732 case PTR_TO_TCP_SOCK: 2733 case PTR_TO_TCP_SOCK_OR_NULL: 2734 case PTR_TO_XDP_SOCK: 2735 case PTR_TO_BTF_ID: 2736 case PTR_TO_BTF_ID_OR_NULL: 2737 case PTR_TO_RDONLY_BUF: 2738 case PTR_TO_RDONLY_BUF_OR_NULL: 2739 case PTR_TO_RDWR_BUF: 2740 case PTR_TO_RDWR_BUF_OR_NULL: 2741 case PTR_TO_PERCPU_BTF_ID: 2742 case PTR_TO_MEM: 2743 case PTR_TO_MEM_OR_NULL: 2744 case PTR_TO_FUNC: 2745 case PTR_TO_MAP_KEY: 2746 return true; 2747 default: 2748 return false; 2749 } 2750 } 2751 2752 /* Does this register contain a constant zero? */ 2753 static bool register_is_null(struct bpf_reg_state *reg) 2754 { 2755 return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0); 2756 } 2757 2758 static bool register_is_const(struct bpf_reg_state *reg) 2759 { 2760 return reg->type == SCALAR_VALUE && tnum_is_const(reg->var_off); 2761 } 2762 2763 static bool __is_scalar_unbounded(struct bpf_reg_state *reg) 2764 { 2765 return tnum_is_unknown(reg->var_off) && 2766 reg->smin_value == S64_MIN && reg->smax_value == S64_MAX && 2767 reg->umin_value == 0 && reg->umax_value == U64_MAX && 2768 reg->s32_min_value == S32_MIN && reg->s32_max_value == S32_MAX && 2769 reg->u32_min_value == 0 && reg->u32_max_value == U32_MAX; 2770 } 2771 2772 static bool register_is_bounded(struct bpf_reg_state *reg) 2773 { 2774 return reg->type == SCALAR_VALUE && !__is_scalar_unbounded(reg); 2775 } 2776 2777 static bool __is_pointer_value(bool allow_ptr_leaks, 2778 const struct bpf_reg_state *reg) 2779 { 2780 if (allow_ptr_leaks) 2781 return false; 2782 2783 return reg->type != SCALAR_VALUE; 2784 } 2785 2786 static void save_register_state(struct bpf_func_state *state, 2787 int spi, struct bpf_reg_state *reg, 2788 int size) 2789 { 2790 int i; 2791 2792 state->stack[spi].spilled_ptr = *reg; 2793 if (size == BPF_REG_SIZE) 2794 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2795 2796 for (i = BPF_REG_SIZE; i > BPF_REG_SIZE - size; i--) 2797 state->stack[spi].slot_type[i - 1] = STACK_SPILL; 2798 2799 /* size < 8 bytes spill */ 2800 for (; i; i--) 2801 scrub_spilled_slot(&state->stack[spi].slot_type[i - 1]); 2802 } 2803 2804 /* check_stack_{read,write}_fixed_off functions track spill/fill of registers, 2805 * stack boundary and alignment are checked in check_mem_access() 2806 */ 2807 static int check_stack_write_fixed_off(struct bpf_verifier_env *env, 2808 /* stack frame we're writing to */ 2809 struct bpf_func_state *state, 2810 int off, int size, int value_regno, 2811 int insn_idx) 2812 { 2813 struct bpf_func_state *cur; /* state of the current function */ 2814 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE, err; 2815 u32 dst_reg = env->prog->insnsi[insn_idx].dst_reg; 2816 struct bpf_reg_state *reg = NULL; 2817 2818 err = grow_stack_state(state, round_up(slot + 1, BPF_REG_SIZE)); 2819 if (err) 2820 return err; 2821 /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, 2822 * so it's aligned access and [off, off + size) are within stack limits 2823 */ 2824 if (!env->allow_ptr_leaks && 2825 state->stack[spi].slot_type[0] == STACK_SPILL && 2826 size != BPF_REG_SIZE) { 2827 verbose(env, "attempt to corrupt spilled pointer on stack\n"); 2828 return -EACCES; 2829 } 2830 2831 cur = env->cur_state->frame[env->cur_state->curframe]; 2832 if (value_regno >= 0) 2833 reg = &cur->regs[value_regno]; 2834 if (!env->bypass_spec_v4) { 2835 bool sanitize = reg && is_spillable_regtype(reg->type); 2836 2837 for (i = 0; i < size; i++) { 2838 if (state->stack[spi].slot_type[i] == STACK_INVALID) { 2839 sanitize = true; 2840 break; 2841 } 2842 } 2843 2844 if (sanitize) 2845 env->insn_aux_data[insn_idx].sanitize_stack_spill = true; 2846 } 2847 2848 if (reg && !(off % BPF_REG_SIZE) && register_is_bounded(reg) && 2849 !register_is_null(reg) && env->bpf_capable) { 2850 if (dst_reg != BPF_REG_FP) { 2851 /* The backtracking logic can only recognize explicit 2852 * stack slot address like [fp - 8]. Other spill of 2853 * scalar via different register has to be conservative. 2854 * Backtrack from here and mark all registers as precise 2855 * that contributed into 'reg' being a constant. 2856 */ 2857 err = mark_chain_precision(env, value_regno); 2858 if (err) 2859 return err; 2860 } 2861 save_register_state(state, spi, reg, size); 2862 } else if (reg && is_spillable_regtype(reg->type)) { 2863 /* register containing pointer is being spilled into stack */ 2864 if (size != BPF_REG_SIZE) { 2865 verbose_linfo(env, insn_idx, "; "); 2866 verbose(env, "invalid size of register spill\n"); 2867 return -EACCES; 2868 } 2869 if (state != cur && reg->type == PTR_TO_STACK) { 2870 verbose(env, "cannot spill pointers to stack into stack frame of the caller\n"); 2871 return -EINVAL; 2872 } 2873 save_register_state(state, spi, reg, size); 2874 } else { 2875 u8 type = STACK_MISC; 2876 2877 /* regular write of data into stack destroys any spilled ptr */ 2878 state->stack[spi].spilled_ptr.type = NOT_INIT; 2879 /* Mark slots as STACK_MISC if they belonged to spilled ptr. */ 2880 if (is_spilled_reg(&state->stack[spi])) 2881 for (i = 0; i < BPF_REG_SIZE; i++) 2882 scrub_spilled_slot(&state->stack[spi].slot_type[i]); 2883 2884 /* only mark the slot as written if all 8 bytes were written 2885 * otherwise read propagation may incorrectly stop too soon 2886 * when stack slots are partially written. 2887 * This heuristic means that read propagation will be 2888 * conservative, since it will add reg_live_read marks 2889 * to stack slots all the way to first state when programs 2890 * writes+reads less than 8 bytes 2891 */ 2892 if (size == BPF_REG_SIZE) 2893 state->stack[spi].spilled_ptr.live |= REG_LIVE_WRITTEN; 2894 2895 /* when we zero initialize stack slots mark them as such */ 2896 if (reg && register_is_null(reg)) { 2897 /* backtracking doesn't work for STACK_ZERO yet. */ 2898 err = mark_chain_precision(env, value_regno); 2899 if (err) 2900 return err; 2901 type = STACK_ZERO; 2902 } 2903 2904 /* Mark slots affected by this stack write. */ 2905 for (i = 0; i < size; i++) 2906 state->stack[spi].slot_type[(slot - i) % BPF_REG_SIZE] = 2907 type; 2908 } 2909 return 0; 2910 } 2911 2912 /* Write the stack: 'stack[ptr_regno + off] = value_regno'. 'ptr_regno' is 2913 * known to contain a variable offset. 2914 * This function checks whether the write is permitted and conservatively 2915 * tracks the effects of the write, considering that each stack slot in the 2916 * dynamic range is potentially written to. 2917 * 2918 * 'off' includes 'regno->off'. 2919 * 'value_regno' can be -1, meaning that an unknown value is being written to 2920 * the stack. 2921 * 2922 * Spilled pointers in range are not marked as written because we don't know 2923 * what's going to be actually written. This means that read propagation for 2924 * future reads cannot be terminated by this write. 2925 * 2926 * For privileged programs, uninitialized stack slots are considered 2927 * initialized by this write (even though we don't know exactly what offsets 2928 * are going to be written to). The idea is that we don't want the verifier to 2929 * reject future reads that access slots written to through variable offsets. 2930 */ 2931 static int check_stack_write_var_off(struct bpf_verifier_env *env, 2932 /* func where register points to */ 2933 struct bpf_func_state *state, 2934 int ptr_regno, int off, int size, 2935 int value_regno, int insn_idx) 2936 { 2937 struct bpf_func_state *cur; /* state of the current function */ 2938 int min_off, max_off; 2939 int i, err; 2940 struct bpf_reg_state *ptr_reg = NULL, *value_reg = NULL; 2941 bool writing_zero = false; 2942 /* set if the fact that we're writing a zero is used to let any 2943 * stack slots remain STACK_ZERO 2944 */ 2945 bool zero_used = false; 2946 2947 cur = env->cur_state->frame[env->cur_state->curframe]; 2948 ptr_reg = &cur->regs[ptr_regno]; 2949 min_off = ptr_reg->smin_value + off; 2950 max_off = ptr_reg->smax_value + off + size; 2951 if (value_regno >= 0) 2952 value_reg = &cur->regs[value_regno]; 2953 if (value_reg && register_is_null(value_reg)) 2954 writing_zero = true; 2955 2956 err = grow_stack_state(state, round_up(-min_off, BPF_REG_SIZE)); 2957 if (err) 2958 return err; 2959 2960 2961 /* Variable offset writes destroy any spilled pointers in range. */ 2962 for (i = min_off; i < max_off; i++) { 2963 u8 new_type, *stype; 2964 int slot, spi; 2965 2966 slot = -i - 1; 2967 spi = slot / BPF_REG_SIZE; 2968 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 2969 2970 if (!env->allow_ptr_leaks 2971 && *stype != NOT_INIT 2972 && *stype != SCALAR_VALUE) { 2973 /* Reject the write if there's are spilled pointers in 2974 * range. If we didn't reject here, the ptr status 2975 * would be erased below (even though not all slots are 2976 * actually overwritten), possibly opening the door to 2977 * leaks. 2978 */ 2979 verbose(env, "spilled ptr in range of var-offset stack write; insn %d, ptr off: %d", 2980 insn_idx, i); 2981 return -EINVAL; 2982 } 2983 2984 /* Erase all spilled pointers. */ 2985 state->stack[spi].spilled_ptr.type = NOT_INIT; 2986 2987 /* Update the slot type. */ 2988 new_type = STACK_MISC; 2989 if (writing_zero && *stype == STACK_ZERO) { 2990 new_type = STACK_ZERO; 2991 zero_used = true; 2992 } 2993 /* If the slot is STACK_INVALID, we check whether it's OK to 2994 * pretend that it will be initialized by this write. The slot 2995 * might not actually be written to, and so if we mark it as 2996 * initialized future reads might leak uninitialized memory. 2997 * For privileged programs, we will accept such reads to slots 2998 * that may or may not be written because, if we're reject 2999 * them, the error would be too confusing. 3000 */ 3001 if (*stype == STACK_INVALID && !env->allow_uninit_stack) { 3002 verbose(env, "uninit stack in range of var-offset write prohibited for !root; insn %d, off: %d", 3003 insn_idx, i); 3004 return -EINVAL; 3005 } 3006 *stype = new_type; 3007 } 3008 if (zero_used) { 3009 /* backtracking doesn't work for STACK_ZERO yet. */ 3010 err = mark_chain_precision(env, value_regno); 3011 if (err) 3012 return err; 3013 } 3014 return 0; 3015 } 3016 3017 /* When register 'dst_regno' is assigned some values from stack[min_off, 3018 * max_off), we set the register's type according to the types of the 3019 * respective stack slots. If all the stack values are known to be zeros, then 3020 * so is the destination reg. Otherwise, the register is considered to be 3021 * SCALAR. This function does not deal with register filling; the caller must 3022 * ensure that all spilled registers in the stack range have been marked as 3023 * read. 3024 */ 3025 static void mark_reg_stack_read(struct bpf_verifier_env *env, 3026 /* func where src register points to */ 3027 struct bpf_func_state *ptr_state, 3028 int min_off, int max_off, int dst_regno) 3029 { 3030 struct bpf_verifier_state *vstate = env->cur_state; 3031 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3032 int i, slot, spi; 3033 u8 *stype; 3034 int zeros = 0; 3035 3036 for (i = min_off; i < max_off; i++) { 3037 slot = -i - 1; 3038 spi = slot / BPF_REG_SIZE; 3039 stype = ptr_state->stack[spi].slot_type; 3040 if (stype[slot % BPF_REG_SIZE] != STACK_ZERO) 3041 break; 3042 zeros++; 3043 } 3044 if (zeros == max_off - min_off) { 3045 /* any access_size read into register is zero extended, 3046 * so the whole register == const_zero 3047 */ 3048 __mark_reg_const_zero(&state->regs[dst_regno]); 3049 /* backtracking doesn't support STACK_ZERO yet, 3050 * so mark it precise here, so that later 3051 * backtracking can stop here. 3052 * Backtracking may not need this if this register 3053 * doesn't participate in pointer adjustment. 3054 * Forward propagation of precise flag is not 3055 * necessary either. This mark is only to stop 3056 * backtracking. Any register that contributed 3057 * to const 0 was marked precise before spill. 3058 */ 3059 state->regs[dst_regno].precise = true; 3060 } else { 3061 /* have read misc data from the stack */ 3062 mark_reg_unknown(env, state->regs, dst_regno); 3063 } 3064 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3065 } 3066 3067 /* Read the stack at 'off' and put the results into the register indicated by 3068 * 'dst_regno'. It handles reg filling if the addressed stack slot is a 3069 * spilled reg. 3070 * 3071 * 'dst_regno' can be -1, meaning that the read value is not going to a 3072 * register. 3073 * 3074 * The access is assumed to be within the current stack bounds. 3075 */ 3076 static int check_stack_read_fixed_off(struct bpf_verifier_env *env, 3077 /* func where src register points to */ 3078 struct bpf_func_state *reg_state, 3079 int off, int size, int dst_regno) 3080 { 3081 struct bpf_verifier_state *vstate = env->cur_state; 3082 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3083 int i, slot = -off - 1, spi = slot / BPF_REG_SIZE; 3084 struct bpf_reg_state *reg; 3085 u8 *stype, type; 3086 3087 stype = reg_state->stack[spi].slot_type; 3088 reg = ®_state->stack[spi].spilled_ptr; 3089 3090 if (is_spilled_reg(®_state->stack[spi])) { 3091 u8 spill_size = 1; 3092 3093 for (i = BPF_REG_SIZE - 1; i > 0 && stype[i - 1] == STACK_SPILL; i--) 3094 spill_size++; 3095 3096 if (size != BPF_REG_SIZE || spill_size != BPF_REG_SIZE) { 3097 if (reg->type != SCALAR_VALUE) { 3098 verbose_linfo(env, env->insn_idx, "; "); 3099 verbose(env, "invalid size of register fill\n"); 3100 return -EACCES; 3101 } 3102 3103 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3104 if (dst_regno < 0) 3105 return 0; 3106 3107 if (!(off % BPF_REG_SIZE) && size == spill_size) { 3108 /* The earlier check_reg_arg() has decided the 3109 * subreg_def for this insn. Save it first. 3110 */ 3111 s32 subreg_def = state->regs[dst_regno].subreg_def; 3112 3113 state->regs[dst_regno] = *reg; 3114 state->regs[dst_regno].subreg_def = subreg_def; 3115 } else { 3116 for (i = 0; i < size; i++) { 3117 type = stype[(slot - i) % BPF_REG_SIZE]; 3118 if (type == STACK_SPILL) 3119 continue; 3120 if (type == STACK_MISC) 3121 continue; 3122 verbose(env, "invalid read from stack off %d+%d size %d\n", 3123 off, i, size); 3124 return -EACCES; 3125 } 3126 mark_reg_unknown(env, state->regs, dst_regno); 3127 } 3128 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3129 return 0; 3130 } 3131 3132 if (dst_regno >= 0) { 3133 /* restore register state from stack */ 3134 state->regs[dst_regno] = *reg; 3135 /* mark reg as written since spilled pointer state likely 3136 * has its liveness marks cleared by is_state_visited() 3137 * which resets stack/reg liveness for state transitions 3138 */ 3139 state->regs[dst_regno].live |= REG_LIVE_WRITTEN; 3140 } else if (__is_pointer_value(env->allow_ptr_leaks, reg)) { 3141 /* If dst_regno==-1, the caller is asking us whether 3142 * it is acceptable to use this value as a SCALAR_VALUE 3143 * (e.g. for XADD). 3144 * We must not allow unprivileged callers to do that 3145 * with spilled pointers. 3146 */ 3147 verbose(env, "leaking pointer from stack off %d\n", 3148 off); 3149 return -EACCES; 3150 } 3151 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3152 } else { 3153 for (i = 0; i < size; i++) { 3154 type = stype[(slot - i) % BPF_REG_SIZE]; 3155 if (type == STACK_MISC) 3156 continue; 3157 if (type == STACK_ZERO) 3158 continue; 3159 verbose(env, "invalid read from stack off %d+%d size %d\n", 3160 off, i, size); 3161 return -EACCES; 3162 } 3163 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 3164 if (dst_regno >= 0) 3165 mark_reg_stack_read(env, reg_state, off, off + size, dst_regno); 3166 } 3167 return 0; 3168 } 3169 3170 enum stack_access_src { 3171 ACCESS_DIRECT = 1, /* the access is performed by an instruction */ 3172 ACCESS_HELPER = 2, /* the access is performed by a helper */ 3173 }; 3174 3175 static int check_stack_range_initialized(struct bpf_verifier_env *env, 3176 int regno, int off, int access_size, 3177 bool zero_size_allowed, 3178 enum stack_access_src type, 3179 struct bpf_call_arg_meta *meta); 3180 3181 static struct bpf_reg_state *reg_state(struct bpf_verifier_env *env, int regno) 3182 { 3183 return cur_regs(env) + regno; 3184 } 3185 3186 /* Read the stack at 'ptr_regno + off' and put the result into the register 3187 * 'dst_regno'. 3188 * 'off' includes the pointer register's fixed offset(i.e. 'ptr_regno.off'), 3189 * but not its variable offset. 3190 * 'size' is assumed to be <= reg size and the access is assumed to be aligned. 3191 * 3192 * As opposed to check_stack_read_fixed_off, this function doesn't deal with 3193 * filling registers (i.e. reads of spilled register cannot be detected when 3194 * the offset is not fixed). We conservatively mark 'dst_regno' as containing 3195 * SCALAR_VALUE. That's why we assert that the 'ptr_regno' has a variable 3196 * offset; for a fixed offset check_stack_read_fixed_off should be used 3197 * instead. 3198 */ 3199 static int check_stack_read_var_off(struct bpf_verifier_env *env, 3200 int ptr_regno, int off, int size, int dst_regno) 3201 { 3202 /* The state of the source register. */ 3203 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3204 struct bpf_func_state *ptr_state = func(env, reg); 3205 int err; 3206 int min_off, max_off; 3207 3208 /* Note that we pass a NULL meta, so raw access will not be permitted. 3209 */ 3210 err = check_stack_range_initialized(env, ptr_regno, off, size, 3211 false, ACCESS_DIRECT, NULL); 3212 if (err) 3213 return err; 3214 3215 min_off = reg->smin_value + off; 3216 max_off = reg->smax_value + off; 3217 mark_reg_stack_read(env, ptr_state, min_off, max_off + size, dst_regno); 3218 return 0; 3219 } 3220 3221 /* check_stack_read dispatches to check_stack_read_fixed_off or 3222 * check_stack_read_var_off. 3223 * 3224 * The caller must ensure that the offset falls within the allocated stack 3225 * bounds. 3226 * 3227 * 'dst_regno' is a register which will receive the value from the stack. It 3228 * can be -1, meaning that the read value is not going to a register. 3229 */ 3230 static int check_stack_read(struct bpf_verifier_env *env, 3231 int ptr_regno, int off, int size, 3232 int dst_regno) 3233 { 3234 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3235 struct bpf_func_state *state = func(env, reg); 3236 int err; 3237 /* Some accesses are only permitted with a static offset. */ 3238 bool var_off = !tnum_is_const(reg->var_off); 3239 3240 /* The offset is required to be static when reads don't go to a 3241 * register, in order to not leak pointers (see 3242 * check_stack_read_fixed_off). 3243 */ 3244 if (dst_regno < 0 && var_off) { 3245 char tn_buf[48]; 3246 3247 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3248 verbose(env, "variable offset stack pointer cannot be passed into helper function; var_off=%s off=%d size=%d\n", 3249 tn_buf, off, size); 3250 return -EACCES; 3251 } 3252 /* Variable offset is prohibited for unprivileged mode for simplicity 3253 * since it requires corresponding support in Spectre masking for stack 3254 * ALU. See also retrieve_ptr_limit(). 3255 */ 3256 if (!env->bypass_spec_v1 && var_off) { 3257 char tn_buf[48]; 3258 3259 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3260 verbose(env, "R%d variable offset stack access prohibited for !root, var_off=%s\n", 3261 ptr_regno, tn_buf); 3262 return -EACCES; 3263 } 3264 3265 if (!var_off) { 3266 off += reg->var_off.value; 3267 err = check_stack_read_fixed_off(env, state, off, size, 3268 dst_regno); 3269 } else { 3270 /* Variable offset stack reads need more conservative handling 3271 * than fixed offset ones. Note that dst_regno >= 0 on this 3272 * branch. 3273 */ 3274 err = check_stack_read_var_off(env, ptr_regno, off, size, 3275 dst_regno); 3276 } 3277 return err; 3278 } 3279 3280 3281 /* check_stack_write dispatches to check_stack_write_fixed_off or 3282 * check_stack_write_var_off. 3283 * 3284 * 'ptr_regno' is the register used as a pointer into the stack. 3285 * 'off' includes 'ptr_regno->off', but not its variable offset (if any). 3286 * 'value_regno' is the register whose value we're writing to the stack. It can 3287 * be -1, meaning that we're not writing from a register. 3288 * 3289 * The caller must ensure that the offset falls within the maximum stack size. 3290 */ 3291 static int check_stack_write(struct bpf_verifier_env *env, 3292 int ptr_regno, int off, int size, 3293 int value_regno, int insn_idx) 3294 { 3295 struct bpf_reg_state *reg = reg_state(env, ptr_regno); 3296 struct bpf_func_state *state = func(env, reg); 3297 int err; 3298 3299 if (tnum_is_const(reg->var_off)) { 3300 off += reg->var_off.value; 3301 err = check_stack_write_fixed_off(env, state, off, size, 3302 value_regno, insn_idx); 3303 } else { 3304 /* Variable offset stack reads need more conservative handling 3305 * than fixed offset ones. 3306 */ 3307 err = check_stack_write_var_off(env, state, 3308 ptr_regno, off, size, 3309 value_regno, insn_idx); 3310 } 3311 return err; 3312 } 3313 3314 static int check_map_access_type(struct bpf_verifier_env *env, u32 regno, 3315 int off, int size, enum bpf_access_type type) 3316 { 3317 struct bpf_reg_state *regs = cur_regs(env); 3318 struct bpf_map *map = regs[regno].map_ptr; 3319 u32 cap = bpf_map_flags_to_cap(map); 3320 3321 if (type == BPF_WRITE && !(cap & BPF_MAP_CAN_WRITE)) { 3322 verbose(env, "write into map forbidden, value_size=%d off=%d size=%d\n", 3323 map->value_size, off, size); 3324 return -EACCES; 3325 } 3326 3327 if (type == BPF_READ && !(cap & BPF_MAP_CAN_READ)) { 3328 verbose(env, "read from map forbidden, value_size=%d off=%d size=%d\n", 3329 map->value_size, off, size); 3330 return -EACCES; 3331 } 3332 3333 return 0; 3334 } 3335 3336 /* check read/write into memory region (e.g., map value, ringbuf sample, etc) */ 3337 static int __check_mem_access(struct bpf_verifier_env *env, int regno, 3338 int off, int size, u32 mem_size, 3339 bool zero_size_allowed) 3340 { 3341 bool size_ok = size > 0 || (size == 0 && zero_size_allowed); 3342 struct bpf_reg_state *reg; 3343 3344 if (off >= 0 && size_ok && (u64)off + size <= mem_size) 3345 return 0; 3346 3347 reg = &cur_regs(env)[regno]; 3348 switch (reg->type) { 3349 case PTR_TO_MAP_KEY: 3350 verbose(env, "invalid access to map key, key_size=%d off=%d size=%d\n", 3351 mem_size, off, size); 3352 break; 3353 case PTR_TO_MAP_VALUE: 3354 verbose(env, "invalid access to map value, value_size=%d off=%d size=%d\n", 3355 mem_size, off, size); 3356 break; 3357 case PTR_TO_PACKET: 3358 case PTR_TO_PACKET_META: 3359 case PTR_TO_PACKET_END: 3360 verbose(env, "invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", 3361 off, size, regno, reg->id, off, mem_size); 3362 break; 3363 case PTR_TO_MEM: 3364 default: 3365 verbose(env, "invalid access to memory, mem_size=%u off=%d size=%d\n", 3366 mem_size, off, size); 3367 } 3368 3369 return -EACCES; 3370 } 3371 3372 /* check read/write into a memory region with possible variable offset */ 3373 static int check_mem_region_access(struct bpf_verifier_env *env, u32 regno, 3374 int off, int size, u32 mem_size, 3375 bool zero_size_allowed) 3376 { 3377 struct bpf_verifier_state *vstate = env->cur_state; 3378 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3379 struct bpf_reg_state *reg = &state->regs[regno]; 3380 int err; 3381 3382 /* We may have adjusted the register pointing to memory region, so we 3383 * need to try adding each of min_value and max_value to off 3384 * to make sure our theoretical access will be safe. 3385 */ 3386 if (env->log.level & BPF_LOG_LEVEL) 3387 print_verifier_state(env, state); 3388 3389 /* The minimum value is only important with signed 3390 * comparisons where we can't assume the floor of a 3391 * value is 0. If we are using signed variables for our 3392 * index'es we need to make sure that whatever we use 3393 * will have a set floor within our range. 3394 */ 3395 if (reg->smin_value < 0 && 3396 (reg->smin_value == S64_MIN || 3397 (off + reg->smin_value != (s64)(s32)(off + reg->smin_value)) || 3398 reg->smin_value + off < 0)) { 3399 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3400 regno); 3401 return -EACCES; 3402 } 3403 err = __check_mem_access(env, regno, reg->smin_value + off, size, 3404 mem_size, zero_size_allowed); 3405 if (err) { 3406 verbose(env, "R%d min value is outside of the allowed memory range\n", 3407 regno); 3408 return err; 3409 } 3410 3411 /* If we haven't set a max value then we need to bail since we can't be 3412 * sure we won't do bad things. 3413 * If reg->umax_value + off could overflow, treat that as unbounded too. 3414 */ 3415 if (reg->umax_value >= BPF_MAX_VAR_OFF) { 3416 verbose(env, "R%d unbounded memory access, make sure to bounds check any such access\n", 3417 regno); 3418 return -EACCES; 3419 } 3420 err = __check_mem_access(env, regno, reg->umax_value + off, size, 3421 mem_size, zero_size_allowed); 3422 if (err) { 3423 verbose(env, "R%d max value is outside of the allowed memory range\n", 3424 regno); 3425 return err; 3426 } 3427 3428 return 0; 3429 } 3430 3431 /* check read/write into a map element with possible variable offset */ 3432 static int check_map_access(struct bpf_verifier_env *env, u32 regno, 3433 int off, int size, bool zero_size_allowed) 3434 { 3435 struct bpf_verifier_state *vstate = env->cur_state; 3436 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 3437 struct bpf_reg_state *reg = &state->regs[regno]; 3438 struct bpf_map *map = reg->map_ptr; 3439 int err; 3440 3441 err = check_mem_region_access(env, regno, off, size, map->value_size, 3442 zero_size_allowed); 3443 if (err) 3444 return err; 3445 3446 if (map_value_has_spin_lock(map)) { 3447 u32 lock = map->spin_lock_off; 3448 3449 /* if any part of struct bpf_spin_lock can be touched by 3450 * load/store reject this program. 3451 * To check that [x1, x2) overlaps with [y1, y2) 3452 * it is sufficient to check x1 < y2 && y1 < x2. 3453 */ 3454 if (reg->smin_value + off < lock + sizeof(struct bpf_spin_lock) && 3455 lock < reg->umax_value + off + size) { 3456 verbose(env, "bpf_spin_lock cannot be accessed directly by load/store\n"); 3457 return -EACCES; 3458 } 3459 } 3460 if (map_value_has_timer(map)) { 3461 u32 t = map->timer_off; 3462 3463 if (reg->smin_value + off < t + sizeof(struct bpf_timer) && 3464 t < reg->umax_value + off + size) { 3465 verbose(env, "bpf_timer cannot be accessed directly by load/store\n"); 3466 return -EACCES; 3467 } 3468 } 3469 return err; 3470 } 3471 3472 #define MAX_PACKET_OFF 0xffff 3473 3474 static enum bpf_prog_type resolve_prog_type(struct bpf_prog *prog) 3475 { 3476 return prog->aux->dst_prog ? prog->aux->dst_prog->type : prog->type; 3477 } 3478 3479 static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, 3480 const struct bpf_call_arg_meta *meta, 3481 enum bpf_access_type t) 3482 { 3483 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 3484 3485 switch (prog_type) { 3486 /* Program types only with direct read access go here! */ 3487 case BPF_PROG_TYPE_LWT_IN: 3488 case BPF_PROG_TYPE_LWT_OUT: 3489 case BPF_PROG_TYPE_LWT_SEG6LOCAL: 3490 case BPF_PROG_TYPE_SK_REUSEPORT: 3491 case BPF_PROG_TYPE_FLOW_DISSECTOR: 3492 case BPF_PROG_TYPE_CGROUP_SKB: 3493 if (t == BPF_WRITE) 3494 return false; 3495 fallthrough; 3496 3497 /* Program types with direct read + write access go here! */ 3498 case BPF_PROG_TYPE_SCHED_CLS: 3499 case BPF_PROG_TYPE_SCHED_ACT: 3500 case BPF_PROG_TYPE_XDP: 3501 case BPF_PROG_TYPE_LWT_XMIT: 3502 case BPF_PROG_TYPE_SK_SKB: 3503 case BPF_PROG_TYPE_SK_MSG: 3504 if (meta) 3505 return meta->pkt_access; 3506 3507 env->seen_direct_write = true; 3508 return true; 3509 3510 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 3511 if (t == BPF_WRITE) 3512 env->seen_direct_write = true; 3513 3514 return true; 3515 3516 default: 3517 return false; 3518 } 3519 } 3520 3521 static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, 3522 int size, bool zero_size_allowed) 3523 { 3524 struct bpf_reg_state *regs = cur_regs(env); 3525 struct bpf_reg_state *reg = ®s[regno]; 3526 int err; 3527 3528 /* We may have added a variable offset to the packet pointer; but any 3529 * reg->range we have comes after that. We are only checking the fixed 3530 * offset. 3531 */ 3532 3533 /* We don't allow negative numbers, because we aren't tracking enough 3534 * detail to prove they're safe. 3535 */ 3536 if (reg->smin_value < 0) { 3537 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3538 regno); 3539 return -EACCES; 3540 } 3541 3542 err = reg->range < 0 ? -EINVAL : 3543 __check_mem_access(env, regno, off, size, reg->range, 3544 zero_size_allowed); 3545 if (err) { 3546 verbose(env, "R%d offset is outside of the packet\n", regno); 3547 return err; 3548 } 3549 3550 /* __check_mem_access has made sure "off + size - 1" is within u16. 3551 * reg->umax_value can't be bigger than MAX_PACKET_OFF which is 0xffff, 3552 * otherwise find_good_pkt_pointers would have refused to set range info 3553 * that __check_mem_access would have rejected this pkt access. 3554 * Therefore, "off + reg->umax_value + size - 1" won't overflow u32. 3555 */ 3556 env->prog->aux->max_pkt_offset = 3557 max_t(u32, env->prog->aux->max_pkt_offset, 3558 off + reg->umax_value + size - 1); 3559 3560 return err; 3561 } 3562 3563 /* check access to 'struct bpf_context' fields. Supports fixed offsets only */ 3564 static int check_ctx_access(struct bpf_verifier_env *env, int insn_idx, int off, int size, 3565 enum bpf_access_type t, enum bpf_reg_type *reg_type, 3566 struct btf **btf, u32 *btf_id) 3567 { 3568 struct bpf_insn_access_aux info = { 3569 .reg_type = *reg_type, 3570 .log = &env->log, 3571 }; 3572 3573 if (env->ops->is_valid_access && 3574 env->ops->is_valid_access(off, size, t, env->prog, &info)) { 3575 /* A non zero info.ctx_field_size indicates that this field is a 3576 * candidate for later verifier transformation to load the whole 3577 * field and then apply a mask when accessed with a narrower 3578 * access than actual ctx access size. A zero info.ctx_field_size 3579 * will only allow for whole field access and rejects any other 3580 * type of narrower access. 3581 */ 3582 *reg_type = info.reg_type; 3583 3584 if (*reg_type == PTR_TO_BTF_ID || *reg_type == PTR_TO_BTF_ID_OR_NULL) { 3585 *btf = info.btf; 3586 *btf_id = info.btf_id; 3587 } else { 3588 env->insn_aux_data[insn_idx].ctx_field_size = info.ctx_field_size; 3589 } 3590 /* remember the offset of last byte accessed in ctx */ 3591 if (env->prog->aux->max_ctx_offset < off + size) 3592 env->prog->aux->max_ctx_offset = off + size; 3593 return 0; 3594 } 3595 3596 verbose(env, "invalid bpf_context access off=%d size=%d\n", off, size); 3597 return -EACCES; 3598 } 3599 3600 static int check_flow_keys_access(struct bpf_verifier_env *env, int off, 3601 int size) 3602 { 3603 if (size < 0 || off < 0 || 3604 (u64)off + size > sizeof(struct bpf_flow_keys)) { 3605 verbose(env, "invalid access to flow keys off=%d size=%d\n", 3606 off, size); 3607 return -EACCES; 3608 } 3609 return 0; 3610 } 3611 3612 static int check_sock_access(struct bpf_verifier_env *env, int insn_idx, 3613 u32 regno, int off, int size, 3614 enum bpf_access_type t) 3615 { 3616 struct bpf_reg_state *regs = cur_regs(env); 3617 struct bpf_reg_state *reg = ®s[regno]; 3618 struct bpf_insn_access_aux info = {}; 3619 bool valid; 3620 3621 if (reg->smin_value < 0) { 3622 verbose(env, "R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", 3623 regno); 3624 return -EACCES; 3625 } 3626 3627 switch (reg->type) { 3628 case PTR_TO_SOCK_COMMON: 3629 valid = bpf_sock_common_is_valid_access(off, size, t, &info); 3630 break; 3631 case PTR_TO_SOCKET: 3632 valid = bpf_sock_is_valid_access(off, size, t, &info); 3633 break; 3634 case PTR_TO_TCP_SOCK: 3635 valid = bpf_tcp_sock_is_valid_access(off, size, t, &info); 3636 break; 3637 case PTR_TO_XDP_SOCK: 3638 valid = bpf_xdp_sock_is_valid_access(off, size, t, &info); 3639 break; 3640 default: 3641 valid = false; 3642 } 3643 3644 3645 if (valid) { 3646 env->insn_aux_data[insn_idx].ctx_field_size = 3647 info.ctx_field_size; 3648 return 0; 3649 } 3650 3651 verbose(env, "R%d invalid %s access off=%d size=%d\n", 3652 regno, reg_type_str[reg->type], off, size); 3653 3654 return -EACCES; 3655 } 3656 3657 static bool is_pointer_value(struct bpf_verifier_env *env, int regno) 3658 { 3659 return __is_pointer_value(env->allow_ptr_leaks, reg_state(env, regno)); 3660 } 3661 3662 static bool is_ctx_reg(struct bpf_verifier_env *env, int regno) 3663 { 3664 const struct bpf_reg_state *reg = reg_state(env, regno); 3665 3666 return reg->type == PTR_TO_CTX; 3667 } 3668 3669 static bool is_sk_reg(struct bpf_verifier_env *env, int regno) 3670 { 3671 const struct bpf_reg_state *reg = reg_state(env, regno); 3672 3673 return type_is_sk_pointer(reg->type); 3674 } 3675 3676 static bool is_pkt_reg(struct bpf_verifier_env *env, int regno) 3677 { 3678 const struct bpf_reg_state *reg = reg_state(env, regno); 3679 3680 return type_is_pkt_pointer(reg->type); 3681 } 3682 3683 static bool is_flow_key_reg(struct bpf_verifier_env *env, int regno) 3684 { 3685 const struct bpf_reg_state *reg = reg_state(env, regno); 3686 3687 /* Separate to is_ctx_reg() since we still want to allow BPF_ST here. */ 3688 return reg->type == PTR_TO_FLOW_KEYS; 3689 } 3690 3691 static int check_pkt_ptr_alignment(struct bpf_verifier_env *env, 3692 const struct bpf_reg_state *reg, 3693 int off, int size, bool strict) 3694 { 3695 struct tnum reg_off; 3696 int ip_align; 3697 3698 /* Byte size accesses are always allowed. */ 3699 if (!strict || size == 1) 3700 return 0; 3701 3702 /* For platforms that do not have a Kconfig enabling 3703 * CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS the value of 3704 * NET_IP_ALIGN is universally set to '2'. And on platforms 3705 * that do set CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS, we get 3706 * to this code only in strict mode where we want to emulate 3707 * the NET_IP_ALIGN==2 checking. Therefore use an 3708 * unconditional IP align value of '2'. 3709 */ 3710 ip_align = 2; 3711 3712 reg_off = tnum_add(reg->var_off, tnum_const(ip_align + reg->off + off)); 3713 if (!tnum_is_aligned(reg_off, size)) { 3714 char tn_buf[48]; 3715 3716 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3717 verbose(env, 3718 "misaligned packet access off %d+%s+%d+%d size %d\n", 3719 ip_align, tn_buf, reg->off, off, size); 3720 return -EACCES; 3721 } 3722 3723 return 0; 3724 } 3725 3726 static int check_generic_ptr_alignment(struct bpf_verifier_env *env, 3727 const struct bpf_reg_state *reg, 3728 const char *pointer_desc, 3729 int off, int size, bool strict) 3730 { 3731 struct tnum reg_off; 3732 3733 /* Byte size accesses are always allowed. */ 3734 if (!strict || size == 1) 3735 return 0; 3736 3737 reg_off = tnum_add(reg->var_off, tnum_const(reg->off + off)); 3738 if (!tnum_is_aligned(reg_off, size)) { 3739 char tn_buf[48]; 3740 3741 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3742 verbose(env, "misaligned %saccess off %s+%d+%d size %d\n", 3743 pointer_desc, tn_buf, reg->off, off, size); 3744 return -EACCES; 3745 } 3746 3747 return 0; 3748 } 3749 3750 static int check_ptr_alignment(struct bpf_verifier_env *env, 3751 const struct bpf_reg_state *reg, int off, 3752 int size, bool strict_alignment_once) 3753 { 3754 bool strict = env->strict_alignment || strict_alignment_once; 3755 const char *pointer_desc = ""; 3756 3757 switch (reg->type) { 3758 case PTR_TO_PACKET: 3759 case PTR_TO_PACKET_META: 3760 /* Special case, because of NET_IP_ALIGN. Given metadata sits 3761 * right in front, treat it the very same way. 3762 */ 3763 return check_pkt_ptr_alignment(env, reg, off, size, strict); 3764 case PTR_TO_FLOW_KEYS: 3765 pointer_desc = "flow keys "; 3766 break; 3767 case PTR_TO_MAP_KEY: 3768 pointer_desc = "key "; 3769 break; 3770 case PTR_TO_MAP_VALUE: 3771 pointer_desc = "value "; 3772 break; 3773 case PTR_TO_CTX: 3774 pointer_desc = "context "; 3775 break; 3776 case PTR_TO_STACK: 3777 pointer_desc = "stack "; 3778 /* The stack spill tracking logic in check_stack_write_fixed_off() 3779 * and check_stack_read_fixed_off() relies on stack accesses being 3780 * aligned. 3781 */ 3782 strict = true; 3783 break; 3784 case PTR_TO_SOCKET: 3785 pointer_desc = "sock "; 3786 break; 3787 case PTR_TO_SOCK_COMMON: 3788 pointer_desc = "sock_common "; 3789 break; 3790 case PTR_TO_TCP_SOCK: 3791 pointer_desc = "tcp_sock "; 3792 break; 3793 case PTR_TO_XDP_SOCK: 3794 pointer_desc = "xdp_sock "; 3795 break; 3796 default: 3797 break; 3798 } 3799 return check_generic_ptr_alignment(env, reg, pointer_desc, off, size, 3800 strict); 3801 } 3802 3803 static int update_stack_depth(struct bpf_verifier_env *env, 3804 const struct bpf_func_state *func, 3805 int off) 3806 { 3807 u16 stack = env->subprog_info[func->subprogno].stack_depth; 3808 3809 if (stack >= -off) 3810 return 0; 3811 3812 /* update known max for given subprogram */ 3813 env->subprog_info[func->subprogno].stack_depth = -off; 3814 return 0; 3815 } 3816 3817 /* starting from main bpf function walk all instructions of the function 3818 * and recursively walk all callees that given function can call. 3819 * Ignore jump and exit insns. 3820 * Since recursion is prevented by check_cfg() this algorithm 3821 * only needs a local stack of MAX_CALL_FRAMES to remember callsites 3822 */ 3823 static int check_max_stack_depth(struct bpf_verifier_env *env) 3824 { 3825 int depth = 0, frame = 0, idx = 0, i = 0, subprog_end; 3826 struct bpf_subprog_info *subprog = env->subprog_info; 3827 struct bpf_insn *insn = env->prog->insnsi; 3828 bool tail_call_reachable = false; 3829 int ret_insn[MAX_CALL_FRAMES]; 3830 int ret_prog[MAX_CALL_FRAMES]; 3831 int j; 3832 3833 process_func: 3834 /* protect against potential stack overflow that might happen when 3835 * bpf2bpf calls get combined with tailcalls. Limit the caller's stack 3836 * depth for such case down to 256 so that the worst case scenario 3837 * would result in 8k stack size (32 which is tailcall limit * 256 = 3838 * 8k). 3839 * 3840 * To get the idea what might happen, see an example: 3841 * func1 -> sub rsp, 128 3842 * subfunc1 -> sub rsp, 256 3843 * tailcall1 -> add rsp, 256 3844 * func2 -> sub rsp, 192 (total stack size = 128 + 192 = 320) 3845 * subfunc2 -> sub rsp, 64 3846 * subfunc22 -> sub rsp, 128 3847 * tailcall2 -> add rsp, 128 3848 * func3 -> sub rsp, 32 (total stack size 128 + 192 + 64 + 32 = 416) 3849 * 3850 * tailcall will unwind the current stack frame but it will not get rid 3851 * of caller's stack as shown on the example above. 3852 */ 3853 if (idx && subprog[idx].has_tail_call && depth >= 256) { 3854 verbose(env, 3855 "tail_calls are not allowed when call stack of previous frames is %d bytes. Too large\n", 3856 depth); 3857 return -EACCES; 3858 } 3859 /* round up to 32-bytes, since this is granularity 3860 * of interpreter stack size 3861 */ 3862 depth += round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 3863 if (depth > MAX_BPF_STACK) { 3864 verbose(env, "combined stack size of %d calls is %d. Too large\n", 3865 frame + 1, depth); 3866 return -EACCES; 3867 } 3868 continue_func: 3869 subprog_end = subprog[idx + 1].start; 3870 for (; i < subprog_end; i++) { 3871 int next_insn; 3872 3873 if (!bpf_pseudo_call(insn + i) && !bpf_pseudo_func(insn + i)) 3874 continue; 3875 /* remember insn and function to return to */ 3876 ret_insn[frame] = i + 1; 3877 ret_prog[frame] = idx; 3878 3879 /* find the callee */ 3880 next_insn = i + insn[i].imm + 1; 3881 idx = find_subprog(env, next_insn); 3882 if (idx < 0) { 3883 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 3884 next_insn); 3885 return -EFAULT; 3886 } 3887 if (subprog[idx].is_async_cb) { 3888 if (subprog[idx].has_tail_call) { 3889 verbose(env, "verifier bug. subprog has tail_call and async cb\n"); 3890 return -EFAULT; 3891 } 3892 /* async callbacks don't increase bpf prog stack size */ 3893 continue; 3894 } 3895 i = next_insn; 3896 3897 if (subprog[idx].has_tail_call) 3898 tail_call_reachable = true; 3899 3900 frame++; 3901 if (frame >= MAX_CALL_FRAMES) { 3902 verbose(env, "the call stack of %d frames is too deep !\n", 3903 frame); 3904 return -E2BIG; 3905 } 3906 goto process_func; 3907 } 3908 /* if tail call got detected across bpf2bpf calls then mark each of the 3909 * currently present subprog frames as tail call reachable subprogs; 3910 * this info will be utilized by JIT so that we will be preserving the 3911 * tail call counter throughout bpf2bpf calls combined with tailcalls 3912 */ 3913 if (tail_call_reachable) 3914 for (j = 0; j < frame; j++) 3915 subprog[ret_prog[j]].tail_call_reachable = true; 3916 if (subprog[0].tail_call_reachable) 3917 env->prog->aux->tail_call_reachable = true; 3918 3919 /* end of for() loop means the last insn of the 'subprog' 3920 * was reached. Doesn't matter whether it was JA or EXIT 3921 */ 3922 if (frame == 0) 3923 return 0; 3924 depth -= round_up(max_t(u32, subprog[idx].stack_depth, 1), 32); 3925 frame--; 3926 i = ret_insn[frame]; 3927 idx = ret_prog[frame]; 3928 goto continue_func; 3929 } 3930 3931 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 3932 static int get_callee_stack_depth(struct bpf_verifier_env *env, 3933 const struct bpf_insn *insn, int idx) 3934 { 3935 int start = idx + insn->imm + 1, subprog; 3936 3937 subprog = find_subprog(env, start); 3938 if (subprog < 0) { 3939 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 3940 start); 3941 return -EFAULT; 3942 } 3943 return env->subprog_info[subprog].stack_depth; 3944 } 3945 #endif 3946 3947 int check_ctx_reg(struct bpf_verifier_env *env, 3948 const struct bpf_reg_state *reg, int regno) 3949 { 3950 /* Access to ctx or passing it to a helper is only allowed in 3951 * its original, unmodified form. 3952 */ 3953 3954 if (reg->off) { 3955 verbose(env, "dereference of modified ctx ptr R%d off=%d disallowed\n", 3956 regno, reg->off); 3957 return -EACCES; 3958 } 3959 3960 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3961 char tn_buf[48]; 3962 3963 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3964 verbose(env, "variable ctx access var_off=%s disallowed\n", tn_buf); 3965 return -EACCES; 3966 } 3967 3968 return 0; 3969 } 3970 3971 static int __check_buffer_access(struct bpf_verifier_env *env, 3972 const char *buf_info, 3973 const struct bpf_reg_state *reg, 3974 int regno, int off, int size) 3975 { 3976 if (off < 0) { 3977 verbose(env, 3978 "R%d invalid %s buffer access: off=%d, size=%d\n", 3979 regno, buf_info, off, size); 3980 return -EACCES; 3981 } 3982 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 3983 char tn_buf[48]; 3984 3985 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 3986 verbose(env, 3987 "R%d invalid variable buffer offset: off=%d, var_off=%s\n", 3988 regno, off, tn_buf); 3989 return -EACCES; 3990 } 3991 3992 return 0; 3993 } 3994 3995 static int check_tp_buffer_access(struct bpf_verifier_env *env, 3996 const struct bpf_reg_state *reg, 3997 int regno, int off, int size) 3998 { 3999 int err; 4000 4001 err = __check_buffer_access(env, "tracepoint", reg, regno, off, size); 4002 if (err) 4003 return err; 4004 4005 if (off + size > env->prog->aux->max_tp_access) 4006 env->prog->aux->max_tp_access = off + size; 4007 4008 return 0; 4009 } 4010 4011 static int check_buffer_access(struct bpf_verifier_env *env, 4012 const struct bpf_reg_state *reg, 4013 int regno, int off, int size, 4014 bool zero_size_allowed, 4015 const char *buf_info, 4016 u32 *max_access) 4017 { 4018 int err; 4019 4020 err = __check_buffer_access(env, buf_info, reg, regno, off, size); 4021 if (err) 4022 return err; 4023 4024 if (off + size > *max_access) 4025 *max_access = off + size; 4026 4027 return 0; 4028 } 4029 4030 /* BPF architecture zero extends alu32 ops into 64-bit registesr */ 4031 static void zext_32_to_64(struct bpf_reg_state *reg) 4032 { 4033 reg->var_off = tnum_subreg(reg->var_off); 4034 __reg_assign_32_into_64(reg); 4035 } 4036 4037 /* truncate register to smaller size (in bytes) 4038 * must be called with size < BPF_REG_SIZE 4039 */ 4040 static void coerce_reg_to_size(struct bpf_reg_state *reg, int size) 4041 { 4042 u64 mask; 4043 4044 /* clear high bits in bit representation */ 4045 reg->var_off = tnum_cast(reg->var_off, size); 4046 4047 /* fix arithmetic bounds */ 4048 mask = ((u64)1 << (size * 8)) - 1; 4049 if ((reg->umin_value & ~mask) == (reg->umax_value & ~mask)) { 4050 reg->umin_value &= mask; 4051 reg->umax_value &= mask; 4052 } else { 4053 reg->umin_value = 0; 4054 reg->umax_value = mask; 4055 } 4056 reg->smin_value = reg->umin_value; 4057 reg->smax_value = reg->umax_value; 4058 4059 /* If size is smaller than 32bit register the 32bit register 4060 * values are also truncated so we push 64-bit bounds into 4061 * 32-bit bounds. Above were truncated < 32-bits already. 4062 */ 4063 if (size >= 4) 4064 return; 4065 __reg_combine_64_into_32(reg); 4066 } 4067 4068 static bool bpf_map_is_rdonly(const struct bpf_map *map) 4069 { 4070 return (map->map_flags & BPF_F_RDONLY_PROG) && map->frozen; 4071 } 4072 4073 static int bpf_map_direct_read(struct bpf_map *map, int off, int size, u64 *val) 4074 { 4075 void *ptr; 4076 u64 addr; 4077 int err; 4078 4079 err = map->ops->map_direct_value_addr(map, &addr, off); 4080 if (err) 4081 return err; 4082 ptr = (void *)(long)addr + off; 4083 4084 switch (size) { 4085 case sizeof(u8): 4086 *val = (u64)*(u8 *)ptr; 4087 break; 4088 case sizeof(u16): 4089 *val = (u64)*(u16 *)ptr; 4090 break; 4091 case sizeof(u32): 4092 *val = (u64)*(u32 *)ptr; 4093 break; 4094 case sizeof(u64): 4095 *val = *(u64 *)ptr; 4096 break; 4097 default: 4098 return -EINVAL; 4099 } 4100 return 0; 4101 } 4102 4103 static int check_ptr_to_btf_access(struct bpf_verifier_env *env, 4104 struct bpf_reg_state *regs, 4105 int regno, int off, int size, 4106 enum bpf_access_type atype, 4107 int value_regno) 4108 { 4109 struct bpf_reg_state *reg = regs + regno; 4110 const struct btf_type *t = btf_type_by_id(reg->btf, reg->btf_id); 4111 const char *tname = btf_name_by_offset(reg->btf, t->name_off); 4112 u32 btf_id; 4113 int ret; 4114 4115 if (off < 0) { 4116 verbose(env, 4117 "R%d is ptr_%s invalid negative access: off=%d\n", 4118 regno, tname, off); 4119 return -EACCES; 4120 } 4121 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 4122 char tn_buf[48]; 4123 4124 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4125 verbose(env, 4126 "R%d is ptr_%s invalid variable offset: off=%d, var_off=%s\n", 4127 regno, tname, off, tn_buf); 4128 return -EACCES; 4129 } 4130 4131 if (env->ops->btf_struct_access) { 4132 ret = env->ops->btf_struct_access(&env->log, reg->btf, t, 4133 off, size, atype, &btf_id); 4134 } else { 4135 if (atype != BPF_READ) { 4136 verbose(env, "only read is supported\n"); 4137 return -EACCES; 4138 } 4139 4140 ret = btf_struct_access(&env->log, reg->btf, t, off, size, 4141 atype, &btf_id); 4142 } 4143 4144 if (ret < 0) 4145 return ret; 4146 4147 if (atype == BPF_READ && value_regno >= 0) 4148 mark_btf_ld_reg(env, regs, value_regno, ret, reg->btf, btf_id); 4149 4150 return 0; 4151 } 4152 4153 static int check_ptr_to_map_access(struct bpf_verifier_env *env, 4154 struct bpf_reg_state *regs, 4155 int regno, int off, int size, 4156 enum bpf_access_type atype, 4157 int value_regno) 4158 { 4159 struct bpf_reg_state *reg = regs + regno; 4160 struct bpf_map *map = reg->map_ptr; 4161 const struct btf_type *t; 4162 const char *tname; 4163 u32 btf_id; 4164 int ret; 4165 4166 if (!btf_vmlinux) { 4167 verbose(env, "map_ptr access not supported without CONFIG_DEBUG_INFO_BTF\n"); 4168 return -ENOTSUPP; 4169 } 4170 4171 if (!map->ops->map_btf_id || !*map->ops->map_btf_id) { 4172 verbose(env, "map_ptr access not supported for map type %d\n", 4173 map->map_type); 4174 return -ENOTSUPP; 4175 } 4176 4177 t = btf_type_by_id(btf_vmlinux, *map->ops->map_btf_id); 4178 tname = btf_name_by_offset(btf_vmlinux, t->name_off); 4179 4180 if (!env->allow_ptr_to_map_access) { 4181 verbose(env, 4182 "%s access is allowed only to CAP_PERFMON and CAP_SYS_ADMIN\n", 4183 tname); 4184 return -EPERM; 4185 } 4186 4187 if (off < 0) { 4188 verbose(env, "R%d is %s invalid negative access: off=%d\n", 4189 regno, tname, off); 4190 return -EACCES; 4191 } 4192 4193 if (atype != BPF_READ) { 4194 verbose(env, "only read from %s is supported\n", tname); 4195 return -EACCES; 4196 } 4197 4198 ret = btf_struct_access(&env->log, btf_vmlinux, t, off, size, atype, &btf_id); 4199 if (ret < 0) 4200 return ret; 4201 4202 if (value_regno >= 0) 4203 mark_btf_ld_reg(env, regs, value_regno, ret, btf_vmlinux, btf_id); 4204 4205 return 0; 4206 } 4207 4208 /* Check that the stack access at the given offset is within bounds. The 4209 * maximum valid offset is -1. 4210 * 4211 * The minimum valid offset is -MAX_BPF_STACK for writes, and 4212 * -state->allocated_stack for reads. 4213 */ 4214 static int check_stack_slot_within_bounds(int off, 4215 struct bpf_func_state *state, 4216 enum bpf_access_type t) 4217 { 4218 int min_valid_off; 4219 4220 if (t == BPF_WRITE) 4221 min_valid_off = -MAX_BPF_STACK; 4222 else 4223 min_valid_off = -state->allocated_stack; 4224 4225 if (off < min_valid_off || off > -1) 4226 return -EACCES; 4227 return 0; 4228 } 4229 4230 /* Check that the stack access at 'regno + off' falls within the maximum stack 4231 * bounds. 4232 * 4233 * 'off' includes `regno->offset`, but not its dynamic part (if any). 4234 */ 4235 static int check_stack_access_within_bounds( 4236 struct bpf_verifier_env *env, 4237 int regno, int off, int access_size, 4238 enum stack_access_src src, enum bpf_access_type type) 4239 { 4240 struct bpf_reg_state *regs = cur_regs(env); 4241 struct bpf_reg_state *reg = regs + regno; 4242 struct bpf_func_state *state = func(env, reg); 4243 int min_off, max_off; 4244 int err; 4245 char *err_extra; 4246 4247 if (src == ACCESS_HELPER) 4248 /* We don't know if helpers are reading or writing (or both). */ 4249 err_extra = " indirect access to"; 4250 else if (type == BPF_READ) 4251 err_extra = " read from"; 4252 else 4253 err_extra = " write to"; 4254 4255 if (tnum_is_const(reg->var_off)) { 4256 min_off = reg->var_off.value + off; 4257 if (access_size > 0) 4258 max_off = min_off + access_size - 1; 4259 else 4260 max_off = min_off; 4261 } else { 4262 if (reg->smax_value >= BPF_MAX_VAR_OFF || 4263 reg->smin_value <= -BPF_MAX_VAR_OFF) { 4264 verbose(env, "invalid unbounded variable-offset%s stack R%d\n", 4265 err_extra, regno); 4266 return -EACCES; 4267 } 4268 min_off = reg->smin_value + off; 4269 if (access_size > 0) 4270 max_off = reg->smax_value + off + access_size - 1; 4271 else 4272 max_off = min_off; 4273 } 4274 4275 err = check_stack_slot_within_bounds(min_off, state, type); 4276 if (!err) 4277 err = check_stack_slot_within_bounds(max_off, state, type); 4278 4279 if (err) { 4280 if (tnum_is_const(reg->var_off)) { 4281 verbose(env, "invalid%s stack R%d off=%d size=%d\n", 4282 err_extra, regno, off, access_size); 4283 } else { 4284 char tn_buf[48]; 4285 4286 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4287 verbose(env, "invalid variable-offset%s stack R%d var_off=%s size=%d\n", 4288 err_extra, regno, tn_buf, access_size); 4289 } 4290 } 4291 return err; 4292 } 4293 4294 /* check whether memory at (regno + off) is accessible for t = (read | write) 4295 * if t==write, value_regno is a register which value is stored into memory 4296 * if t==read, value_regno is a register which will receive the value from memory 4297 * if t==write && value_regno==-1, some unknown value is stored into memory 4298 * if t==read && value_regno==-1, don't care what we read from memory 4299 */ 4300 static int check_mem_access(struct bpf_verifier_env *env, int insn_idx, u32 regno, 4301 int off, int bpf_size, enum bpf_access_type t, 4302 int value_regno, bool strict_alignment_once) 4303 { 4304 struct bpf_reg_state *regs = cur_regs(env); 4305 struct bpf_reg_state *reg = regs + regno; 4306 struct bpf_func_state *state; 4307 int size, err = 0; 4308 4309 size = bpf_size_to_bytes(bpf_size); 4310 if (size < 0) 4311 return size; 4312 4313 /* alignment checks will add in reg->off themselves */ 4314 err = check_ptr_alignment(env, reg, off, size, strict_alignment_once); 4315 if (err) 4316 return err; 4317 4318 /* for access checks, reg->off is just part of off */ 4319 off += reg->off; 4320 4321 if (reg->type == PTR_TO_MAP_KEY) { 4322 if (t == BPF_WRITE) { 4323 verbose(env, "write to change key R%d not allowed\n", regno); 4324 return -EACCES; 4325 } 4326 4327 err = check_mem_region_access(env, regno, off, size, 4328 reg->map_ptr->key_size, false); 4329 if (err) 4330 return err; 4331 if (value_regno >= 0) 4332 mark_reg_unknown(env, regs, value_regno); 4333 } else if (reg->type == PTR_TO_MAP_VALUE) { 4334 if (t == BPF_WRITE && value_regno >= 0 && 4335 is_pointer_value(env, value_regno)) { 4336 verbose(env, "R%d leaks addr into map\n", value_regno); 4337 return -EACCES; 4338 } 4339 err = check_map_access_type(env, regno, off, size, t); 4340 if (err) 4341 return err; 4342 err = check_map_access(env, regno, off, size, false); 4343 if (!err && t == BPF_READ && value_regno >= 0) { 4344 struct bpf_map *map = reg->map_ptr; 4345 4346 /* if map is read-only, track its contents as scalars */ 4347 if (tnum_is_const(reg->var_off) && 4348 bpf_map_is_rdonly(map) && 4349 map->ops->map_direct_value_addr) { 4350 int map_off = off + reg->var_off.value; 4351 u64 val = 0; 4352 4353 err = bpf_map_direct_read(map, map_off, size, 4354 &val); 4355 if (err) 4356 return err; 4357 4358 regs[value_regno].type = SCALAR_VALUE; 4359 __mark_reg_known(®s[value_regno], val); 4360 } else { 4361 mark_reg_unknown(env, regs, value_regno); 4362 } 4363 } 4364 } else if (reg->type == PTR_TO_MEM) { 4365 if (t == BPF_WRITE && value_regno >= 0 && 4366 is_pointer_value(env, value_regno)) { 4367 verbose(env, "R%d leaks addr into mem\n", value_regno); 4368 return -EACCES; 4369 } 4370 err = check_mem_region_access(env, regno, off, size, 4371 reg->mem_size, false); 4372 if (!err && t == BPF_READ && value_regno >= 0) 4373 mark_reg_unknown(env, regs, value_regno); 4374 } else if (reg->type == PTR_TO_CTX) { 4375 enum bpf_reg_type reg_type = SCALAR_VALUE; 4376 struct btf *btf = NULL; 4377 u32 btf_id = 0; 4378 4379 if (t == BPF_WRITE && value_regno >= 0 && 4380 is_pointer_value(env, value_regno)) { 4381 verbose(env, "R%d leaks addr into ctx\n", value_regno); 4382 return -EACCES; 4383 } 4384 4385 err = check_ctx_reg(env, reg, regno); 4386 if (err < 0) 4387 return err; 4388 4389 err = check_ctx_access(env, insn_idx, off, size, t, ®_type, &btf, &btf_id); 4390 if (err) 4391 verbose_linfo(env, insn_idx, "; "); 4392 if (!err && t == BPF_READ && value_regno >= 0) { 4393 /* ctx access returns either a scalar, or a 4394 * PTR_TO_PACKET[_META,_END]. In the latter 4395 * case, we know the offset is zero. 4396 */ 4397 if (reg_type == SCALAR_VALUE) { 4398 mark_reg_unknown(env, regs, value_regno); 4399 } else { 4400 mark_reg_known_zero(env, regs, 4401 value_regno); 4402 if (reg_type_may_be_null(reg_type)) 4403 regs[value_regno].id = ++env->id_gen; 4404 /* A load of ctx field could have different 4405 * actual load size with the one encoded in the 4406 * insn. When the dst is PTR, it is for sure not 4407 * a sub-register. 4408 */ 4409 regs[value_regno].subreg_def = DEF_NOT_SUBREG; 4410 if (reg_type == PTR_TO_BTF_ID || 4411 reg_type == PTR_TO_BTF_ID_OR_NULL) { 4412 regs[value_regno].btf = btf; 4413 regs[value_regno].btf_id = btf_id; 4414 } 4415 } 4416 regs[value_regno].type = reg_type; 4417 } 4418 4419 } else if (reg->type == PTR_TO_STACK) { 4420 /* Basic bounds checks. */ 4421 err = check_stack_access_within_bounds(env, regno, off, size, ACCESS_DIRECT, t); 4422 if (err) 4423 return err; 4424 4425 state = func(env, reg); 4426 err = update_stack_depth(env, state, off); 4427 if (err) 4428 return err; 4429 4430 if (t == BPF_READ) 4431 err = check_stack_read(env, regno, off, size, 4432 value_regno); 4433 else 4434 err = check_stack_write(env, regno, off, size, 4435 value_regno, insn_idx); 4436 } else if (reg_is_pkt_pointer(reg)) { 4437 if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { 4438 verbose(env, "cannot write into packet\n"); 4439 return -EACCES; 4440 } 4441 if (t == BPF_WRITE && value_regno >= 0 && 4442 is_pointer_value(env, value_regno)) { 4443 verbose(env, "R%d leaks addr into packet\n", 4444 value_regno); 4445 return -EACCES; 4446 } 4447 err = check_packet_access(env, regno, off, size, false); 4448 if (!err && t == BPF_READ && value_regno >= 0) 4449 mark_reg_unknown(env, regs, value_regno); 4450 } else if (reg->type == PTR_TO_FLOW_KEYS) { 4451 if (t == BPF_WRITE && value_regno >= 0 && 4452 is_pointer_value(env, value_regno)) { 4453 verbose(env, "R%d leaks addr into flow keys\n", 4454 value_regno); 4455 return -EACCES; 4456 } 4457 4458 err = check_flow_keys_access(env, off, size); 4459 if (!err && t == BPF_READ && value_regno >= 0) 4460 mark_reg_unknown(env, regs, value_regno); 4461 } else if (type_is_sk_pointer(reg->type)) { 4462 if (t == BPF_WRITE) { 4463 verbose(env, "R%d cannot write into %s\n", 4464 regno, reg_type_str[reg->type]); 4465 return -EACCES; 4466 } 4467 err = check_sock_access(env, insn_idx, regno, off, size, t); 4468 if (!err && value_regno >= 0) 4469 mark_reg_unknown(env, regs, value_regno); 4470 } else if (reg->type == PTR_TO_TP_BUFFER) { 4471 err = check_tp_buffer_access(env, reg, regno, off, size); 4472 if (!err && t == BPF_READ && value_regno >= 0) 4473 mark_reg_unknown(env, regs, value_regno); 4474 } else if (reg->type == PTR_TO_BTF_ID) { 4475 err = check_ptr_to_btf_access(env, regs, regno, off, size, t, 4476 value_regno); 4477 } else if (reg->type == CONST_PTR_TO_MAP) { 4478 err = check_ptr_to_map_access(env, regs, regno, off, size, t, 4479 value_regno); 4480 } else if (reg->type == PTR_TO_RDONLY_BUF) { 4481 if (t == BPF_WRITE) { 4482 verbose(env, "R%d cannot write into %s\n", 4483 regno, reg_type_str[reg->type]); 4484 return -EACCES; 4485 } 4486 err = check_buffer_access(env, reg, regno, off, size, false, 4487 "rdonly", 4488 &env->prog->aux->max_rdonly_access); 4489 if (!err && value_regno >= 0) 4490 mark_reg_unknown(env, regs, value_regno); 4491 } else if (reg->type == PTR_TO_RDWR_BUF) { 4492 err = check_buffer_access(env, reg, regno, off, size, false, 4493 "rdwr", 4494 &env->prog->aux->max_rdwr_access); 4495 if (!err && t == BPF_READ && value_regno >= 0) 4496 mark_reg_unknown(env, regs, value_regno); 4497 } else { 4498 verbose(env, "R%d invalid mem access '%s'\n", regno, 4499 reg_type_str[reg->type]); 4500 return -EACCES; 4501 } 4502 4503 if (!err && size < BPF_REG_SIZE && value_regno >= 0 && t == BPF_READ && 4504 regs[value_regno].type == SCALAR_VALUE) { 4505 /* b/h/w load zero-extends, mark upper bits as known 0 */ 4506 coerce_reg_to_size(®s[value_regno], size); 4507 } 4508 return err; 4509 } 4510 4511 static int check_atomic(struct bpf_verifier_env *env, int insn_idx, struct bpf_insn *insn) 4512 { 4513 int load_reg; 4514 int err; 4515 4516 switch (insn->imm) { 4517 case BPF_ADD: 4518 case BPF_ADD | BPF_FETCH: 4519 case BPF_AND: 4520 case BPF_AND | BPF_FETCH: 4521 case BPF_OR: 4522 case BPF_OR | BPF_FETCH: 4523 case BPF_XOR: 4524 case BPF_XOR | BPF_FETCH: 4525 case BPF_XCHG: 4526 case BPF_CMPXCHG: 4527 break; 4528 default: 4529 verbose(env, "BPF_ATOMIC uses invalid atomic opcode %02x\n", insn->imm); 4530 return -EINVAL; 4531 } 4532 4533 if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { 4534 verbose(env, "invalid atomic operand size\n"); 4535 return -EINVAL; 4536 } 4537 4538 /* check src1 operand */ 4539 err = check_reg_arg(env, insn->src_reg, SRC_OP); 4540 if (err) 4541 return err; 4542 4543 /* check src2 operand */ 4544 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 4545 if (err) 4546 return err; 4547 4548 if (insn->imm == BPF_CMPXCHG) { 4549 /* Check comparison of R0 with memory location */ 4550 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 4551 if (err) 4552 return err; 4553 } 4554 4555 if (is_pointer_value(env, insn->src_reg)) { 4556 verbose(env, "R%d leaks addr into mem\n", insn->src_reg); 4557 return -EACCES; 4558 } 4559 4560 if (is_ctx_reg(env, insn->dst_reg) || 4561 is_pkt_reg(env, insn->dst_reg) || 4562 is_flow_key_reg(env, insn->dst_reg) || 4563 is_sk_reg(env, insn->dst_reg)) { 4564 verbose(env, "BPF_ATOMIC stores into R%d %s is not allowed\n", 4565 insn->dst_reg, 4566 reg_type_str[reg_state(env, insn->dst_reg)->type]); 4567 return -EACCES; 4568 } 4569 4570 if (insn->imm & BPF_FETCH) { 4571 if (insn->imm == BPF_CMPXCHG) 4572 load_reg = BPF_REG_0; 4573 else 4574 load_reg = insn->src_reg; 4575 4576 /* check and record load of old value */ 4577 err = check_reg_arg(env, load_reg, DST_OP); 4578 if (err) 4579 return err; 4580 } else { 4581 /* This instruction accesses a memory location but doesn't 4582 * actually load it into a register. 4583 */ 4584 load_reg = -1; 4585 } 4586 4587 /* check whether we can read the memory */ 4588 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 4589 BPF_SIZE(insn->code), BPF_READ, load_reg, true); 4590 if (err) 4591 return err; 4592 4593 /* check whether we can write into the same memory */ 4594 err = check_mem_access(env, insn_idx, insn->dst_reg, insn->off, 4595 BPF_SIZE(insn->code), BPF_WRITE, -1, true); 4596 if (err) 4597 return err; 4598 4599 return 0; 4600 } 4601 4602 /* When register 'regno' is used to read the stack (either directly or through 4603 * a helper function) make sure that it's within stack boundary and, depending 4604 * on the access type, that all elements of the stack are initialized. 4605 * 4606 * 'off' includes 'regno->off', but not its dynamic part (if any). 4607 * 4608 * All registers that have been spilled on the stack in the slots within the 4609 * read offsets are marked as read. 4610 */ 4611 static int check_stack_range_initialized( 4612 struct bpf_verifier_env *env, int regno, int off, 4613 int access_size, bool zero_size_allowed, 4614 enum stack_access_src type, struct bpf_call_arg_meta *meta) 4615 { 4616 struct bpf_reg_state *reg = reg_state(env, regno); 4617 struct bpf_func_state *state = func(env, reg); 4618 int err, min_off, max_off, i, j, slot, spi; 4619 char *err_extra = type == ACCESS_HELPER ? " indirect" : ""; 4620 enum bpf_access_type bounds_check_type; 4621 /* Some accesses can write anything into the stack, others are 4622 * read-only. 4623 */ 4624 bool clobber = false; 4625 4626 if (access_size == 0 && !zero_size_allowed) { 4627 verbose(env, "invalid zero-sized read\n"); 4628 return -EACCES; 4629 } 4630 4631 if (type == ACCESS_HELPER) { 4632 /* The bounds checks for writes are more permissive than for 4633 * reads. However, if raw_mode is not set, we'll do extra 4634 * checks below. 4635 */ 4636 bounds_check_type = BPF_WRITE; 4637 clobber = true; 4638 } else { 4639 bounds_check_type = BPF_READ; 4640 } 4641 err = check_stack_access_within_bounds(env, regno, off, access_size, 4642 type, bounds_check_type); 4643 if (err) 4644 return err; 4645 4646 4647 if (tnum_is_const(reg->var_off)) { 4648 min_off = max_off = reg->var_off.value + off; 4649 } else { 4650 /* Variable offset is prohibited for unprivileged mode for 4651 * simplicity since it requires corresponding support in 4652 * Spectre masking for stack ALU. 4653 * See also retrieve_ptr_limit(). 4654 */ 4655 if (!env->bypass_spec_v1) { 4656 char tn_buf[48]; 4657 4658 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4659 verbose(env, "R%d%s variable offset stack access prohibited for !root, var_off=%s\n", 4660 regno, err_extra, tn_buf); 4661 return -EACCES; 4662 } 4663 /* Only initialized buffer on stack is allowed to be accessed 4664 * with variable offset. With uninitialized buffer it's hard to 4665 * guarantee that whole memory is marked as initialized on 4666 * helper return since specific bounds are unknown what may 4667 * cause uninitialized stack leaking. 4668 */ 4669 if (meta && meta->raw_mode) 4670 meta = NULL; 4671 4672 min_off = reg->smin_value + off; 4673 max_off = reg->smax_value + off; 4674 } 4675 4676 if (meta && meta->raw_mode) { 4677 meta->access_size = access_size; 4678 meta->regno = regno; 4679 return 0; 4680 } 4681 4682 for (i = min_off; i < max_off + access_size; i++) { 4683 u8 *stype; 4684 4685 slot = -i - 1; 4686 spi = slot / BPF_REG_SIZE; 4687 if (state->allocated_stack <= slot) 4688 goto err; 4689 stype = &state->stack[spi].slot_type[slot % BPF_REG_SIZE]; 4690 if (*stype == STACK_MISC) 4691 goto mark; 4692 if (*stype == STACK_ZERO) { 4693 if (clobber) { 4694 /* helper can write anything into the stack */ 4695 *stype = STACK_MISC; 4696 } 4697 goto mark; 4698 } 4699 4700 if (is_spilled_reg(&state->stack[spi]) && 4701 state->stack[spi].spilled_ptr.type == PTR_TO_BTF_ID) 4702 goto mark; 4703 4704 if (is_spilled_reg(&state->stack[spi]) && 4705 (state->stack[spi].spilled_ptr.type == SCALAR_VALUE || 4706 env->allow_ptr_leaks)) { 4707 if (clobber) { 4708 __mark_reg_unknown(env, &state->stack[spi].spilled_ptr); 4709 for (j = 0; j < BPF_REG_SIZE; j++) 4710 scrub_spilled_slot(&state->stack[spi].slot_type[j]); 4711 } 4712 goto mark; 4713 } 4714 4715 err: 4716 if (tnum_is_const(reg->var_off)) { 4717 verbose(env, "invalid%s read from stack R%d off %d+%d size %d\n", 4718 err_extra, regno, min_off, i - min_off, access_size); 4719 } else { 4720 char tn_buf[48]; 4721 4722 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 4723 verbose(env, "invalid%s read from stack R%d var_off %s+%d size %d\n", 4724 err_extra, regno, tn_buf, i - min_off, access_size); 4725 } 4726 return -EACCES; 4727 mark: 4728 /* reading any byte out of 8-byte 'spill_slot' will cause 4729 * the whole slot to be marked as 'read' 4730 */ 4731 mark_reg_read(env, &state->stack[spi].spilled_ptr, 4732 state->stack[spi].spilled_ptr.parent, 4733 REG_LIVE_READ64); 4734 } 4735 return update_stack_depth(env, state, min_off); 4736 } 4737 4738 static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, 4739 int access_size, bool zero_size_allowed, 4740 struct bpf_call_arg_meta *meta) 4741 { 4742 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4743 4744 switch (reg->type) { 4745 case PTR_TO_PACKET: 4746 case PTR_TO_PACKET_META: 4747 return check_packet_access(env, regno, reg->off, access_size, 4748 zero_size_allowed); 4749 case PTR_TO_MAP_KEY: 4750 return check_mem_region_access(env, regno, reg->off, access_size, 4751 reg->map_ptr->key_size, false); 4752 case PTR_TO_MAP_VALUE: 4753 if (check_map_access_type(env, regno, reg->off, access_size, 4754 meta && meta->raw_mode ? BPF_WRITE : 4755 BPF_READ)) 4756 return -EACCES; 4757 return check_map_access(env, regno, reg->off, access_size, 4758 zero_size_allowed); 4759 case PTR_TO_MEM: 4760 return check_mem_region_access(env, regno, reg->off, 4761 access_size, reg->mem_size, 4762 zero_size_allowed); 4763 case PTR_TO_RDONLY_BUF: 4764 if (meta && meta->raw_mode) 4765 return -EACCES; 4766 return check_buffer_access(env, reg, regno, reg->off, 4767 access_size, zero_size_allowed, 4768 "rdonly", 4769 &env->prog->aux->max_rdonly_access); 4770 case PTR_TO_RDWR_BUF: 4771 return check_buffer_access(env, reg, regno, reg->off, 4772 access_size, zero_size_allowed, 4773 "rdwr", 4774 &env->prog->aux->max_rdwr_access); 4775 case PTR_TO_STACK: 4776 return check_stack_range_initialized( 4777 env, 4778 regno, reg->off, access_size, 4779 zero_size_allowed, ACCESS_HELPER, meta); 4780 default: /* scalar_value or invalid ptr */ 4781 /* Allow zero-byte read from NULL, regardless of pointer type */ 4782 if (zero_size_allowed && access_size == 0 && 4783 register_is_null(reg)) 4784 return 0; 4785 4786 verbose(env, "R%d type=%s expected=%s\n", regno, 4787 reg_type_str[reg->type], 4788 reg_type_str[PTR_TO_STACK]); 4789 return -EACCES; 4790 } 4791 } 4792 4793 int check_mem_reg(struct bpf_verifier_env *env, struct bpf_reg_state *reg, 4794 u32 regno, u32 mem_size) 4795 { 4796 if (register_is_null(reg)) 4797 return 0; 4798 4799 if (reg_type_may_be_null(reg->type)) { 4800 /* Assuming that the register contains a value check if the memory 4801 * access is safe. Temporarily save and restore the register's state as 4802 * the conversion shouldn't be visible to a caller. 4803 */ 4804 const struct bpf_reg_state saved_reg = *reg; 4805 int rv; 4806 4807 mark_ptr_not_null_reg(reg); 4808 rv = check_helper_mem_access(env, regno, mem_size, true, NULL); 4809 *reg = saved_reg; 4810 return rv; 4811 } 4812 4813 return check_helper_mem_access(env, regno, mem_size, true, NULL); 4814 } 4815 4816 /* Implementation details: 4817 * bpf_map_lookup returns PTR_TO_MAP_VALUE_OR_NULL 4818 * Two bpf_map_lookups (even with the same key) will have different reg->id. 4819 * For traditional PTR_TO_MAP_VALUE the verifier clears reg->id after 4820 * value_or_null->value transition, since the verifier only cares about 4821 * the range of access to valid map value pointer and doesn't care about actual 4822 * address of the map element. 4823 * For maps with 'struct bpf_spin_lock' inside map value the verifier keeps 4824 * reg->id > 0 after value_or_null->value transition. By doing so 4825 * two bpf_map_lookups will be considered two different pointers that 4826 * point to different bpf_spin_locks. 4827 * The verifier allows taking only one bpf_spin_lock at a time to avoid 4828 * dead-locks. 4829 * Since only one bpf_spin_lock is allowed the checks are simpler than 4830 * reg_is_refcounted() logic. The verifier needs to remember only 4831 * one spin_lock instead of array of acquired_refs. 4832 * cur_state->active_spin_lock remembers which map value element got locked 4833 * and clears it after bpf_spin_unlock. 4834 */ 4835 static int process_spin_lock(struct bpf_verifier_env *env, int regno, 4836 bool is_lock) 4837 { 4838 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4839 struct bpf_verifier_state *cur = env->cur_state; 4840 bool is_const = tnum_is_const(reg->var_off); 4841 struct bpf_map *map = reg->map_ptr; 4842 u64 val = reg->var_off.value; 4843 4844 if (!is_const) { 4845 verbose(env, 4846 "R%d doesn't have constant offset. bpf_spin_lock has to be at the constant offset\n", 4847 regno); 4848 return -EINVAL; 4849 } 4850 if (!map->btf) { 4851 verbose(env, 4852 "map '%s' has to have BTF in order to use bpf_spin_lock\n", 4853 map->name); 4854 return -EINVAL; 4855 } 4856 if (!map_value_has_spin_lock(map)) { 4857 if (map->spin_lock_off == -E2BIG) 4858 verbose(env, 4859 "map '%s' has more than one 'struct bpf_spin_lock'\n", 4860 map->name); 4861 else if (map->spin_lock_off == -ENOENT) 4862 verbose(env, 4863 "map '%s' doesn't have 'struct bpf_spin_lock'\n", 4864 map->name); 4865 else 4866 verbose(env, 4867 "map '%s' is not a struct type or bpf_spin_lock is mangled\n", 4868 map->name); 4869 return -EINVAL; 4870 } 4871 if (map->spin_lock_off != val + reg->off) { 4872 verbose(env, "off %lld doesn't point to 'struct bpf_spin_lock'\n", 4873 val + reg->off); 4874 return -EINVAL; 4875 } 4876 if (is_lock) { 4877 if (cur->active_spin_lock) { 4878 verbose(env, 4879 "Locking two bpf_spin_locks are not allowed\n"); 4880 return -EINVAL; 4881 } 4882 cur->active_spin_lock = reg->id; 4883 } else { 4884 if (!cur->active_spin_lock) { 4885 verbose(env, "bpf_spin_unlock without taking a lock\n"); 4886 return -EINVAL; 4887 } 4888 if (cur->active_spin_lock != reg->id) { 4889 verbose(env, "bpf_spin_unlock of different lock\n"); 4890 return -EINVAL; 4891 } 4892 cur->active_spin_lock = 0; 4893 } 4894 return 0; 4895 } 4896 4897 static int process_timer_func(struct bpf_verifier_env *env, int regno, 4898 struct bpf_call_arg_meta *meta) 4899 { 4900 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 4901 bool is_const = tnum_is_const(reg->var_off); 4902 struct bpf_map *map = reg->map_ptr; 4903 u64 val = reg->var_off.value; 4904 4905 if (!is_const) { 4906 verbose(env, 4907 "R%d doesn't have constant offset. bpf_timer has to be at the constant offset\n", 4908 regno); 4909 return -EINVAL; 4910 } 4911 if (!map->btf) { 4912 verbose(env, "map '%s' has to have BTF in order to use bpf_timer\n", 4913 map->name); 4914 return -EINVAL; 4915 } 4916 if (!map_value_has_timer(map)) { 4917 if (map->timer_off == -E2BIG) 4918 verbose(env, 4919 "map '%s' has more than one 'struct bpf_timer'\n", 4920 map->name); 4921 else if (map->timer_off == -ENOENT) 4922 verbose(env, 4923 "map '%s' doesn't have 'struct bpf_timer'\n", 4924 map->name); 4925 else 4926 verbose(env, 4927 "map '%s' is not a struct type or bpf_timer is mangled\n", 4928 map->name); 4929 return -EINVAL; 4930 } 4931 if (map->timer_off != val + reg->off) { 4932 verbose(env, "off %lld doesn't point to 'struct bpf_timer' that is at %d\n", 4933 val + reg->off, map->timer_off); 4934 return -EINVAL; 4935 } 4936 if (meta->map_ptr) { 4937 verbose(env, "verifier bug. Two map pointers in a timer helper\n"); 4938 return -EFAULT; 4939 } 4940 meta->map_uid = reg->map_uid; 4941 meta->map_ptr = map; 4942 return 0; 4943 } 4944 4945 static bool arg_type_is_mem_ptr(enum bpf_arg_type type) 4946 { 4947 return type == ARG_PTR_TO_MEM || 4948 type == ARG_PTR_TO_MEM_OR_NULL || 4949 type == ARG_PTR_TO_UNINIT_MEM; 4950 } 4951 4952 static bool arg_type_is_mem_size(enum bpf_arg_type type) 4953 { 4954 return type == ARG_CONST_SIZE || 4955 type == ARG_CONST_SIZE_OR_ZERO; 4956 } 4957 4958 static bool arg_type_is_alloc_size(enum bpf_arg_type type) 4959 { 4960 return type == ARG_CONST_ALLOC_SIZE_OR_ZERO; 4961 } 4962 4963 static bool arg_type_is_int_ptr(enum bpf_arg_type type) 4964 { 4965 return type == ARG_PTR_TO_INT || 4966 type == ARG_PTR_TO_LONG; 4967 } 4968 4969 static int int_ptr_type_to_size(enum bpf_arg_type type) 4970 { 4971 if (type == ARG_PTR_TO_INT) 4972 return sizeof(u32); 4973 else if (type == ARG_PTR_TO_LONG) 4974 return sizeof(u64); 4975 4976 return -EINVAL; 4977 } 4978 4979 static int resolve_map_arg_type(struct bpf_verifier_env *env, 4980 const struct bpf_call_arg_meta *meta, 4981 enum bpf_arg_type *arg_type) 4982 { 4983 if (!meta->map_ptr) { 4984 /* kernel subsystem misconfigured verifier */ 4985 verbose(env, "invalid map_ptr to access map->type\n"); 4986 return -EACCES; 4987 } 4988 4989 switch (meta->map_ptr->map_type) { 4990 case BPF_MAP_TYPE_SOCKMAP: 4991 case BPF_MAP_TYPE_SOCKHASH: 4992 if (*arg_type == ARG_PTR_TO_MAP_VALUE) { 4993 *arg_type = ARG_PTR_TO_BTF_ID_SOCK_COMMON; 4994 } else { 4995 verbose(env, "invalid arg_type for sockmap/sockhash\n"); 4996 return -EINVAL; 4997 } 4998 break; 4999 case BPF_MAP_TYPE_BLOOM_FILTER: 5000 if (meta->func_id == BPF_FUNC_map_peek_elem) 5001 *arg_type = ARG_PTR_TO_MAP_VALUE; 5002 break; 5003 default: 5004 break; 5005 } 5006 return 0; 5007 } 5008 5009 struct bpf_reg_types { 5010 const enum bpf_reg_type types[10]; 5011 u32 *btf_id; 5012 }; 5013 5014 static const struct bpf_reg_types map_key_value_types = { 5015 .types = { 5016 PTR_TO_STACK, 5017 PTR_TO_PACKET, 5018 PTR_TO_PACKET_META, 5019 PTR_TO_MAP_KEY, 5020 PTR_TO_MAP_VALUE, 5021 }, 5022 }; 5023 5024 static const struct bpf_reg_types sock_types = { 5025 .types = { 5026 PTR_TO_SOCK_COMMON, 5027 PTR_TO_SOCKET, 5028 PTR_TO_TCP_SOCK, 5029 PTR_TO_XDP_SOCK, 5030 }, 5031 }; 5032 5033 #ifdef CONFIG_NET 5034 static const struct bpf_reg_types btf_id_sock_common_types = { 5035 .types = { 5036 PTR_TO_SOCK_COMMON, 5037 PTR_TO_SOCKET, 5038 PTR_TO_TCP_SOCK, 5039 PTR_TO_XDP_SOCK, 5040 PTR_TO_BTF_ID, 5041 }, 5042 .btf_id = &btf_sock_ids[BTF_SOCK_TYPE_SOCK_COMMON], 5043 }; 5044 #endif 5045 5046 static const struct bpf_reg_types mem_types = { 5047 .types = { 5048 PTR_TO_STACK, 5049 PTR_TO_PACKET, 5050 PTR_TO_PACKET_META, 5051 PTR_TO_MAP_KEY, 5052 PTR_TO_MAP_VALUE, 5053 PTR_TO_MEM, 5054 PTR_TO_RDONLY_BUF, 5055 PTR_TO_RDWR_BUF, 5056 }, 5057 }; 5058 5059 static const struct bpf_reg_types int_ptr_types = { 5060 .types = { 5061 PTR_TO_STACK, 5062 PTR_TO_PACKET, 5063 PTR_TO_PACKET_META, 5064 PTR_TO_MAP_KEY, 5065 PTR_TO_MAP_VALUE, 5066 }, 5067 }; 5068 5069 static const struct bpf_reg_types fullsock_types = { .types = { PTR_TO_SOCKET } }; 5070 static const struct bpf_reg_types scalar_types = { .types = { SCALAR_VALUE } }; 5071 static const struct bpf_reg_types context_types = { .types = { PTR_TO_CTX } }; 5072 static const struct bpf_reg_types alloc_mem_types = { .types = { PTR_TO_MEM } }; 5073 static const struct bpf_reg_types const_map_ptr_types = { .types = { CONST_PTR_TO_MAP } }; 5074 static const struct bpf_reg_types btf_ptr_types = { .types = { PTR_TO_BTF_ID } }; 5075 static const struct bpf_reg_types spin_lock_types = { .types = { PTR_TO_MAP_VALUE } }; 5076 static const struct bpf_reg_types percpu_btf_ptr_types = { .types = { PTR_TO_PERCPU_BTF_ID } }; 5077 static const struct bpf_reg_types func_ptr_types = { .types = { PTR_TO_FUNC } }; 5078 static const struct bpf_reg_types stack_ptr_types = { .types = { PTR_TO_STACK } }; 5079 static const struct bpf_reg_types const_str_ptr_types = { .types = { PTR_TO_MAP_VALUE } }; 5080 static const struct bpf_reg_types timer_types = { .types = { PTR_TO_MAP_VALUE } }; 5081 5082 static const struct bpf_reg_types *compatible_reg_types[__BPF_ARG_TYPE_MAX] = { 5083 [ARG_PTR_TO_MAP_KEY] = &map_key_value_types, 5084 [ARG_PTR_TO_MAP_VALUE] = &map_key_value_types, 5085 [ARG_PTR_TO_UNINIT_MAP_VALUE] = &map_key_value_types, 5086 [ARG_PTR_TO_MAP_VALUE_OR_NULL] = &map_key_value_types, 5087 [ARG_CONST_SIZE] = &scalar_types, 5088 [ARG_CONST_SIZE_OR_ZERO] = &scalar_types, 5089 [ARG_CONST_ALLOC_SIZE_OR_ZERO] = &scalar_types, 5090 [ARG_CONST_MAP_PTR] = &const_map_ptr_types, 5091 [ARG_PTR_TO_CTX] = &context_types, 5092 [ARG_PTR_TO_CTX_OR_NULL] = &context_types, 5093 [ARG_PTR_TO_SOCK_COMMON] = &sock_types, 5094 #ifdef CONFIG_NET 5095 [ARG_PTR_TO_BTF_ID_SOCK_COMMON] = &btf_id_sock_common_types, 5096 #endif 5097 [ARG_PTR_TO_SOCKET] = &fullsock_types, 5098 [ARG_PTR_TO_SOCKET_OR_NULL] = &fullsock_types, 5099 [ARG_PTR_TO_BTF_ID] = &btf_ptr_types, 5100 [ARG_PTR_TO_SPIN_LOCK] = &spin_lock_types, 5101 [ARG_PTR_TO_MEM] = &mem_types, 5102 [ARG_PTR_TO_MEM_OR_NULL] = &mem_types, 5103 [ARG_PTR_TO_UNINIT_MEM] = &mem_types, 5104 [ARG_PTR_TO_ALLOC_MEM] = &alloc_mem_types, 5105 [ARG_PTR_TO_ALLOC_MEM_OR_NULL] = &alloc_mem_types, 5106 [ARG_PTR_TO_INT] = &int_ptr_types, 5107 [ARG_PTR_TO_LONG] = &int_ptr_types, 5108 [ARG_PTR_TO_PERCPU_BTF_ID] = &percpu_btf_ptr_types, 5109 [ARG_PTR_TO_FUNC] = &func_ptr_types, 5110 [ARG_PTR_TO_STACK_OR_NULL] = &stack_ptr_types, 5111 [ARG_PTR_TO_CONST_STR] = &const_str_ptr_types, 5112 [ARG_PTR_TO_TIMER] = &timer_types, 5113 }; 5114 5115 static int check_reg_type(struct bpf_verifier_env *env, u32 regno, 5116 enum bpf_arg_type arg_type, 5117 const u32 *arg_btf_id) 5118 { 5119 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5120 enum bpf_reg_type expected, type = reg->type; 5121 const struct bpf_reg_types *compatible; 5122 int i, j; 5123 5124 compatible = compatible_reg_types[arg_type]; 5125 if (!compatible) { 5126 verbose(env, "verifier internal error: unsupported arg type %d\n", arg_type); 5127 return -EFAULT; 5128 } 5129 5130 for (i = 0; i < ARRAY_SIZE(compatible->types); i++) { 5131 expected = compatible->types[i]; 5132 if (expected == NOT_INIT) 5133 break; 5134 5135 if (type == expected) 5136 goto found; 5137 } 5138 5139 verbose(env, "R%d type=%s expected=", regno, reg_type_str[type]); 5140 for (j = 0; j + 1 < i; j++) 5141 verbose(env, "%s, ", reg_type_str[compatible->types[j]]); 5142 verbose(env, "%s\n", reg_type_str[compatible->types[j]]); 5143 return -EACCES; 5144 5145 found: 5146 if (type == PTR_TO_BTF_ID) { 5147 if (!arg_btf_id) { 5148 if (!compatible->btf_id) { 5149 verbose(env, "verifier internal error: missing arg compatible BTF ID\n"); 5150 return -EFAULT; 5151 } 5152 arg_btf_id = compatible->btf_id; 5153 } 5154 5155 if (!btf_struct_ids_match(&env->log, reg->btf, reg->btf_id, reg->off, 5156 btf_vmlinux, *arg_btf_id)) { 5157 verbose(env, "R%d is of type %s but %s is expected\n", 5158 regno, kernel_type_name(reg->btf, reg->btf_id), 5159 kernel_type_name(btf_vmlinux, *arg_btf_id)); 5160 return -EACCES; 5161 } 5162 5163 if (!tnum_is_const(reg->var_off) || reg->var_off.value) { 5164 verbose(env, "R%d is a pointer to in-kernel struct with non-zero offset\n", 5165 regno); 5166 return -EACCES; 5167 } 5168 } 5169 5170 return 0; 5171 } 5172 5173 static int check_func_arg(struct bpf_verifier_env *env, u32 arg, 5174 struct bpf_call_arg_meta *meta, 5175 const struct bpf_func_proto *fn) 5176 { 5177 u32 regno = BPF_REG_1 + arg; 5178 struct bpf_reg_state *regs = cur_regs(env), *reg = ®s[regno]; 5179 enum bpf_arg_type arg_type = fn->arg_type[arg]; 5180 enum bpf_reg_type type = reg->type; 5181 int err = 0; 5182 5183 if (arg_type == ARG_DONTCARE) 5184 return 0; 5185 5186 err = check_reg_arg(env, regno, SRC_OP); 5187 if (err) 5188 return err; 5189 5190 if (arg_type == ARG_ANYTHING) { 5191 if (is_pointer_value(env, regno)) { 5192 verbose(env, "R%d leaks addr into helper function\n", 5193 regno); 5194 return -EACCES; 5195 } 5196 return 0; 5197 } 5198 5199 if (type_is_pkt_pointer(type) && 5200 !may_access_direct_pkt_data(env, meta, BPF_READ)) { 5201 verbose(env, "helper access to the packet is not allowed\n"); 5202 return -EACCES; 5203 } 5204 5205 if (arg_type == ARG_PTR_TO_MAP_VALUE || 5206 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE || 5207 arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL) { 5208 err = resolve_map_arg_type(env, meta, &arg_type); 5209 if (err) 5210 return err; 5211 } 5212 5213 if (register_is_null(reg) && arg_type_may_be_null(arg_type)) 5214 /* A NULL register has a SCALAR_VALUE type, so skip 5215 * type checking. 5216 */ 5217 goto skip_type_check; 5218 5219 err = check_reg_type(env, regno, arg_type, fn->arg_btf_id[arg]); 5220 if (err) 5221 return err; 5222 5223 if (type == PTR_TO_CTX) { 5224 err = check_ctx_reg(env, reg, regno); 5225 if (err < 0) 5226 return err; 5227 } 5228 5229 skip_type_check: 5230 if (reg->ref_obj_id) { 5231 if (meta->ref_obj_id) { 5232 verbose(env, "verifier internal error: more than one arg with ref_obj_id R%d %u %u\n", 5233 regno, reg->ref_obj_id, 5234 meta->ref_obj_id); 5235 return -EFAULT; 5236 } 5237 meta->ref_obj_id = reg->ref_obj_id; 5238 } 5239 5240 if (arg_type == ARG_CONST_MAP_PTR) { 5241 /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ 5242 if (meta->map_ptr) { 5243 /* Use map_uid (which is unique id of inner map) to reject: 5244 * inner_map1 = bpf_map_lookup_elem(outer_map, key1) 5245 * inner_map2 = bpf_map_lookup_elem(outer_map, key2) 5246 * if (inner_map1 && inner_map2) { 5247 * timer = bpf_map_lookup_elem(inner_map1); 5248 * if (timer) 5249 * // mismatch would have been allowed 5250 * bpf_timer_init(timer, inner_map2); 5251 * } 5252 * 5253 * Comparing map_ptr is enough to distinguish normal and outer maps. 5254 */ 5255 if (meta->map_ptr != reg->map_ptr || 5256 meta->map_uid != reg->map_uid) { 5257 verbose(env, 5258 "timer pointer in R1 map_uid=%d doesn't match map pointer in R2 map_uid=%d\n", 5259 meta->map_uid, reg->map_uid); 5260 return -EINVAL; 5261 } 5262 } 5263 meta->map_ptr = reg->map_ptr; 5264 meta->map_uid = reg->map_uid; 5265 } else if (arg_type == ARG_PTR_TO_MAP_KEY) { 5266 /* bpf_map_xxx(..., map_ptr, ..., key) call: 5267 * check that [key, key + map->key_size) are within 5268 * stack limits and initialized 5269 */ 5270 if (!meta->map_ptr) { 5271 /* in function declaration map_ptr must come before 5272 * map_key, so that it's verified and known before 5273 * we have to check map_key here. Otherwise it means 5274 * that kernel subsystem misconfigured verifier 5275 */ 5276 verbose(env, "invalid map_ptr to access map->key\n"); 5277 return -EACCES; 5278 } 5279 err = check_helper_mem_access(env, regno, 5280 meta->map_ptr->key_size, false, 5281 NULL); 5282 } else if (arg_type == ARG_PTR_TO_MAP_VALUE || 5283 (arg_type == ARG_PTR_TO_MAP_VALUE_OR_NULL && 5284 !register_is_null(reg)) || 5285 arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE) { 5286 /* bpf_map_xxx(..., map_ptr, ..., value) call: 5287 * check [value, value + map->value_size) validity 5288 */ 5289 if (!meta->map_ptr) { 5290 /* kernel subsystem misconfigured verifier */ 5291 verbose(env, "invalid map_ptr to access map->value\n"); 5292 return -EACCES; 5293 } 5294 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MAP_VALUE); 5295 err = check_helper_mem_access(env, regno, 5296 meta->map_ptr->value_size, false, 5297 meta); 5298 } else if (arg_type == ARG_PTR_TO_PERCPU_BTF_ID) { 5299 if (!reg->btf_id) { 5300 verbose(env, "Helper has invalid btf_id in R%d\n", regno); 5301 return -EACCES; 5302 } 5303 meta->ret_btf = reg->btf; 5304 meta->ret_btf_id = reg->btf_id; 5305 } else if (arg_type == ARG_PTR_TO_SPIN_LOCK) { 5306 if (meta->func_id == BPF_FUNC_spin_lock) { 5307 if (process_spin_lock(env, regno, true)) 5308 return -EACCES; 5309 } else if (meta->func_id == BPF_FUNC_spin_unlock) { 5310 if (process_spin_lock(env, regno, false)) 5311 return -EACCES; 5312 } else { 5313 verbose(env, "verifier internal error\n"); 5314 return -EFAULT; 5315 } 5316 } else if (arg_type == ARG_PTR_TO_TIMER) { 5317 if (process_timer_func(env, regno, meta)) 5318 return -EACCES; 5319 } else if (arg_type == ARG_PTR_TO_FUNC) { 5320 meta->subprogno = reg->subprogno; 5321 } else if (arg_type_is_mem_ptr(arg_type)) { 5322 /* The access to this pointer is only checked when we hit the 5323 * next is_mem_size argument below. 5324 */ 5325 meta->raw_mode = (arg_type == ARG_PTR_TO_UNINIT_MEM); 5326 } else if (arg_type_is_mem_size(arg_type)) { 5327 bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); 5328 5329 /* This is used to refine r0 return value bounds for helpers 5330 * that enforce this value as an upper bound on return values. 5331 * See do_refine_retval_range() for helpers that can refine 5332 * the return value. C type of helper is u32 so we pull register 5333 * bound from umax_value however, if negative verifier errors 5334 * out. Only upper bounds can be learned because retval is an 5335 * int type and negative retvals are allowed. 5336 */ 5337 meta->msize_max_value = reg->umax_value; 5338 5339 /* The register is SCALAR_VALUE; the access check 5340 * happens using its boundaries. 5341 */ 5342 if (!tnum_is_const(reg->var_off)) 5343 /* For unprivileged variable accesses, disable raw 5344 * mode so that the program is required to 5345 * initialize all the memory that the helper could 5346 * just partially fill up. 5347 */ 5348 meta = NULL; 5349 5350 if (reg->smin_value < 0) { 5351 verbose(env, "R%d min value is negative, either use unsigned or 'var &= const'\n", 5352 regno); 5353 return -EACCES; 5354 } 5355 5356 if (reg->umin_value == 0) { 5357 err = check_helper_mem_access(env, regno - 1, 0, 5358 zero_size_allowed, 5359 meta); 5360 if (err) 5361 return err; 5362 } 5363 5364 if (reg->umax_value >= BPF_MAX_VAR_SIZ) { 5365 verbose(env, "R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", 5366 regno); 5367 return -EACCES; 5368 } 5369 err = check_helper_mem_access(env, regno - 1, 5370 reg->umax_value, 5371 zero_size_allowed, meta); 5372 if (!err) 5373 err = mark_chain_precision(env, regno); 5374 } else if (arg_type_is_alloc_size(arg_type)) { 5375 if (!tnum_is_const(reg->var_off)) { 5376 verbose(env, "R%d is not a known constant'\n", 5377 regno); 5378 return -EACCES; 5379 } 5380 meta->mem_size = reg->var_off.value; 5381 } else if (arg_type_is_int_ptr(arg_type)) { 5382 int size = int_ptr_type_to_size(arg_type); 5383 5384 err = check_helper_mem_access(env, regno, size, false, meta); 5385 if (err) 5386 return err; 5387 err = check_ptr_alignment(env, reg, 0, size, true); 5388 } else if (arg_type == ARG_PTR_TO_CONST_STR) { 5389 struct bpf_map *map = reg->map_ptr; 5390 int map_off; 5391 u64 map_addr; 5392 char *str_ptr; 5393 5394 if (!bpf_map_is_rdonly(map)) { 5395 verbose(env, "R%d does not point to a readonly map'\n", regno); 5396 return -EACCES; 5397 } 5398 5399 if (!tnum_is_const(reg->var_off)) { 5400 verbose(env, "R%d is not a constant address'\n", regno); 5401 return -EACCES; 5402 } 5403 5404 if (!map->ops->map_direct_value_addr) { 5405 verbose(env, "no direct value access support for this map type\n"); 5406 return -EACCES; 5407 } 5408 5409 err = check_map_access(env, regno, reg->off, 5410 map->value_size - reg->off, false); 5411 if (err) 5412 return err; 5413 5414 map_off = reg->off + reg->var_off.value; 5415 err = map->ops->map_direct_value_addr(map, &map_addr, map_off); 5416 if (err) { 5417 verbose(env, "direct value access on string failed\n"); 5418 return err; 5419 } 5420 5421 str_ptr = (char *)(long)(map_addr); 5422 if (!strnchr(str_ptr + map_off, map->value_size - map_off, 0)) { 5423 verbose(env, "string is not zero-terminated\n"); 5424 return -EINVAL; 5425 } 5426 } 5427 5428 return err; 5429 } 5430 5431 static bool may_update_sockmap(struct bpf_verifier_env *env, int func_id) 5432 { 5433 enum bpf_attach_type eatype = env->prog->expected_attach_type; 5434 enum bpf_prog_type type = resolve_prog_type(env->prog); 5435 5436 if (func_id != BPF_FUNC_map_update_elem) 5437 return false; 5438 5439 /* It's not possible to get access to a locked struct sock in these 5440 * contexts, so updating is safe. 5441 */ 5442 switch (type) { 5443 case BPF_PROG_TYPE_TRACING: 5444 if (eatype == BPF_TRACE_ITER) 5445 return true; 5446 break; 5447 case BPF_PROG_TYPE_SOCKET_FILTER: 5448 case BPF_PROG_TYPE_SCHED_CLS: 5449 case BPF_PROG_TYPE_SCHED_ACT: 5450 case BPF_PROG_TYPE_XDP: 5451 case BPF_PROG_TYPE_SK_REUSEPORT: 5452 case BPF_PROG_TYPE_FLOW_DISSECTOR: 5453 case BPF_PROG_TYPE_SK_LOOKUP: 5454 return true; 5455 default: 5456 break; 5457 } 5458 5459 verbose(env, "cannot update sockmap in this context\n"); 5460 return false; 5461 } 5462 5463 static bool allow_tail_call_in_subprogs(struct bpf_verifier_env *env) 5464 { 5465 return env->prog->jit_requested && IS_ENABLED(CONFIG_X86_64); 5466 } 5467 5468 static int check_map_func_compatibility(struct bpf_verifier_env *env, 5469 struct bpf_map *map, int func_id) 5470 { 5471 if (!map) 5472 return 0; 5473 5474 /* We need a two way check, first is from map perspective ... */ 5475 switch (map->map_type) { 5476 case BPF_MAP_TYPE_PROG_ARRAY: 5477 if (func_id != BPF_FUNC_tail_call) 5478 goto error; 5479 break; 5480 case BPF_MAP_TYPE_PERF_EVENT_ARRAY: 5481 if (func_id != BPF_FUNC_perf_event_read && 5482 func_id != BPF_FUNC_perf_event_output && 5483 func_id != BPF_FUNC_skb_output && 5484 func_id != BPF_FUNC_perf_event_read_value && 5485 func_id != BPF_FUNC_xdp_output) 5486 goto error; 5487 break; 5488 case BPF_MAP_TYPE_RINGBUF: 5489 if (func_id != BPF_FUNC_ringbuf_output && 5490 func_id != BPF_FUNC_ringbuf_reserve && 5491 func_id != BPF_FUNC_ringbuf_query) 5492 goto error; 5493 break; 5494 case BPF_MAP_TYPE_STACK_TRACE: 5495 if (func_id != BPF_FUNC_get_stackid) 5496 goto error; 5497 break; 5498 case BPF_MAP_TYPE_CGROUP_ARRAY: 5499 if (func_id != BPF_FUNC_skb_under_cgroup && 5500 func_id != BPF_FUNC_current_task_under_cgroup) 5501 goto error; 5502 break; 5503 case BPF_MAP_TYPE_CGROUP_STORAGE: 5504 case BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE: 5505 if (func_id != BPF_FUNC_get_local_storage) 5506 goto error; 5507 break; 5508 case BPF_MAP_TYPE_DEVMAP: 5509 case BPF_MAP_TYPE_DEVMAP_HASH: 5510 if (func_id != BPF_FUNC_redirect_map && 5511 func_id != BPF_FUNC_map_lookup_elem) 5512 goto error; 5513 break; 5514 /* Restrict bpf side of cpumap and xskmap, open when use-cases 5515 * appear. 5516 */ 5517 case BPF_MAP_TYPE_CPUMAP: 5518 if (func_id != BPF_FUNC_redirect_map) 5519 goto error; 5520 break; 5521 case BPF_MAP_TYPE_XSKMAP: 5522 if (func_id != BPF_FUNC_redirect_map && 5523 func_id != BPF_FUNC_map_lookup_elem) 5524 goto error; 5525 break; 5526 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 5527 case BPF_MAP_TYPE_HASH_OF_MAPS: 5528 if (func_id != BPF_FUNC_map_lookup_elem) 5529 goto error; 5530 break; 5531 case BPF_MAP_TYPE_SOCKMAP: 5532 if (func_id != BPF_FUNC_sk_redirect_map && 5533 func_id != BPF_FUNC_sock_map_update && 5534 func_id != BPF_FUNC_map_delete_elem && 5535 func_id != BPF_FUNC_msg_redirect_map && 5536 func_id != BPF_FUNC_sk_select_reuseport && 5537 func_id != BPF_FUNC_map_lookup_elem && 5538 !may_update_sockmap(env, func_id)) 5539 goto error; 5540 break; 5541 case BPF_MAP_TYPE_SOCKHASH: 5542 if (func_id != BPF_FUNC_sk_redirect_hash && 5543 func_id != BPF_FUNC_sock_hash_update && 5544 func_id != BPF_FUNC_map_delete_elem && 5545 func_id != BPF_FUNC_msg_redirect_hash && 5546 func_id != BPF_FUNC_sk_select_reuseport && 5547 func_id != BPF_FUNC_map_lookup_elem && 5548 !may_update_sockmap(env, func_id)) 5549 goto error; 5550 break; 5551 case BPF_MAP_TYPE_REUSEPORT_SOCKARRAY: 5552 if (func_id != BPF_FUNC_sk_select_reuseport) 5553 goto error; 5554 break; 5555 case BPF_MAP_TYPE_QUEUE: 5556 case BPF_MAP_TYPE_STACK: 5557 if (func_id != BPF_FUNC_map_peek_elem && 5558 func_id != BPF_FUNC_map_pop_elem && 5559 func_id != BPF_FUNC_map_push_elem) 5560 goto error; 5561 break; 5562 case BPF_MAP_TYPE_SK_STORAGE: 5563 if (func_id != BPF_FUNC_sk_storage_get && 5564 func_id != BPF_FUNC_sk_storage_delete) 5565 goto error; 5566 break; 5567 case BPF_MAP_TYPE_INODE_STORAGE: 5568 if (func_id != BPF_FUNC_inode_storage_get && 5569 func_id != BPF_FUNC_inode_storage_delete) 5570 goto error; 5571 break; 5572 case BPF_MAP_TYPE_TASK_STORAGE: 5573 if (func_id != BPF_FUNC_task_storage_get && 5574 func_id != BPF_FUNC_task_storage_delete) 5575 goto error; 5576 break; 5577 case BPF_MAP_TYPE_BLOOM_FILTER: 5578 if (func_id != BPF_FUNC_map_peek_elem && 5579 func_id != BPF_FUNC_map_push_elem) 5580 goto error; 5581 break; 5582 default: 5583 break; 5584 } 5585 5586 /* ... and second from the function itself. */ 5587 switch (func_id) { 5588 case BPF_FUNC_tail_call: 5589 if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) 5590 goto error; 5591 if (env->subprog_cnt > 1 && !allow_tail_call_in_subprogs(env)) { 5592 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 5593 return -EINVAL; 5594 } 5595 break; 5596 case BPF_FUNC_perf_event_read: 5597 case BPF_FUNC_perf_event_output: 5598 case BPF_FUNC_perf_event_read_value: 5599 case BPF_FUNC_skb_output: 5600 case BPF_FUNC_xdp_output: 5601 if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) 5602 goto error; 5603 break; 5604 case BPF_FUNC_ringbuf_output: 5605 case BPF_FUNC_ringbuf_reserve: 5606 case BPF_FUNC_ringbuf_query: 5607 if (map->map_type != BPF_MAP_TYPE_RINGBUF) 5608 goto error; 5609 break; 5610 case BPF_FUNC_get_stackid: 5611 if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) 5612 goto error; 5613 break; 5614 case BPF_FUNC_current_task_under_cgroup: 5615 case BPF_FUNC_skb_under_cgroup: 5616 if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) 5617 goto error; 5618 break; 5619 case BPF_FUNC_redirect_map: 5620 if (map->map_type != BPF_MAP_TYPE_DEVMAP && 5621 map->map_type != BPF_MAP_TYPE_DEVMAP_HASH && 5622 map->map_type != BPF_MAP_TYPE_CPUMAP && 5623 map->map_type != BPF_MAP_TYPE_XSKMAP) 5624 goto error; 5625 break; 5626 case BPF_FUNC_sk_redirect_map: 5627 case BPF_FUNC_msg_redirect_map: 5628 case BPF_FUNC_sock_map_update: 5629 if (map->map_type != BPF_MAP_TYPE_SOCKMAP) 5630 goto error; 5631 break; 5632 case BPF_FUNC_sk_redirect_hash: 5633 case BPF_FUNC_msg_redirect_hash: 5634 case BPF_FUNC_sock_hash_update: 5635 if (map->map_type != BPF_MAP_TYPE_SOCKHASH) 5636 goto error; 5637 break; 5638 case BPF_FUNC_get_local_storage: 5639 if (map->map_type != BPF_MAP_TYPE_CGROUP_STORAGE && 5640 map->map_type != BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE) 5641 goto error; 5642 break; 5643 case BPF_FUNC_sk_select_reuseport: 5644 if (map->map_type != BPF_MAP_TYPE_REUSEPORT_SOCKARRAY && 5645 map->map_type != BPF_MAP_TYPE_SOCKMAP && 5646 map->map_type != BPF_MAP_TYPE_SOCKHASH) 5647 goto error; 5648 break; 5649 case BPF_FUNC_map_pop_elem: 5650 if (map->map_type != BPF_MAP_TYPE_QUEUE && 5651 map->map_type != BPF_MAP_TYPE_STACK) 5652 goto error; 5653 break; 5654 case BPF_FUNC_map_peek_elem: 5655 case BPF_FUNC_map_push_elem: 5656 if (map->map_type != BPF_MAP_TYPE_QUEUE && 5657 map->map_type != BPF_MAP_TYPE_STACK && 5658 map->map_type != BPF_MAP_TYPE_BLOOM_FILTER) 5659 goto error; 5660 break; 5661 case BPF_FUNC_sk_storage_get: 5662 case BPF_FUNC_sk_storage_delete: 5663 if (map->map_type != BPF_MAP_TYPE_SK_STORAGE) 5664 goto error; 5665 break; 5666 case BPF_FUNC_inode_storage_get: 5667 case BPF_FUNC_inode_storage_delete: 5668 if (map->map_type != BPF_MAP_TYPE_INODE_STORAGE) 5669 goto error; 5670 break; 5671 case BPF_FUNC_task_storage_get: 5672 case BPF_FUNC_task_storage_delete: 5673 if (map->map_type != BPF_MAP_TYPE_TASK_STORAGE) 5674 goto error; 5675 break; 5676 default: 5677 break; 5678 } 5679 5680 return 0; 5681 error: 5682 verbose(env, "cannot pass map_type %d into func %s#%d\n", 5683 map->map_type, func_id_name(func_id), func_id); 5684 return -EINVAL; 5685 } 5686 5687 static bool check_raw_mode_ok(const struct bpf_func_proto *fn) 5688 { 5689 int count = 0; 5690 5691 if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) 5692 count++; 5693 if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) 5694 count++; 5695 if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) 5696 count++; 5697 if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) 5698 count++; 5699 if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) 5700 count++; 5701 5702 /* We only support one arg being in raw mode at the moment, 5703 * which is sufficient for the helper functions we have 5704 * right now. 5705 */ 5706 return count <= 1; 5707 } 5708 5709 static bool check_args_pair_invalid(enum bpf_arg_type arg_curr, 5710 enum bpf_arg_type arg_next) 5711 { 5712 return (arg_type_is_mem_ptr(arg_curr) && 5713 !arg_type_is_mem_size(arg_next)) || 5714 (!arg_type_is_mem_ptr(arg_curr) && 5715 arg_type_is_mem_size(arg_next)); 5716 } 5717 5718 static bool check_arg_pair_ok(const struct bpf_func_proto *fn) 5719 { 5720 /* bpf_xxx(..., buf, len) call will access 'len' 5721 * bytes from memory 'buf'. Both arg types need 5722 * to be paired, so make sure there's no buggy 5723 * helper function specification. 5724 */ 5725 if (arg_type_is_mem_size(fn->arg1_type) || 5726 arg_type_is_mem_ptr(fn->arg5_type) || 5727 check_args_pair_invalid(fn->arg1_type, fn->arg2_type) || 5728 check_args_pair_invalid(fn->arg2_type, fn->arg3_type) || 5729 check_args_pair_invalid(fn->arg3_type, fn->arg4_type) || 5730 check_args_pair_invalid(fn->arg4_type, fn->arg5_type)) 5731 return false; 5732 5733 return true; 5734 } 5735 5736 static bool check_refcount_ok(const struct bpf_func_proto *fn, int func_id) 5737 { 5738 int count = 0; 5739 5740 if (arg_type_may_be_refcounted(fn->arg1_type)) 5741 count++; 5742 if (arg_type_may_be_refcounted(fn->arg2_type)) 5743 count++; 5744 if (arg_type_may_be_refcounted(fn->arg3_type)) 5745 count++; 5746 if (arg_type_may_be_refcounted(fn->arg4_type)) 5747 count++; 5748 if (arg_type_may_be_refcounted(fn->arg5_type)) 5749 count++; 5750 5751 /* A reference acquiring function cannot acquire 5752 * another refcounted ptr. 5753 */ 5754 if (may_be_acquire_function(func_id) && count) 5755 return false; 5756 5757 /* We only support one arg being unreferenced at the moment, 5758 * which is sufficient for the helper functions we have right now. 5759 */ 5760 return count <= 1; 5761 } 5762 5763 static bool check_btf_id_ok(const struct bpf_func_proto *fn) 5764 { 5765 int i; 5766 5767 for (i = 0; i < ARRAY_SIZE(fn->arg_type); i++) { 5768 if (fn->arg_type[i] == ARG_PTR_TO_BTF_ID && !fn->arg_btf_id[i]) 5769 return false; 5770 5771 if (fn->arg_type[i] != ARG_PTR_TO_BTF_ID && fn->arg_btf_id[i]) 5772 return false; 5773 } 5774 5775 return true; 5776 } 5777 5778 static int check_func_proto(const struct bpf_func_proto *fn, int func_id) 5779 { 5780 return check_raw_mode_ok(fn) && 5781 check_arg_pair_ok(fn) && 5782 check_btf_id_ok(fn) && 5783 check_refcount_ok(fn, func_id) ? 0 : -EINVAL; 5784 } 5785 5786 /* Packet data might have moved, any old PTR_TO_PACKET[_META,_END] 5787 * are now invalid, so turn them into unknown SCALAR_VALUE. 5788 */ 5789 static void __clear_all_pkt_pointers(struct bpf_verifier_env *env, 5790 struct bpf_func_state *state) 5791 { 5792 struct bpf_reg_state *regs = state->regs, *reg; 5793 int i; 5794 5795 for (i = 0; i < MAX_BPF_REG; i++) 5796 if (reg_is_pkt_pointer_any(®s[i])) 5797 mark_reg_unknown(env, regs, i); 5798 5799 bpf_for_each_spilled_reg(i, state, reg) { 5800 if (!reg) 5801 continue; 5802 if (reg_is_pkt_pointer_any(reg)) 5803 __mark_reg_unknown(env, reg); 5804 } 5805 } 5806 5807 static void clear_all_pkt_pointers(struct bpf_verifier_env *env) 5808 { 5809 struct bpf_verifier_state *vstate = env->cur_state; 5810 int i; 5811 5812 for (i = 0; i <= vstate->curframe; i++) 5813 __clear_all_pkt_pointers(env, vstate->frame[i]); 5814 } 5815 5816 enum { 5817 AT_PKT_END = -1, 5818 BEYOND_PKT_END = -2, 5819 }; 5820 5821 static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range_open) 5822 { 5823 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 5824 struct bpf_reg_state *reg = &state->regs[regn]; 5825 5826 if (reg->type != PTR_TO_PACKET) 5827 /* PTR_TO_PACKET_META is not supported yet */ 5828 return; 5829 5830 /* The 'reg' is pkt > pkt_end or pkt >= pkt_end. 5831 * How far beyond pkt_end it goes is unknown. 5832 * if (!range_open) it's the case of pkt >= pkt_end 5833 * if (range_open) it's the case of pkt > pkt_end 5834 * hence this pointer is at least 1 byte bigger than pkt_end 5835 */ 5836 if (range_open) 5837 reg->range = BEYOND_PKT_END; 5838 else 5839 reg->range = AT_PKT_END; 5840 } 5841 5842 static void release_reg_references(struct bpf_verifier_env *env, 5843 struct bpf_func_state *state, 5844 int ref_obj_id) 5845 { 5846 struct bpf_reg_state *regs = state->regs, *reg; 5847 int i; 5848 5849 for (i = 0; i < MAX_BPF_REG; i++) 5850 if (regs[i].ref_obj_id == ref_obj_id) 5851 mark_reg_unknown(env, regs, i); 5852 5853 bpf_for_each_spilled_reg(i, state, reg) { 5854 if (!reg) 5855 continue; 5856 if (reg->ref_obj_id == ref_obj_id) 5857 __mark_reg_unknown(env, reg); 5858 } 5859 } 5860 5861 /* The pointer with the specified id has released its reference to kernel 5862 * resources. Identify all copies of the same pointer and clear the reference. 5863 */ 5864 static int release_reference(struct bpf_verifier_env *env, 5865 int ref_obj_id) 5866 { 5867 struct bpf_verifier_state *vstate = env->cur_state; 5868 int err; 5869 int i; 5870 5871 err = release_reference_state(cur_func(env), ref_obj_id); 5872 if (err) 5873 return err; 5874 5875 for (i = 0; i <= vstate->curframe; i++) 5876 release_reg_references(env, vstate->frame[i], ref_obj_id); 5877 5878 return 0; 5879 } 5880 5881 static void clear_caller_saved_regs(struct bpf_verifier_env *env, 5882 struct bpf_reg_state *regs) 5883 { 5884 int i; 5885 5886 /* after the call registers r0 - r5 were scratched */ 5887 for (i = 0; i < CALLER_SAVED_REGS; i++) { 5888 mark_reg_not_init(env, regs, caller_saved[i]); 5889 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 5890 } 5891 } 5892 5893 typedef int (*set_callee_state_fn)(struct bpf_verifier_env *env, 5894 struct bpf_func_state *caller, 5895 struct bpf_func_state *callee, 5896 int insn_idx); 5897 5898 static int __check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 5899 int *insn_idx, int subprog, 5900 set_callee_state_fn set_callee_state_cb) 5901 { 5902 struct bpf_verifier_state *state = env->cur_state; 5903 struct bpf_func_info_aux *func_info_aux; 5904 struct bpf_func_state *caller, *callee; 5905 int err; 5906 bool is_global = false; 5907 5908 if (state->curframe + 1 >= MAX_CALL_FRAMES) { 5909 verbose(env, "the call stack of %d frames is too deep\n", 5910 state->curframe + 2); 5911 return -E2BIG; 5912 } 5913 5914 caller = state->frame[state->curframe]; 5915 if (state->frame[state->curframe + 1]) { 5916 verbose(env, "verifier bug. Frame %d already allocated\n", 5917 state->curframe + 1); 5918 return -EFAULT; 5919 } 5920 5921 func_info_aux = env->prog->aux->func_info_aux; 5922 if (func_info_aux) 5923 is_global = func_info_aux[subprog].linkage == BTF_FUNC_GLOBAL; 5924 err = btf_check_subprog_arg_match(env, subprog, caller->regs); 5925 if (err == -EFAULT) 5926 return err; 5927 if (is_global) { 5928 if (err) { 5929 verbose(env, "Caller passes invalid args into func#%d\n", 5930 subprog); 5931 return err; 5932 } else { 5933 if (env->log.level & BPF_LOG_LEVEL) 5934 verbose(env, 5935 "Func#%d is global and valid. Skipping.\n", 5936 subprog); 5937 clear_caller_saved_regs(env, caller->regs); 5938 5939 /* All global functions return a 64-bit SCALAR_VALUE */ 5940 mark_reg_unknown(env, caller->regs, BPF_REG_0); 5941 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 5942 5943 /* continue with next insn after call */ 5944 return 0; 5945 } 5946 } 5947 5948 if (insn->code == (BPF_JMP | BPF_CALL) && 5949 insn->imm == BPF_FUNC_timer_set_callback) { 5950 struct bpf_verifier_state *async_cb; 5951 5952 /* there is no real recursion here. timer callbacks are async */ 5953 env->subprog_info[subprog].is_async_cb = true; 5954 async_cb = push_async_cb(env, env->subprog_info[subprog].start, 5955 *insn_idx, subprog); 5956 if (!async_cb) 5957 return -EFAULT; 5958 callee = async_cb->frame[0]; 5959 callee->async_entry_cnt = caller->async_entry_cnt + 1; 5960 5961 /* Convert bpf_timer_set_callback() args into timer callback args */ 5962 err = set_callee_state_cb(env, caller, callee, *insn_idx); 5963 if (err) 5964 return err; 5965 5966 clear_caller_saved_regs(env, caller->regs); 5967 mark_reg_unknown(env, caller->regs, BPF_REG_0); 5968 caller->regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 5969 /* continue with next insn after call */ 5970 return 0; 5971 } 5972 5973 callee = kzalloc(sizeof(*callee), GFP_KERNEL); 5974 if (!callee) 5975 return -ENOMEM; 5976 state->frame[state->curframe + 1] = callee; 5977 5978 /* callee cannot access r0, r6 - r9 for reading and has to write 5979 * into its own stack before reading from it. 5980 * callee can read/write into caller's stack 5981 */ 5982 init_func_state(env, callee, 5983 /* remember the callsite, it will be used by bpf_exit */ 5984 *insn_idx /* callsite */, 5985 state->curframe + 1 /* frameno within this callchain */, 5986 subprog /* subprog number within this prog */); 5987 5988 /* Transfer references to the callee */ 5989 err = copy_reference_state(callee, caller); 5990 if (err) 5991 return err; 5992 5993 err = set_callee_state_cb(env, caller, callee, *insn_idx); 5994 if (err) 5995 return err; 5996 5997 clear_caller_saved_regs(env, caller->regs); 5998 5999 /* only increment it after check_reg_arg() finished */ 6000 state->curframe++; 6001 6002 /* and go analyze first insn of the callee */ 6003 *insn_idx = env->subprog_info[subprog].start - 1; 6004 6005 if (env->log.level & BPF_LOG_LEVEL) { 6006 verbose(env, "caller:\n"); 6007 print_verifier_state(env, caller); 6008 verbose(env, "callee:\n"); 6009 print_verifier_state(env, callee); 6010 } 6011 return 0; 6012 } 6013 6014 int map_set_for_each_callback_args(struct bpf_verifier_env *env, 6015 struct bpf_func_state *caller, 6016 struct bpf_func_state *callee) 6017 { 6018 /* bpf_for_each_map_elem(struct bpf_map *map, void *callback_fn, 6019 * void *callback_ctx, u64 flags); 6020 * callback_fn(struct bpf_map *map, void *key, void *value, 6021 * void *callback_ctx); 6022 */ 6023 callee->regs[BPF_REG_1] = caller->regs[BPF_REG_1]; 6024 6025 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 6026 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 6027 callee->regs[BPF_REG_2].map_ptr = caller->regs[BPF_REG_1].map_ptr; 6028 6029 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 6030 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 6031 callee->regs[BPF_REG_3].map_ptr = caller->regs[BPF_REG_1].map_ptr; 6032 6033 /* pointer to stack or null */ 6034 callee->regs[BPF_REG_4] = caller->regs[BPF_REG_3]; 6035 6036 /* unused */ 6037 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 6038 return 0; 6039 } 6040 6041 static int set_callee_state(struct bpf_verifier_env *env, 6042 struct bpf_func_state *caller, 6043 struct bpf_func_state *callee, int insn_idx) 6044 { 6045 int i; 6046 6047 /* copy r1 - r5 args that callee can access. The copy includes parent 6048 * pointers, which connects us up to the liveness chain 6049 */ 6050 for (i = BPF_REG_1; i <= BPF_REG_5; i++) 6051 callee->regs[i] = caller->regs[i]; 6052 return 0; 6053 } 6054 6055 static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 6056 int *insn_idx) 6057 { 6058 int subprog, target_insn; 6059 6060 target_insn = *insn_idx + insn->imm + 1; 6061 subprog = find_subprog(env, target_insn); 6062 if (subprog < 0) { 6063 verbose(env, "verifier bug. No program starts at insn %d\n", 6064 target_insn); 6065 return -EFAULT; 6066 } 6067 6068 return __check_func_call(env, insn, insn_idx, subprog, set_callee_state); 6069 } 6070 6071 static int set_map_elem_callback_state(struct bpf_verifier_env *env, 6072 struct bpf_func_state *caller, 6073 struct bpf_func_state *callee, 6074 int insn_idx) 6075 { 6076 struct bpf_insn_aux_data *insn_aux = &env->insn_aux_data[insn_idx]; 6077 struct bpf_map *map; 6078 int err; 6079 6080 if (bpf_map_ptr_poisoned(insn_aux)) { 6081 verbose(env, "tail_call abusing map_ptr\n"); 6082 return -EINVAL; 6083 } 6084 6085 map = BPF_MAP_PTR(insn_aux->map_ptr_state); 6086 if (!map->ops->map_set_for_each_callback_args || 6087 !map->ops->map_for_each_callback) { 6088 verbose(env, "callback function not allowed for map\n"); 6089 return -ENOTSUPP; 6090 } 6091 6092 err = map->ops->map_set_for_each_callback_args(env, caller, callee); 6093 if (err) 6094 return err; 6095 6096 callee->in_callback_fn = true; 6097 return 0; 6098 } 6099 6100 static int set_timer_callback_state(struct bpf_verifier_env *env, 6101 struct bpf_func_state *caller, 6102 struct bpf_func_state *callee, 6103 int insn_idx) 6104 { 6105 struct bpf_map *map_ptr = caller->regs[BPF_REG_1].map_ptr; 6106 6107 /* bpf_timer_set_callback(struct bpf_timer *timer, void *callback_fn); 6108 * callback_fn(struct bpf_map *map, void *key, void *value); 6109 */ 6110 callee->regs[BPF_REG_1].type = CONST_PTR_TO_MAP; 6111 __mark_reg_known_zero(&callee->regs[BPF_REG_1]); 6112 callee->regs[BPF_REG_1].map_ptr = map_ptr; 6113 6114 callee->regs[BPF_REG_2].type = PTR_TO_MAP_KEY; 6115 __mark_reg_known_zero(&callee->regs[BPF_REG_2]); 6116 callee->regs[BPF_REG_2].map_ptr = map_ptr; 6117 6118 callee->regs[BPF_REG_3].type = PTR_TO_MAP_VALUE; 6119 __mark_reg_known_zero(&callee->regs[BPF_REG_3]); 6120 callee->regs[BPF_REG_3].map_ptr = map_ptr; 6121 6122 /* unused */ 6123 __mark_reg_not_init(env, &callee->regs[BPF_REG_4]); 6124 __mark_reg_not_init(env, &callee->regs[BPF_REG_5]); 6125 callee->in_async_callback_fn = true; 6126 return 0; 6127 } 6128 6129 static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx) 6130 { 6131 struct bpf_verifier_state *state = env->cur_state; 6132 struct bpf_func_state *caller, *callee; 6133 struct bpf_reg_state *r0; 6134 int err; 6135 6136 callee = state->frame[state->curframe]; 6137 r0 = &callee->regs[BPF_REG_0]; 6138 if (r0->type == PTR_TO_STACK) { 6139 /* technically it's ok to return caller's stack pointer 6140 * (or caller's caller's pointer) back to the caller, 6141 * since these pointers are valid. Only current stack 6142 * pointer will be invalid as soon as function exits, 6143 * but let's be conservative 6144 */ 6145 verbose(env, "cannot return stack pointer to the caller\n"); 6146 return -EINVAL; 6147 } 6148 6149 state->curframe--; 6150 caller = state->frame[state->curframe]; 6151 if (callee->in_callback_fn) { 6152 /* enforce R0 return value range [0, 1]. */ 6153 struct tnum range = tnum_range(0, 1); 6154 6155 if (r0->type != SCALAR_VALUE) { 6156 verbose(env, "R0 not a scalar value\n"); 6157 return -EACCES; 6158 } 6159 if (!tnum_in(range, r0->var_off)) { 6160 verbose_invalid_scalar(env, r0, &range, "callback return", "R0"); 6161 return -EINVAL; 6162 } 6163 } else { 6164 /* return to the caller whatever r0 had in the callee */ 6165 caller->regs[BPF_REG_0] = *r0; 6166 } 6167 6168 /* Transfer references to the caller */ 6169 err = copy_reference_state(caller, callee); 6170 if (err) 6171 return err; 6172 6173 *insn_idx = callee->callsite + 1; 6174 if (env->log.level & BPF_LOG_LEVEL) { 6175 verbose(env, "returning from callee:\n"); 6176 print_verifier_state(env, callee); 6177 verbose(env, "to caller at %d:\n", *insn_idx); 6178 print_verifier_state(env, caller); 6179 } 6180 /* clear everything in the callee */ 6181 free_func_state(callee); 6182 state->frame[state->curframe + 1] = NULL; 6183 return 0; 6184 } 6185 6186 static void do_refine_retval_range(struct bpf_reg_state *regs, int ret_type, 6187 int func_id, 6188 struct bpf_call_arg_meta *meta) 6189 { 6190 struct bpf_reg_state *ret_reg = ®s[BPF_REG_0]; 6191 6192 if (ret_type != RET_INTEGER || 6193 (func_id != BPF_FUNC_get_stack && 6194 func_id != BPF_FUNC_get_task_stack && 6195 func_id != BPF_FUNC_probe_read_str && 6196 func_id != BPF_FUNC_probe_read_kernel_str && 6197 func_id != BPF_FUNC_probe_read_user_str)) 6198 return; 6199 6200 ret_reg->smax_value = meta->msize_max_value; 6201 ret_reg->s32_max_value = meta->msize_max_value; 6202 ret_reg->smin_value = -MAX_ERRNO; 6203 ret_reg->s32_min_value = -MAX_ERRNO; 6204 __reg_deduce_bounds(ret_reg); 6205 __reg_bound_offset(ret_reg); 6206 __update_reg_bounds(ret_reg); 6207 } 6208 6209 static int 6210 record_func_map(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 6211 int func_id, int insn_idx) 6212 { 6213 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 6214 struct bpf_map *map = meta->map_ptr; 6215 6216 if (func_id != BPF_FUNC_tail_call && 6217 func_id != BPF_FUNC_map_lookup_elem && 6218 func_id != BPF_FUNC_map_update_elem && 6219 func_id != BPF_FUNC_map_delete_elem && 6220 func_id != BPF_FUNC_map_push_elem && 6221 func_id != BPF_FUNC_map_pop_elem && 6222 func_id != BPF_FUNC_map_peek_elem && 6223 func_id != BPF_FUNC_for_each_map_elem && 6224 func_id != BPF_FUNC_redirect_map) 6225 return 0; 6226 6227 if (map == NULL) { 6228 verbose(env, "kernel subsystem misconfigured verifier\n"); 6229 return -EINVAL; 6230 } 6231 6232 /* In case of read-only, some additional restrictions 6233 * need to be applied in order to prevent altering the 6234 * state of the map from program side. 6235 */ 6236 if ((map->map_flags & BPF_F_RDONLY_PROG) && 6237 (func_id == BPF_FUNC_map_delete_elem || 6238 func_id == BPF_FUNC_map_update_elem || 6239 func_id == BPF_FUNC_map_push_elem || 6240 func_id == BPF_FUNC_map_pop_elem)) { 6241 verbose(env, "write into map forbidden\n"); 6242 return -EACCES; 6243 } 6244 6245 if (!BPF_MAP_PTR(aux->map_ptr_state)) 6246 bpf_map_ptr_store(aux, meta->map_ptr, 6247 !meta->map_ptr->bypass_spec_v1); 6248 else if (BPF_MAP_PTR(aux->map_ptr_state) != meta->map_ptr) 6249 bpf_map_ptr_store(aux, BPF_MAP_PTR_POISON, 6250 !meta->map_ptr->bypass_spec_v1); 6251 return 0; 6252 } 6253 6254 static int 6255 record_func_key(struct bpf_verifier_env *env, struct bpf_call_arg_meta *meta, 6256 int func_id, int insn_idx) 6257 { 6258 struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx]; 6259 struct bpf_reg_state *regs = cur_regs(env), *reg; 6260 struct bpf_map *map = meta->map_ptr; 6261 struct tnum range; 6262 u64 val; 6263 int err; 6264 6265 if (func_id != BPF_FUNC_tail_call) 6266 return 0; 6267 if (!map || map->map_type != BPF_MAP_TYPE_PROG_ARRAY) { 6268 verbose(env, "kernel subsystem misconfigured verifier\n"); 6269 return -EINVAL; 6270 } 6271 6272 range = tnum_range(0, map->max_entries - 1); 6273 reg = ®s[BPF_REG_3]; 6274 6275 if (!register_is_const(reg) || !tnum_in(range, reg->var_off)) { 6276 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 6277 return 0; 6278 } 6279 6280 err = mark_chain_precision(env, BPF_REG_3); 6281 if (err) 6282 return err; 6283 6284 val = reg->var_off.value; 6285 if (bpf_map_key_unseen(aux)) 6286 bpf_map_key_store(aux, val); 6287 else if (!bpf_map_key_poisoned(aux) && 6288 bpf_map_key_immediate(aux) != val) 6289 bpf_map_key_store(aux, BPF_MAP_KEY_POISON); 6290 return 0; 6291 } 6292 6293 static int check_reference_leak(struct bpf_verifier_env *env) 6294 { 6295 struct bpf_func_state *state = cur_func(env); 6296 int i; 6297 6298 for (i = 0; i < state->acquired_refs; i++) { 6299 verbose(env, "Unreleased reference id=%d alloc_insn=%d\n", 6300 state->refs[i].id, state->refs[i].insn_idx); 6301 } 6302 return state->acquired_refs ? -EINVAL : 0; 6303 } 6304 6305 static int check_bpf_snprintf_call(struct bpf_verifier_env *env, 6306 struct bpf_reg_state *regs) 6307 { 6308 struct bpf_reg_state *fmt_reg = ®s[BPF_REG_3]; 6309 struct bpf_reg_state *data_len_reg = ®s[BPF_REG_5]; 6310 struct bpf_map *fmt_map = fmt_reg->map_ptr; 6311 int err, fmt_map_off, num_args; 6312 u64 fmt_addr; 6313 char *fmt; 6314 6315 /* data must be an array of u64 */ 6316 if (data_len_reg->var_off.value % 8) 6317 return -EINVAL; 6318 num_args = data_len_reg->var_off.value / 8; 6319 6320 /* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const 6321 * and map_direct_value_addr is set. 6322 */ 6323 fmt_map_off = fmt_reg->off + fmt_reg->var_off.value; 6324 err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr, 6325 fmt_map_off); 6326 if (err) { 6327 verbose(env, "verifier bug\n"); 6328 return -EFAULT; 6329 } 6330 fmt = (char *)(long)fmt_addr + fmt_map_off; 6331 6332 /* We are also guaranteed that fmt+fmt_map_off is NULL terminated, we 6333 * can focus on validating the format specifiers. 6334 */ 6335 err = bpf_bprintf_prepare(fmt, UINT_MAX, NULL, NULL, num_args); 6336 if (err < 0) 6337 verbose(env, "Invalid format string\n"); 6338 6339 return err; 6340 } 6341 6342 static int check_get_func_ip(struct bpf_verifier_env *env) 6343 { 6344 enum bpf_attach_type eatype = env->prog->expected_attach_type; 6345 enum bpf_prog_type type = resolve_prog_type(env->prog); 6346 int func_id = BPF_FUNC_get_func_ip; 6347 6348 if (type == BPF_PROG_TYPE_TRACING) { 6349 if (eatype != BPF_TRACE_FENTRY && eatype != BPF_TRACE_FEXIT && 6350 eatype != BPF_MODIFY_RETURN) { 6351 verbose(env, "func %s#%d supported only for fentry/fexit/fmod_ret programs\n", 6352 func_id_name(func_id), func_id); 6353 return -ENOTSUPP; 6354 } 6355 return 0; 6356 } else if (type == BPF_PROG_TYPE_KPROBE) { 6357 return 0; 6358 } 6359 6360 verbose(env, "func %s#%d not supported for program type %d\n", 6361 func_id_name(func_id), func_id, type); 6362 return -ENOTSUPP; 6363 } 6364 6365 static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn, 6366 int *insn_idx_p) 6367 { 6368 const struct bpf_func_proto *fn = NULL; 6369 struct bpf_reg_state *regs; 6370 struct bpf_call_arg_meta meta; 6371 int insn_idx = *insn_idx_p; 6372 bool changes_data; 6373 int i, err, func_id; 6374 6375 /* find function prototype */ 6376 func_id = insn->imm; 6377 if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { 6378 verbose(env, "invalid func %s#%d\n", func_id_name(func_id), 6379 func_id); 6380 return -EINVAL; 6381 } 6382 6383 if (env->ops->get_func_proto) 6384 fn = env->ops->get_func_proto(func_id, env->prog); 6385 if (!fn) { 6386 verbose(env, "unknown func %s#%d\n", func_id_name(func_id), 6387 func_id); 6388 return -EINVAL; 6389 } 6390 6391 /* eBPF programs must be GPL compatible to use GPL-ed functions */ 6392 if (!env->prog->gpl_compatible && fn->gpl_only) { 6393 verbose(env, "cannot call GPL-restricted function from non-GPL compatible program\n"); 6394 return -EINVAL; 6395 } 6396 6397 if (fn->allowed && !fn->allowed(env->prog)) { 6398 verbose(env, "helper call is not allowed in probe\n"); 6399 return -EINVAL; 6400 } 6401 6402 /* With LD_ABS/IND some JITs save/restore skb from r1. */ 6403 changes_data = bpf_helper_changes_pkt_data(fn->func); 6404 if (changes_data && fn->arg1_type != ARG_PTR_TO_CTX) { 6405 verbose(env, "kernel subsystem misconfigured func %s#%d: r1 != ctx\n", 6406 func_id_name(func_id), func_id); 6407 return -EINVAL; 6408 } 6409 6410 memset(&meta, 0, sizeof(meta)); 6411 meta.pkt_access = fn->pkt_access; 6412 6413 err = check_func_proto(fn, func_id); 6414 if (err) { 6415 verbose(env, "kernel subsystem misconfigured func %s#%d\n", 6416 func_id_name(func_id), func_id); 6417 return err; 6418 } 6419 6420 meta.func_id = func_id; 6421 /* check args */ 6422 for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) { 6423 err = check_func_arg(env, i, &meta, fn); 6424 if (err) 6425 return err; 6426 } 6427 6428 err = record_func_map(env, &meta, func_id, insn_idx); 6429 if (err) 6430 return err; 6431 6432 err = record_func_key(env, &meta, func_id, insn_idx); 6433 if (err) 6434 return err; 6435 6436 /* Mark slots with STACK_MISC in case of raw mode, stack offset 6437 * is inferred from register state. 6438 */ 6439 for (i = 0; i < meta.access_size; i++) { 6440 err = check_mem_access(env, insn_idx, meta.regno, i, BPF_B, 6441 BPF_WRITE, -1, false); 6442 if (err) 6443 return err; 6444 } 6445 6446 if (func_id == BPF_FUNC_tail_call) { 6447 err = check_reference_leak(env); 6448 if (err) { 6449 verbose(env, "tail_call would lead to reference leak\n"); 6450 return err; 6451 } 6452 } else if (is_release_function(func_id)) { 6453 err = release_reference(env, meta.ref_obj_id); 6454 if (err) { 6455 verbose(env, "func %s#%d reference has not been acquired before\n", 6456 func_id_name(func_id), func_id); 6457 return err; 6458 } 6459 } 6460 6461 regs = cur_regs(env); 6462 6463 /* check that flags argument in get_local_storage(map, flags) is 0, 6464 * this is required because get_local_storage() can't return an error. 6465 */ 6466 if (func_id == BPF_FUNC_get_local_storage && 6467 !register_is_null(®s[BPF_REG_2])) { 6468 verbose(env, "get_local_storage() doesn't support non-zero flags\n"); 6469 return -EINVAL; 6470 } 6471 6472 if (func_id == BPF_FUNC_for_each_map_elem) { 6473 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 6474 set_map_elem_callback_state); 6475 if (err < 0) 6476 return -EINVAL; 6477 } 6478 6479 if (func_id == BPF_FUNC_timer_set_callback) { 6480 err = __check_func_call(env, insn, insn_idx_p, meta.subprogno, 6481 set_timer_callback_state); 6482 if (err < 0) 6483 return -EINVAL; 6484 } 6485 6486 if (func_id == BPF_FUNC_snprintf) { 6487 err = check_bpf_snprintf_call(env, regs); 6488 if (err < 0) 6489 return err; 6490 } 6491 6492 /* reset caller saved regs */ 6493 for (i = 0; i < CALLER_SAVED_REGS; i++) { 6494 mark_reg_not_init(env, regs, caller_saved[i]); 6495 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 6496 } 6497 6498 /* helper call returns 64-bit value. */ 6499 regs[BPF_REG_0].subreg_def = DEF_NOT_SUBREG; 6500 6501 /* update return register (already marked as written above) */ 6502 if (fn->ret_type == RET_INTEGER) { 6503 /* sets type to SCALAR_VALUE */ 6504 mark_reg_unknown(env, regs, BPF_REG_0); 6505 } else if (fn->ret_type == RET_VOID) { 6506 regs[BPF_REG_0].type = NOT_INIT; 6507 } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL || 6508 fn->ret_type == RET_PTR_TO_MAP_VALUE) { 6509 /* There is no offset yet applied, variable or fixed */ 6510 mark_reg_known_zero(env, regs, BPF_REG_0); 6511 /* remember map_ptr, so that check_map_access() 6512 * can check 'value_size' boundary of memory access 6513 * to map element returned from bpf_map_lookup_elem() 6514 */ 6515 if (meta.map_ptr == NULL) { 6516 verbose(env, 6517 "kernel subsystem misconfigured verifier\n"); 6518 return -EINVAL; 6519 } 6520 regs[BPF_REG_0].map_ptr = meta.map_ptr; 6521 regs[BPF_REG_0].map_uid = meta.map_uid; 6522 if (fn->ret_type == RET_PTR_TO_MAP_VALUE) { 6523 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE; 6524 if (map_value_has_spin_lock(meta.map_ptr)) 6525 regs[BPF_REG_0].id = ++env->id_gen; 6526 } else { 6527 regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; 6528 } 6529 } else if (fn->ret_type == RET_PTR_TO_SOCKET_OR_NULL) { 6530 mark_reg_known_zero(env, regs, BPF_REG_0); 6531 regs[BPF_REG_0].type = PTR_TO_SOCKET_OR_NULL; 6532 } else if (fn->ret_type == RET_PTR_TO_SOCK_COMMON_OR_NULL) { 6533 mark_reg_known_zero(env, regs, BPF_REG_0); 6534 regs[BPF_REG_0].type = PTR_TO_SOCK_COMMON_OR_NULL; 6535 } else if (fn->ret_type == RET_PTR_TO_TCP_SOCK_OR_NULL) { 6536 mark_reg_known_zero(env, regs, BPF_REG_0); 6537 regs[BPF_REG_0].type = PTR_TO_TCP_SOCK_OR_NULL; 6538 } else if (fn->ret_type == RET_PTR_TO_ALLOC_MEM_OR_NULL) { 6539 mark_reg_known_zero(env, regs, BPF_REG_0); 6540 regs[BPF_REG_0].type = PTR_TO_MEM_OR_NULL; 6541 regs[BPF_REG_0].mem_size = meta.mem_size; 6542 } else if (fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID_OR_NULL || 6543 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID) { 6544 const struct btf_type *t; 6545 6546 mark_reg_known_zero(env, regs, BPF_REG_0); 6547 t = btf_type_skip_modifiers(meta.ret_btf, meta.ret_btf_id, NULL); 6548 if (!btf_type_is_struct(t)) { 6549 u32 tsize; 6550 const struct btf_type *ret; 6551 const char *tname; 6552 6553 /* resolve the type size of ksym. */ 6554 ret = btf_resolve_size(meta.ret_btf, t, &tsize); 6555 if (IS_ERR(ret)) { 6556 tname = btf_name_by_offset(meta.ret_btf, t->name_off); 6557 verbose(env, "unable to resolve the size of type '%s': %ld\n", 6558 tname, PTR_ERR(ret)); 6559 return -EINVAL; 6560 } 6561 regs[BPF_REG_0].type = 6562 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ? 6563 PTR_TO_MEM : PTR_TO_MEM_OR_NULL; 6564 regs[BPF_REG_0].mem_size = tsize; 6565 } else { 6566 regs[BPF_REG_0].type = 6567 fn->ret_type == RET_PTR_TO_MEM_OR_BTF_ID ? 6568 PTR_TO_BTF_ID : PTR_TO_BTF_ID_OR_NULL; 6569 regs[BPF_REG_0].btf = meta.ret_btf; 6570 regs[BPF_REG_0].btf_id = meta.ret_btf_id; 6571 } 6572 } else if (fn->ret_type == RET_PTR_TO_BTF_ID_OR_NULL || 6573 fn->ret_type == RET_PTR_TO_BTF_ID) { 6574 int ret_btf_id; 6575 6576 mark_reg_known_zero(env, regs, BPF_REG_0); 6577 regs[BPF_REG_0].type = fn->ret_type == RET_PTR_TO_BTF_ID ? 6578 PTR_TO_BTF_ID : 6579 PTR_TO_BTF_ID_OR_NULL; 6580 ret_btf_id = *fn->ret_btf_id; 6581 if (ret_btf_id == 0) { 6582 verbose(env, "invalid return type %d of func %s#%d\n", 6583 fn->ret_type, func_id_name(func_id), func_id); 6584 return -EINVAL; 6585 } 6586 /* current BPF helper definitions are only coming from 6587 * built-in code with type IDs from vmlinux BTF 6588 */ 6589 regs[BPF_REG_0].btf = btf_vmlinux; 6590 regs[BPF_REG_0].btf_id = ret_btf_id; 6591 } else { 6592 verbose(env, "unknown return type %d of func %s#%d\n", 6593 fn->ret_type, func_id_name(func_id), func_id); 6594 return -EINVAL; 6595 } 6596 6597 if (reg_type_may_be_null(regs[BPF_REG_0].type)) 6598 regs[BPF_REG_0].id = ++env->id_gen; 6599 6600 if (is_ptr_cast_function(func_id)) { 6601 /* For release_reference() */ 6602 regs[BPF_REG_0].ref_obj_id = meta.ref_obj_id; 6603 } else if (is_acquire_function(func_id, meta.map_ptr)) { 6604 int id = acquire_reference_state(env, insn_idx); 6605 6606 if (id < 0) 6607 return id; 6608 /* For mark_ptr_or_null_reg() */ 6609 regs[BPF_REG_0].id = id; 6610 /* For release_reference() */ 6611 regs[BPF_REG_0].ref_obj_id = id; 6612 } 6613 6614 do_refine_retval_range(regs, fn->ret_type, func_id, &meta); 6615 6616 err = check_map_func_compatibility(env, meta.map_ptr, func_id); 6617 if (err) 6618 return err; 6619 6620 if ((func_id == BPF_FUNC_get_stack || 6621 func_id == BPF_FUNC_get_task_stack) && 6622 !env->prog->has_callchain_buf) { 6623 const char *err_str; 6624 6625 #ifdef CONFIG_PERF_EVENTS 6626 err = get_callchain_buffers(sysctl_perf_event_max_stack); 6627 err_str = "cannot get callchain buffer for func %s#%d\n"; 6628 #else 6629 err = -ENOTSUPP; 6630 err_str = "func %s#%d not supported without CONFIG_PERF_EVENTS\n"; 6631 #endif 6632 if (err) { 6633 verbose(env, err_str, func_id_name(func_id), func_id); 6634 return err; 6635 } 6636 6637 env->prog->has_callchain_buf = true; 6638 } 6639 6640 if (func_id == BPF_FUNC_get_stackid || func_id == BPF_FUNC_get_stack) 6641 env->prog->call_get_stack = true; 6642 6643 if (func_id == BPF_FUNC_get_func_ip) { 6644 if (check_get_func_ip(env)) 6645 return -ENOTSUPP; 6646 env->prog->call_get_func_ip = true; 6647 } 6648 6649 if (changes_data) 6650 clear_all_pkt_pointers(env); 6651 return 0; 6652 } 6653 6654 /* mark_btf_func_reg_size() is used when the reg size is determined by 6655 * the BTF func_proto's return value size and argument. 6656 */ 6657 static void mark_btf_func_reg_size(struct bpf_verifier_env *env, u32 regno, 6658 size_t reg_size) 6659 { 6660 struct bpf_reg_state *reg = &cur_regs(env)[regno]; 6661 6662 if (regno == BPF_REG_0) { 6663 /* Function return value */ 6664 reg->live |= REG_LIVE_WRITTEN; 6665 reg->subreg_def = reg_size == sizeof(u64) ? 6666 DEF_NOT_SUBREG : env->insn_idx + 1; 6667 } else { 6668 /* Function argument */ 6669 if (reg_size == sizeof(u64)) { 6670 mark_insn_zext(env, reg); 6671 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ64); 6672 } else { 6673 mark_reg_read(env, reg, reg->parent, REG_LIVE_READ32); 6674 } 6675 } 6676 } 6677 6678 static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn) 6679 { 6680 const struct btf_type *t, *func, *func_proto, *ptr_type; 6681 struct bpf_reg_state *regs = cur_regs(env); 6682 const char *func_name, *ptr_type_name; 6683 u32 i, nargs, func_id, ptr_type_id; 6684 struct module *btf_mod = NULL; 6685 const struct btf_param *args; 6686 struct btf *desc_btf; 6687 int err; 6688 6689 /* skip for now, but return error when we find this in fixup_kfunc_call */ 6690 if (!insn->imm) 6691 return 0; 6692 6693 desc_btf = find_kfunc_desc_btf(env, insn->imm, insn->off, &btf_mod); 6694 if (IS_ERR(desc_btf)) 6695 return PTR_ERR(desc_btf); 6696 6697 func_id = insn->imm; 6698 func = btf_type_by_id(desc_btf, func_id); 6699 func_name = btf_name_by_offset(desc_btf, func->name_off); 6700 func_proto = btf_type_by_id(desc_btf, func->type); 6701 6702 if (!env->ops->check_kfunc_call || 6703 !env->ops->check_kfunc_call(func_id, btf_mod)) { 6704 verbose(env, "calling kernel function %s is not allowed\n", 6705 func_name); 6706 return -EACCES; 6707 } 6708 6709 /* Check the arguments */ 6710 err = btf_check_kfunc_arg_match(env, desc_btf, func_id, regs); 6711 if (err) 6712 return err; 6713 6714 for (i = 0; i < CALLER_SAVED_REGS; i++) 6715 mark_reg_not_init(env, regs, caller_saved[i]); 6716 6717 /* Check return type */ 6718 t = btf_type_skip_modifiers(desc_btf, func_proto->type, NULL); 6719 if (btf_type_is_scalar(t)) { 6720 mark_reg_unknown(env, regs, BPF_REG_0); 6721 mark_btf_func_reg_size(env, BPF_REG_0, t->size); 6722 } else if (btf_type_is_ptr(t)) { 6723 ptr_type = btf_type_skip_modifiers(desc_btf, t->type, 6724 &ptr_type_id); 6725 if (!btf_type_is_struct(ptr_type)) { 6726 ptr_type_name = btf_name_by_offset(desc_btf, 6727 ptr_type->name_off); 6728 verbose(env, "kernel function %s returns pointer type %s %s is not supported\n", 6729 func_name, btf_type_str(ptr_type), 6730 ptr_type_name); 6731 return -EINVAL; 6732 } 6733 mark_reg_known_zero(env, regs, BPF_REG_0); 6734 regs[BPF_REG_0].btf = desc_btf; 6735 regs[BPF_REG_0].type = PTR_TO_BTF_ID; 6736 regs[BPF_REG_0].btf_id = ptr_type_id; 6737 mark_btf_func_reg_size(env, BPF_REG_0, sizeof(void *)); 6738 } /* else { add_kfunc_call() ensures it is btf_type_is_void(t) } */ 6739 6740 nargs = btf_type_vlen(func_proto); 6741 args = (const struct btf_param *)(func_proto + 1); 6742 for (i = 0; i < nargs; i++) { 6743 u32 regno = i + 1; 6744 6745 t = btf_type_skip_modifiers(desc_btf, args[i].type, NULL); 6746 if (btf_type_is_ptr(t)) 6747 mark_btf_func_reg_size(env, regno, sizeof(void *)); 6748 else 6749 /* scalar. ensured by btf_check_kfunc_arg_match() */ 6750 mark_btf_func_reg_size(env, regno, t->size); 6751 } 6752 6753 return 0; 6754 } 6755 6756 static bool signed_add_overflows(s64 a, s64 b) 6757 { 6758 /* Do the add in u64, where overflow is well-defined */ 6759 s64 res = (s64)((u64)a + (u64)b); 6760 6761 if (b < 0) 6762 return res > a; 6763 return res < a; 6764 } 6765 6766 static bool signed_add32_overflows(s32 a, s32 b) 6767 { 6768 /* Do the add in u32, where overflow is well-defined */ 6769 s32 res = (s32)((u32)a + (u32)b); 6770 6771 if (b < 0) 6772 return res > a; 6773 return res < a; 6774 } 6775 6776 static bool signed_sub_overflows(s64 a, s64 b) 6777 { 6778 /* Do the sub in u64, where overflow is well-defined */ 6779 s64 res = (s64)((u64)a - (u64)b); 6780 6781 if (b < 0) 6782 return res < a; 6783 return res > a; 6784 } 6785 6786 static bool signed_sub32_overflows(s32 a, s32 b) 6787 { 6788 /* Do the sub in u32, where overflow is well-defined */ 6789 s32 res = (s32)((u32)a - (u32)b); 6790 6791 if (b < 0) 6792 return res < a; 6793 return res > a; 6794 } 6795 6796 static bool check_reg_sane_offset(struct bpf_verifier_env *env, 6797 const struct bpf_reg_state *reg, 6798 enum bpf_reg_type type) 6799 { 6800 bool known = tnum_is_const(reg->var_off); 6801 s64 val = reg->var_off.value; 6802 s64 smin = reg->smin_value; 6803 6804 if (known && (val >= BPF_MAX_VAR_OFF || val <= -BPF_MAX_VAR_OFF)) { 6805 verbose(env, "math between %s pointer and %lld is not allowed\n", 6806 reg_type_str[type], val); 6807 return false; 6808 } 6809 6810 if (reg->off >= BPF_MAX_VAR_OFF || reg->off <= -BPF_MAX_VAR_OFF) { 6811 verbose(env, "%s pointer offset %d is not allowed\n", 6812 reg_type_str[type], reg->off); 6813 return false; 6814 } 6815 6816 if (smin == S64_MIN) { 6817 verbose(env, "math between %s pointer and register with unbounded min value is not allowed\n", 6818 reg_type_str[type]); 6819 return false; 6820 } 6821 6822 if (smin >= BPF_MAX_VAR_OFF || smin <= -BPF_MAX_VAR_OFF) { 6823 verbose(env, "value %lld makes %s pointer be out of bounds\n", 6824 smin, reg_type_str[type]); 6825 return false; 6826 } 6827 6828 return true; 6829 } 6830 6831 static struct bpf_insn_aux_data *cur_aux(struct bpf_verifier_env *env) 6832 { 6833 return &env->insn_aux_data[env->insn_idx]; 6834 } 6835 6836 enum { 6837 REASON_BOUNDS = -1, 6838 REASON_TYPE = -2, 6839 REASON_PATHS = -3, 6840 REASON_LIMIT = -4, 6841 REASON_STACK = -5, 6842 }; 6843 6844 static int retrieve_ptr_limit(const struct bpf_reg_state *ptr_reg, 6845 u32 *alu_limit, bool mask_to_left) 6846 { 6847 u32 max = 0, ptr_limit = 0; 6848 6849 switch (ptr_reg->type) { 6850 case PTR_TO_STACK: 6851 /* Offset 0 is out-of-bounds, but acceptable start for the 6852 * left direction, see BPF_REG_FP. Also, unknown scalar 6853 * offset where we would need to deal with min/max bounds is 6854 * currently prohibited for unprivileged. 6855 */ 6856 max = MAX_BPF_STACK + mask_to_left; 6857 ptr_limit = -(ptr_reg->var_off.value + ptr_reg->off); 6858 break; 6859 case PTR_TO_MAP_VALUE: 6860 max = ptr_reg->map_ptr->value_size; 6861 ptr_limit = (mask_to_left ? 6862 ptr_reg->smin_value : 6863 ptr_reg->umax_value) + ptr_reg->off; 6864 break; 6865 default: 6866 return REASON_TYPE; 6867 } 6868 6869 if (ptr_limit >= max) 6870 return REASON_LIMIT; 6871 *alu_limit = ptr_limit; 6872 return 0; 6873 } 6874 6875 static bool can_skip_alu_sanitation(const struct bpf_verifier_env *env, 6876 const struct bpf_insn *insn) 6877 { 6878 return env->bypass_spec_v1 || BPF_SRC(insn->code) == BPF_K; 6879 } 6880 6881 static int update_alu_sanitation_state(struct bpf_insn_aux_data *aux, 6882 u32 alu_state, u32 alu_limit) 6883 { 6884 /* If we arrived here from different branches with different 6885 * state or limits to sanitize, then this won't work. 6886 */ 6887 if (aux->alu_state && 6888 (aux->alu_state != alu_state || 6889 aux->alu_limit != alu_limit)) 6890 return REASON_PATHS; 6891 6892 /* Corresponding fixup done in do_misc_fixups(). */ 6893 aux->alu_state = alu_state; 6894 aux->alu_limit = alu_limit; 6895 return 0; 6896 } 6897 6898 static int sanitize_val_alu(struct bpf_verifier_env *env, 6899 struct bpf_insn *insn) 6900 { 6901 struct bpf_insn_aux_data *aux = cur_aux(env); 6902 6903 if (can_skip_alu_sanitation(env, insn)) 6904 return 0; 6905 6906 return update_alu_sanitation_state(aux, BPF_ALU_NON_POINTER, 0); 6907 } 6908 6909 static bool sanitize_needed(u8 opcode) 6910 { 6911 return opcode == BPF_ADD || opcode == BPF_SUB; 6912 } 6913 6914 struct bpf_sanitize_info { 6915 struct bpf_insn_aux_data aux; 6916 bool mask_to_left; 6917 }; 6918 6919 static struct bpf_verifier_state * 6920 sanitize_speculative_path(struct bpf_verifier_env *env, 6921 const struct bpf_insn *insn, 6922 u32 next_idx, u32 curr_idx) 6923 { 6924 struct bpf_verifier_state *branch; 6925 struct bpf_reg_state *regs; 6926 6927 branch = push_stack(env, next_idx, curr_idx, true); 6928 if (branch && insn) { 6929 regs = branch->frame[branch->curframe]->regs; 6930 if (BPF_SRC(insn->code) == BPF_K) { 6931 mark_reg_unknown(env, regs, insn->dst_reg); 6932 } else if (BPF_SRC(insn->code) == BPF_X) { 6933 mark_reg_unknown(env, regs, insn->dst_reg); 6934 mark_reg_unknown(env, regs, insn->src_reg); 6935 } 6936 } 6937 return branch; 6938 } 6939 6940 static int sanitize_ptr_alu(struct bpf_verifier_env *env, 6941 struct bpf_insn *insn, 6942 const struct bpf_reg_state *ptr_reg, 6943 const struct bpf_reg_state *off_reg, 6944 struct bpf_reg_state *dst_reg, 6945 struct bpf_sanitize_info *info, 6946 const bool commit_window) 6947 { 6948 struct bpf_insn_aux_data *aux = commit_window ? cur_aux(env) : &info->aux; 6949 struct bpf_verifier_state *vstate = env->cur_state; 6950 bool off_is_imm = tnum_is_const(off_reg->var_off); 6951 bool off_is_neg = off_reg->smin_value < 0; 6952 bool ptr_is_dst_reg = ptr_reg == dst_reg; 6953 u8 opcode = BPF_OP(insn->code); 6954 u32 alu_state, alu_limit; 6955 struct bpf_reg_state tmp; 6956 bool ret; 6957 int err; 6958 6959 if (can_skip_alu_sanitation(env, insn)) 6960 return 0; 6961 6962 /* We already marked aux for masking from non-speculative 6963 * paths, thus we got here in the first place. We only care 6964 * to explore bad access from here. 6965 */ 6966 if (vstate->speculative) 6967 goto do_sim; 6968 6969 if (!commit_window) { 6970 if (!tnum_is_const(off_reg->var_off) && 6971 (off_reg->smin_value < 0) != (off_reg->smax_value < 0)) 6972 return REASON_BOUNDS; 6973 6974 info->mask_to_left = (opcode == BPF_ADD && off_is_neg) || 6975 (opcode == BPF_SUB && !off_is_neg); 6976 } 6977 6978 err = retrieve_ptr_limit(ptr_reg, &alu_limit, info->mask_to_left); 6979 if (err < 0) 6980 return err; 6981 6982 if (commit_window) { 6983 /* In commit phase we narrow the masking window based on 6984 * the observed pointer move after the simulated operation. 6985 */ 6986 alu_state = info->aux.alu_state; 6987 alu_limit = abs(info->aux.alu_limit - alu_limit); 6988 } else { 6989 alu_state = off_is_neg ? BPF_ALU_NEG_VALUE : 0; 6990 alu_state |= off_is_imm ? BPF_ALU_IMMEDIATE : 0; 6991 alu_state |= ptr_is_dst_reg ? 6992 BPF_ALU_SANITIZE_SRC : BPF_ALU_SANITIZE_DST; 6993 6994 /* Limit pruning on unknown scalars to enable deep search for 6995 * potential masking differences from other program paths. 6996 */ 6997 if (!off_is_imm) 6998 env->explore_alu_limits = true; 6999 } 7000 7001 err = update_alu_sanitation_state(aux, alu_state, alu_limit); 7002 if (err < 0) 7003 return err; 7004 do_sim: 7005 /* If we're in commit phase, we're done here given we already 7006 * pushed the truncated dst_reg into the speculative verification 7007 * stack. 7008 * 7009 * Also, when register is a known constant, we rewrite register-based 7010 * operation to immediate-based, and thus do not need masking (and as 7011 * a consequence, do not need to simulate the zero-truncation either). 7012 */ 7013 if (commit_window || off_is_imm) 7014 return 0; 7015 7016 /* Simulate and find potential out-of-bounds access under 7017 * speculative execution from truncation as a result of 7018 * masking when off was not within expected range. If off 7019 * sits in dst, then we temporarily need to move ptr there 7020 * to simulate dst (== 0) +/-= ptr. Needed, for example, 7021 * for cases where we use K-based arithmetic in one direction 7022 * and truncated reg-based in the other in order to explore 7023 * bad access. 7024 */ 7025 if (!ptr_is_dst_reg) { 7026 tmp = *dst_reg; 7027 *dst_reg = *ptr_reg; 7028 } 7029 ret = sanitize_speculative_path(env, NULL, env->insn_idx + 1, 7030 env->insn_idx); 7031 if (!ptr_is_dst_reg && ret) 7032 *dst_reg = tmp; 7033 return !ret ? REASON_STACK : 0; 7034 } 7035 7036 static void sanitize_mark_insn_seen(struct bpf_verifier_env *env) 7037 { 7038 struct bpf_verifier_state *vstate = env->cur_state; 7039 7040 /* If we simulate paths under speculation, we don't update the 7041 * insn as 'seen' such that when we verify unreachable paths in 7042 * the non-speculative domain, sanitize_dead_code() can still 7043 * rewrite/sanitize them. 7044 */ 7045 if (!vstate->speculative) 7046 env->insn_aux_data[env->insn_idx].seen = env->pass_cnt; 7047 } 7048 7049 static int sanitize_err(struct bpf_verifier_env *env, 7050 const struct bpf_insn *insn, int reason, 7051 const struct bpf_reg_state *off_reg, 7052 const struct bpf_reg_state *dst_reg) 7053 { 7054 static const char *err = "pointer arithmetic with it prohibited for !root"; 7055 const char *op = BPF_OP(insn->code) == BPF_ADD ? "add" : "sub"; 7056 u32 dst = insn->dst_reg, src = insn->src_reg; 7057 7058 switch (reason) { 7059 case REASON_BOUNDS: 7060 verbose(env, "R%d has unknown scalar with mixed signed bounds, %s\n", 7061 off_reg == dst_reg ? dst : src, err); 7062 break; 7063 case REASON_TYPE: 7064 verbose(env, "R%d has pointer with unsupported alu operation, %s\n", 7065 off_reg == dst_reg ? src : dst, err); 7066 break; 7067 case REASON_PATHS: 7068 verbose(env, "R%d tried to %s from different maps, paths or scalars, %s\n", 7069 dst, op, err); 7070 break; 7071 case REASON_LIMIT: 7072 verbose(env, "R%d tried to %s beyond pointer bounds, %s\n", 7073 dst, op, err); 7074 break; 7075 case REASON_STACK: 7076 verbose(env, "R%d could not be pushed for speculative verification, %s\n", 7077 dst, err); 7078 break; 7079 default: 7080 verbose(env, "verifier internal error: unknown reason (%d)\n", 7081 reason); 7082 break; 7083 } 7084 7085 return -EACCES; 7086 } 7087 7088 /* check that stack access falls within stack limits and that 'reg' doesn't 7089 * have a variable offset. 7090 * 7091 * Variable offset is prohibited for unprivileged mode for simplicity since it 7092 * requires corresponding support in Spectre masking for stack ALU. See also 7093 * retrieve_ptr_limit(). 7094 * 7095 * 7096 * 'off' includes 'reg->off'. 7097 */ 7098 static int check_stack_access_for_ptr_arithmetic( 7099 struct bpf_verifier_env *env, 7100 int regno, 7101 const struct bpf_reg_state *reg, 7102 int off) 7103 { 7104 if (!tnum_is_const(reg->var_off)) { 7105 char tn_buf[48]; 7106 7107 tnum_strn(tn_buf, sizeof(tn_buf), reg->var_off); 7108 verbose(env, "R%d variable stack access prohibited for !root, var_off=%s off=%d\n", 7109 regno, tn_buf, off); 7110 return -EACCES; 7111 } 7112 7113 if (off >= 0 || off < -MAX_BPF_STACK) { 7114 verbose(env, "R%d stack pointer arithmetic goes out of range, " 7115 "prohibited for !root; off=%d\n", regno, off); 7116 return -EACCES; 7117 } 7118 7119 return 0; 7120 } 7121 7122 static int sanitize_check_bounds(struct bpf_verifier_env *env, 7123 const struct bpf_insn *insn, 7124 const struct bpf_reg_state *dst_reg) 7125 { 7126 u32 dst = insn->dst_reg; 7127 7128 /* For unprivileged we require that resulting offset must be in bounds 7129 * in order to be able to sanitize access later on. 7130 */ 7131 if (env->bypass_spec_v1) 7132 return 0; 7133 7134 switch (dst_reg->type) { 7135 case PTR_TO_STACK: 7136 if (check_stack_access_for_ptr_arithmetic(env, dst, dst_reg, 7137 dst_reg->off + dst_reg->var_off.value)) 7138 return -EACCES; 7139 break; 7140 case PTR_TO_MAP_VALUE: 7141 if (check_map_access(env, dst, dst_reg->off, 1, false)) { 7142 verbose(env, "R%d pointer arithmetic of map value goes out of range, " 7143 "prohibited for !root\n", dst); 7144 return -EACCES; 7145 } 7146 break; 7147 default: 7148 break; 7149 } 7150 7151 return 0; 7152 } 7153 7154 /* Handles arithmetic on a pointer and a scalar: computes new min/max and var_off. 7155 * Caller should also handle BPF_MOV case separately. 7156 * If we return -EACCES, caller may want to try again treating pointer as a 7157 * scalar. So we only emit a diagnostic if !env->allow_ptr_leaks. 7158 */ 7159 static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, 7160 struct bpf_insn *insn, 7161 const struct bpf_reg_state *ptr_reg, 7162 const struct bpf_reg_state *off_reg) 7163 { 7164 struct bpf_verifier_state *vstate = env->cur_state; 7165 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 7166 struct bpf_reg_state *regs = state->regs, *dst_reg; 7167 bool known = tnum_is_const(off_reg->var_off); 7168 s64 smin_val = off_reg->smin_value, smax_val = off_reg->smax_value, 7169 smin_ptr = ptr_reg->smin_value, smax_ptr = ptr_reg->smax_value; 7170 u64 umin_val = off_reg->umin_value, umax_val = off_reg->umax_value, 7171 umin_ptr = ptr_reg->umin_value, umax_ptr = ptr_reg->umax_value; 7172 struct bpf_sanitize_info info = {}; 7173 u8 opcode = BPF_OP(insn->code); 7174 u32 dst = insn->dst_reg; 7175 int ret; 7176 7177 dst_reg = ®s[dst]; 7178 7179 if ((known && (smin_val != smax_val || umin_val != umax_val)) || 7180 smin_val > smax_val || umin_val > umax_val) { 7181 /* Taint dst register if offset had invalid bounds derived from 7182 * e.g. dead branches. 7183 */ 7184 __mark_reg_unknown(env, dst_reg); 7185 return 0; 7186 } 7187 7188 if (BPF_CLASS(insn->code) != BPF_ALU64) { 7189 /* 32-bit ALU ops on pointers produce (meaningless) scalars */ 7190 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 7191 __mark_reg_unknown(env, dst_reg); 7192 return 0; 7193 } 7194 7195 verbose(env, 7196 "R%d 32-bit pointer arithmetic prohibited\n", 7197 dst); 7198 return -EACCES; 7199 } 7200 7201 switch (ptr_reg->type) { 7202 case PTR_TO_MAP_VALUE_OR_NULL: 7203 verbose(env, "R%d pointer arithmetic on %s prohibited, null-check it first\n", 7204 dst, reg_type_str[ptr_reg->type]); 7205 return -EACCES; 7206 case CONST_PTR_TO_MAP: 7207 /* smin_val represents the known value */ 7208 if (known && smin_val == 0 && opcode == BPF_ADD) 7209 break; 7210 fallthrough; 7211 case PTR_TO_PACKET_END: 7212 case PTR_TO_SOCKET: 7213 case PTR_TO_SOCKET_OR_NULL: 7214 case PTR_TO_SOCK_COMMON: 7215 case PTR_TO_SOCK_COMMON_OR_NULL: 7216 case PTR_TO_TCP_SOCK: 7217 case PTR_TO_TCP_SOCK_OR_NULL: 7218 case PTR_TO_XDP_SOCK: 7219 verbose(env, "R%d pointer arithmetic on %s prohibited\n", 7220 dst, reg_type_str[ptr_reg->type]); 7221 return -EACCES; 7222 default: 7223 break; 7224 } 7225 7226 /* In case of 'scalar += pointer', dst_reg inherits pointer type and id. 7227 * The id may be overwritten later if we create a new variable offset. 7228 */ 7229 dst_reg->type = ptr_reg->type; 7230 dst_reg->id = ptr_reg->id; 7231 7232 if (!check_reg_sane_offset(env, off_reg, ptr_reg->type) || 7233 !check_reg_sane_offset(env, ptr_reg, ptr_reg->type)) 7234 return -EINVAL; 7235 7236 /* pointer types do not carry 32-bit bounds at the moment. */ 7237 __mark_reg32_unbounded(dst_reg); 7238 7239 if (sanitize_needed(opcode)) { 7240 ret = sanitize_ptr_alu(env, insn, ptr_reg, off_reg, dst_reg, 7241 &info, false); 7242 if (ret < 0) 7243 return sanitize_err(env, insn, ret, off_reg, dst_reg); 7244 } 7245 7246 switch (opcode) { 7247 case BPF_ADD: 7248 /* We can take a fixed offset as long as it doesn't overflow 7249 * the s32 'off' field 7250 */ 7251 if (known && (ptr_reg->off + smin_val == 7252 (s64)(s32)(ptr_reg->off + smin_val))) { 7253 /* pointer += K. Accumulate it into fixed offset */ 7254 dst_reg->smin_value = smin_ptr; 7255 dst_reg->smax_value = smax_ptr; 7256 dst_reg->umin_value = umin_ptr; 7257 dst_reg->umax_value = umax_ptr; 7258 dst_reg->var_off = ptr_reg->var_off; 7259 dst_reg->off = ptr_reg->off + smin_val; 7260 dst_reg->raw = ptr_reg->raw; 7261 break; 7262 } 7263 /* A new variable offset is created. Note that off_reg->off 7264 * == 0, since it's a scalar. 7265 * dst_reg gets the pointer type and since some positive 7266 * integer value was added to the pointer, give it a new 'id' 7267 * if it's a PTR_TO_PACKET. 7268 * this creates a new 'base' pointer, off_reg (variable) gets 7269 * added into the variable offset, and we copy the fixed offset 7270 * from ptr_reg. 7271 */ 7272 if (signed_add_overflows(smin_ptr, smin_val) || 7273 signed_add_overflows(smax_ptr, smax_val)) { 7274 dst_reg->smin_value = S64_MIN; 7275 dst_reg->smax_value = S64_MAX; 7276 } else { 7277 dst_reg->smin_value = smin_ptr + smin_val; 7278 dst_reg->smax_value = smax_ptr + smax_val; 7279 } 7280 if (umin_ptr + umin_val < umin_ptr || 7281 umax_ptr + umax_val < umax_ptr) { 7282 dst_reg->umin_value = 0; 7283 dst_reg->umax_value = U64_MAX; 7284 } else { 7285 dst_reg->umin_value = umin_ptr + umin_val; 7286 dst_reg->umax_value = umax_ptr + umax_val; 7287 } 7288 dst_reg->var_off = tnum_add(ptr_reg->var_off, off_reg->var_off); 7289 dst_reg->off = ptr_reg->off; 7290 dst_reg->raw = ptr_reg->raw; 7291 if (reg_is_pkt_pointer(ptr_reg)) { 7292 dst_reg->id = ++env->id_gen; 7293 /* something was added to pkt_ptr, set range to zero */ 7294 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 7295 } 7296 break; 7297 case BPF_SUB: 7298 if (dst_reg == off_reg) { 7299 /* scalar -= pointer. Creates an unknown scalar */ 7300 verbose(env, "R%d tried to subtract pointer from scalar\n", 7301 dst); 7302 return -EACCES; 7303 } 7304 /* We don't allow subtraction from FP, because (according to 7305 * test_verifier.c test "invalid fp arithmetic", JITs might not 7306 * be able to deal with it. 7307 */ 7308 if (ptr_reg->type == PTR_TO_STACK) { 7309 verbose(env, "R%d subtraction from stack pointer prohibited\n", 7310 dst); 7311 return -EACCES; 7312 } 7313 if (known && (ptr_reg->off - smin_val == 7314 (s64)(s32)(ptr_reg->off - smin_val))) { 7315 /* pointer -= K. Subtract it from fixed offset */ 7316 dst_reg->smin_value = smin_ptr; 7317 dst_reg->smax_value = smax_ptr; 7318 dst_reg->umin_value = umin_ptr; 7319 dst_reg->umax_value = umax_ptr; 7320 dst_reg->var_off = ptr_reg->var_off; 7321 dst_reg->id = ptr_reg->id; 7322 dst_reg->off = ptr_reg->off - smin_val; 7323 dst_reg->raw = ptr_reg->raw; 7324 break; 7325 } 7326 /* A new variable offset is created. If the subtrahend is known 7327 * nonnegative, then any reg->range we had before is still good. 7328 */ 7329 if (signed_sub_overflows(smin_ptr, smax_val) || 7330 signed_sub_overflows(smax_ptr, smin_val)) { 7331 /* Overflow possible, we know nothing */ 7332 dst_reg->smin_value = S64_MIN; 7333 dst_reg->smax_value = S64_MAX; 7334 } else { 7335 dst_reg->smin_value = smin_ptr - smax_val; 7336 dst_reg->smax_value = smax_ptr - smin_val; 7337 } 7338 if (umin_ptr < umax_val) { 7339 /* Overflow possible, we know nothing */ 7340 dst_reg->umin_value = 0; 7341 dst_reg->umax_value = U64_MAX; 7342 } else { 7343 /* Cannot overflow (as long as bounds are consistent) */ 7344 dst_reg->umin_value = umin_ptr - umax_val; 7345 dst_reg->umax_value = umax_ptr - umin_val; 7346 } 7347 dst_reg->var_off = tnum_sub(ptr_reg->var_off, off_reg->var_off); 7348 dst_reg->off = ptr_reg->off; 7349 dst_reg->raw = ptr_reg->raw; 7350 if (reg_is_pkt_pointer(ptr_reg)) { 7351 dst_reg->id = ++env->id_gen; 7352 /* something was added to pkt_ptr, set range to zero */ 7353 if (smin_val < 0) 7354 memset(&dst_reg->raw, 0, sizeof(dst_reg->raw)); 7355 } 7356 break; 7357 case BPF_AND: 7358 case BPF_OR: 7359 case BPF_XOR: 7360 /* bitwise ops on pointers are troublesome, prohibit. */ 7361 verbose(env, "R%d bitwise operator %s on pointer prohibited\n", 7362 dst, bpf_alu_string[opcode >> 4]); 7363 return -EACCES; 7364 default: 7365 /* other operators (e.g. MUL,LSH) produce non-pointer results */ 7366 verbose(env, "R%d pointer arithmetic with %s operator prohibited\n", 7367 dst, bpf_alu_string[opcode >> 4]); 7368 return -EACCES; 7369 } 7370 7371 if (!check_reg_sane_offset(env, dst_reg, ptr_reg->type)) 7372 return -EINVAL; 7373 7374 __update_reg_bounds(dst_reg); 7375 __reg_deduce_bounds(dst_reg); 7376 __reg_bound_offset(dst_reg); 7377 7378 if (sanitize_check_bounds(env, insn, dst_reg) < 0) 7379 return -EACCES; 7380 if (sanitize_needed(opcode)) { 7381 ret = sanitize_ptr_alu(env, insn, dst_reg, off_reg, dst_reg, 7382 &info, true); 7383 if (ret < 0) 7384 return sanitize_err(env, insn, ret, off_reg, dst_reg); 7385 } 7386 7387 return 0; 7388 } 7389 7390 static void scalar32_min_max_add(struct bpf_reg_state *dst_reg, 7391 struct bpf_reg_state *src_reg) 7392 { 7393 s32 smin_val = src_reg->s32_min_value; 7394 s32 smax_val = src_reg->s32_max_value; 7395 u32 umin_val = src_reg->u32_min_value; 7396 u32 umax_val = src_reg->u32_max_value; 7397 7398 if (signed_add32_overflows(dst_reg->s32_min_value, smin_val) || 7399 signed_add32_overflows(dst_reg->s32_max_value, smax_val)) { 7400 dst_reg->s32_min_value = S32_MIN; 7401 dst_reg->s32_max_value = S32_MAX; 7402 } else { 7403 dst_reg->s32_min_value += smin_val; 7404 dst_reg->s32_max_value += smax_val; 7405 } 7406 if (dst_reg->u32_min_value + umin_val < umin_val || 7407 dst_reg->u32_max_value + umax_val < umax_val) { 7408 dst_reg->u32_min_value = 0; 7409 dst_reg->u32_max_value = U32_MAX; 7410 } else { 7411 dst_reg->u32_min_value += umin_val; 7412 dst_reg->u32_max_value += umax_val; 7413 } 7414 } 7415 7416 static void scalar_min_max_add(struct bpf_reg_state *dst_reg, 7417 struct bpf_reg_state *src_reg) 7418 { 7419 s64 smin_val = src_reg->smin_value; 7420 s64 smax_val = src_reg->smax_value; 7421 u64 umin_val = src_reg->umin_value; 7422 u64 umax_val = src_reg->umax_value; 7423 7424 if (signed_add_overflows(dst_reg->smin_value, smin_val) || 7425 signed_add_overflows(dst_reg->smax_value, smax_val)) { 7426 dst_reg->smin_value = S64_MIN; 7427 dst_reg->smax_value = S64_MAX; 7428 } else { 7429 dst_reg->smin_value += smin_val; 7430 dst_reg->smax_value += smax_val; 7431 } 7432 if (dst_reg->umin_value + umin_val < umin_val || 7433 dst_reg->umax_value + umax_val < umax_val) { 7434 dst_reg->umin_value = 0; 7435 dst_reg->umax_value = U64_MAX; 7436 } else { 7437 dst_reg->umin_value += umin_val; 7438 dst_reg->umax_value += umax_val; 7439 } 7440 } 7441 7442 static void scalar32_min_max_sub(struct bpf_reg_state *dst_reg, 7443 struct bpf_reg_state *src_reg) 7444 { 7445 s32 smin_val = src_reg->s32_min_value; 7446 s32 smax_val = src_reg->s32_max_value; 7447 u32 umin_val = src_reg->u32_min_value; 7448 u32 umax_val = src_reg->u32_max_value; 7449 7450 if (signed_sub32_overflows(dst_reg->s32_min_value, smax_val) || 7451 signed_sub32_overflows(dst_reg->s32_max_value, smin_val)) { 7452 /* Overflow possible, we know nothing */ 7453 dst_reg->s32_min_value = S32_MIN; 7454 dst_reg->s32_max_value = S32_MAX; 7455 } else { 7456 dst_reg->s32_min_value -= smax_val; 7457 dst_reg->s32_max_value -= smin_val; 7458 } 7459 if (dst_reg->u32_min_value < umax_val) { 7460 /* Overflow possible, we know nothing */ 7461 dst_reg->u32_min_value = 0; 7462 dst_reg->u32_max_value = U32_MAX; 7463 } else { 7464 /* Cannot overflow (as long as bounds are consistent) */ 7465 dst_reg->u32_min_value -= umax_val; 7466 dst_reg->u32_max_value -= umin_val; 7467 } 7468 } 7469 7470 static void scalar_min_max_sub(struct bpf_reg_state *dst_reg, 7471 struct bpf_reg_state *src_reg) 7472 { 7473 s64 smin_val = src_reg->smin_value; 7474 s64 smax_val = src_reg->smax_value; 7475 u64 umin_val = src_reg->umin_value; 7476 u64 umax_val = src_reg->umax_value; 7477 7478 if (signed_sub_overflows(dst_reg->smin_value, smax_val) || 7479 signed_sub_overflows(dst_reg->smax_value, smin_val)) { 7480 /* Overflow possible, we know nothing */ 7481 dst_reg->smin_value = S64_MIN; 7482 dst_reg->smax_value = S64_MAX; 7483 } else { 7484 dst_reg->smin_value -= smax_val; 7485 dst_reg->smax_value -= smin_val; 7486 } 7487 if (dst_reg->umin_value < umax_val) { 7488 /* Overflow possible, we know nothing */ 7489 dst_reg->umin_value = 0; 7490 dst_reg->umax_value = U64_MAX; 7491 } else { 7492 /* Cannot overflow (as long as bounds are consistent) */ 7493 dst_reg->umin_value -= umax_val; 7494 dst_reg->umax_value -= umin_val; 7495 } 7496 } 7497 7498 static void scalar32_min_max_mul(struct bpf_reg_state *dst_reg, 7499 struct bpf_reg_state *src_reg) 7500 { 7501 s32 smin_val = src_reg->s32_min_value; 7502 u32 umin_val = src_reg->u32_min_value; 7503 u32 umax_val = src_reg->u32_max_value; 7504 7505 if (smin_val < 0 || dst_reg->s32_min_value < 0) { 7506 /* Ain't nobody got time to multiply that sign */ 7507 __mark_reg32_unbounded(dst_reg); 7508 return; 7509 } 7510 /* Both values are positive, so we can work with unsigned and 7511 * copy the result to signed (unless it exceeds S32_MAX). 7512 */ 7513 if (umax_val > U16_MAX || dst_reg->u32_max_value > U16_MAX) { 7514 /* Potential overflow, we know nothing */ 7515 __mark_reg32_unbounded(dst_reg); 7516 return; 7517 } 7518 dst_reg->u32_min_value *= umin_val; 7519 dst_reg->u32_max_value *= umax_val; 7520 if (dst_reg->u32_max_value > S32_MAX) { 7521 /* Overflow possible, we know nothing */ 7522 dst_reg->s32_min_value = S32_MIN; 7523 dst_reg->s32_max_value = S32_MAX; 7524 } else { 7525 dst_reg->s32_min_value = dst_reg->u32_min_value; 7526 dst_reg->s32_max_value = dst_reg->u32_max_value; 7527 } 7528 } 7529 7530 static void scalar_min_max_mul(struct bpf_reg_state *dst_reg, 7531 struct bpf_reg_state *src_reg) 7532 { 7533 s64 smin_val = src_reg->smin_value; 7534 u64 umin_val = src_reg->umin_value; 7535 u64 umax_val = src_reg->umax_value; 7536 7537 if (smin_val < 0 || dst_reg->smin_value < 0) { 7538 /* Ain't nobody got time to multiply that sign */ 7539 __mark_reg64_unbounded(dst_reg); 7540 return; 7541 } 7542 /* Both values are positive, so we can work with unsigned and 7543 * copy the result to signed (unless it exceeds S64_MAX). 7544 */ 7545 if (umax_val > U32_MAX || dst_reg->umax_value > U32_MAX) { 7546 /* Potential overflow, we know nothing */ 7547 __mark_reg64_unbounded(dst_reg); 7548 return; 7549 } 7550 dst_reg->umin_value *= umin_val; 7551 dst_reg->umax_value *= umax_val; 7552 if (dst_reg->umax_value > S64_MAX) { 7553 /* Overflow possible, we know nothing */ 7554 dst_reg->smin_value = S64_MIN; 7555 dst_reg->smax_value = S64_MAX; 7556 } else { 7557 dst_reg->smin_value = dst_reg->umin_value; 7558 dst_reg->smax_value = dst_reg->umax_value; 7559 } 7560 } 7561 7562 static void scalar32_min_max_and(struct bpf_reg_state *dst_reg, 7563 struct bpf_reg_state *src_reg) 7564 { 7565 bool src_known = tnum_subreg_is_const(src_reg->var_off); 7566 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 7567 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 7568 s32 smin_val = src_reg->s32_min_value; 7569 u32 umax_val = src_reg->u32_max_value; 7570 7571 if (src_known && dst_known) { 7572 __mark_reg32_known(dst_reg, var32_off.value); 7573 return; 7574 } 7575 7576 /* We get our minimum from the var_off, since that's inherently 7577 * bitwise. Our maximum is the minimum of the operands' maxima. 7578 */ 7579 dst_reg->u32_min_value = var32_off.value; 7580 dst_reg->u32_max_value = min(dst_reg->u32_max_value, umax_val); 7581 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 7582 /* Lose signed bounds when ANDing negative numbers, 7583 * ain't nobody got time for that. 7584 */ 7585 dst_reg->s32_min_value = S32_MIN; 7586 dst_reg->s32_max_value = S32_MAX; 7587 } else { 7588 /* ANDing two positives gives a positive, so safe to 7589 * cast result into s64. 7590 */ 7591 dst_reg->s32_min_value = dst_reg->u32_min_value; 7592 dst_reg->s32_max_value = dst_reg->u32_max_value; 7593 } 7594 } 7595 7596 static void scalar_min_max_and(struct bpf_reg_state *dst_reg, 7597 struct bpf_reg_state *src_reg) 7598 { 7599 bool src_known = tnum_is_const(src_reg->var_off); 7600 bool dst_known = tnum_is_const(dst_reg->var_off); 7601 s64 smin_val = src_reg->smin_value; 7602 u64 umax_val = src_reg->umax_value; 7603 7604 if (src_known && dst_known) { 7605 __mark_reg_known(dst_reg, dst_reg->var_off.value); 7606 return; 7607 } 7608 7609 /* We get our minimum from the var_off, since that's inherently 7610 * bitwise. Our maximum is the minimum of the operands' maxima. 7611 */ 7612 dst_reg->umin_value = dst_reg->var_off.value; 7613 dst_reg->umax_value = min(dst_reg->umax_value, umax_val); 7614 if (dst_reg->smin_value < 0 || smin_val < 0) { 7615 /* Lose signed bounds when ANDing negative numbers, 7616 * ain't nobody got time for that. 7617 */ 7618 dst_reg->smin_value = S64_MIN; 7619 dst_reg->smax_value = S64_MAX; 7620 } else { 7621 /* ANDing two positives gives a positive, so safe to 7622 * cast result into s64. 7623 */ 7624 dst_reg->smin_value = dst_reg->umin_value; 7625 dst_reg->smax_value = dst_reg->umax_value; 7626 } 7627 /* We may learn something more from the var_off */ 7628 __update_reg_bounds(dst_reg); 7629 } 7630 7631 static void scalar32_min_max_or(struct bpf_reg_state *dst_reg, 7632 struct bpf_reg_state *src_reg) 7633 { 7634 bool src_known = tnum_subreg_is_const(src_reg->var_off); 7635 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 7636 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 7637 s32 smin_val = src_reg->s32_min_value; 7638 u32 umin_val = src_reg->u32_min_value; 7639 7640 if (src_known && dst_known) { 7641 __mark_reg32_known(dst_reg, var32_off.value); 7642 return; 7643 } 7644 7645 /* We get our maximum from the var_off, and our minimum is the 7646 * maximum of the operands' minima 7647 */ 7648 dst_reg->u32_min_value = max(dst_reg->u32_min_value, umin_val); 7649 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 7650 if (dst_reg->s32_min_value < 0 || smin_val < 0) { 7651 /* Lose signed bounds when ORing negative numbers, 7652 * ain't nobody got time for that. 7653 */ 7654 dst_reg->s32_min_value = S32_MIN; 7655 dst_reg->s32_max_value = S32_MAX; 7656 } else { 7657 /* ORing two positives gives a positive, so safe to 7658 * cast result into s64. 7659 */ 7660 dst_reg->s32_min_value = dst_reg->u32_min_value; 7661 dst_reg->s32_max_value = dst_reg->u32_max_value; 7662 } 7663 } 7664 7665 static void scalar_min_max_or(struct bpf_reg_state *dst_reg, 7666 struct bpf_reg_state *src_reg) 7667 { 7668 bool src_known = tnum_is_const(src_reg->var_off); 7669 bool dst_known = tnum_is_const(dst_reg->var_off); 7670 s64 smin_val = src_reg->smin_value; 7671 u64 umin_val = src_reg->umin_value; 7672 7673 if (src_known && dst_known) { 7674 __mark_reg_known(dst_reg, dst_reg->var_off.value); 7675 return; 7676 } 7677 7678 /* We get our maximum from the var_off, and our minimum is the 7679 * maximum of the operands' minima 7680 */ 7681 dst_reg->umin_value = max(dst_reg->umin_value, umin_val); 7682 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 7683 if (dst_reg->smin_value < 0 || smin_val < 0) { 7684 /* Lose signed bounds when ORing negative numbers, 7685 * ain't nobody got time for that. 7686 */ 7687 dst_reg->smin_value = S64_MIN; 7688 dst_reg->smax_value = S64_MAX; 7689 } else { 7690 /* ORing two positives gives a positive, so safe to 7691 * cast result into s64. 7692 */ 7693 dst_reg->smin_value = dst_reg->umin_value; 7694 dst_reg->smax_value = dst_reg->umax_value; 7695 } 7696 /* We may learn something more from the var_off */ 7697 __update_reg_bounds(dst_reg); 7698 } 7699 7700 static void scalar32_min_max_xor(struct bpf_reg_state *dst_reg, 7701 struct bpf_reg_state *src_reg) 7702 { 7703 bool src_known = tnum_subreg_is_const(src_reg->var_off); 7704 bool dst_known = tnum_subreg_is_const(dst_reg->var_off); 7705 struct tnum var32_off = tnum_subreg(dst_reg->var_off); 7706 s32 smin_val = src_reg->s32_min_value; 7707 7708 if (src_known && dst_known) { 7709 __mark_reg32_known(dst_reg, var32_off.value); 7710 return; 7711 } 7712 7713 /* We get both minimum and maximum from the var32_off. */ 7714 dst_reg->u32_min_value = var32_off.value; 7715 dst_reg->u32_max_value = var32_off.value | var32_off.mask; 7716 7717 if (dst_reg->s32_min_value >= 0 && smin_val >= 0) { 7718 /* XORing two positive sign numbers gives a positive, 7719 * so safe to cast u32 result into s32. 7720 */ 7721 dst_reg->s32_min_value = dst_reg->u32_min_value; 7722 dst_reg->s32_max_value = dst_reg->u32_max_value; 7723 } else { 7724 dst_reg->s32_min_value = S32_MIN; 7725 dst_reg->s32_max_value = S32_MAX; 7726 } 7727 } 7728 7729 static void scalar_min_max_xor(struct bpf_reg_state *dst_reg, 7730 struct bpf_reg_state *src_reg) 7731 { 7732 bool src_known = tnum_is_const(src_reg->var_off); 7733 bool dst_known = tnum_is_const(dst_reg->var_off); 7734 s64 smin_val = src_reg->smin_value; 7735 7736 if (src_known && dst_known) { 7737 /* dst_reg->var_off.value has been updated earlier */ 7738 __mark_reg_known(dst_reg, dst_reg->var_off.value); 7739 return; 7740 } 7741 7742 /* We get both minimum and maximum from the var_off. */ 7743 dst_reg->umin_value = dst_reg->var_off.value; 7744 dst_reg->umax_value = dst_reg->var_off.value | dst_reg->var_off.mask; 7745 7746 if (dst_reg->smin_value >= 0 && smin_val >= 0) { 7747 /* XORing two positive sign numbers gives a positive, 7748 * so safe to cast u64 result into s64. 7749 */ 7750 dst_reg->smin_value = dst_reg->umin_value; 7751 dst_reg->smax_value = dst_reg->umax_value; 7752 } else { 7753 dst_reg->smin_value = S64_MIN; 7754 dst_reg->smax_value = S64_MAX; 7755 } 7756 7757 __update_reg_bounds(dst_reg); 7758 } 7759 7760 static void __scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 7761 u64 umin_val, u64 umax_val) 7762 { 7763 /* We lose all sign bit information (except what we can pick 7764 * up from var_off) 7765 */ 7766 dst_reg->s32_min_value = S32_MIN; 7767 dst_reg->s32_max_value = S32_MAX; 7768 /* If we might shift our top bit out, then we know nothing */ 7769 if (umax_val > 31 || dst_reg->u32_max_value > 1ULL << (31 - umax_val)) { 7770 dst_reg->u32_min_value = 0; 7771 dst_reg->u32_max_value = U32_MAX; 7772 } else { 7773 dst_reg->u32_min_value <<= umin_val; 7774 dst_reg->u32_max_value <<= umax_val; 7775 } 7776 } 7777 7778 static void scalar32_min_max_lsh(struct bpf_reg_state *dst_reg, 7779 struct bpf_reg_state *src_reg) 7780 { 7781 u32 umax_val = src_reg->u32_max_value; 7782 u32 umin_val = src_reg->u32_min_value; 7783 /* u32 alu operation will zext upper bits */ 7784 struct tnum subreg = tnum_subreg(dst_reg->var_off); 7785 7786 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 7787 dst_reg->var_off = tnum_subreg(tnum_lshift(subreg, umin_val)); 7788 /* Not required but being careful mark reg64 bounds as unknown so 7789 * that we are forced to pick them up from tnum and zext later and 7790 * if some path skips this step we are still safe. 7791 */ 7792 __mark_reg64_unbounded(dst_reg); 7793 __update_reg32_bounds(dst_reg); 7794 } 7795 7796 static void __scalar64_min_max_lsh(struct bpf_reg_state *dst_reg, 7797 u64 umin_val, u64 umax_val) 7798 { 7799 /* Special case <<32 because it is a common compiler pattern to sign 7800 * extend subreg by doing <<32 s>>32. In this case if 32bit bounds are 7801 * positive we know this shift will also be positive so we can track 7802 * bounds correctly. Otherwise we lose all sign bit information except 7803 * what we can pick up from var_off. Perhaps we can generalize this 7804 * later to shifts of any length. 7805 */ 7806 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_max_value >= 0) 7807 dst_reg->smax_value = (s64)dst_reg->s32_max_value << 32; 7808 else 7809 dst_reg->smax_value = S64_MAX; 7810 7811 if (umin_val == 32 && umax_val == 32 && dst_reg->s32_min_value >= 0) 7812 dst_reg->smin_value = (s64)dst_reg->s32_min_value << 32; 7813 else 7814 dst_reg->smin_value = S64_MIN; 7815 7816 /* If we might shift our top bit out, then we know nothing */ 7817 if (dst_reg->umax_value > 1ULL << (63 - umax_val)) { 7818 dst_reg->umin_value = 0; 7819 dst_reg->umax_value = U64_MAX; 7820 } else { 7821 dst_reg->umin_value <<= umin_val; 7822 dst_reg->umax_value <<= umax_val; 7823 } 7824 } 7825 7826 static void scalar_min_max_lsh(struct bpf_reg_state *dst_reg, 7827 struct bpf_reg_state *src_reg) 7828 { 7829 u64 umax_val = src_reg->umax_value; 7830 u64 umin_val = src_reg->umin_value; 7831 7832 /* scalar64 calc uses 32bit unshifted bounds so must be called first */ 7833 __scalar64_min_max_lsh(dst_reg, umin_val, umax_val); 7834 __scalar32_min_max_lsh(dst_reg, umin_val, umax_val); 7835 7836 dst_reg->var_off = tnum_lshift(dst_reg->var_off, umin_val); 7837 /* We may learn something more from the var_off */ 7838 __update_reg_bounds(dst_reg); 7839 } 7840 7841 static void scalar32_min_max_rsh(struct bpf_reg_state *dst_reg, 7842 struct bpf_reg_state *src_reg) 7843 { 7844 struct tnum subreg = tnum_subreg(dst_reg->var_off); 7845 u32 umax_val = src_reg->u32_max_value; 7846 u32 umin_val = src_reg->u32_min_value; 7847 7848 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 7849 * be negative, then either: 7850 * 1) src_reg might be zero, so the sign bit of the result is 7851 * unknown, so we lose our signed bounds 7852 * 2) it's known negative, thus the unsigned bounds capture the 7853 * signed bounds 7854 * 3) the signed bounds cross zero, so they tell us nothing 7855 * about the result 7856 * If the value in dst_reg is known nonnegative, then again the 7857 * unsigned bounds capture the signed bounds. 7858 * Thus, in all cases it suffices to blow away our signed bounds 7859 * and rely on inferring new ones from the unsigned bounds and 7860 * var_off of the result. 7861 */ 7862 dst_reg->s32_min_value = S32_MIN; 7863 dst_reg->s32_max_value = S32_MAX; 7864 7865 dst_reg->var_off = tnum_rshift(subreg, umin_val); 7866 dst_reg->u32_min_value >>= umax_val; 7867 dst_reg->u32_max_value >>= umin_val; 7868 7869 __mark_reg64_unbounded(dst_reg); 7870 __update_reg32_bounds(dst_reg); 7871 } 7872 7873 static void scalar_min_max_rsh(struct bpf_reg_state *dst_reg, 7874 struct bpf_reg_state *src_reg) 7875 { 7876 u64 umax_val = src_reg->umax_value; 7877 u64 umin_val = src_reg->umin_value; 7878 7879 /* BPF_RSH is an unsigned shift. If the value in dst_reg might 7880 * be negative, then either: 7881 * 1) src_reg might be zero, so the sign bit of the result is 7882 * unknown, so we lose our signed bounds 7883 * 2) it's known negative, thus the unsigned bounds capture the 7884 * signed bounds 7885 * 3) the signed bounds cross zero, so they tell us nothing 7886 * about the result 7887 * If the value in dst_reg is known nonnegative, then again the 7888 * unsigned bounds capture the signed bounds. 7889 * Thus, in all cases it suffices to blow away our signed bounds 7890 * and rely on inferring new ones from the unsigned bounds and 7891 * var_off of the result. 7892 */ 7893 dst_reg->smin_value = S64_MIN; 7894 dst_reg->smax_value = S64_MAX; 7895 dst_reg->var_off = tnum_rshift(dst_reg->var_off, umin_val); 7896 dst_reg->umin_value >>= umax_val; 7897 dst_reg->umax_value >>= umin_val; 7898 7899 /* Its not easy to operate on alu32 bounds here because it depends 7900 * on bits being shifted in. Take easy way out and mark unbounded 7901 * so we can recalculate later from tnum. 7902 */ 7903 __mark_reg32_unbounded(dst_reg); 7904 __update_reg_bounds(dst_reg); 7905 } 7906 7907 static void scalar32_min_max_arsh(struct bpf_reg_state *dst_reg, 7908 struct bpf_reg_state *src_reg) 7909 { 7910 u64 umin_val = src_reg->u32_min_value; 7911 7912 /* Upon reaching here, src_known is true and 7913 * umax_val is equal to umin_val. 7914 */ 7915 dst_reg->s32_min_value = (u32)(((s32)dst_reg->s32_min_value) >> umin_val); 7916 dst_reg->s32_max_value = (u32)(((s32)dst_reg->s32_max_value) >> umin_val); 7917 7918 dst_reg->var_off = tnum_arshift(tnum_subreg(dst_reg->var_off), umin_val, 32); 7919 7920 /* blow away the dst_reg umin_value/umax_value and rely on 7921 * dst_reg var_off to refine the result. 7922 */ 7923 dst_reg->u32_min_value = 0; 7924 dst_reg->u32_max_value = U32_MAX; 7925 7926 __mark_reg64_unbounded(dst_reg); 7927 __update_reg32_bounds(dst_reg); 7928 } 7929 7930 static void scalar_min_max_arsh(struct bpf_reg_state *dst_reg, 7931 struct bpf_reg_state *src_reg) 7932 { 7933 u64 umin_val = src_reg->umin_value; 7934 7935 /* Upon reaching here, src_known is true and umax_val is equal 7936 * to umin_val. 7937 */ 7938 dst_reg->smin_value >>= umin_val; 7939 dst_reg->smax_value >>= umin_val; 7940 7941 dst_reg->var_off = tnum_arshift(dst_reg->var_off, umin_val, 64); 7942 7943 /* blow away the dst_reg umin_value/umax_value and rely on 7944 * dst_reg var_off to refine the result. 7945 */ 7946 dst_reg->umin_value = 0; 7947 dst_reg->umax_value = U64_MAX; 7948 7949 /* Its not easy to operate on alu32 bounds here because it depends 7950 * on bits being shifted in from upper 32-bits. Take easy way out 7951 * and mark unbounded so we can recalculate later from tnum. 7952 */ 7953 __mark_reg32_unbounded(dst_reg); 7954 __update_reg_bounds(dst_reg); 7955 } 7956 7957 /* WARNING: This function does calculations on 64-bit values, but the actual 7958 * execution may occur on 32-bit values. Therefore, things like bitshifts 7959 * need extra checks in the 32-bit case. 7960 */ 7961 static int adjust_scalar_min_max_vals(struct bpf_verifier_env *env, 7962 struct bpf_insn *insn, 7963 struct bpf_reg_state *dst_reg, 7964 struct bpf_reg_state src_reg) 7965 { 7966 struct bpf_reg_state *regs = cur_regs(env); 7967 u8 opcode = BPF_OP(insn->code); 7968 bool src_known; 7969 s64 smin_val, smax_val; 7970 u64 umin_val, umax_val; 7971 s32 s32_min_val, s32_max_val; 7972 u32 u32_min_val, u32_max_val; 7973 u64 insn_bitness = (BPF_CLASS(insn->code) == BPF_ALU64) ? 64 : 32; 7974 bool alu32 = (BPF_CLASS(insn->code) != BPF_ALU64); 7975 int ret; 7976 7977 smin_val = src_reg.smin_value; 7978 smax_val = src_reg.smax_value; 7979 umin_val = src_reg.umin_value; 7980 umax_val = src_reg.umax_value; 7981 7982 s32_min_val = src_reg.s32_min_value; 7983 s32_max_val = src_reg.s32_max_value; 7984 u32_min_val = src_reg.u32_min_value; 7985 u32_max_val = src_reg.u32_max_value; 7986 7987 if (alu32) { 7988 src_known = tnum_subreg_is_const(src_reg.var_off); 7989 if ((src_known && 7990 (s32_min_val != s32_max_val || u32_min_val != u32_max_val)) || 7991 s32_min_val > s32_max_val || u32_min_val > u32_max_val) { 7992 /* Taint dst register if offset had invalid bounds 7993 * derived from e.g. dead branches. 7994 */ 7995 __mark_reg_unknown(env, dst_reg); 7996 return 0; 7997 } 7998 } else { 7999 src_known = tnum_is_const(src_reg.var_off); 8000 if ((src_known && 8001 (smin_val != smax_val || umin_val != umax_val)) || 8002 smin_val > smax_val || umin_val > umax_val) { 8003 /* Taint dst register if offset had invalid bounds 8004 * derived from e.g. dead branches. 8005 */ 8006 __mark_reg_unknown(env, dst_reg); 8007 return 0; 8008 } 8009 } 8010 8011 if (!src_known && 8012 opcode != BPF_ADD && opcode != BPF_SUB && opcode != BPF_AND) { 8013 __mark_reg_unknown(env, dst_reg); 8014 return 0; 8015 } 8016 8017 if (sanitize_needed(opcode)) { 8018 ret = sanitize_val_alu(env, insn); 8019 if (ret < 0) 8020 return sanitize_err(env, insn, ret, NULL, NULL); 8021 } 8022 8023 /* Calculate sign/unsigned bounds and tnum for alu32 and alu64 bit ops. 8024 * There are two classes of instructions: The first class we track both 8025 * alu32 and alu64 sign/unsigned bounds independently this provides the 8026 * greatest amount of precision when alu operations are mixed with jmp32 8027 * operations. These operations are BPF_ADD, BPF_SUB, BPF_MUL, BPF_ADD, 8028 * and BPF_OR. This is possible because these ops have fairly easy to 8029 * understand and calculate behavior in both 32-bit and 64-bit alu ops. 8030 * See alu32 verifier tests for examples. The second class of 8031 * operations, BPF_LSH, BPF_RSH, and BPF_ARSH, however are not so easy 8032 * with regards to tracking sign/unsigned bounds because the bits may 8033 * cross subreg boundaries in the alu64 case. When this happens we mark 8034 * the reg unbounded in the subreg bound space and use the resulting 8035 * tnum to calculate an approximation of the sign/unsigned bounds. 8036 */ 8037 switch (opcode) { 8038 case BPF_ADD: 8039 scalar32_min_max_add(dst_reg, &src_reg); 8040 scalar_min_max_add(dst_reg, &src_reg); 8041 dst_reg->var_off = tnum_add(dst_reg->var_off, src_reg.var_off); 8042 break; 8043 case BPF_SUB: 8044 scalar32_min_max_sub(dst_reg, &src_reg); 8045 scalar_min_max_sub(dst_reg, &src_reg); 8046 dst_reg->var_off = tnum_sub(dst_reg->var_off, src_reg.var_off); 8047 break; 8048 case BPF_MUL: 8049 dst_reg->var_off = tnum_mul(dst_reg->var_off, src_reg.var_off); 8050 scalar32_min_max_mul(dst_reg, &src_reg); 8051 scalar_min_max_mul(dst_reg, &src_reg); 8052 break; 8053 case BPF_AND: 8054 dst_reg->var_off = tnum_and(dst_reg->var_off, src_reg.var_off); 8055 scalar32_min_max_and(dst_reg, &src_reg); 8056 scalar_min_max_and(dst_reg, &src_reg); 8057 break; 8058 case BPF_OR: 8059 dst_reg->var_off = tnum_or(dst_reg->var_off, src_reg.var_off); 8060 scalar32_min_max_or(dst_reg, &src_reg); 8061 scalar_min_max_or(dst_reg, &src_reg); 8062 break; 8063 case BPF_XOR: 8064 dst_reg->var_off = tnum_xor(dst_reg->var_off, src_reg.var_off); 8065 scalar32_min_max_xor(dst_reg, &src_reg); 8066 scalar_min_max_xor(dst_reg, &src_reg); 8067 break; 8068 case BPF_LSH: 8069 if (umax_val >= insn_bitness) { 8070 /* Shifts greater than 31 or 63 are undefined. 8071 * This includes shifts by a negative number. 8072 */ 8073 mark_reg_unknown(env, regs, insn->dst_reg); 8074 break; 8075 } 8076 if (alu32) 8077 scalar32_min_max_lsh(dst_reg, &src_reg); 8078 else 8079 scalar_min_max_lsh(dst_reg, &src_reg); 8080 break; 8081 case BPF_RSH: 8082 if (umax_val >= insn_bitness) { 8083 /* Shifts greater than 31 or 63 are undefined. 8084 * This includes shifts by a negative number. 8085 */ 8086 mark_reg_unknown(env, regs, insn->dst_reg); 8087 break; 8088 } 8089 if (alu32) 8090 scalar32_min_max_rsh(dst_reg, &src_reg); 8091 else 8092 scalar_min_max_rsh(dst_reg, &src_reg); 8093 break; 8094 case BPF_ARSH: 8095 if (umax_val >= insn_bitness) { 8096 /* Shifts greater than 31 or 63 are undefined. 8097 * This includes shifts by a negative number. 8098 */ 8099 mark_reg_unknown(env, regs, insn->dst_reg); 8100 break; 8101 } 8102 if (alu32) 8103 scalar32_min_max_arsh(dst_reg, &src_reg); 8104 else 8105 scalar_min_max_arsh(dst_reg, &src_reg); 8106 break; 8107 default: 8108 mark_reg_unknown(env, regs, insn->dst_reg); 8109 break; 8110 } 8111 8112 /* ALU32 ops are zero extended into 64bit register */ 8113 if (alu32) 8114 zext_32_to_64(dst_reg); 8115 8116 __update_reg_bounds(dst_reg); 8117 __reg_deduce_bounds(dst_reg); 8118 __reg_bound_offset(dst_reg); 8119 return 0; 8120 } 8121 8122 /* Handles ALU ops other than BPF_END, BPF_NEG and BPF_MOV: computes new min/max 8123 * and var_off. 8124 */ 8125 static int adjust_reg_min_max_vals(struct bpf_verifier_env *env, 8126 struct bpf_insn *insn) 8127 { 8128 struct bpf_verifier_state *vstate = env->cur_state; 8129 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 8130 struct bpf_reg_state *regs = state->regs, *dst_reg, *src_reg; 8131 struct bpf_reg_state *ptr_reg = NULL, off_reg = {0}; 8132 u8 opcode = BPF_OP(insn->code); 8133 int err; 8134 8135 dst_reg = ®s[insn->dst_reg]; 8136 src_reg = NULL; 8137 if (dst_reg->type != SCALAR_VALUE) 8138 ptr_reg = dst_reg; 8139 else 8140 /* Make sure ID is cleared otherwise dst_reg min/max could be 8141 * incorrectly propagated into other registers by find_equal_scalars() 8142 */ 8143 dst_reg->id = 0; 8144 if (BPF_SRC(insn->code) == BPF_X) { 8145 src_reg = ®s[insn->src_reg]; 8146 if (src_reg->type != SCALAR_VALUE) { 8147 if (dst_reg->type != SCALAR_VALUE) { 8148 /* Combining two pointers by any ALU op yields 8149 * an arbitrary scalar. Disallow all math except 8150 * pointer subtraction 8151 */ 8152 if (opcode == BPF_SUB && env->allow_ptr_leaks) { 8153 mark_reg_unknown(env, regs, insn->dst_reg); 8154 return 0; 8155 } 8156 verbose(env, "R%d pointer %s pointer prohibited\n", 8157 insn->dst_reg, 8158 bpf_alu_string[opcode >> 4]); 8159 return -EACCES; 8160 } else { 8161 /* scalar += pointer 8162 * This is legal, but we have to reverse our 8163 * src/dest handling in computing the range 8164 */ 8165 err = mark_chain_precision(env, insn->dst_reg); 8166 if (err) 8167 return err; 8168 return adjust_ptr_min_max_vals(env, insn, 8169 src_reg, dst_reg); 8170 } 8171 } else if (ptr_reg) { 8172 /* pointer += scalar */ 8173 err = mark_chain_precision(env, insn->src_reg); 8174 if (err) 8175 return err; 8176 return adjust_ptr_min_max_vals(env, insn, 8177 dst_reg, src_reg); 8178 } 8179 } else { 8180 /* Pretend the src is a reg with a known value, since we only 8181 * need to be able to read from this state. 8182 */ 8183 off_reg.type = SCALAR_VALUE; 8184 __mark_reg_known(&off_reg, insn->imm); 8185 src_reg = &off_reg; 8186 if (ptr_reg) /* pointer += K */ 8187 return adjust_ptr_min_max_vals(env, insn, 8188 ptr_reg, src_reg); 8189 } 8190 8191 /* Got here implies adding two SCALAR_VALUEs */ 8192 if (WARN_ON_ONCE(ptr_reg)) { 8193 print_verifier_state(env, state); 8194 verbose(env, "verifier internal error: unexpected ptr_reg\n"); 8195 return -EINVAL; 8196 } 8197 if (WARN_ON(!src_reg)) { 8198 print_verifier_state(env, state); 8199 verbose(env, "verifier internal error: no src_reg\n"); 8200 return -EINVAL; 8201 } 8202 return adjust_scalar_min_max_vals(env, insn, dst_reg, *src_reg); 8203 } 8204 8205 /* check validity of 32-bit and 64-bit arithmetic operations */ 8206 static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) 8207 { 8208 struct bpf_reg_state *regs = cur_regs(env); 8209 u8 opcode = BPF_OP(insn->code); 8210 int err; 8211 8212 if (opcode == BPF_END || opcode == BPF_NEG) { 8213 if (opcode == BPF_NEG) { 8214 if (BPF_SRC(insn->code) != 0 || 8215 insn->src_reg != BPF_REG_0 || 8216 insn->off != 0 || insn->imm != 0) { 8217 verbose(env, "BPF_NEG uses reserved fields\n"); 8218 return -EINVAL; 8219 } 8220 } else { 8221 if (insn->src_reg != BPF_REG_0 || insn->off != 0 || 8222 (insn->imm != 16 && insn->imm != 32 && insn->imm != 64) || 8223 BPF_CLASS(insn->code) == BPF_ALU64) { 8224 verbose(env, "BPF_END uses reserved fields\n"); 8225 return -EINVAL; 8226 } 8227 } 8228 8229 /* check src operand */ 8230 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8231 if (err) 8232 return err; 8233 8234 if (is_pointer_value(env, insn->dst_reg)) { 8235 verbose(env, "R%d pointer arithmetic prohibited\n", 8236 insn->dst_reg); 8237 return -EACCES; 8238 } 8239 8240 /* check dest operand */ 8241 err = check_reg_arg(env, insn->dst_reg, DST_OP); 8242 if (err) 8243 return err; 8244 8245 } else if (opcode == BPF_MOV) { 8246 8247 if (BPF_SRC(insn->code) == BPF_X) { 8248 if (insn->imm != 0 || insn->off != 0) { 8249 verbose(env, "BPF_MOV uses reserved fields\n"); 8250 return -EINVAL; 8251 } 8252 8253 /* check src operand */ 8254 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8255 if (err) 8256 return err; 8257 } else { 8258 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 8259 verbose(env, "BPF_MOV uses reserved fields\n"); 8260 return -EINVAL; 8261 } 8262 } 8263 8264 /* check dest operand, mark as required later */ 8265 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 8266 if (err) 8267 return err; 8268 8269 if (BPF_SRC(insn->code) == BPF_X) { 8270 struct bpf_reg_state *src_reg = regs + insn->src_reg; 8271 struct bpf_reg_state *dst_reg = regs + insn->dst_reg; 8272 8273 if (BPF_CLASS(insn->code) == BPF_ALU64) { 8274 /* case: R1 = R2 8275 * copy register state to dest reg 8276 */ 8277 if (src_reg->type == SCALAR_VALUE && !src_reg->id) 8278 /* Assign src and dst registers the same ID 8279 * that will be used by find_equal_scalars() 8280 * to propagate min/max range. 8281 */ 8282 src_reg->id = ++env->id_gen; 8283 *dst_reg = *src_reg; 8284 dst_reg->live |= REG_LIVE_WRITTEN; 8285 dst_reg->subreg_def = DEF_NOT_SUBREG; 8286 } else { 8287 /* R1 = (u32) R2 */ 8288 if (is_pointer_value(env, insn->src_reg)) { 8289 verbose(env, 8290 "R%d partial copy of pointer\n", 8291 insn->src_reg); 8292 return -EACCES; 8293 } else if (src_reg->type == SCALAR_VALUE) { 8294 *dst_reg = *src_reg; 8295 /* Make sure ID is cleared otherwise 8296 * dst_reg min/max could be incorrectly 8297 * propagated into src_reg by find_equal_scalars() 8298 */ 8299 dst_reg->id = 0; 8300 dst_reg->live |= REG_LIVE_WRITTEN; 8301 dst_reg->subreg_def = env->insn_idx + 1; 8302 } else { 8303 mark_reg_unknown(env, regs, 8304 insn->dst_reg); 8305 } 8306 zext_32_to_64(dst_reg); 8307 } 8308 } else { 8309 /* case: R = imm 8310 * remember the value we stored into this reg 8311 */ 8312 /* clear any state __mark_reg_known doesn't set */ 8313 mark_reg_unknown(env, regs, insn->dst_reg); 8314 regs[insn->dst_reg].type = SCALAR_VALUE; 8315 if (BPF_CLASS(insn->code) == BPF_ALU64) { 8316 __mark_reg_known(regs + insn->dst_reg, 8317 insn->imm); 8318 } else { 8319 __mark_reg_known(regs + insn->dst_reg, 8320 (u32)insn->imm); 8321 } 8322 } 8323 8324 } else if (opcode > BPF_END) { 8325 verbose(env, "invalid BPF_ALU opcode %x\n", opcode); 8326 return -EINVAL; 8327 8328 } else { /* all other ALU ops: and, sub, xor, add, ... */ 8329 8330 if (BPF_SRC(insn->code) == BPF_X) { 8331 if (insn->imm != 0 || insn->off != 0) { 8332 verbose(env, "BPF_ALU uses reserved fields\n"); 8333 return -EINVAL; 8334 } 8335 /* check src1 operand */ 8336 err = check_reg_arg(env, insn->src_reg, SRC_OP); 8337 if (err) 8338 return err; 8339 } else { 8340 if (insn->src_reg != BPF_REG_0 || insn->off != 0) { 8341 verbose(env, "BPF_ALU uses reserved fields\n"); 8342 return -EINVAL; 8343 } 8344 } 8345 8346 /* check src2 operand */ 8347 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 8348 if (err) 8349 return err; 8350 8351 if ((opcode == BPF_MOD || opcode == BPF_DIV) && 8352 BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { 8353 verbose(env, "div by zero\n"); 8354 return -EINVAL; 8355 } 8356 8357 if ((opcode == BPF_LSH || opcode == BPF_RSH || 8358 opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { 8359 int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; 8360 8361 if (insn->imm < 0 || insn->imm >= size) { 8362 verbose(env, "invalid shift %d\n", insn->imm); 8363 return -EINVAL; 8364 } 8365 } 8366 8367 /* check dest operand */ 8368 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 8369 if (err) 8370 return err; 8371 8372 return adjust_reg_min_max_vals(env, insn); 8373 } 8374 8375 return 0; 8376 } 8377 8378 static void __find_good_pkt_pointers(struct bpf_func_state *state, 8379 struct bpf_reg_state *dst_reg, 8380 enum bpf_reg_type type, int new_range) 8381 { 8382 struct bpf_reg_state *reg; 8383 int i; 8384 8385 for (i = 0; i < MAX_BPF_REG; i++) { 8386 reg = &state->regs[i]; 8387 if (reg->type == type && reg->id == dst_reg->id) 8388 /* keep the maximum range already checked */ 8389 reg->range = max(reg->range, new_range); 8390 } 8391 8392 bpf_for_each_spilled_reg(i, state, reg) { 8393 if (!reg) 8394 continue; 8395 if (reg->type == type && reg->id == dst_reg->id) 8396 reg->range = max(reg->range, new_range); 8397 } 8398 } 8399 8400 static void find_good_pkt_pointers(struct bpf_verifier_state *vstate, 8401 struct bpf_reg_state *dst_reg, 8402 enum bpf_reg_type type, 8403 bool range_right_open) 8404 { 8405 int new_range, i; 8406 8407 if (dst_reg->off < 0 || 8408 (dst_reg->off == 0 && range_right_open)) 8409 /* This doesn't give us any range */ 8410 return; 8411 8412 if (dst_reg->umax_value > MAX_PACKET_OFF || 8413 dst_reg->umax_value + dst_reg->off > MAX_PACKET_OFF) 8414 /* Risk of overflow. For instance, ptr + (1<<63) may be less 8415 * than pkt_end, but that's because it's also less than pkt. 8416 */ 8417 return; 8418 8419 new_range = dst_reg->off; 8420 if (range_right_open) 8421 new_range--; 8422 8423 /* Examples for register markings: 8424 * 8425 * pkt_data in dst register: 8426 * 8427 * r2 = r3; 8428 * r2 += 8; 8429 * if (r2 > pkt_end) goto <handle exception> 8430 * <access okay> 8431 * 8432 * r2 = r3; 8433 * r2 += 8; 8434 * if (r2 < pkt_end) goto <access okay> 8435 * <handle exception> 8436 * 8437 * Where: 8438 * r2 == dst_reg, pkt_end == src_reg 8439 * r2=pkt(id=n,off=8,r=0) 8440 * r3=pkt(id=n,off=0,r=0) 8441 * 8442 * pkt_data in src register: 8443 * 8444 * r2 = r3; 8445 * r2 += 8; 8446 * if (pkt_end >= r2) goto <access okay> 8447 * <handle exception> 8448 * 8449 * r2 = r3; 8450 * r2 += 8; 8451 * if (pkt_end <= r2) goto <handle exception> 8452 * <access okay> 8453 * 8454 * Where: 8455 * pkt_end == dst_reg, r2 == src_reg 8456 * r2=pkt(id=n,off=8,r=0) 8457 * r3=pkt(id=n,off=0,r=0) 8458 * 8459 * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) 8460 * or r3=pkt(id=n,off=0,r=8-1), so that range of bytes [r3, r3 + 8) 8461 * and [r3, r3 + 8-1) respectively is safe to access depending on 8462 * the check. 8463 */ 8464 8465 /* If our ids match, then we must have the same max_value. And we 8466 * don't care about the other reg's fixed offset, since if it's too big 8467 * the range won't allow anything. 8468 * dst_reg->off is known < MAX_PACKET_OFF, therefore it fits in a u16. 8469 */ 8470 for (i = 0; i <= vstate->curframe; i++) 8471 __find_good_pkt_pointers(vstate->frame[i], dst_reg, type, 8472 new_range); 8473 } 8474 8475 static int is_branch32_taken(struct bpf_reg_state *reg, u32 val, u8 opcode) 8476 { 8477 struct tnum subreg = tnum_subreg(reg->var_off); 8478 s32 sval = (s32)val; 8479 8480 switch (opcode) { 8481 case BPF_JEQ: 8482 if (tnum_is_const(subreg)) 8483 return !!tnum_equals_const(subreg, val); 8484 break; 8485 case BPF_JNE: 8486 if (tnum_is_const(subreg)) 8487 return !tnum_equals_const(subreg, val); 8488 break; 8489 case BPF_JSET: 8490 if ((~subreg.mask & subreg.value) & val) 8491 return 1; 8492 if (!((subreg.mask | subreg.value) & val)) 8493 return 0; 8494 break; 8495 case BPF_JGT: 8496 if (reg->u32_min_value > val) 8497 return 1; 8498 else if (reg->u32_max_value <= val) 8499 return 0; 8500 break; 8501 case BPF_JSGT: 8502 if (reg->s32_min_value > sval) 8503 return 1; 8504 else if (reg->s32_max_value <= sval) 8505 return 0; 8506 break; 8507 case BPF_JLT: 8508 if (reg->u32_max_value < val) 8509 return 1; 8510 else if (reg->u32_min_value >= val) 8511 return 0; 8512 break; 8513 case BPF_JSLT: 8514 if (reg->s32_max_value < sval) 8515 return 1; 8516 else if (reg->s32_min_value >= sval) 8517 return 0; 8518 break; 8519 case BPF_JGE: 8520 if (reg->u32_min_value >= val) 8521 return 1; 8522 else if (reg->u32_max_value < val) 8523 return 0; 8524 break; 8525 case BPF_JSGE: 8526 if (reg->s32_min_value >= sval) 8527 return 1; 8528 else if (reg->s32_max_value < sval) 8529 return 0; 8530 break; 8531 case BPF_JLE: 8532 if (reg->u32_max_value <= val) 8533 return 1; 8534 else if (reg->u32_min_value > val) 8535 return 0; 8536 break; 8537 case BPF_JSLE: 8538 if (reg->s32_max_value <= sval) 8539 return 1; 8540 else if (reg->s32_min_value > sval) 8541 return 0; 8542 break; 8543 } 8544 8545 return -1; 8546 } 8547 8548 8549 static int is_branch64_taken(struct bpf_reg_state *reg, u64 val, u8 opcode) 8550 { 8551 s64 sval = (s64)val; 8552 8553 switch (opcode) { 8554 case BPF_JEQ: 8555 if (tnum_is_const(reg->var_off)) 8556 return !!tnum_equals_const(reg->var_off, val); 8557 break; 8558 case BPF_JNE: 8559 if (tnum_is_const(reg->var_off)) 8560 return !tnum_equals_const(reg->var_off, val); 8561 break; 8562 case BPF_JSET: 8563 if ((~reg->var_off.mask & reg->var_off.value) & val) 8564 return 1; 8565 if (!((reg->var_off.mask | reg->var_off.value) & val)) 8566 return 0; 8567 break; 8568 case BPF_JGT: 8569 if (reg->umin_value > val) 8570 return 1; 8571 else if (reg->umax_value <= val) 8572 return 0; 8573 break; 8574 case BPF_JSGT: 8575 if (reg->smin_value > sval) 8576 return 1; 8577 else if (reg->smax_value <= sval) 8578 return 0; 8579 break; 8580 case BPF_JLT: 8581 if (reg->umax_value < val) 8582 return 1; 8583 else if (reg->umin_value >= val) 8584 return 0; 8585 break; 8586 case BPF_JSLT: 8587 if (reg->smax_value < sval) 8588 return 1; 8589 else if (reg->smin_value >= sval) 8590 return 0; 8591 break; 8592 case BPF_JGE: 8593 if (reg->umin_value >= val) 8594 return 1; 8595 else if (reg->umax_value < val) 8596 return 0; 8597 break; 8598 case BPF_JSGE: 8599 if (reg->smin_value >= sval) 8600 return 1; 8601 else if (reg->smax_value < sval) 8602 return 0; 8603 break; 8604 case BPF_JLE: 8605 if (reg->umax_value <= val) 8606 return 1; 8607 else if (reg->umin_value > val) 8608 return 0; 8609 break; 8610 case BPF_JSLE: 8611 if (reg->smax_value <= sval) 8612 return 1; 8613 else if (reg->smin_value > sval) 8614 return 0; 8615 break; 8616 } 8617 8618 return -1; 8619 } 8620 8621 /* compute branch direction of the expression "if (reg opcode val) goto target;" 8622 * and return: 8623 * 1 - branch will be taken and "goto target" will be executed 8624 * 0 - branch will not be taken and fall-through to next insn 8625 * -1 - unknown. Example: "if (reg < 5)" is unknown when register value 8626 * range [0,10] 8627 */ 8628 static int is_branch_taken(struct bpf_reg_state *reg, u64 val, u8 opcode, 8629 bool is_jmp32) 8630 { 8631 if (__is_pointer_value(false, reg)) { 8632 if (!reg_type_not_null(reg->type)) 8633 return -1; 8634 8635 /* If pointer is valid tests against zero will fail so we can 8636 * use this to direct branch taken. 8637 */ 8638 if (val != 0) 8639 return -1; 8640 8641 switch (opcode) { 8642 case BPF_JEQ: 8643 return 0; 8644 case BPF_JNE: 8645 return 1; 8646 default: 8647 return -1; 8648 } 8649 } 8650 8651 if (is_jmp32) 8652 return is_branch32_taken(reg, val, opcode); 8653 return is_branch64_taken(reg, val, opcode); 8654 } 8655 8656 static int flip_opcode(u32 opcode) 8657 { 8658 /* How can we transform "a <op> b" into "b <op> a"? */ 8659 static const u8 opcode_flip[16] = { 8660 /* these stay the same */ 8661 [BPF_JEQ >> 4] = BPF_JEQ, 8662 [BPF_JNE >> 4] = BPF_JNE, 8663 [BPF_JSET >> 4] = BPF_JSET, 8664 /* these swap "lesser" and "greater" (L and G in the opcodes) */ 8665 [BPF_JGE >> 4] = BPF_JLE, 8666 [BPF_JGT >> 4] = BPF_JLT, 8667 [BPF_JLE >> 4] = BPF_JGE, 8668 [BPF_JLT >> 4] = BPF_JGT, 8669 [BPF_JSGE >> 4] = BPF_JSLE, 8670 [BPF_JSGT >> 4] = BPF_JSLT, 8671 [BPF_JSLE >> 4] = BPF_JSGE, 8672 [BPF_JSLT >> 4] = BPF_JSGT 8673 }; 8674 return opcode_flip[opcode >> 4]; 8675 } 8676 8677 static int is_pkt_ptr_branch_taken(struct bpf_reg_state *dst_reg, 8678 struct bpf_reg_state *src_reg, 8679 u8 opcode) 8680 { 8681 struct bpf_reg_state *pkt; 8682 8683 if (src_reg->type == PTR_TO_PACKET_END) { 8684 pkt = dst_reg; 8685 } else if (dst_reg->type == PTR_TO_PACKET_END) { 8686 pkt = src_reg; 8687 opcode = flip_opcode(opcode); 8688 } else { 8689 return -1; 8690 } 8691 8692 if (pkt->range >= 0) 8693 return -1; 8694 8695 switch (opcode) { 8696 case BPF_JLE: 8697 /* pkt <= pkt_end */ 8698 fallthrough; 8699 case BPF_JGT: 8700 /* pkt > pkt_end */ 8701 if (pkt->range == BEYOND_PKT_END) 8702 /* pkt has at last one extra byte beyond pkt_end */ 8703 return opcode == BPF_JGT; 8704 break; 8705 case BPF_JLT: 8706 /* pkt < pkt_end */ 8707 fallthrough; 8708 case BPF_JGE: 8709 /* pkt >= pkt_end */ 8710 if (pkt->range == BEYOND_PKT_END || pkt->range == AT_PKT_END) 8711 return opcode == BPF_JGE; 8712 break; 8713 } 8714 return -1; 8715 } 8716 8717 /* Adjusts the register min/max values in the case that the dst_reg is the 8718 * variable register that we are working on, and src_reg is a constant or we're 8719 * simply doing a BPF_K check. 8720 * In JEQ/JNE cases we also adjust the var_off values. 8721 */ 8722 static void reg_set_min_max(struct bpf_reg_state *true_reg, 8723 struct bpf_reg_state *false_reg, 8724 u64 val, u32 val32, 8725 u8 opcode, bool is_jmp32) 8726 { 8727 struct tnum false_32off = tnum_subreg(false_reg->var_off); 8728 struct tnum false_64off = false_reg->var_off; 8729 struct tnum true_32off = tnum_subreg(true_reg->var_off); 8730 struct tnum true_64off = true_reg->var_off; 8731 s64 sval = (s64)val; 8732 s32 sval32 = (s32)val32; 8733 8734 /* If the dst_reg is a pointer, we can't learn anything about its 8735 * variable offset from the compare (unless src_reg were a pointer into 8736 * the same object, but we don't bother with that. 8737 * Since false_reg and true_reg have the same type by construction, we 8738 * only need to check one of them for pointerness. 8739 */ 8740 if (__is_pointer_value(false, false_reg)) 8741 return; 8742 8743 switch (opcode) { 8744 case BPF_JEQ: 8745 case BPF_JNE: 8746 { 8747 struct bpf_reg_state *reg = 8748 opcode == BPF_JEQ ? true_reg : false_reg; 8749 8750 /* JEQ/JNE comparison doesn't change the register equivalence. 8751 * r1 = r2; 8752 * if (r1 == 42) goto label; 8753 * ... 8754 * label: // here both r1 and r2 are known to be 42. 8755 * 8756 * Hence when marking register as known preserve it's ID. 8757 */ 8758 if (is_jmp32) 8759 __mark_reg32_known(reg, val32); 8760 else 8761 ___mark_reg_known(reg, val); 8762 break; 8763 } 8764 case BPF_JSET: 8765 if (is_jmp32) { 8766 false_32off = tnum_and(false_32off, tnum_const(~val32)); 8767 if (is_power_of_2(val32)) 8768 true_32off = tnum_or(true_32off, 8769 tnum_const(val32)); 8770 } else { 8771 false_64off = tnum_and(false_64off, tnum_const(~val)); 8772 if (is_power_of_2(val)) 8773 true_64off = tnum_or(true_64off, 8774 tnum_const(val)); 8775 } 8776 break; 8777 case BPF_JGE: 8778 case BPF_JGT: 8779 { 8780 if (is_jmp32) { 8781 u32 false_umax = opcode == BPF_JGT ? val32 : val32 - 1; 8782 u32 true_umin = opcode == BPF_JGT ? val32 + 1 : val32; 8783 8784 false_reg->u32_max_value = min(false_reg->u32_max_value, 8785 false_umax); 8786 true_reg->u32_min_value = max(true_reg->u32_min_value, 8787 true_umin); 8788 } else { 8789 u64 false_umax = opcode == BPF_JGT ? val : val - 1; 8790 u64 true_umin = opcode == BPF_JGT ? val + 1 : val; 8791 8792 false_reg->umax_value = min(false_reg->umax_value, false_umax); 8793 true_reg->umin_value = max(true_reg->umin_value, true_umin); 8794 } 8795 break; 8796 } 8797 case BPF_JSGE: 8798 case BPF_JSGT: 8799 { 8800 if (is_jmp32) { 8801 s32 false_smax = opcode == BPF_JSGT ? sval32 : sval32 - 1; 8802 s32 true_smin = opcode == BPF_JSGT ? sval32 + 1 : sval32; 8803 8804 false_reg->s32_max_value = min(false_reg->s32_max_value, false_smax); 8805 true_reg->s32_min_value = max(true_reg->s32_min_value, true_smin); 8806 } else { 8807 s64 false_smax = opcode == BPF_JSGT ? sval : sval - 1; 8808 s64 true_smin = opcode == BPF_JSGT ? sval + 1 : sval; 8809 8810 false_reg->smax_value = min(false_reg->smax_value, false_smax); 8811 true_reg->smin_value = max(true_reg->smin_value, true_smin); 8812 } 8813 break; 8814 } 8815 case BPF_JLE: 8816 case BPF_JLT: 8817 { 8818 if (is_jmp32) { 8819 u32 false_umin = opcode == BPF_JLT ? val32 : val32 + 1; 8820 u32 true_umax = opcode == BPF_JLT ? val32 - 1 : val32; 8821 8822 false_reg->u32_min_value = max(false_reg->u32_min_value, 8823 false_umin); 8824 true_reg->u32_max_value = min(true_reg->u32_max_value, 8825 true_umax); 8826 } else { 8827 u64 false_umin = opcode == BPF_JLT ? val : val + 1; 8828 u64 true_umax = opcode == BPF_JLT ? val - 1 : val; 8829 8830 false_reg->umin_value = max(false_reg->umin_value, false_umin); 8831 true_reg->umax_value = min(true_reg->umax_value, true_umax); 8832 } 8833 break; 8834 } 8835 case BPF_JSLE: 8836 case BPF_JSLT: 8837 { 8838 if (is_jmp32) { 8839 s32 false_smin = opcode == BPF_JSLT ? sval32 : sval32 + 1; 8840 s32 true_smax = opcode == BPF_JSLT ? sval32 - 1 : sval32; 8841 8842 false_reg->s32_min_value = max(false_reg->s32_min_value, false_smin); 8843 true_reg->s32_max_value = min(true_reg->s32_max_value, true_smax); 8844 } else { 8845 s64 false_smin = opcode == BPF_JSLT ? sval : sval + 1; 8846 s64 true_smax = opcode == BPF_JSLT ? sval - 1 : sval; 8847 8848 false_reg->smin_value = max(false_reg->smin_value, false_smin); 8849 true_reg->smax_value = min(true_reg->smax_value, true_smax); 8850 } 8851 break; 8852 } 8853 default: 8854 return; 8855 } 8856 8857 if (is_jmp32) { 8858 false_reg->var_off = tnum_or(tnum_clear_subreg(false_64off), 8859 tnum_subreg(false_32off)); 8860 true_reg->var_off = tnum_or(tnum_clear_subreg(true_64off), 8861 tnum_subreg(true_32off)); 8862 __reg_combine_32_into_64(false_reg); 8863 __reg_combine_32_into_64(true_reg); 8864 } else { 8865 false_reg->var_off = false_64off; 8866 true_reg->var_off = true_64off; 8867 __reg_combine_64_into_32(false_reg); 8868 __reg_combine_64_into_32(true_reg); 8869 } 8870 } 8871 8872 /* Same as above, but for the case that dst_reg holds a constant and src_reg is 8873 * the variable reg. 8874 */ 8875 static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, 8876 struct bpf_reg_state *false_reg, 8877 u64 val, u32 val32, 8878 u8 opcode, bool is_jmp32) 8879 { 8880 opcode = flip_opcode(opcode); 8881 /* This uses zero as "not present in table"; luckily the zero opcode, 8882 * BPF_JA, can't get here. 8883 */ 8884 if (opcode) 8885 reg_set_min_max(true_reg, false_reg, val, val32, opcode, is_jmp32); 8886 } 8887 8888 /* Regs are known to be equal, so intersect their min/max/var_off */ 8889 static void __reg_combine_min_max(struct bpf_reg_state *src_reg, 8890 struct bpf_reg_state *dst_reg) 8891 { 8892 src_reg->umin_value = dst_reg->umin_value = max(src_reg->umin_value, 8893 dst_reg->umin_value); 8894 src_reg->umax_value = dst_reg->umax_value = min(src_reg->umax_value, 8895 dst_reg->umax_value); 8896 src_reg->smin_value = dst_reg->smin_value = max(src_reg->smin_value, 8897 dst_reg->smin_value); 8898 src_reg->smax_value = dst_reg->smax_value = min(src_reg->smax_value, 8899 dst_reg->smax_value); 8900 src_reg->var_off = dst_reg->var_off = tnum_intersect(src_reg->var_off, 8901 dst_reg->var_off); 8902 /* We might have learned new bounds from the var_off. */ 8903 __update_reg_bounds(src_reg); 8904 __update_reg_bounds(dst_reg); 8905 /* We might have learned something about the sign bit. */ 8906 __reg_deduce_bounds(src_reg); 8907 __reg_deduce_bounds(dst_reg); 8908 /* We might have learned some bits from the bounds. */ 8909 __reg_bound_offset(src_reg); 8910 __reg_bound_offset(dst_reg); 8911 /* Intersecting with the old var_off might have improved our bounds 8912 * slightly. e.g. if umax was 0x7f...f and var_off was (0; 0xf...fc), 8913 * then new var_off is (0; 0x7f...fc) which improves our umax. 8914 */ 8915 __update_reg_bounds(src_reg); 8916 __update_reg_bounds(dst_reg); 8917 } 8918 8919 static void reg_combine_min_max(struct bpf_reg_state *true_src, 8920 struct bpf_reg_state *true_dst, 8921 struct bpf_reg_state *false_src, 8922 struct bpf_reg_state *false_dst, 8923 u8 opcode) 8924 { 8925 switch (opcode) { 8926 case BPF_JEQ: 8927 __reg_combine_min_max(true_src, true_dst); 8928 break; 8929 case BPF_JNE: 8930 __reg_combine_min_max(false_src, false_dst); 8931 break; 8932 } 8933 } 8934 8935 static void mark_ptr_or_null_reg(struct bpf_func_state *state, 8936 struct bpf_reg_state *reg, u32 id, 8937 bool is_null) 8938 { 8939 if (reg_type_may_be_null(reg->type) && reg->id == id && 8940 !WARN_ON_ONCE(!reg->id)) { 8941 /* Old offset (both fixed and variable parts) should 8942 * have been known-zero, because we don't allow pointer 8943 * arithmetic on pointers that might be NULL. 8944 */ 8945 if (WARN_ON_ONCE(reg->smin_value || reg->smax_value || 8946 !tnum_equals_const(reg->var_off, 0) || 8947 reg->off)) { 8948 __mark_reg_known_zero(reg); 8949 reg->off = 0; 8950 } 8951 if (is_null) { 8952 reg->type = SCALAR_VALUE; 8953 /* We don't need id and ref_obj_id from this point 8954 * onwards anymore, thus we should better reset it, 8955 * so that state pruning has chances to take effect. 8956 */ 8957 reg->id = 0; 8958 reg->ref_obj_id = 0; 8959 8960 return; 8961 } 8962 8963 mark_ptr_not_null_reg(reg); 8964 8965 if (!reg_may_point_to_spin_lock(reg)) { 8966 /* For not-NULL ptr, reg->ref_obj_id will be reset 8967 * in release_reg_references(). 8968 * 8969 * reg->id is still used by spin_lock ptr. Other 8970 * than spin_lock ptr type, reg->id can be reset. 8971 */ 8972 reg->id = 0; 8973 } 8974 } 8975 } 8976 8977 static void __mark_ptr_or_null_regs(struct bpf_func_state *state, u32 id, 8978 bool is_null) 8979 { 8980 struct bpf_reg_state *reg; 8981 int i; 8982 8983 for (i = 0; i < MAX_BPF_REG; i++) 8984 mark_ptr_or_null_reg(state, &state->regs[i], id, is_null); 8985 8986 bpf_for_each_spilled_reg(i, state, reg) { 8987 if (!reg) 8988 continue; 8989 mark_ptr_or_null_reg(state, reg, id, is_null); 8990 } 8991 } 8992 8993 /* The logic is similar to find_good_pkt_pointers(), both could eventually 8994 * be folded together at some point. 8995 */ 8996 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, 8997 bool is_null) 8998 { 8999 struct bpf_func_state *state = vstate->frame[vstate->curframe]; 9000 struct bpf_reg_state *regs = state->regs; 9001 u32 ref_obj_id = regs[regno].ref_obj_id; 9002 u32 id = regs[regno].id; 9003 int i; 9004 9005 if (ref_obj_id && ref_obj_id == id && is_null) 9006 /* regs[regno] is in the " == NULL" branch. 9007 * No one could have freed the reference state before 9008 * doing the NULL check. 9009 */ 9010 WARN_ON_ONCE(release_reference_state(state, id)); 9011 9012 for (i = 0; i <= vstate->curframe; i++) 9013 __mark_ptr_or_null_regs(vstate->frame[i], id, is_null); 9014 } 9015 9016 static bool try_match_pkt_pointers(const struct bpf_insn *insn, 9017 struct bpf_reg_state *dst_reg, 9018 struct bpf_reg_state *src_reg, 9019 struct bpf_verifier_state *this_branch, 9020 struct bpf_verifier_state *other_branch) 9021 { 9022 if (BPF_SRC(insn->code) != BPF_X) 9023 return false; 9024 9025 /* Pointers are always 64-bit. */ 9026 if (BPF_CLASS(insn->code) == BPF_JMP32) 9027 return false; 9028 9029 switch (BPF_OP(insn->code)) { 9030 case BPF_JGT: 9031 if ((dst_reg->type == PTR_TO_PACKET && 9032 src_reg->type == PTR_TO_PACKET_END) || 9033 (dst_reg->type == PTR_TO_PACKET_META && 9034 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 9035 /* pkt_data' > pkt_end, pkt_meta' > pkt_data */ 9036 find_good_pkt_pointers(this_branch, dst_reg, 9037 dst_reg->type, false); 9038 mark_pkt_end(other_branch, insn->dst_reg, true); 9039 } else if ((dst_reg->type == PTR_TO_PACKET_END && 9040 src_reg->type == PTR_TO_PACKET) || 9041 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 9042 src_reg->type == PTR_TO_PACKET_META)) { 9043 /* pkt_end > pkt_data', pkt_data > pkt_meta' */ 9044 find_good_pkt_pointers(other_branch, src_reg, 9045 src_reg->type, true); 9046 mark_pkt_end(this_branch, insn->src_reg, false); 9047 } else { 9048 return false; 9049 } 9050 break; 9051 case BPF_JLT: 9052 if ((dst_reg->type == PTR_TO_PACKET && 9053 src_reg->type == PTR_TO_PACKET_END) || 9054 (dst_reg->type == PTR_TO_PACKET_META && 9055 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 9056 /* pkt_data' < pkt_end, pkt_meta' < pkt_data */ 9057 find_good_pkt_pointers(other_branch, dst_reg, 9058 dst_reg->type, true); 9059 mark_pkt_end(this_branch, insn->dst_reg, false); 9060 } else if ((dst_reg->type == PTR_TO_PACKET_END && 9061 src_reg->type == PTR_TO_PACKET) || 9062 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 9063 src_reg->type == PTR_TO_PACKET_META)) { 9064 /* pkt_end < pkt_data', pkt_data > pkt_meta' */ 9065 find_good_pkt_pointers(this_branch, src_reg, 9066 src_reg->type, false); 9067 mark_pkt_end(other_branch, insn->src_reg, true); 9068 } else { 9069 return false; 9070 } 9071 break; 9072 case BPF_JGE: 9073 if ((dst_reg->type == PTR_TO_PACKET && 9074 src_reg->type == PTR_TO_PACKET_END) || 9075 (dst_reg->type == PTR_TO_PACKET_META && 9076 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 9077 /* pkt_data' >= pkt_end, pkt_meta' >= pkt_data */ 9078 find_good_pkt_pointers(this_branch, dst_reg, 9079 dst_reg->type, true); 9080 mark_pkt_end(other_branch, insn->dst_reg, false); 9081 } else if ((dst_reg->type == PTR_TO_PACKET_END && 9082 src_reg->type == PTR_TO_PACKET) || 9083 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 9084 src_reg->type == PTR_TO_PACKET_META)) { 9085 /* pkt_end >= pkt_data', pkt_data >= pkt_meta' */ 9086 find_good_pkt_pointers(other_branch, src_reg, 9087 src_reg->type, false); 9088 mark_pkt_end(this_branch, insn->src_reg, true); 9089 } else { 9090 return false; 9091 } 9092 break; 9093 case BPF_JLE: 9094 if ((dst_reg->type == PTR_TO_PACKET && 9095 src_reg->type == PTR_TO_PACKET_END) || 9096 (dst_reg->type == PTR_TO_PACKET_META && 9097 reg_is_init_pkt_pointer(src_reg, PTR_TO_PACKET))) { 9098 /* pkt_data' <= pkt_end, pkt_meta' <= pkt_data */ 9099 find_good_pkt_pointers(other_branch, dst_reg, 9100 dst_reg->type, false); 9101 mark_pkt_end(this_branch, insn->dst_reg, true); 9102 } else if ((dst_reg->type == PTR_TO_PACKET_END && 9103 src_reg->type == PTR_TO_PACKET) || 9104 (reg_is_init_pkt_pointer(dst_reg, PTR_TO_PACKET) && 9105 src_reg->type == PTR_TO_PACKET_META)) { 9106 /* pkt_end <= pkt_data', pkt_data <= pkt_meta' */ 9107 find_good_pkt_pointers(this_branch, src_reg, 9108 src_reg->type, true); 9109 mark_pkt_end(other_branch, insn->src_reg, false); 9110 } else { 9111 return false; 9112 } 9113 break; 9114 default: 9115 return false; 9116 } 9117 9118 return true; 9119 } 9120 9121 static void find_equal_scalars(struct bpf_verifier_state *vstate, 9122 struct bpf_reg_state *known_reg) 9123 { 9124 struct bpf_func_state *state; 9125 struct bpf_reg_state *reg; 9126 int i, j; 9127 9128 for (i = 0; i <= vstate->curframe; i++) { 9129 state = vstate->frame[i]; 9130 for (j = 0; j < MAX_BPF_REG; j++) { 9131 reg = &state->regs[j]; 9132 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 9133 *reg = *known_reg; 9134 } 9135 9136 bpf_for_each_spilled_reg(j, state, reg) { 9137 if (!reg) 9138 continue; 9139 if (reg->type == SCALAR_VALUE && reg->id == known_reg->id) 9140 *reg = *known_reg; 9141 } 9142 } 9143 } 9144 9145 static int check_cond_jmp_op(struct bpf_verifier_env *env, 9146 struct bpf_insn *insn, int *insn_idx) 9147 { 9148 struct bpf_verifier_state *this_branch = env->cur_state; 9149 struct bpf_verifier_state *other_branch; 9150 struct bpf_reg_state *regs = this_branch->frame[this_branch->curframe]->regs; 9151 struct bpf_reg_state *dst_reg, *other_branch_regs, *src_reg = NULL; 9152 u8 opcode = BPF_OP(insn->code); 9153 bool is_jmp32; 9154 int pred = -1; 9155 int err; 9156 9157 /* Only conditional jumps are expected to reach here. */ 9158 if (opcode == BPF_JA || opcode > BPF_JSLE) { 9159 verbose(env, "invalid BPF_JMP/JMP32 opcode %x\n", opcode); 9160 return -EINVAL; 9161 } 9162 9163 if (BPF_SRC(insn->code) == BPF_X) { 9164 if (insn->imm != 0) { 9165 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 9166 return -EINVAL; 9167 } 9168 9169 /* check src1 operand */ 9170 err = check_reg_arg(env, insn->src_reg, SRC_OP); 9171 if (err) 9172 return err; 9173 9174 if (is_pointer_value(env, insn->src_reg)) { 9175 verbose(env, "R%d pointer comparison prohibited\n", 9176 insn->src_reg); 9177 return -EACCES; 9178 } 9179 src_reg = ®s[insn->src_reg]; 9180 } else { 9181 if (insn->src_reg != BPF_REG_0) { 9182 verbose(env, "BPF_JMP/JMP32 uses reserved fields\n"); 9183 return -EINVAL; 9184 } 9185 } 9186 9187 /* check src2 operand */ 9188 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 9189 if (err) 9190 return err; 9191 9192 dst_reg = ®s[insn->dst_reg]; 9193 is_jmp32 = BPF_CLASS(insn->code) == BPF_JMP32; 9194 9195 if (BPF_SRC(insn->code) == BPF_K) { 9196 pred = is_branch_taken(dst_reg, insn->imm, opcode, is_jmp32); 9197 } else if (src_reg->type == SCALAR_VALUE && 9198 is_jmp32 && tnum_is_const(tnum_subreg(src_reg->var_off))) { 9199 pred = is_branch_taken(dst_reg, 9200 tnum_subreg(src_reg->var_off).value, 9201 opcode, 9202 is_jmp32); 9203 } else if (src_reg->type == SCALAR_VALUE && 9204 !is_jmp32 && tnum_is_const(src_reg->var_off)) { 9205 pred = is_branch_taken(dst_reg, 9206 src_reg->var_off.value, 9207 opcode, 9208 is_jmp32); 9209 } else if (reg_is_pkt_pointer_any(dst_reg) && 9210 reg_is_pkt_pointer_any(src_reg) && 9211 !is_jmp32) { 9212 pred = is_pkt_ptr_branch_taken(dst_reg, src_reg, opcode); 9213 } 9214 9215 if (pred >= 0) { 9216 /* If we get here with a dst_reg pointer type it is because 9217 * above is_branch_taken() special cased the 0 comparison. 9218 */ 9219 if (!__is_pointer_value(false, dst_reg)) 9220 err = mark_chain_precision(env, insn->dst_reg); 9221 if (BPF_SRC(insn->code) == BPF_X && !err && 9222 !__is_pointer_value(false, src_reg)) 9223 err = mark_chain_precision(env, insn->src_reg); 9224 if (err) 9225 return err; 9226 } 9227 9228 if (pred == 1) { 9229 /* Only follow the goto, ignore fall-through. If needed, push 9230 * the fall-through branch for simulation under speculative 9231 * execution. 9232 */ 9233 if (!env->bypass_spec_v1 && 9234 !sanitize_speculative_path(env, insn, *insn_idx + 1, 9235 *insn_idx)) 9236 return -EFAULT; 9237 *insn_idx += insn->off; 9238 return 0; 9239 } else if (pred == 0) { 9240 /* Only follow the fall-through branch, since that's where the 9241 * program will go. If needed, push the goto branch for 9242 * simulation under speculative execution. 9243 */ 9244 if (!env->bypass_spec_v1 && 9245 !sanitize_speculative_path(env, insn, 9246 *insn_idx + insn->off + 1, 9247 *insn_idx)) 9248 return -EFAULT; 9249 return 0; 9250 } 9251 9252 other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx, 9253 false); 9254 if (!other_branch) 9255 return -EFAULT; 9256 other_branch_regs = other_branch->frame[other_branch->curframe]->regs; 9257 9258 /* detect if we are comparing against a constant value so we can adjust 9259 * our min/max values for our dst register. 9260 * this is only legit if both are scalars (or pointers to the same 9261 * object, I suppose, but we don't support that right now), because 9262 * otherwise the different base pointers mean the offsets aren't 9263 * comparable. 9264 */ 9265 if (BPF_SRC(insn->code) == BPF_X) { 9266 struct bpf_reg_state *src_reg = ®s[insn->src_reg]; 9267 9268 if (dst_reg->type == SCALAR_VALUE && 9269 src_reg->type == SCALAR_VALUE) { 9270 if (tnum_is_const(src_reg->var_off) || 9271 (is_jmp32 && 9272 tnum_is_const(tnum_subreg(src_reg->var_off)))) 9273 reg_set_min_max(&other_branch_regs[insn->dst_reg], 9274 dst_reg, 9275 src_reg->var_off.value, 9276 tnum_subreg(src_reg->var_off).value, 9277 opcode, is_jmp32); 9278 else if (tnum_is_const(dst_reg->var_off) || 9279 (is_jmp32 && 9280 tnum_is_const(tnum_subreg(dst_reg->var_off)))) 9281 reg_set_min_max_inv(&other_branch_regs[insn->src_reg], 9282 src_reg, 9283 dst_reg->var_off.value, 9284 tnum_subreg(dst_reg->var_off).value, 9285 opcode, is_jmp32); 9286 else if (!is_jmp32 && 9287 (opcode == BPF_JEQ || opcode == BPF_JNE)) 9288 /* Comparing for equality, we can combine knowledge */ 9289 reg_combine_min_max(&other_branch_regs[insn->src_reg], 9290 &other_branch_regs[insn->dst_reg], 9291 src_reg, dst_reg, opcode); 9292 if (src_reg->id && 9293 !WARN_ON_ONCE(src_reg->id != other_branch_regs[insn->src_reg].id)) { 9294 find_equal_scalars(this_branch, src_reg); 9295 find_equal_scalars(other_branch, &other_branch_regs[insn->src_reg]); 9296 } 9297 9298 } 9299 } else if (dst_reg->type == SCALAR_VALUE) { 9300 reg_set_min_max(&other_branch_regs[insn->dst_reg], 9301 dst_reg, insn->imm, (u32)insn->imm, 9302 opcode, is_jmp32); 9303 } 9304 9305 if (dst_reg->type == SCALAR_VALUE && dst_reg->id && 9306 !WARN_ON_ONCE(dst_reg->id != other_branch_regs[insn->dst_reg].id)) { 9307 find_equal_scalars(this_branch, dst_reg); 9308 find_equal_scalars(other_branch, &other_branch_regs[insn->dst_reg]); 9309 } 9310 9311 /* detect if R == 0 where R is returned from bpf_map_lookup_elem(). 9312 * NOTE: these optimizations below are related with pointer comparison 9313 * which will never be JMP32. 9314 */ 9315 if (!is_jmp32 && BPF_SRC(insn->code) == BPF_K && 9316 insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && 9317 reg_type_may_be_null(dst_reg->type)) { 9318 /* Mark all identical registers in each branch as either 9319 * safe or unknown depending R == 0 or R != 0 conditional. 9320 */ 9321 mark_ptr_or_null_regs(this_branch, insn->dst_reg, 9322 opcode == BPF_JNE); 9323 mark_ptr_or_null_regs(other_branch, insn->dst_reg, 9324 opcode == BPF_JEQ); 9325 } else if (!try_match_pkt_pointers(insn, dst_reg, ®s[insn->src_reg], 9326 this_branch, other_branch) && 9327 is_pointer_value(env, insn->dst_reg)) { 9328 verbose(env, "R%d pointer comparison prohibited\n", 9329 insn->dst_reg); 9330 return -EACCES; 9331 } 9332 if (env->log.level & BPF_LOG_LEVEL) 9333 print_verifier_state(env, this_branch->frame[this_branch->curframe]); 9334 return 0; 9335 } 9336 9337 /* verify BPF_LD_IMM64 instruction */ 9338 static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) 9339 { 9340 struct bpf_insn_aux_data *aux = cur_aux(env); 9341 struct bpf_reg_state *regs = cur_regs(env); 9342 struct bpf_reg_state *dst_reg; 9343 struct bpf_map *map; 9344 int err; 9345 9346 if (BPF_SIZE(insn->code) != BPF_DW) { 9347 verbose(env, "invalid BPF_LD_IMM insn\n"); 9348 return -EINVAL; 9349 } 9350 if (insn->off != 0) { 9351 verbose(env, "BPF_LD_IMM64 uses reserved fields\n"); 9352 return -EINVAL; 9353 } 9354 9355 err = check_reg_arg(env, insn->dst_reg, DST_OP); 9356 if (err) 9357 return err; 9358 9359 dst_reg = ®s[insn->dst_reg]; 9360 if (insn->src_reg == 0) { 9361 u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; 9362 9363 dst_reg->type = SCALAR_VALUE; 9364 __mark_reg_known(®s[insn->dst_reg], imm); 9365 return 0; 9366 } 9367 9368 if (insn->src_reg == BPF_PSEUDO_BTF_ID) { 9369 mark_reg_known_zero(env, regs, insn->dst_reg); 9370 9371 dst_reg->type = aux->btf_var.reg_type; 9372 switch (dst_reg->type) { 9373 case PTR_TO_MEM: 9374 dst_reg->mem_size = aux->btf_var.mem_size; 9375 break; 9376 case PTR_TO_BTF_ID: 9377 case PTR_TO_PERCPU_BTF_ID: 9378 dst_reg->btf = aux->btf_var.btf; 9379 dst_reg->btf_id = aux->btf_var.btf_id; 9380 break; 9381 default: 9382 verbose(env, "bpf verifier is misconfigured\n"); 9383 return -EFAULT; 9384 } 9385 return 0; 9386 } 9387 9388 if (insn->src_reg == BPF_PSEUDO_FUNC) { 9389 struct bpf_prog_aux *aux = env->prog->aux; 9390 u32 subprogno = insn[1].imm; 9391 9392 if (!aux->func_info) { 9393 verbose(env, "missing btf func_info\n"); 9394 return -EINVAL; 9395 } 9396 if (aux->func_info_aux[subprogno].linkage != BTF_FUNC_STATIC) { 9397 verbose(env, "callback function not static\n"); 9398 return -EINVAL; 9399 } 9400 9401 dst_reg->type = PTR_TO_FUNC; 9402 dst_reg->subprogno = subprogno; 9403 return 0; 9404 } 9405 9406 map = env->used_maps[aux->map_index]; 9407 mark_reg_known_zero(env, regs, insn->dst_reg); 9408 dst_reg->map_ptr = map; 9409 9410 if (insn->src_reg == BPF_PSEUDO_MAP_VALUE || 9411 insn->src_reg == BPF_PSEUDO_MAP_IDX_VALUE) { 9412 dst_reg->type = PTR_TO_MAP_VALUE; 9413 dst_reg->off = aux->map_off; 9414 if (map_value_has_spin_lock(map)) 9415 dst_reg->id = ++env->id_gen; 9416 } else if (insn->src_reg == BPF_PSEUDO_MAP_FD || 9417 insn->src_reg == BPF_PSEUDO_MAP_IDX) { 9418 dst_reg->type = CONST_PTR_TO_MAP; 9419 } else { 9420 verbose(env, "bpf verifier is misconfigured\n"); 9421 return -EINVAL; 9422 } 9423 9424 return 0; 9425 } 9426 9427 static bool may_access_skb(enum bpf_prog_type type) 9428 { 9429 switch (type) { 9430 case BPF_PROG_TYPE_SOCKET_FILTER: 9431 case BPF_PROG_TYPE_SCHED_CLS: 9432 case BPF_PROG_TYPE_SCHED_ACT: 9433 return true; 9434 default: 9435 return false; 9436 } 9437 } 9438 9439 /* verify safety of LD_ABS|LD_IND instructions: 9440 * - they can only appear in the programs where ctx == skb 9441 * - since they are wrappers of function calls, they scratch R1-R5 registers, 9442 * preserve R6-R9, and store return value into R0 9443 * 9444 * Implicit input: 9445 * ctx == skb == R6 == CTX 9446 * 9447 * Explicit input: 9448 * SRC == any register 9449 * IMM == 32-bit immediate 9450 * 9451 * Output: 9452 * R0 - 8/16/32-bit skb data converted to cpu endianness 9453 */ 9454 static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) 9455 { 9456 struct bpf_reg_state *regs = cur_regs(env); 9457 static const int ctx_reg = BPF_REG_6; 9458 u8 mode = BPF_MODE(insn->code); 9459 int i, err; 9460 9461 if (!may_access_skb(resolve_prog_type(env->prog))) { 9462 verbose(env, "BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); 9463 return -EINVAL; 9464 } 9465 9466 if (!env->ops->gen_ld_abs) { 9467 verbose(env, "bpf verifier is misconfigured\n"); 9468 return -EINVAL; 9469 } 9470 9471 if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || 9472 BPF_SIZE(insn->code) == BPF_DW || 9473 (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { 9474 verbose(env, "BPF_LD_[ABS|IND] uses reserved fields\n"); 9475 return -EINVAL; 9476 } 9477 9478 /* check whether implicit source operand (register R6) is readable */ 9479 err = check_reg_arg(env, ctx_reg, SRC_OP); 9480 if (err) 9481 return err; 9482 9483 /* Disallow usage of BPF_LD_[ABS|IND] with reference tracking, as 9484 * gen_ld_abs() may terminate the program at runtime, leading to 9485 * reference leak. 9486 */ 9487 err = check_reference_leak(env); 9488 if (err) { 9489 verbose(env, "BPF_LD_[ABS|IND] cannot be mixed with socket references\n"); 9490 return err; 9491 } 9492 9493 if (env->cur_state->active_spin_lock) { 9494 verbose(env, "BPF_LD_[ABS|IND] cannot be used inside bpf_spin_lock-ed region\n"); 9495 return -EINVAL; 9496 } 9497 9498 if (regs[ctx_reg].type != PTR_TO_CTX) { 9499 verbose(env, 9500 "at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); 9501 return -EINVAL; 9502 } 9503 9504 if (mode == BPF_IND) { 9505 /* check explicit source operand */ 9506 err = check_reg_arg(env, insn->src_reg, SRC_OP); 9507 if (err) 9508 return err; 9509 } 9510 9511 err = check_ctx_reg(env, ®s[ctx_reg], ctx_reg); 9512 if (err < 0) 9513 return err; 9514 9515 /* reset caller saved regs to unreadable */ 9516 for (i = 0; i < CALLER_SAVED_REGS; i++) { 9517 mark_reg_not_init(env, regs, caller_saved[i]); 9518 check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK); 9519 } 9520 9521 /* mark destination R0 register as readable, since it contains 9522 * the value fetched from the packet. 9523 * Already marked as written above. 9524 */ 9525 mark_reg_unknown(env, regs, BPF_REG_0); 9526 /* ld_abs load up to 32-bit skb data. */ 9527 regs[BPF_REG_0].subreg_def = env->insn_idx + 1; 9528 return 0; 9529 } 9530 9531 static int check_return_code(struct bpf_verifier_env *env) 9532 { 9533 struct tnum enforce_attach_type_range = tnum_unknown; 9534 const struct bpf_prog *prog = env->prog; 9535 struct bpf_reg_state *reg; 9536 struct tnum range = tnum_range(0, 1); 9537 enum bpf_prog_type prog_type = resolve_prog_type(env->prog); 9538 int err; 9539 struct bpf_func_state *frame = env->cur_state->frame[0]; 9540 const bool is_subprog = frame->subprogno; 9541 9542 /* LSM and struct_ops func-ptr's return type could be "void" */ 9543 if (!is_subprog && 9544 (prog_type == BPF_PROG_TYPE_STRUCT_OPS || 9545 prog_type == BPF_PROG_TYPE_LSM) && 9546 !prog->aux->attach_func_proto->type) 9547 return 0; 9548 9549 /* eBPF calling convention is such that R0 is used 9550 * to return the value from eBPF program. 9551 * Make sure that it's readable at this time 9552 * of bpf_exit, which means that program wrote 9553 * something into it earlier 9554 */ 9555 err = check_reg_arg(env, BPF_REG_0, SRC_OP); 9556 if (err) 9557 return err; 9558 9559 if (is_pointer_value(env, BPF_REG_0)) { 9560 verbose(env, "R0 leaks addr as return value\n"); 9561 return -EACCES; 9562 } 9563 9564 reg = cur_regs(env) + BPF_REG_0; 9565 9566 if (frame->in_async_callback_fn) { 9567 /* enforce return zero from async callbacks like timer */ 9568 if (reg->type != SCALAR_VALUE) { 9569 verbose(env, "In async callback the register R0 is not a known value (%s)\n", 9570 reg_type_str[reg->type]); 9571 return -EINVAL; 9572 } 9573 9574 if (!tnum_in(tnum_const(0), reg->var_off)) { 9575 verbose_invalid_scalar(env, reg, &range, "async callback", "R0"); 9576 return -EINVAL; 9577 } 9578 return 0; 9579 } 9580 9581 if (is_subprog) { 9582 if (reg->type != SCALAR_VALUE) { 9583 verbose(env, "At subprogram exit the register R0 is not a scalar value (%s)\n", 9584 reg_type_str[reg->type]); 9585 return -EINVAL; 9586 } 9587 return 0; 9588 } 9589 9590 switch (prog_type) { 9591 case BPF_PROG_TYPE_CGROUP_SOCK_ADDR: 9592 if (env->prog->expected_attach_type == BPF_CGROUP_UDP4_RECVMSG || 9593 env->prog->expected_attach_type == BPF_CGROUP_UDP6_RECVMSG || 9594 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETPEERNAME || 9595 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETPEERNAME || 9596 env->prog->expected_attach_type == BPF_CGROUP_INET4_GETSOCKNAME || 9597 env->prog->expected_attach_type == BPF_CGROUP_INET6_GETSOCKNAME) 9598 range = tnum_range(1, 1); 9599 if (env->prog->expected_attach_type == BPF_CGROUP_INET4_BIND || 9600 env->prog->expected_attach_type == BPF_CGROUP_INET6_BIND) 9601 range = tnum_range(0, 3); 9602 break; 9603 case BPF_PROG_TYPE_CGROUP_SKB: 9604 if (env->prog->expected_attach_type == BPF_CGROUP_INET_EGRESS) { 9605 range = tnum_range(0, 3); 9606 enforce_attach_type_range = tnum_range(2, 3); 9607 } 9608 break; 9609 case BPF_PROG_TYPE_CGROUP_SOCK: 9610 case BPF_PROG_TYPE_SOCK_OPS: 9611 case BPF_PROG_TYPE_CGROUP_DEVICE: 9612 case BPF_PROG_TYPE_CGROUP_SYSCTL: 9613 case BPF_PROG_TYPE_CGROUP_SOCKOPT: 9614 break; 9615 case BPF_PROG_TYPE_RAW_TRACEPOINT: 9616 if (!env->prog->aux->attach_btf_id) 9617 return 0; 9618 range = tnum_const(0); 9619 break; 9620 case BPF_PROG_TYPE_TRACING: 9621 switch (env->prog->expected_attach_type) { 9622 case BPF_TRACE_FENTRY: 9623 case BPF_TRACE_FEXIT: 9624 range = tnum_const(0); 9625 break; 9626 case BPF_TRACE_RAW_TP: 9627 case BPF_MODIFY_RETURN: 9628 return 0; 9629 case BPF_TRACE_ITER: 9630 break; 9631 default: 9632 return -ENOTSUPP; 9633 } 9634 break; 9635 case BPF_PROG_TYPE_SK_LOOKUP: 9636 range = tnum_range(SK_DROP, SK_PASS); 9637 break; 9638 case BPF_PROG_TYPE_EXT: 9639 /* freplace program can return anything as its return value 9640 * depends on the to-be-replaced kernel func or bpf program. 9641 */ 9642 default: 9643 return 0; 9644 } 9645 9646 if (reg->type != SCALAR_VALUE) { 9647 verbose(env, "At program exit the register R0 is not a known value (%s)\n", 9648 reg_type_str[reg->type]); 9649 return -EINVAL; 9650 } 9651 9652 if (!tnum_in(range, reg->var_off)) { 9653 verbose_invalid_scalar(env, reg, &range, "program exit", "R0"); 9654 return -EINVAL; 9655 } 9656 9657 if (!tnum_is_unknown(enforce_attach_type_range) && 9658 tnum_in(enforce_attach_type_range, reg->var_off)) 9659 env->prog->enforce_expected_attach_type = 1; 9660 return 0; 9661 } 9662 9663 /* non-recursive DFS pseudo code 9664 * 1 procedure DFS-iterative(G,v): 9665 * 2 label v as discovered 9666 * 3 let S be a stack 9667 * 4 S.push(v) 9668 * 5 while S is not empty 9669 * 6 t <- S.pop() 9670 * 7 if t is what we're looking for: 9671 * 8 return t 9672 * 9 for all edges e in G.adjacentEdges(t) do 9673 * 10 if edge e is already labelled 9674 * 11 continue with the next edge 9675 * 12 w <- G.adjacentVertex(t,e) 9676 * 13 if vertex w is not discovered and not explored 9677 * 14 label e as tree-edge 9678 * 15 label w as discovered 9679 * 16 S.push(w) 9680 * 17 continue at 5 9681 * 18 else if vertex w is discovered 9682 * 19 label e as back-edge 9683 * 20 else 9684 * 21 // vertex w is explored 9685 * 22 label e as forward- or cross-edge 9686 * 23 label t as explored 9687 * 24 S.pop() 9688 * 9689 * convention: 9690 * 0x10 - discovered 9691 * 0x11 - discovered and fall-through edge labelled 9692 * 0x12 - discovered and fall-through and branch edges labelled 9693 * 0x20 - explored 9694 */ 9695 9696 enum { 9697 DISCOVERED = 0x10, 9698 EXPLORED = 0x20, 9699 FALLTHROUGH = 1, 9700 BRANCH = 2, 9701 }; 9702 9703 static u32 state_htab_size(struct bpf_verifier_env *env) 9704 { 9705 return env->prog->len; 9706 } 9707 9708 static struct bpf_verifier_state_list **explored_state( 9709 struct bpf_verifier_env *env, 9710 int idx) 9711 { 9712 struct bpf_verifier_state *cur = env->cur_state; 9713 struct bpf_func_state *state = cur->frame[cur->curframe]; 9714 9715 return &env->explored_states[(idx ^ state->callsite) % state_htab_size(env)]; 9716 } 9717 9718 static void init_explored_state(struct bpf_verifier_env *env, int idx) 9719 { 9720 env->insn_aux_data[idx].prune_point = true; 9721 } 9722 9723 enum { 9724 DONE_EXPLORING = 0, 9725 KEEP_EXPLORING = 1, 9726 }; 9727 9728 /* t, w, e - match pseudo-code above: 9729 * t - index of current instruction 9730 * w - next instruction 9731 * e - edge 9732 */ 9733 static int push_insn(int t, int w, int e, struct bpf_verifier_env *env, 9734 bool loop_ok) 9735 { 9736 int *insn_stack = env->cfg.insn_stack; 9737 int *insn_state = env->cfg.insn_state; 9738 9739 if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) 9740 return DONE_EXPLORING; 9741 9742 if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) 9743 return DONE_EXPLORING; 9744 9745 if (w < 0 || w >= env->prog->len) { 9746 verbose_linfo(env, t, "%d: ", t); 9747 verbose(env, "jump out of range from insn %d to %d\n", t, w); 9748 return -EINVAL; 9749 } 9750 9751 if (e == BRANCH) 9752 /* mark branch target for state pruning */ 9753 init_explored_state(env, w); 9754 9755 if (insn_state[w] == 0) { 9756 /* tree-edge */ 9757 insn_state[t] = DISCOVERED | e; 9758 insn_state[w] = DISCOVERED; 9759 if (env->cfg.cur_stack >= env->prog->len) 9760 return -E2BIG; 9761 insn_stack[env->cfg.cur_stack++] = w; 9762 return KEEP_EXPLORING; 9763 } else if ((insn_state[w] & 0xF0) == DISCOVERED) { 9764 if (loop_ok && env->bpf_capable) 9765 return DONE_EXPLORING; 9766 verbose_linfo(env, t, "%d: ", t); 9767 verbose_linfo(env, w, "%d: ", w); 9768 verbose(env, "back-edge from insn %d to %d\n", t, w); 9769 return -EINVAL; 9770 } else if (insn_state[w] == EXPLORED) { 9771 /* forward- or cross-edge */ 9772 insn_state[t] = DISCOVERED | e; 9773 } else { 9774 verbose(env, "insn state internal bug\n"); 9775 return -EFAULT; 9776 } 9777 return DONE_EXPLORING; 9778 } 9779 9780 static int visit_func_call_insn(int t, int insn_cnt, 9781 struct bpf_insn *insns, 9782 struct bpf_verifier_env *env, 9783 bool visit_callee) 9784 { 9785 int ret; 9786 9787 ret = push_insn(t, t + 1, FALLTHROUGH, env, false); 9788 if (ret) 9789 return ret; 9790 9791 if (t + 1 < insn_cnt) 9792 init_explored_state(env, t + 1); 9793 if (visit_callee) { 9794 init_explored_state(env, t); 9795 ret = push_insn(t, t + insns[t].imm + 1, BRANCH, env, 9796 /* It's ok to allow recursion from CFG point of 9797 * view. __check_func_call() will do the actual 9798 * check. 9799 */ 9800 bpf_pseudo_func(insns + t)); 9801 } 9802 return ret; 9803 } 9804 9805 /* Visits the instruction at index t and returns one of the following: 9806 * < 0 - an error occurred 9807 * DONE_EXPLORING - the instruction was fully explored 9808 * KEEP_EXPLORING - there is still work to be done before it is fully explored 9809 */ 9810 static int visit_insn(int t, int insn_cnt, struct bpf_verifier_env *env) 9811 { 9812 struct bpf_insn *insns = env->prog->insnsi; 9813 int ret; 9814 9815 if (bpf_pseudo_func(insns + t)) 9816 return visit_func_call_insn(t, insn_cnt, insns, env, true); 9817 9818 /* All non-branch instructions have a single fall-through edge. */ 9819 if (BPF_CLASS(insns[t].code) != BPF_JMP && 9820 BPF_CLASS(insns[t].code) != BPF_JMP32) 9821 return push_insn(t, t + 1, FALLTHROUGH, env, false); 9822 9823 switch (BPF_OP(insns[t].code)) { 9824 case BPF_EXIT: 9825 return DONE_EXPLORING; 9826 9827 case BPF_CALL: 9828 if (insns[t].imm == BPF_FUNC_timer_set_callback) 9829 /* Mark this call insn to trigger is_state_visited() check 9830 * before call itself is processed by __check_func_call(). 9831 * Otherwise new async state will be pushed for further 9832 * exploration. 9833 */ 9834 init_explored_state(env, t); 9835 return visit_func_call_insn(t, insn_cnt, insns, env, 9836 insns[t].src_reg == BPF_PSEUDO_CALL); 9837 9838 case BPF_JA: 9839 if (BPF_SRC(insns[t].code) != BPF_K) 9840 return -EINVAL; 9841 9842 /* unconditional jump with single edge */ 9843 ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env, 9844 true); 9845 if (ret) 9846 return ret; 9847 9848 /* unconditional jmp is not a good pruning point, 9849 * but it's marked, since backtracking needs 9850 * to record jmp history in is_state_visited(). 9851 */ 9852 init_explored_state(env, t + insns[t].off + 1); 9853 /* tell verifier to check for equivalent states 9854 * after every call and jump 9855 */ 9856 if (t + 1 < insn_cnt) 9857 init_explored_state(env, t + 1); 9858 9859 return ret; 9860 9861 default: 9862 /* conditional jump with two edges */ 9863 init_explored_state(env, t); 9864 ret = push_insn(t, t + 1, FALLTHROUGH, env, true); 9865 if (ret) 9866 return ret; 9867 9868 return push_insn(t, t + insns[t].off + 1, BRANCH, env, true); 9869 } 9870 } 9871 9872 /* non-recursive depth-first-search to detect loops in BPF program 9873 * loop == back-edge in directed graph 9874 */ 9875 static int check_cfg(struct bpf_verifier_env *env) 9876 { 9877 int insn_cnt = env->prog->len; 9878 int *insn_stack, *insn_state; 9879 int ret = 0; 9880 int i; 9881 9882 insn_state = env->cfg.insn_state = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 9883 if (!insn_state) 9884 return -ENOMEM; 9885 9886 insn_stack = env->cfg.insn_stack = kvcalloc(insn_cnt, sizeof(int), GFP_KERNEL); 9887 if (!insn_stack) { 9888 kvfree(insn_state); 9889 return -ENOMEM; 9890 } 9891 9892 insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ 9893 insn_stack[0] = 0; /* 0 is the first instruction */ 9894 env->cfg.cur_stack = 1; 9895 9896 while (env->cfg.cur_stack > 0) { 9897 int t = insn_stack[env->cfg.cur_stack - 1]; 9898 9899 ret = visit_insn(t, insn_cnt, env); 9900 switch (ret) { 9901 case DONE_EXPLORING: 9902 insn_state[t] = EXPLORED; 9903 env->cfg.cur_stack--; 9904 break; 9905 case KEEP_EXPLORING: 9906 break; 9907 default: 9908 if (ret > 0) { 9909 verbose(env, "visit_insn internal bug\n"); 9910 ret = -EFAULT; 9911 } 9912 goto err_free; 9913 } 9914 } 9915 9916 if (env->cfg.cur_stack < 0) { 9917 verbose(env, "pop stack internal bug\n"); 9918 ret = -EFAULT; 9919 goto err_free; 9920 } 9921 9922 for (i = 0; i < insn_cnt; i++) { 9923 if (insn_state[i] != EXPLORED) { 9924 verbose(env, "unreachable insn %d\n", i); 9925 ret = -EINVAL; 9926 goto err_free; 9927 } 9928 } 9929 ret = 0; /* cfg looks good */ 9930 9931 err_free: 9932 kvfree(insn_state); 9933 kvfree(insn_stack); 9934 env->cfg.insn_state = env->cfg.insn_stack = NULL; 9935 return ret; 9936 } 9937 9938 static int check_abnormal_return(struct bpf_verifier_env *env) 9939 { 9940 int i; 9941 9942 for (i = 1; i < env->subprog_cnt; i++) { 9943 if (env->subprog_info[i].has_ld_abs) { 9944 verbose(env, "LD_ABS is not allowed in subprogs without BTF\n"); 9945 return -EINVAL; 9946 } 9947 if (env->subprog_info[i].has_tail_call) { 9948 verbose(env, "tail_call is not allowed in subprogs without BTF\n"); 9949 return -EINVAL; 9950 } 9951 } 9952 return 0; 9953 } 9954 9955 /* The minimum supported BTF func info size */ 9956 #define MIN_BPF_FUNCINFO_SIZE 8 9957 #define MAX_FUNCINFO_REC_SIZE 252 9958 9959 static int check_btf_func(struct bpf_verifier_env *env, 9960 const union bpf_attr *attr, 9961 bpfptr_t uattr) 9962 { 9963 const struct btf_type *type, *func_proto, *ret_type; 9964 u32 i, nfuncs, urec_size, min_size; 9965 u32 krec_size = sizeof(struct bpf_func_info); 9966 struct bpf_func_info *krecord; 9967 struct bpf_func_info_aux *info_aux = NULL; 9968 struct bpf_prog *prog; 9969 const struct btf *btf; 9970 bpfptr_t urecord; 9971 u32 prev_offset = 0; 9972 bool scalar_return; 9973 int ret = -ENOMEM; 9974 9975 nfuncs = attr->func_info_cnt; 9976 if (!nfuncs) { 9977 if (check_abnormal_return(env)) 9978 return -EINVAL; 9979 return 0; 9980 } 9981 9982 if (nfuncs != env->subprog_cnt) { 9983 verbose(env, "number of funcs in func_info doesn't match number of subprogs\n"); 9984 return -EINVAL; 9985 } 9986 9987 urec_size = attr->func_info_rec_size; 9988 if (urec_size < MIN_BPF_FUNCINFO_SIZE || 9989 urec_size > MAX_FUNCINFO_REC_SIZE || 9990 urec_size % sizeof(u32)) { 9991 verbose(env, "invalid func info rec size %u\n", urec_size); 9992 return -EINVAL; 9993 } 9994 9995 prog = env->prog; 9996 btf = prog->aux->btf; 9997 9998 urecord = make_bpfptr(attr->func_info, uattr.is_kernel); 9999 min_size = min_t(u32, krec_size, urec_size); 10000 10001 krecord = kvcalloc(nfuncs, krec_size, GFP_KERNEL | __GFP_NOWARN); 10002 if (!krecord) 10003 return -ENOMEM; 10004 info_aux = kcalloc(nfuncs, sizeof(*info_aux), GFP_KERNEL | __GFP_NOWARN); 10005 if (!info_aux) 10006 goto err_free; 10007 10008 for (i = 0; i < nfuncs; i++) { 10009 ret = bpf_check_uarg_tail_zero(urecord, krec_size, urec_size); 10010 if (ret) { 10011 if (ret == -E2BIG) { 10012 verbose(env, "nonzero tailing record in func info"); 10013 /* set the size kernel expects so loader can zero 10014 * out the rest of the record. 10015 */ 10016 if (copy_to_bpfptr_offset(uattr, 10017 offsetof(union bpf_attr, func_info_rec_size), 10018 &min_size, sizeof(min_size))) 10019 ret = -EFAULT; 10020 } 10021 goto err_free; 10022 } 10023 10024 if (copy_from_bpfptr(&krecord[i], urecord, min_size)) { 10025 ret = -EFAULT; 10026 goto err_free; 10027 } 10028 10029 /* check insn_off */ 10030 ret = -EINVAL; 10031 if (i == 0) { 10032 if (krecord[i].insn_off) { 10033 verbose(env, 10034 "nonzero insn_off %u for the first func info record", 10035 krecord[i].insn_off); 10036 goto err_free; 10037 } 10038 } else if (krecord[i].insn_off <= prev_offset) { 10039 verbose(env, 10040 "same or smaller insn offset (%u) than previous func info record (%u)", 10041 krecord[i].insn_off, prev_offset); 10042 goto err_free; 10043 } 10044 10045 if (env->subprog_info[i].start != krecord[i].insn_off) { 10046 verbose(env, "func_info BTF section doesn't match subprog layout in BPF program\n"); 10047 goto err_free; 10048 } 10049 10050 /* check type_id */ 10051 type = btf_type_by_id(btf, krecord[i].type_id); 10052 if (!type || !btf_type_is_func(type)) { 10053 verbose(env, "invalid type id %d in func info", 10054 krecord[i].type_id); 10055 goto err_free; 10056 } 10057 info_aux[i].linkage = BTF_INFO_VLEN(type->info); 10058 10059 func_proto = btf_type_by_id(btf, type->type); 10060 if (unlikely(!func_proto || !btf_type_is_func_proto(func_proto))) 10061 /* btf_func_check() already verified it during BTF load */ 10062 goto err_free; 10063 ret_type = btf_type_skip_modifiers(btf, func_proto->type, NULL); 10064 scalar_return = 10065 btf_type_is_small_int(ret_type) || btf_type_is_enum(ret_type); 10066 if (i && !scalar_return && env->subprog_info[i].has_ld_abs) { 10067 verbose(env, "LD_ABS is only allowed in functions that return 'int'.\n"); 10068 goto err_free; 10069 } 10070 if (i && !scalar_return && env->subprog_info[i].has_tail_call) { 10071 verbose(env, "tail_call is only allowed in functions that return 'int'.\n"); 10072 goto err_free; 10073 } 10074 10075 prev_offset = krecord[i].insn_off; 10076 bpfptr_add(&urecord, urec_size); 10077 } 10078 10079 prog->aux->func_info = krecord; 10080 prog->aux->func_info_cnt = nfuncs; 10081 prog->aux->func_info_aux = info_aux; 10082 return 0; 10083 10084 err_free: 10085 kvfree(krecord); 10086 kfree(info_aux); 10087 return ret; 10088 } 10089 10090 static void adjust_btf_func(struct bpf_verifier_env *env) 10091 { 10092 struct bpf_prog_aux *aux = env->prog->aux; 10093 int i; 10094 10095 if (!aux->func_info) 10096 return; 10097 10098 for (i = 0; i < env->subprog_cnt; i++) 10099 aux->func_info[i].insn_off = env->subprog_info[i].start; 10100 } 10101 10102 #define MIN_BPF_LINEINFO_SIZE (offsetof(struct bpf_line_info, line_col) + \ 10103 sizeof(((struct bpf_line_info *)(0))->line_col)) 10104 #define MAX_LINEINFO_REC_SIZE MAX_FUNCINFO_REC_SIZE 10105 10106 static int check_btf_line(struct bpf_verifier_env *env, 10107 const union bpf_attr *attr, 10108 bpfptr_t uattr) 10109 { 10110 u32 i, s, nr_linfo, ncopy, expected_size, rec_size, prev_offset = 0; 10111 struct bpf_subprog_info *sub; 10112 struct bpf_line_info *linfo; 10113 struct bpf_prog *prog; 10114 const struct btf *btf; 10115 bpfptr_t ulinfo; 10116 int err; 10117 10118 nr_linfo = attr->line_info_cnt; 10119 if (!nr_linfo) 10120 return 0; 10121 if (nr_linfo > INT_MAX / sizeof(struct bpf_line_info)) 10122 return -EINVAL; 10123 10124 rec_size = attr->line_info_rec_size; 10125 if (rec_size < MIN_BPF_LINEINFO_SIZE || 10126 rec_size > MAX_LINEINFO_REC_SIZE || 10127 rec_size & (sizeof(u32) - 1)) 10128 return -EINVAL; 10129 10130 /* Need to zero it in case the userspace may 10131 * pass in a smaller bpf_line_info object. 10132 */ 10133 linfo = kvcalloc(nr_linfo, sizeof(struct bpf_line_info), 10134 GFP_KERNEL | __GFP_NOWARN); 10135 if (!linfo) 10136 return -ENOMEM; 10137 10138 prog = env->prog; 10139 btf = prog->aux->btf; 10140 10141 s = 0; 10142 sub = env->subprog_info; 10143 ulinfo = make_bpfptr(attr->line_info, uattr.is_kernel); 10144 expected_size = sizeof(struct bpf_line_info); 10145 ncopy = min_t(u32, expected_size, rec_size); 10146 for (i = 0; i < nr_linfo; i++) { 10147 err = bpf_check_uarg_tail_zero(ulinfo, expected_size, rec_size); 10148 if (err) { 10149 if (err == -E2BIG) { 10150 verbose(env, "nonzero tailing record in line_info"); 10151 if (copy_to_bpfptr_offset(uattr, 10152 offsetof(union bpf_attr, line_info_rec_size), 10153 &expected_size, sizeof(expected_size))) 10154 err = -EFAULT; 10155 } 10156 goto err_free; 10157 } 10158 10159 if (copy_from_bpfptr(&linfo[i], ulinfo, ncopy)) { 10160 err = -EFAULT; 10161 goto err_free; 10162 } 10163 10164 /* 10165 * Check insn_off to ensure 10166 * 1) strictly increasing AND 10167 * 2) bounded by prog->len 10168 * 10169 * The linfo[0].insn_off == 0 check logically falls into 10170 * the later "missing bpf_line_info for func..." case 10171 * because the first linfo[0].insn_off must be the 10172 * first sub also and the first sub must have 10173 * subprog_info[0].start == 0. 10174 */ 10175 if ((i && linfo[i].insn_off <= prev_offset) || 10176 linfo[i].insn_off >= prog->len) { 10177 verbose(env, "Invalid line_info[%u].insn_off:%u (prev_offset:%u prog->len:%u)\n", 10178 i, linfo[i].insn_off, prev_offset, 10179 prog->len); 10180 err = -EINVAL; 10181 goto err_free; 10182 } 10183 10184 if (!prog->insnsi[linfo[i].insn_off].code) { 10185 verbose(env, 10186 "Invalid insn code at line_info[%u].insn_off\n", 10187 i); 10188 err = -EINVAL; 10189 goto err_free; 10190 } 10191 10192 if (!btf_name_by_offset(btf, linfo[i].line_off) || 10193 !btf_name_by_offset(btf, linfo[i].file_name_off)) { 10194 verbose(env, "Invalid line_info[%u].line_off or .file_name_off\n", i); 10195 err = -EINVAL; 10196 goto err_free; 10197 } 10198 10199 if (s != env->subprog_cnt) { 10200 if (linfo[i].insn_off == sub[s].start) { 10201 sub[s].linfo_idx = i; 10202 s++; 10203 } else if (sub[s].start < linfo[i].insn_off) { 10204 verbose(env, "missing bpf_line_info for func#%u\n", s); 10205 err = -EINVAL; 10206 goto err_free; 10207 } 10208 } 10209 10210 prev_offset = linfo[i].insn_off; 10211 bpfptr_add(&ulinfo, rec_size); 10212 } 10213 10214 if (s != env->subprog_cnt) { 10215 verbose(env, "missing bpf_line_info for %u funcs starting from func#%u\n", 10216 env->subprog_cnt - s, s); 10217 err = -EINVAL; 10218 goto err_free; 10219 } 10220 10221 prog->aux->linfo = linfo; 10222 prog->aux->nr_linfo = nr_linfo; 10223 10224 return 0; 10225 10226 err_free: 10227 kvfree(linfo); 10228 return err; 10229 } 10230 10231 static int check_btf_info(struct bpf_verifier_env *env, 10232 const union bpf_attr *attr, 10233 bpfptr_t uattr) 10234 { 10235 struct btf *btf; 10236 int err; 10237 10238 if (!attr->func_info_cnt && !attr->line_info_cnt) { 10239 if (check_abnormal_return(env)) 10240 return -EINVAL; 10241 return 0; 10242 } 10243 10244 btf = btf_get_by_fd(attr->prog_btf_fd); 10245 if (IS_ERR(btf)) 10246 return PTR_ERR(btf); 10247 if (btf_is_kernel(btf)) { 10248 btf_put(btf); 10249 return -EACCES; 10250 } 10251 env->prog->aux->btf = btf; 10252 10253 err = check_btf_func(env, attr, uattr); 10254 if (err) 10255 return err; 10256 10257 err = check_btf_line(env, attr, uattr); 10258 if (err) 10259 return err; 10260 10261 return 0; 10262 } 10263 10264 /* check %cur's range satisfies %old's */ 10265 static bool range_within(struct bpf_reg_state *old, 10266 struct bpf_reg_state *cur) 10267 { 10268 return old->umin_value <= cur->umin_value && 10269 old->umax_value >= cur->umax_value && 10270 old->smin_value <= cur->smin_value && 10271 old->smax_value >= cur->smax_value && 10272 old->u32_min_value <= cur->u32_min_value && 10273 old->u32_max_value >= cur->u32_max_value && 10274 old->s32_min_value <= cur->s32_min_value && 10275 old->s32_max_value >= cur->s32_max_value; 10276 } 10277 10278 /* If in the old state two registers had the same id, then they need to have 10279 * the same id in the new state as well. But that id could be different from 10280 * the old state, so we need to track the mapping from old to new ids. 10281 * Once we have seen that, say, a reg with old id 5 had new id 9, any subsequent 10282 * regs with old id 5 must also have new id 9 for the new state to be safe. But 10283 * regs with a different old id could still have new id 9, we don't care about 10284 * that. 10285 * So we look through our idmap to see if this old id has been seen before. If 10286 * so, we require the new id to match; otherwise, we add the id pair to the map. 10287 */ 10288 static bool check_ids(u32 old_id, u32 cur_id, struct bpf_id_pair *idmap) 10289 { 10290 unsigned int i; 10291 10292 for (i = 0; i < BPF_ID_MAP_SIZE; i++) { 10293 if (!idmap[i].old) { 10294 /* Reached an empty slot; haven't seen this id before */ 10295 idmap[i].old = old_id; 10296 idmap[i].cur = cur_id; 10297 return true; 10298 } 10299 if (idmap[i].old == old_id) 10300 return idmap[i].cur == cur_id; 10301 } 10302 /* We ran out of idmap slots, which should be impossible */ 10303 WARN_ON_ONCE(1); 10304 return false; 10305 } 10306 10307 static void clean_func_state(struct bpf_verifier_env *env, 10308 struct bpf_func_state *st) 10309 { 10310 enum bpf_reg_liveness live; 10311 int i, j; 10312 10313 for (i = 0; i < BPF_REG_FP; i++) { 10314 live = st->regs[i].live; 10315 /* liveness must not touch this register anymore */ 10316 st->regs[i].live |= REG_LIVE_DONE; 10317 if (!(live & REG_LIVE_READ)) 10318 /* since the register is unused, clear its state 10319 * to make further comparison simpler 10320 */ 10321 __mark_reg_not_init(env, &st->regs[i]); 10322 } 10323 10324 for (i = 0; i < st->allocated_stack / BPF_REG_SIZE; i++) { 10325 live = st->stack[i].spilled_ptr.live; 10326 /* liveness must not touch this stack slot anymore */ 10327 st->stack[i].spilled_ptr.live |= REG_LIVE_DONE; 10328 if (!(live & REG_LIVE_READ)) { 10329 __mark_reg_not_init(env, &st->stack[i].spilled_ptr); 10330 for (j = 0; j < BPF_REG_SIZE; j++) 10331 st->stack[i].slot_type[j] = STACK_INVALID; 10332 } 10333 } 10334 } 10335 10336 static void clean_verifier_state(struct bpf_verifier_env *env, 10337 struct bpf_verifier_state *st) 10338 { 10339 int i; 10340 10341 if (st->frame[0]->regs[0].live & REG_LIVE_DONE) 10342 /* all regs in this state in all frames were already marked */ 10343 return; 10344 10345 for (i = 0; i <= st->curframe; i++) 10346 clean_func_state(env, st->frame[i]); 10347 } 10348 10349 /* the parentage chains form a tree. 10350 * the verifier states are added to state lists at given insn and 10351 * pushed into state stack for future exploration. 10352 * when the verifier reaches bpf_exit insn some of the verifer states 10353 * stored in the state lists have their final liveness state already, 10354 * but a lot of states will get revised from liveness point of view when 10355 * the verifier explores other branches. 10356 * Example: 10357 * 1: r0 = 1 10358 * 2: if r1 == 100 goto pc+1 10359 * 3: r0 = 2 10360 * 4: exit 10361 * when the verifier reaches exit insn the register r0 in the state list of 10362 * insn 2 will be seen as !REG_LIVE_READ. Then the verifier pops the other_branch 10363 * of insn 2 and goes exploring further. At the insn 4 it will walk the 10364 * parentage chain from insn 4 into insn 2 and will mark r0 as REG_LIVE_READ. 10365 * 10366 * Since the verifier pushes the branch states as it sees them while exploring 10367 * the program the condition of walking the branch instruction for the second 10368 * time means that all states below this branch were already explored and 10369 * their final liveness marks are already propagated. 10370 * Hence when the verifier completes the search of state list in is_state_visited() 10371 * we can call this clean_live_states() function to mark all liveness states 10372 * as REG_LIVE_DONE to indicate that 'parent' pointers of 'struct bpf_reg_state' 10373 * will not be used. 10374 * This function also clears the registers and stack for states that !READ 10375 * to simplify state merging. 10376 * 10377 * Important note here that walking the same branch instruction in the callee 10378 * doesn't meant that the states are DONE. The verifier has to compare 10379 * the callsites 10380 */ 10381 static void clean_live_states(struct bpf_verifier_env *env, int insn, 10382 struct bpf_verifier_state *cur) 10383 { 10384 struct bpf_verifier_state_list *sl; 10385 int i; 10386 10387 sl = *explored_state(env, insn); 10388 while (sl) { 10389 if (sl->state.branches) 10390 goto next; 10391 if (sl->state.insn_idx != insn || 10392 sl->state.curframe != cur->curframe) 10393 goto next; 10394 for (i = 0; i <= cur->curframe; i++) 10395 if (sl->state.frame[i]->callsite != cur->frame[i]->callsite) 10396 goto next; 10397 clean_verifier_state(env, &sl->state); 10398 next: 10399 sl = sl->next; 10400 } 10401 } 10402 10403 /* Returns true if (rold safe implies rcur safe) */ 10404 static bool regsafe(struct bpf_verifier_env *env, struct bpf_reg_state *rold, 10405 struct bpf_reg_state *rcur, struct bpf_id_pair *idmap) 10406 { 10407 bool equal; 10408 10409 if (!(rold->live & REG_LIVE_READ)) 10410 /* explored state didn't use this */ 10411 return true; 10412 10413 equal = memcmp(rold, rcur, offsetof(struct bpf_reg_state, parent)) == 0; 10414 10415 if (rold->type == PTR_TO_STACK) 10416 /* two stack pointers are equal only if they're pointing to 10417 * the same stack frame, since fp-8 in foo != fp-8 in bar 10418 */ 10419 return equal && rold->frameno == rcur->frameno; 10420 10421 if (equal) 10422 return true; 10423 10424 if (rold->type == NOT_INIT) 10425 /* explored state can't have used this */ 10426 return true; 10427 if (rcur->type == NOT_INIT) 10428 return false; 10429 switch (rold->type) { 10430 case SCALAR_VALUE: 10431 if (env->explore_alu_limits) 10432 return false; 10433 if (rcur->type == SCALAR_VALUE) { 10434 if (!rold->precise && !rcur->precise) 10435 return true; 10436 /* new val must satisfy old val knowledge */ 10437 return range_within(rold, rcur) && 10438 tnum_in(rold->var_off, rcur->var_off); 10439 } else { 10440 /* We're trying to use a pointer in place of a scalar. 10441 * Even if the scalar was unbounded, this could lead to 10442 * pointer leaks because scalars are allowed to leak 10443 * while pointers are not. We could make this safe in 10444 * special cases if root is calling us, but it's 10445 * probably not worth the hassle. 10446 */ 10447 return false; 10448 } 10449 case PTR_TO_MAP_KEY: 10450 case PTR_TO_MAP_VALUE: 10451 /* If the new min/max/var_off satisfy the old ones and 10452 * everything else matches, we are OK. 10453 * 'id' is not compared, since it's only used for maps with 10454 * bpf_spin_lock inside map element and in such cases if 10455 * the rest of the prog is valid for one map element then 10456 * it's valid for all map elements regardless of the key 10457 * used in bpf_map_lookup() 10458 */ 10459 return memcmp(rold, rcur, offsetof(struct bpf_reg_state, id)) == 0 && 10460 range_within(rold, rcur) && 10461 tnum_in(rold->var_off, rcur->var_off); 10462 case PTR_TO_MAP_VALUE_OR_NULL: 10463 /* a PTR_TO_MAP_VALUE could be safe to use as a 10464 * PTR_TO_MAP_VALUE_OR_NULL into the same map. 10465 * However, if the old PTR_TO_MAP_VALUE_OR_NULL then got NULL- 10466 * checked, doing so could have affected others with the same 10467 * id, and we can't check for that because we lost the id when 10468 * we converted to a PTR_TO_MAP_VALUE. 10469 */ 10470 if (rcur->type != PTR_TO_MAP_VALUE_OR_NULL) 10471 return false; 10472 if (memcmp(rold, rcur, offsetof(struct bpf_reg_state, id))) 10473 return false; 10474 /* Check our ids match any regs they're supposed to */ 10475 return check_ids(rold->id, rcur->id, idmap); 10476 case PTR_TO_PACKET_META: 10477 case PTR_TO_PACKET: 10478 if (rcur->type != rold->type) 10479 return false; 10480 /* We must have at least as much range as the old ptr 10481 * did, so that any accesses which were safe before are 10482 * still safe. This is true even if old range < old off, 10483 * since someone could have accessed through (ptr - k), or 10484 * even done ptr -= k in a register, to get a safe access. 10485 */ 10486 if (rold->range > rcur->range) 10487 return false; 10488 /* If the offsets don't match, we can't trust our alignment; 10489 * nor can we be sure that we won't fall out of range. 10490 */ 10491 if (rold->off != rcur->off) 10492 return false; 10493 /* id relations must be preserved */ 10494 if (rold->id && !check_ids(rold->id, rcur->id, idmap)) 10495 return false; 10496 /* new val must satisfy old val knowledge */ 10497 return range_within(rold, rcur) && 10498 tnum_in(rold->var_off, rcur->var_off); 10499 case PTR_TO_CTX: 10500 case CONST_PTR_TO_MAP: 10501 case PTR_TO_PACKET_END: 10502 case PTR_TO_FLOW_KEYS: 10503 case PTR_TO_SOCKET: 10504 case PTR_TO_SOCKET_OR_NULL: 10505 case PTR_TO_SOCK_COMMON: 10506 case PTR_TO_SOCK_COMMON_OR_NULL: 10507 case PTR_TO_TCP_SOCK: 10508 case PTR_TO_TCP_SOCK_OR_NULL: 10509 case PTR_TO_XDP_SOCK: 10510 /* Only valid matches are exact, which memcmp() above 10511 * would have accepted 10512 */ 10513 default: 10514 /* Don't know what's going on, just say it's not safe */ 10515 return false; 10516 } 10517 10518 /* Shouldn't get here; if we do, say it's not safe */ 10519 WARN_ON_ONCE(1); 10520 return false; 10521 } 10522 10523 static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, 10524 struct bpf_func_state *cur, struct bpf_id_pair *idmap) 10525 { 10526 int i, spi; 10527 10528 /* walk slots of the explored stack and ignore any additional 10529 * slots in the current stack, since explored(safe) state 10530 * didn't use them 10531 */ 10532 for (i = 0; i < old->allocated_stack; i++) { 10533 spi = i / BPF_REG_SIZE; 10534 10535 if (!(old->stack[spi].spilled_ptr.live & REG_LIVE_READ)) { 10536 i += BPF_REG_SIZE - 1; 10537 /* explored state didn't use this */ 10538 continue; 10539 } 10540 10541 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_INVALID) 10542 continue; 10543 10544 /* explored stack has more populated slots than current stack 10545 * and these slots were used 10546 */ 10547 if (i >= cur->allocated_stack) 10548 return false; 10549 10550 /* if old state was safe with misc data in the stack 10551 * it will be safe with zero-initialized stack. 10552 * The opposite is not true 10553 */ 10554 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_MISC && 10555 cur->stack[spi].slot_type[i % BPF_REG_SIZE] == STACK_ZERO) 10556 continue; 10557 if (old->stack[spi].slot_type[i % BPF_REG_SIZE] != 10558 cur->stack[spi].slot_type[i % BPF_REG_SIZE]) 10559 /* Ex: old explored (safe) state has STACK_SPILL in 10560 * this stack slot, but current has STACK_MISC -> 10561 * this verifier states are not equivalent, 10562 * return false to continue verification of this path 10563 */ 10564 return false; 10565 if (i % BPF_REG_SIZE != BPF_REG_SIZE - 1) 10566 continue; 10567 if (!is_spilled_reg(&old->stack[spi])) 10568 continue; 10569 if (!regsafe(env, &old->stack[spi].spilled_ptr, 10570 &cur->stack[spi].spilled_ptr, idmap)) 10571 /* when explored and current stack slot are both storing 10572 * spilled registers, check that stored pointers types 10573 * are the same as well. 10574 * Ex: explored safe path could have stored 10575 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -8} 10576 * but current path has stored: 10577 * (bpf_reg_state) {.type = PTR_TO_STACK, .off = -16} 10578 * such verifier states are not equivalent. 10579 * return false to continue verification of this path 10580 */ 10581 return false; 10582 } 10583 return true; 10584 } 10585 10586 static bool refsafe(struct bpf_func_state *old, struct bpf_func_state *cur) 10587 { 10588 if (old->acquired_refs != cur->acquired_refs) 10589 return false; 10590 return !memcmp(old->refs, cur->refs, 10591 sizeof(*old->refs) * old->acquired_refs); 10592 } 10593 10594 /* compare two verifier states 10595 * 10596 * all states stored in state_list are known to be valid, since 10597 * verifier reached 'bpf_exit' instruction through them 10598 * 10599 * this function is called when verifier exploring different branches of 10600 * execution popped from the state stack. If it sees an old state that has 10601 * more strict register state and more strict stack state then this execution 10602 * branch doesn't need to be explored further, since verifier already 10603 * concluded that more strict state leads to valid finish. 10604 * 10605 * Therefore two states are equivalent if register state is more conservative 10606 * and explored stack state is more conservative than the current one. 10607 * Example: 10608 * explored current 10609 * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) 10610 * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) 10611 * 10612 * In other words if current stack state (one being explored) has more 10613 * valid slots than old one that already passed validation, it means 10614 * the verifier can stop exploring and conclude that current state is valid too 10615 * 10616 * Similarly with registers. If explored state has register type as invalid 10617 * whereas register type in current state is meaningful, it means that 10618 * the current state will reach 'bpf_exit' instruction safely 10619 */ 10620 static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_state *old, 10621 struct bpf_func_state *cur) 10622 { 10623 int i; 10624 10625 memset(env->idmap_scratch, 0, sizeof(env->idmap_scratch)); 10626 for (i = 0; i < MAX_BPF_REG; i++) 10627 if (!regsafe(env, &old->regs[i], &cur->regs[i], 10628 env->idmap_scratch)) 10629 return false; 10630 10631 if (!stacksafe(env, old, cur, env->idmap_scratch)) 10632 return false; 10633 10634 if (!refsafe(old, cur)) 10635 return false; 10636 10637 return true; 10638 } 10639 10640 static bool states_equal(struct bpf_verifier_env *env, 10641 struct bpf_verifier_state *old, 10642 struct bpf_verifier_state *cur) 10643 { 10644 int i; 10645 10646 if (old->curframe != cur->curframe) 10647 return false; 10648 10649 /* Verification state from speculative execution simulation 10650 * must never prune a non-speculative execution one. 10651 */ 10652 if (old->speculative && !cur->speculative) 10653 return false; 10654 10655 if (old->active_spin_lock != cur->active_spin_lock) 10656 return false; 10657 10658 /* for states to be equal callsites have to be the same 10659 * and all frame states need to be equivalent 10660 */ 10661 for (i = 0; i <= old->curframe; i++) { 10662 if (old->frame[i]->callsite != cur->frame[i]->callsite) 10663 return false; 10664 if (!func_states_equal(env, old->frame[i], cur->frame[i])) 10665 return false; 10666 } 10667 return true; 10668 } 10669 10670 /* Return 0 if no propagation happened. Return negative error code if error 10671 * happened. Otherwise, return the propagated bit. 10672 */ 10673 static int propagate_liveness_reg(struct bpf_verifier_env *env, 10674 struct bpf_reg_state *reg, 10675 struct bpf_reg_state *parent_reg) 10676 { 10677 u8 parent_flag = parent_reg->live & REG_LIVE_READ; 10678 u8 flag = reg->live & REG_LIVE_READ; 10679 int err; 10680 10681 /* When comes here, read flags of PARENT_REG or REG could be any of 10682 * REG_LIVE_READ64, REG_LIVE_READ32, REG_LIVE_NONE. There is no need 10683 * of propagation if PARENT_REG has strongest REG_LIVE_READ64. 10684 */ 10685 if (parent_flag == REG_LIVE_READ64 || 10686 /* Or if there is no read flag from REG. */ 10687 !flag || 10688 /* Or if the read flag from REG is the same as PARENT_REG. */ 10689 parent_flag == flag) 10690 return 0; 10691 10692 err = mark_reg_read(env, reg, parent_reg, flag); 10693 if (err) 10694 return err; 10695 10696 return flag; 10697 } 10698 10699 /* A write screens off any subsequent reads; but write marks come from the 10700 * straight-line code between a state and its parent. When we arrive at an 10701 * equivalent state (jump target or such) we didn't arrive by the straight-line 10702 * code, so read marks in the state must propagate to the parent regardless 10703 * of the state's write marks. That's what 'parent == state->parent' comparison 10704 * in mark_reg_read() is for. 10705 */ 10706 static int propagate_liveness(struct bpf_verifier_env *env, 10707 const struct bpf_verifier_state *vstate, 10708 struct bpf_verifier_state *vparent) 10709 { 10710 struct bpf_reg_state *state_reg, *parent_reg; 10711 struct bpf_func_state *state, *parent; 10712 int i, frame, err = 0; 10713 10714 if (vparent->curframe != vstate->curframe) { 10715 WARN(1, "propagate_live: parent frame %d current frame %d\n", 10716 vparent->curframe, vstate->curframe); 10717 return -EFAULT; 10718 } 10719 /* Propagate read liveness of registers... */ 10720 BUILD_BUG_ON(BPF_REG_FP + 1 != MAX_BPF_REG); 10721 for (frame = 0; frame <= vstate->curframe; frame++) { 10722 parent = vparent->frame[frame]; 10723 state = vstate->frame[frame]; 10724 parent_reg = parent->regs; 10725 state_reg = state->regs; 10726 /* We don't need to worry about FP liveness, it's read-only */ 10727 for (i = frame < vstate->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) { 10728 err = propagate_liveness_reg(env, &state_reg[i], 10729 &parent_reg[i]); 10730 if (err < 0) 10731 return err; 10732 if (err == REG_LIVE_READ64) 10733 mark_insn_zext(env, &parent_reg[i]); 10734 } 10735 10736 /* Propagate stack slots. */ 10737 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE && 10738 i < parent->allocated_stack / BPF_REG_SIZE; i++) { 10739 parent_reg = &parent->stack[i].spilled_ptr; 10740 state_reg = &state->stack[i].spilled_ptr; 10741 err = propagate_liveness_reg(env, state_reg, 10742 parent_reg); 10743 if (err < 0) 10744 return err; 10745 } 10746 } 10747 return 0; 10748 } 10749 10750 /* find precise scalars in the previous equivalent state and 10751 * propagate them into the current state 10752 */ 10753 static int propagate_precision(struct bpf_verifier_env *env, 10754 const struct bpf_verifier_state *old) 10755 { 10756 struct bpf_reg_state *state_reg; 10757 struct bpf_func_state *state; 10758 int i, err = 0; 10759 10760 state = old->frame[old->curframe]; 10761 state_reg = state->regs; 10762 for (i = 0; i < BPF_REG_FP; i++, state_reg++) { 10763 if (state_reg->type != SCALAR_VALUE || 10764 !state_reg->precise) 10765 continue; 10766 if (env->log.level & BPF_LOG_LEVEL2) 10767 verbose(env, "propagating r%d\n", i); 10768 err = mark_chain_precision(env, i); 10769 if (err < 0) 10770 return err; 10771 } 10772 10773 for (i = 0; i < state->allocated_stack / BPF_REG_SIZE; i++) { 10774 if (!is_spilled_reg(&state->stack[i])) 10775 continue; 10776 state_reg = &state->stack[i].spilled_ptr; 10777 if (state_reg->type != SCALAR_VALUE || 10778 !state_reg->precise) 10779 continue; 10780 if (env->log.level & BPF_LOG_LEVEL2) 10781 verbose(env, "propagating fp%d\n", 10782 (-i - 1) * BPF_REG_SIZE); 10783 err = mark_chain_precision_stack(env, i); 10784 if (err < 0) 10785 return err; 10786 } 10787 return 0; 10788 } 10789 10790 static bool states_maybe_looping(struct bpf_verifier_state *old, 10791 struct bpf_verifier_state *cur) 10792 { 10793 struct bpf_func_state *fold, *fcur; 10794 int i, fr = cur->curframe; 10795 10796 if (old->curframe != fr) 10797 return false; 10798 10799 fold = old->frame[fr]; 10800 fcur = cur->frame[fr]; 10801 for (i = 0; i < MAX_BPF_REG; i++) 10802 if (memcmp(&fold->regs[i], &fcur->regs[i], 10803 offsetof(struct bpf_reg_state, parent))) 10804 return false; 10805 return true; 10806 } 10807 10808 10809 static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) 10810 { 10811 struct bpf_verifier_state_list *new_sl; 10812 struct bpf_verifier_state_list *sl, **pprev; 10813 struct bpf_verifier_state *cur = env->cur_state, *new; 10814 int i, j, err, states_cnt = 0; 10815 bool add_new_state = env->test_state_freq ? true : false; 10816 10817 cur->last_insn_idx = env->prev_insn_idx; 10818 if (!env->insn_aux_data[insn_idx].prune_point) 10819 /* this 'insn_idx' instruction wasn't marked, so we will not 10820 * be doing state search here 10821 */ 10822 return 0; 10823 10824 /* bpf progs typically have pruning point every 4 instructions 10825 * http://vger.kernel.org/bpfconf2019.html#session-1 10826 * Do not add new state for future pruning if the verifier hasn't seen 10827 * at least 2 jumps and at least 8 instructions. 10828 * This heuristics helps decrease 'total_states' and 'peak_states' metric. 10829 * In tests that amounts to up to 50% reduction into total verifier 10830 * memory consumption and 20% verifier time speedup. 10831 */ 10832 if (env->jmps_processed - env->prev_jmps_processed >= 2 && 10833 env->insn_processed - env->prev_insn_processed >= 8) 10834 add_new_state = true; 10835 10836 pprev = explored_state(env, insn_idx); 10837 sl = *pprev; 10838 10839 clean_live_states(env, insn_idx, cur); 10840 10841 while (sl) { 10842 states_cnt++; 10843 if (sl->state.insn_idx != insn_idx) 10844 goto next; 10845 10846 if (sl->state.branches) { 10847 struct bpf_func_state *frame = sl->state.frame[sl->state.curframe]; 10848 10849 if (frame->in_async_callback_fn && 10850 frame->async_entry_cnt != cur->frame[cur->curframe]->async_entry_cnt) { 10851 /* Different async_entry_cnt means that the verifier is 10852 * processing another entry into async callback. 10853 * Seeing the same state is not an indication of infinite 10854 * loop or infinite recursion. 10855 * But finding the same state doesn't mean that it's safe 10856 * to stop processing the current state. The previous state 10857 * hasn't yet reached bpf_exit, since state.branches > 0. 10858 * Checking in_async_callback_fn alone is not enough either. 10859 * Since the verifier still needs to catch infinite loops 10860 * inside async callbacks. 10861 */ 10862 } else if (states_maybe_looping(&sl->state, cur) && 10863 states_equal(env, &sl->state, cur)) { 10864 verbose_linfo(env, insn_idx, "; "); 10865 verbose(env, "infinite loop detected at insn %d\n", insn_idx); 10866 return -EINVAL; 10867 } 10868 /* if the verifier is processing a loop, avoid adding new state 10869 * too often, since different loop iterations have distinct 10870 * states and may not help future pruning. 10871 * This threshold shouldn't be too low to make sure that 10872 * a loop with large bound will be rejected quickly. 10873 * The most abusive loop will be: 10874 * r1 += 1 10875 * if r1 < 1000000 goto pc-2 10876 * 1M insn_procssed limit / 100 == 10k peak states. 10877 * This threshold shouldn't be too high either, since states 10878 * at the end of the loop are likely to be useful in pruning. 10879 */ 10880 if (env->jmps_processed - env->prev_jmps_processed < 20 && 10881 env->insn_processed - env->prev_insn_processed < 100) 10882 add_new_state = false; 10883 goto miss; 10884 } 10885 if (states_equal(env, &sl->state, cur)) { 10886 sl->hit_cnt++; 10887 /* reached equivalent register/stack state, 10888 * prune the search. 10889 * Registers read by the continuation are read by us. 10890 * If we have any write marks in env->cur_state, they 10891 * will prevent corresponding reads in the continuation 10892 * from reaching our parent (an explored_state). Our 10893 * own state will get the read marks recorded, but 10894 * they'll be immediately forgotten as we're pruning 10895 * this state and will pop a new one. 10896 */ 10897 err = propagate_liveness(env, &sl->state, cur); 10898 10899 /* if previous state reached the exit with precision and 10900 * current state is equivalent to it (except precsion marks) 10901 * the precision needs to be propagated back in 10902 * the current state. 10903 */ 10904 err = err ? : push_jmp_history(env, cur); 10905 err = err ? : propagate_precision(env, &sl->state); 10906 if (err) 10907 return err; 10908 return 1; 10909 } 10910 miss: 10911 /* when new state is not going to be added do not increase miss count. 10912 * Otherwise several loop iterations will remove the state 10913 * recorded earlier. The goal of these heuristics is to have 10914 * states from some iterations of the loop (some in the beginning 10915 * and some at the end) to help pruning. 10916 */ 10917 if (add_new_state) 10918 sl->miss_cnt++; 10919 /* heuristic to determine whether this state is beneficial 10920 * to keep checking from state equivalence point of view. 10921 * Higher numbers increase max_states_per_insn and verification time, 10922 * but do not meaningfully decrease insn_processed. 10923 */ 10924 if (sl->miss_cnt > sl->hit_cnt * 3 + 3) { 10925 /* the state is unlikely to be useful. Remove it to 10926 * speed up verification 10927 */ 10928 *pprev = sl->next; 10929 if (sl->state.frame[0]->regs[0].live & REG_LIVE_DONE) { 10930 u32 br = sl->state.branches; 10931 10932 WARN_ONCE(br, 10933 "BUG live_done but branches_to_explore %d\n", 10934 br); 10935 free_verifier_state(&sl->state, false); 10936 kfree(sl); 10937 env->peak_states--; 10938 } else { 10939 /* cannot free this state, since parentage chain may 10940 * walk it later. Add it for free_list instead to 10941 * be freed at the end of verification 10942 */ 10943 sl->next = env->free_list; 10944 env->free_list = sl; 10945 } 10946 sl = *pprev; 10947 continue; 10948 } 10949 next: 10950 pprev = &sl->next; 10951 sl = *pprev; 10952 } 10953 10954 if (env->max_states_per_insn < states_cnt) 10955 env->max_states_per_insn = states_cnt; 10956 10957 if (!env->bpf_capable && states_cnt > BPF_COMPLEXITY_LIMIT_STATES) 10958 return push_jmp_history(env, cur); 10959 10960 if (!add_new_state) 10961 return push_jmp_history(env, cur); 10962 10963 /* There were no equivalent states, remember the current one. 10964 * Technically the current state is not proven to be safe yet, 10965 * but it will either reach outer most bpf_exit (which means it's safe) 10966 * or it will be rejected. When there are no loops the verifier won't be 10967 * seeing this tuple (frame[0].callsite, frame[1].callsite, .. insn_idx) 10968 * again on the way to bpf_exit. 10969 * When looping the sl->state.branches will be > 0 and this state 10970 * will not be considered for equivalence until branches == 0. 10971 */ 10972 new_sl = kzalloc(sizeof(struct bpf_verifier_state_list), GFP_KERNEL); 10973 if (!new_sl) 10974 return -ENOMEM; 10975 env->total_states++; 10976 env->peak_states++; 10977 env->prev_jmps_processed = env->jmps_processed; 10978 env->prev_insn_processed = env->insn_processed; 10979 10980 /* add new state to the head of linked list */ 10981 new = &new_sl->state; 10982 err = copy_verifier_state(new, cur); 10983 if (err) { 10984 free_verifier_state(new, false); 10985 kfree(new_sl); 10986 return err; 10987 } 10988 new->insn_idx = insn_idx; 10989 WARN_ONCE(new->branches != 1, 10990 "BUG is_state_visited:branches_to_explore=%d insn %d\n", new->branches, insn_idx); 10991 10992 cur->parent = new; 10993 cur->first_insn_idx = insn_idx; 10994 clear_jmp_history(cur); 10995 new_sl->next = *explored_state(env, insn_idx); 10996 *explored_state(env, insn_idx) = new_sl; 10997 /* connect new state to parentage chain. Current frame needs all 10998 * registers connected. Only r6 - r9 of the callers are alive (pushed 10999 * to the stack implicitly by JITs) so in callers' frames connect just 11000 * r6 - r9 as an optimization. Callers will have r1 - r5 connected to 11001 * the state of the call instruction (with WRITTEN set), and r0 comes 11002 * from callee with its full parentage chain, anyway. 11003 */ 11004 /* clear write marks in current state: the writes we did are not writes 11005 * our child did, so they don't screen off its reads from us. 11006 * (There are no read marks in current state, because reads always mark 11007 * their parent and current state never has children yet. Only 11008 * explored_states can get read marks.) 11009 */ 11010 for (j = 0; j <= cur->curframe; j++) { 11011 for (i = j < cur->curframe ? BPF_REG_6 : 0; i < BPF_REG_FP; i++) 11012 cur->frame[j]->regs[i].parent = &new->frame[j]->regs[i]; 11013 for (i = 0; i < BPF_REG_FP; i++) 11014 cur->frame[j]->regs[i].live = REG_LIVE_NONE; 11015 } 11016 11017 /* all stack frames are accessible from callee, clear them all */ 11018 for (j = 0; j <= cur->curframe; j++) { 11019 struct bpf_func_state *frame = cur->frame[j]; 11020 struct bpf_func_state *newframe = new->frame[j]; 11021 11022 for (i = 0; i < frame->allocated_stack / BPF_REG_SIZE; i++) { 11023 frame->stack[i].spilled_ptr.live = REG_LIVE_NONE; 11024 frame->stack[i].spilled_ptr.parent = 11025 &newframe->stack[i].spilled_ptr; 11026 } 11027 } 11028 return 0; 11029 } 11030 11031 /* Return true if it's OK to have the same insn return a different type. */ 11032 static bool reg_type_mismatch_ok(enum bpf_reg_type type) 11033 { 11034 switch (type) { 11035 case PTR_TO_CTX: 11036 case PTR_TO_SOCKET: 11037 case PTR_TO_SOCKET_OR_NULL: 11038 case PTR_TO_SOCK_COMMON: 11039 case PTR_TO_SOCK_COMMON_OR_NULL: 11040 case PTR_TO_TCP_SOCK: 11041 case PTR_TO_TCP_SOCK_OR_NULL: 11042 case PTR_TO_XDP_SOCK: 11043 case PTR_TO_BTF_ID: 11044 case PTR_TO_BTF_ID_OR_NULL: 11045 return false; 11046 default: 11047 return true; 11048 } 11049 } 11050 11051 /* If an instruction was previously used with particular pointer types, then we 11052 * need to be careful to avoid cases such as the below, where it may be ok 11053 * for one branch accessing the pointer, but not ok for the other branch: 11054 * 11055 * R1 = sock_ptr 11056 * goto X; 11057 * ... 11058 * R1 = some_other_valid_ptr; 11059 * goto X; 11060 * ... 11061 * R2 = *(u32 *)(R1 + 0); 11062 */ 11063 static bool reg_type_mismatch(enum bpf_reg_type src, enum bpf_reg_type prev) 11064 { 11065 return src != prev && (!reg_type_mismatch_ok(src) || 11066 !reg_type_mismatch_ok(prev)); 11067 } 11068 11069 static int do_check(struct bpf_verifier_env *env) 11070 { 11071 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 11072 struct bpf_verifier_state *state = env->cur_state; 11073 struct bpf_insn *insns = env->prog->insnsi; 11074 struct bpf_reg_state *regs; 11075 int insn_cnt = env->prog->len; 11076 bool do_print_state = false; 11077 int prev_insn_idx = -1; 11078 11079 for (;;) { 11080 struct bpf_insn *insn; 11081 u8 class; 11082 int err; 11083 11084 env->prev_insn_idx = prev_insn_idx; 11085 if (env->insn_idx >= insn_cnt) { 11086 verbose(env, "invalid insn idx %d insn_cnt %d\n", 11087 env->insn_idx, insn_cnt); 11088 return -EFAULT; 11089 } 11090 11091 insn = &insns[env->insn_idx]; 11092 class = BPF_CLASS(insn->code); 11093 11094 if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { 11095 verbose(env, 11096 "BPF program is too large. Processed %d insn\n", 11097 env->insn_processed); 11098 return -E2BIG; 11099 } 11100 11101 err = is_state_visited(env, env->insn_idx); 11102 if (err < 0) 11103 return err; 11104 if (err == 1) { 11105 /* found equivalent state, can prune the search */ 11106 if (env->log.level & BPF_LOG_LEVEL) { 11107 if (do_print_state) 11108 verbose(env, "\nfrom %d to %d%s: safe\n", 11109 env->prev_insn_idx, env->insn_idx, 11110 env->cur_state->speculative ? 11111 " (speculative execution)" : ""); 11112 else 11113 verbose(env, "%d: safe\n", env->insn_idx); 11114 } 11115 goto process_bpf_exit; 11116 } 11117 11118 if (signal_pending(current)) 11119 return -EAGAIN; 11120 11121 if (need_resched()) 11122 cond_resched(); 11123 11124 if (env->log.level & BPF_LOG_LEVEL2 || 11125 (env->log.level & BPF_LOG_LEVEL && do_print_state)) { 11126 if (env->log.level & BPF_LOG_LEVEL2) 11127 verbose(env, "%d:", env->insn_idx); 11128 else 11129 verbose(env, "\nfrom %d to %d%s:", 11130 env->prev_insn_idx, env->insn_idx, 11131 env->cur_state->speculative ? 11132 " (speculative execution)" : ""); 11133 print_verifier_state(env, state->frame[state->curframe]); 11134 do_print_state = false; 11135 } 11136 11137 if (env->log.level & BPF_LOG_LEVEL) { 11138 const struct bpf_insn_cbs cbs = { 11139 .cb_call = disasm_kfunc_name, 11140 .cb_print = verbose, 11141 .private_data = env, 11142 }; 11143 11144 verbose_linfo(env, env->insn_idx, "; "); 11145 verbose(env, "%d: ", env->insn_idx); 11146 print_bpf_insn(&cbs, insn, env->allow_ptr_leaks); 11147 } 11148 11149 if (bpf_prog_is_dev_bound(env->prog->aux)) { 11150 err = bpf_prog_offload_verify_insn(env, env->insn_idx, 11151 env->prev_insn_idx); 11152 if (err) 11153 return err; 11154 } 11155 11156 regs = cur_regs(env); 11157 sanitize_mark_insn_seen(env); 11158 prev_insn_idx = env->insn_idx; 11159 11160 if (class == BPF_ALU || class == BPF_ALU64) { 11161 err = check_alu_op(env, insn); 11162 if (err) 11163 return err; 11164 11165 } else if (class == BPF_LDX) { 11166 enum bpf_reg_type *prev_src_type, src_reg_type; 11167 11168 /* check for reserved fields is already done */ 11169 11170 /* check src operand */ 11171 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11172 if (err) 11173 return err; 11174 11175 err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK); 11176 if (err) 11177 return err; 11178 11179 src_reg_type = regs[insn->src_reg].type; 11180 11181 /* check that memory (src_reg + off) is readable, 11182 * the state of dst_reg will be updated by this func 11183 */ 11184 err = check_mem_access(env, env->insn_idx, insn->src_reg, 11185 insn->off, BPF_SIZE(insn->code), 11186 BPF_READ, insn->dst_reg, false); 11187 if (err) 11188 return err; 11189 11190 prev_src_type = &env->insn_aux_data[env->insn_idx].ptr_type; 11191 11192 if (*prev_src_type == NOT_INIT) { 11193 /* saw a valid insn 11194 * dst_reg = *(u32 *)(src_reg + off) 11195 * save type to validate intersecting paths 11196 */ 11197 *prev_src_type = src_reg_type; 11198 11199 } else if (reg_type_mismatch(src_reg_type, *prev_src_type)) { 11200 /* ABuser program is trying to use the same insn 11201 * dst_reg = *(u32*) (src_reg + off) 11202 * with different pointer types: 11203 * src_reg == ctx in one branch and 11204 * src_reg == stack|map in some other branch. 11205 * Reject it. 11206 */ 11207 verbose(env, "same insn cannot be used with different pointers\n"); 11208 return -EINVAL; 11209 } 11210 11211 } else if (class == BPF_STX) { 11212 enum bpf_reg_type *prev_dst_type, dst_reg_type; 11213 11214 if (BPF_MODE(insn->code) == BPF_ATOMIC) { 11215 err = check_atomic(env, env->insn_idx, insn); 11216 if (err) 11217 return err; 11218 env->insn_idx++; 11219 continue; 11220 } 11221 11222 if (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0) { 11223 verbose(env, "BPF_STX uses reserved fields\n"); 11224 return -EINVAL; 11225 } 11226 11227 /* check src1 operand */ 11228 err = check_reg_arg(env, insn->src_reg, SRC_OP); 11229 if (err) 11230 return err; 11231 /* check src2 operand */ 11232 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11233 if (err) 11234 return err; 11235 11236 dst_reg_type = regs[insn->dst_reg].type; 11237 11238 /* check that memory (dst_reg + off) is writeable */ 11239 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 11240 insn->off, BPF_SIZE(insn->code), 11241 BPF_WRITE, insn->src_reg, false); 11242 if (err) 11243 return err; 11244 11245 prev_dst_type = &env->insn_aux_data[env->insn_idx].ptr_type; 11246 11247 if (*prev_dst_type == NOT_INIT) { 11248 *prev_dst_type = dst_reg_type; 11249 } else if (reg_type_mismatch(dst_reg_type, *prev_dst_type)) { 11250 verbose(env, "same insn cannot be used with different pointers\n"); 11251 return -EINVAL; 11252 } 11253 11254 } else if (class == BPF_ST) { 11255 if (BPF_MODE(insn->code) != BPF_MEM || 11256 insn->src_reg != BPF_REG_0) { 11257 verbose(env, "BPF_ST uses reserved fields\n"); 11258 return -EINVAL; 11259 } 11260 /* check src operand */ 11261 err = check_reg_arg(env, insn->dst_reg, SRC_OP); 11262 if (err) 11263 return err; 11264 11265 if (is_ctx_reg(env, insn->dst_reg)) { 11266 verbose(env, "BPF_ST stores into R%d %s is not allowed\n", 11267 insn->dst_reg, 11268 reg_type_str[reg_state(env, insn->dst_reg)->type]); 11269 return -EACCES; 11270 } 11271 11272 /* check that memory (dst_reg + off) is writeable */ 11273 err = check_mem_access(env, env->insn_idx, insn->dst_reg, 11274 insn->off, BPF_SIZE(insn->code), 11275 BPF_WRITE, -1, false); 11276 if (err) 11277 return err; 11278 11279 } else if (class == BPF_JMP || class == BPF_JMP32) { 11280 u8 opcode = BPF_OP(insn->code); 11281 11282 env->jmps_processed++; 11283 if (opcode == BPF_CALL) { 11284 if (BPF_SRC(insn->code) != BPF_K || 11285 (insn->src_reg != BPF_PSEUDO_KFUNC_CALL 11286 && insn->off != 0) || 11287 (insn->src_reg != BPF_REG_0 && 11288 insn->src_reg != BPF_PSEUDO_CALL && 11289 insn->src_reg != BPF_PSEUDO_KFUNC_CALL) || 11290 insn->dst_reg != BPF_REG_0 || 11291 class == BPF_JMP32) { 11292 verbose(env, "BPF_CALL uses reserved fields\n"); 11293 return -EINVAL; 11294 } 11295 11296 if (env->cur_state->active_spin_lock && 11297 (insn->src_reg == BPF_PSEUDO_CALL || 11298 insn->imm != BPF_FUNC_spin_unlock)) { 11299 verbose(env, "function calls are not allowed while holding a lock\n"); 11300 return -EINVAL; 11301 } 11302 if (insn->src_reg == BPF_PSEUDO_CALL) 11303 err = check_func_call(env, insn, &env->insn_idx); 11304 else if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) 11305 err = check_kfunc_call(env, insn); 11306 else 11307 err = check_helper_call(env, insn, &env->insn_idx); 11308 if (err) 11309 return err; 11310 } else if (opcode == BPF_JA) { 11311 if (BPF_SRC(insn->code) != BPF_K || 11312 insn->imm != 0 || 11313 insn->src_reg != BPF_REG_0 || 11314 insn->dst_reg != BPF_REG_0 || 11315 class == BPF_JMP32) { 11316 verbose(env, "BPF_JA uses reserved fields\n"); 11317 return -EINVAL; 11318 } 11319 11320 env->insn_idx += insn->off + 1; 11321 continue; 11322 11323 } else if (opcode == BPF_EXIT) { 11324 if (BPF_SRC(insn->code) != BPF_K || 11325 insn->imm != 0 || 11326 insn->src_reg != BPF_REG_0 || 11327 insn->dst_reg != BPF_REG_0 || 11328 class == BPF_JMP32) { 11329 verbose(env, "BPF_EXIT uses reserved fields\n"); 11330 return -EINVAL; 11331 } 11332 11333 if (env->cur_state->active_spin_lock) { 11334 verbose(env, "bpf_spin_unlock is missing\n"); 11335 return -EINVAL; 11336 } 11337 11338 if (state->curframe) { 11339 /* exit from nested function */ 11340 err = prepare_func_exit(env, &env->insn_idx); 11341 if (err) 11342 return err; 11343 do_print_state = true; 11344 continue; 11345 } 11346 11347 err = check_reference_leak(env); 11348 if (err) 11349 return err; 11350 11351 err = check_return_code(env); 11352 if (err) 11353 return err; 11354 process_bpf_exit: 11355 update_branch_counts(env, env->cur_state); 11356 err = pop_stack(env, &prev_insn_idx, 11357 &env->insn_idx, pop_log); 11358 if (err < 0) { 11359 if (err != -ENOENT) 11360 return err; 11361 break; 11362 } else { 11363 do_print_state = true; 11364 continue; 11365 } 11366 } else { 11367 err = check_cond_jmp_op(env, insn, &env->insn_idx); 11368 if (err) 11369 return err; 11370 } 11371 } else if (class == BPF_LD) { 11372 u8 mode = BPF_MODE(insn->code); 11373 11374 if (mode == BPF_ABS || mode == BPF_IND) { 11375 err = check_ld_abs(env, insn); 11376 if (err) 11377 return err; 11378 11379 } else if (mode == BPF_IMM) { 11380 err = check_ld_imm(env, insn); 11381 if (err) 11382 return err; 11383 11384 env->insn_idx++; 11385 sanitize_mark_insn_seen(env); 11386 } else { 11387 verbose(env, "invalid BPF_LD mode\n"); 11388 return -EINVAL; 11389 } 11390 } else { 11391 verbose(env, "unknown insn class %d\n", class); 11392 return -EINVAL; 11393 } 11394 11395 env->insn_idx++; 11396 } 11397 11398 return 0; 11399 } 11400 11401 static int find_btf_percpu_datasec(struct btf *btf) 11402 { 11403 const struct btf_type *t; 11404 const char *tname; 11405 int i, n; 11406 11407 /* 11408 * Both vmlinux and module each have their own ".data..percpu" 11409 * DATASECs in BTF. So for module's case, we need to skip vmlinux BTF 11410 * types to look at only module's own BTF types. 11411 */ 11412 n = btf_nr_types(btf); 11413 if (btf_is_module(btf)) 11414 i = btf_nr_types(btf_vmlinux); 11415 else 11416 i = 1; 11417 11418 for(; i < n; i++) { 11419 t = btf_type_by_id(btf, i); 11420 if (BTF_INFO_KIND(t->info) != BTF_KIND_DATASEC) 11421 continue; 11422 11423 tname = btf_name_by_offset(btf, t->name_off); 11424 if (!strcmp(tname, ".data..percpu")) 11425 return i; 11426 } 11427 11428 return -ENOENT; 11429 } 11430 11431 /* replace pseudo btf_id with kernel symbol address */ 11432 static int check_pseudo_btf_id(struct bpf_verifier_env *env, 11433 struct bpf_insn *insn, 11434 struct bpf_insn_aux_data *aux) 11435 { 11436 const struct btf_var_secinfo *vsi; 11437 const struct btf_type *datasec; 11438 struct btf_mod_pair *btf_mod; 11439 const struct btf_type *t; 11440 const char *sym_name; 11441 bool percpu = false; 11442 u32 type, id = insn->imm; 11443 struct btf *btf; 11444 s32 datasec_id; 11445 u64 addr; 11446 int i, btf_fd, err; 11447 11448 btf_fd = insn[1].imm; 11449 if (btf_fd) { 11450 btf = btf_get_by_fd(btf_fd); 11451 if (IS_ERR(btf)) { 11452 verbose(env, "invalid module BTF object FD specified.\n"); 11453 return -EINVAL; 11454 } 11455 } else { 11456 if (!btf_vmlinux) { 11457 verbose(env, "kernel is missing BTF, make sure CONFIG_DEBUG_INFO_BTF=y is specified in Kconfig.\n"); 11458 return -EINVAL; 11459 } 11460 btf = btf_vmlinux; 11461 btf_get(btf); 11462 } 11463 11464 t = btf_type_by_id(btf, id); 11465 if (!t) { 11466 verbose(env, "ldimm64 insn specifies invalid btf_id %d.\n", id); 11467 err = -ENOENT; 11468 goto err_put; 11469 } 11470 11471 if (!btf_type_is_var(t)) { 11472 verbose(env, "pseudo btf_id %d in ldimm64 isn't KIND_VAR.\n", id); 11473 err = -EINVAL; 11474 goto err_put; 11475 } 11476 11477 sym_name = btf_name_by_offset(btf, t->name_off); 11478 addr = kallsyms_lookup_name(sym_name); 11479 if (!addr) { 11480 verbose(env, "ldimm64 failed to find the address for kernel symbol '%s'.\n", 11481 sym_name); 11482 err = -ENOENT; 11483 goto err_put; 11484 } 11485 11486 datasec_id = find_btf_percpu_datasec(btf); 11487 if (datasec_id > 0) { 11488 datasec = btf_type_by_id(btf, datasec_id); 11489 for_each_vsi(i, datasec, vsi) { 11490 if (vsi->type == id) { 11491 percpu = true; 11492 break; 11493 } 11494 } 11495 } 11496 11497 insn[0].imm = (u32)addr; 11498 insn[1].imm = addr >> 32; 11499 11500 type = t->type; 11501 t = btf_type_skip_modifiers(btf, type, NULL); 11502 if (percpu) { 11503 aux->btf_var.reg_type = PTR_TO_PERCPU_BTF_ID; 11504 aux->btf_var.btf = btf; 11505 aux->btf_var.btf_id = type; 11506 } else if (!btf_type_is_struct(t)) { 11507 const struct btf_type *ret; 11508 const char *tname; 11509 u32 tsize; 11510 11511 /* resolve the type size of ksym. */ 11512 ret = btf_resolve_size(btf, t, &tsize); 11513 if (IS_ERR(ret)) { 11514 tname = btf_name_by_offset(btf, t->name_off); 11515 verbose(env, "ldimm64 unable to resolve the size of type '%s': %ld\n", 11516 tname, PTR_ERR(ret)); 11517 err = -EINVAL; 11518 goto err_put; 11519 } 11520 aux->btf_var.reg_type = PTR_TO_MEM; 11521 aux->btf_var.mem_size = tsize; 11522 } else { 11523 aux->btf_var.reg_type = PTR_TO_BTF_ID; 11524 aux->btf_var.btf = btf; 11525 aux->btf_var.btf_id = type; 11526 } 11527 11528 /* check whether we recorded this BTF (and maybe module) already */ 11529 for (i = 0; i < env->used_btf_cnt; i++) { 11530 if (env->used_btfs[i].btf == btf) { 11531 btf_put(btf); 11532 return 0; 11533 } 11534 } 11535 11536 if (env->used_btf_cnt >= MAX_USED_BTFS) { 11537 err = -E2BIG; 11538 goto err_put; 11539 } 11540 11541 btf_mod = &env->used_btfs[env->used_btf_cnt]; 11542 btf_mod->btf = btf; 11543 btf_mod->module = NULL; 11544 11545 /* if we reference variables from kernel module, bump its refcount */ 11546 if (btf_is_module(btf)) { 11547 btf_mod->module = btf_try_get_module(btf); 11548 if (!btf_mod->module) { 11549 err = -ENXIO; 11550 goto err_put; 11551 } 11552 } 11553 11554 env->used_btf_cnt++; 11555 11556 return 0; 11557 err_put: 11558 btf_put(btf); 11559 return err; 11560 } 11561 11562 static int check_map_prealloc(struct bpf_map *map) 11563 { 11564 return (map->map_type != BPF_MAP_TYPE_HASH && 11565 map->map_type != BPF_MAP_TYPE_PERCPU_HASH && 11566 map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || 11567 !(map->map_flags & BPF_F_NO_PREALLOC); 11568 } 11569 11570 static bool is_tracing_prog_type(enum bpf_prog_type type) 11571 { 11572 switch (type) { 11573 case BPF_PROG_TYPE_KPROBE: 11574 case BPF_PROG_TYPE_TRACEPOINT: 11575 case BPF_PROG_TYPE_PERF_EVENT: 11576 case BPF_PROG_TYPE_RAW_TRACEPOINT: 11577 return true; 11578 default: 11579 return false; 11580 } 11581 } 11582 11583 static bool is_preallocated_map(struct bpf_map *map) 11584 { 11585 if (!check_map_prealloc(map)) 11586 return false; 11587 if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) 11588 return false; 11589 return true; 11590 } 11591 11592 static int check_map_prog_compatibility(struct bpf_verifier_env *env, 11593 struct bpf_map *map, 11594 struct bpf_prog *prog) 11595 11596 { 11597 enum bpf_prog_type prog_type = resolve_prog_type(prog); 11598 /* 11599 * Validate that trace type programs use preallocated hash maps. 11600 * 11601 * For programs attached to PERF events this is mandatory as the 11602 * perf NMI can hit any arbitrary code sequence. 11603 * 11604 * All other trace types using preallocated hash maps are unsafe as 11605 * well because tracepoint or kprobes can be inside locked regions 11606 * of the memory allocator or at a place where a recursion into the 11607 * memory allocator would see inconsistent state. 11608 * 11609 * On RT enabled kernels run-time allocation of all trace type 11610 * programs is strictly prohibited due to lock type constraints. On 11611 * !RT kernels it is allowed for backwards compatibility reasons for 11612 * now, but warnings are emitted so developers are made aware of 11613 * the unsafety and can fix their programs before this is enforced. 11614 */ 11615 if (is_tracing_prog_type(prog_type) && !is_preallocated_map(map)) { 11616 if (prog_type == BPF_PROG_TYPE_PERF_EVENT) { 11617 verbose(env, "perf_event programs can only use preallocated hash map\n"); 11618 return -EINVAL; 11619 } 11620 if (IS_ENABLED(CONFIG_PREEMPT_RT)) { 11621 verbose(env, "trace type programs can only use preallocated hash map\n"); 11622 return -EINVAL; 11623 } 11624 WARN_ONCE(1, "trace type BPF program uses run-time allocation\n"); 11625 verbose(env, "trace type programs with run-time allocated hash maps are unsafe. Switch to preallocated hash maps.\n"); 11626 } 11627 11628 if (map_value_has_spin_lock(map)) { 11629 if (prog_type == BPF_PROG_TYPE_SOCKET_FILTER) { 11630 verbose(env, "socket filter progs cannot use bpf_spin_lock yet\n"); 11631 return -EINVAL; 11632 } 11633 11634 if (is_tracing_prog_type(prog_type)) { 11635 verbose(env, "tracing progs cannot use bpf_spin_lock yet\n"); 11636 return -EINVAL; 11637 } 11638 11639 if (prog->aux->sleepable) { 11640 verbose(env, "sleepable progs cannot use bpf_spin_lock yet\n"); 11641 return -EINVAL; 11642 } 11643 } 11644 11645 if ((bpf_prog_is_dev_bound(prog->aux) || bpf_map_is_dev_bound(map)) && 11646 !bpf_offload_prog_map_match(prog, map)) { 11647 verbose(env, "offload device mismatch between prog and map\n"); 11648 return -EINVAL; 11649 } 11650 11651 if (map->map_type == BPF_MAP_TYPE_STRUCT_OPS) { 11652 verbose(env, "bpf_struct_ops map cannot be used in prog\n"); 11653 return -EINVAL; 11654 } 11655 11656 if (prog->aux->sleepable) 11657 switch (map->map_type) { 11658 case BPF_MAP_TYPE_HASH: 11659 case BPF_MAP_TYPE_LRU_HASH: 11660 case BPF_MAP_TYPE_ARRAY: 11661 case BPF_MAP_TYPE_PERCPU_HASH: 11662 case BPF_MAP_TYPE_PERCPU_ARRAY: 11663 case BPF_MAP_TYPE_LRU_PERCPU_HASH: 11664 case BPF_MAP_TYPE_ARRAY_OF_MAPS: 11665 case BPF_MAP_TYPE_HASH_OF_MAPS: 11666 if (!is_preallocated_map(map)) { 11667 verbose(env, 11668 "Sleepable programs can only use preallocated maps\n"); 11669 return -EINVAL; 11670 } 11671 break; 11672 case BPF_MAP_TYPE_RINGBUF: 11673 break; 11674 default: 11675 verbose(env, 11676 "Sleepable programs can only use array, hash, and ringbuf maps\n"); 11677 return -EINVAL; 11678 } 11679 11680 return 0; 11681 } 11682 11683 static bool bpf_map_is_cgroup_storage(struct bpf_map *map) 11684 { 11685 return (map->map_type == BPF_MAP_TYPE_CGROUP_STORAGE || 11686 map->map_type == BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE); 11687 } 11688 11689 /* find and rewrite pseudo imm in ld_imm64 instructions: 11690 * 11691 * 1. if it accesses map FD, replace it with actual map pointer. 11692 * 2. if it accesses btf_id of a VAR, replace it with pointer to the var. 11693 * 11694 * NOTE: btf_vmlinux is required for converting pseudo btf_id. 11695 */ 11696 static int resolve_pseudo_ldimm64(struct bpf_verifier_env *env) 11697 { 11698 struct bpf_insn *insn = env->prog->insnsi; 11699 int insn_cnt = env->prog->len; 11700 int i, j, err; 11701 11702 err = bpf_prog_calc_tag(env->prog); 11703 if (err) 11704 return err; 11705 11706 for (i = 0; i < insn_cnt; i++, insn++) { 11707 if (BPF_CLASS(insn->code) == BPF_LDX && 11708 (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { 11709 verbose(env, "BPF_LDX uses reserved fields\n"); 11710 return -EINVAL; 11711 } 11712 11713 if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { 11714 struct bpf_insn_aux_data *aux; 11715 struct bpf_map *map; 11716 struct fd f; 11717 u64 addr; 11718 u32 fd; 11719 11720 if (i == insn_cnt - 1 || insn[1].code != 0 || 11721 insn[1].dst_reg != 0 || insn[1].src_reg != 0 || 11722 insn[1].off != 0) { 11723 verbose(env, "invalid bpf_ld_imm64 insn\n"); 11724 return -EINVAL; 11725 } 11726 11727 if (insn[0].src_reg == 0) 11728 /* valid generic load 64-bit imm */ 11729 goto next_insn; 11730 11731 if (insn[0].src_reg == BPF_PSEUDO_BTF_ID) { 11732 aux = &env->insn_aux_data[i]; 11733 err = check_pseudo_btf_id(env, insn, aux); 11734 if (err) 11735 return err; 11736 goto next_insn; 11737 } 11738 11739 if (insn[0].src_reg == BPF_PSEUDO_FUNC) { 11740 aux = &env->insn_aux_data[i]; 11741 aux->ptr_type = PTR_TO_FUNC; 11742 goto next_insn; 11743 } 11744 11745 /* In final convert_pseudo_ld_imm64() step, this is 11746 * converted into regular 64-bit imm load insn. 11747 */ 11748 switch (insn[0].src_reg) { 11749 case BPF_PSEUDO_MAP_VALUE: 11750 case BPF_PSEUDO_MAP_IDX_VALUE: 11751 break; 11752 case BPF_PSEUDO_MAP_FD: 11753 case BPF_PSEUDO_MAP_IDX: 11754 if (insn[1].imm == 0) 11755 break; 11756 fallthrough; 11757 default: 11758 verbose(env, "unrecognized bpf_ld_imm64 insn\n"); 11759 return -EINVAL; 11760 } 11761 11762 switch (insn[0].src_reg) { 11763 case BPF_PSEUDO_MAP_IDX_VALUE: 11764 case BPF_PSEUDO_MAP_IDX: 11765 if (bpfptr_is_null(env->fd_array)) { 11766 verbose(env, "fd_idx without fd_array is invalid\n"); 11767 return -EPROTO; 11768 } 11769 if (copy_from_bpfptr_offset(&fd, env->fd_array, 11770 insn[0].imm * sizeof(fd), 11771 sizeof(fd))) 11772 return -EFAULT; 11773 break; 11774 default: 11775 fd = insn[0].imm; 11776 break; 11777 } 11778 11779 f = fdget(fd); 11780 map = __bpf_map_get(f); 11781 if (IS_ERR(map)) { 11782 verbose(env, "fd %d is not pointing to valid bpf_map\n", 11783 insn[0].imm); 11784 return PTR_ERR(map); 11785 } 11786 11787 err = check_map_prog_compatibility(env, map, env->prog); 11788 if (err) { 11789 fdput(f); 11790 return err; 11791 } 11792 11793 aux = &env->insn_aux_data[i]; 11794 if (insn[0].src_reg == BPF_PSEUDO_MAP_FD || 11795 insn[0].src_reg == BPF_PSEUDO_MAP_IDX) { 11796 addr = (unsigned long)map; 11797 } else { 11798 u32 off = insn[1].imm; 11799 11800 if (off >= BPF_MAX_VAR_OFF) { 11801 verbose(env, "direct value offset of %u is not allowed\n", off); 11802 fdput(f); 11803 return -EINVAL; 11804 } 11805 11806 if (!map->ops->map_direct_value_addr) { 11807 verbose(env, "no direct value access support for this map type\n"); 11808 fdput(f); 11809 return -EINVAL; 11810 } 11811 11812 err = map->ops->map_direct_value_addr(map, &addr, off); 11813 if (err) { 11814 verbose(env, "invalid access to map value pointer, value_size=%u off=%u\n", 11815 map->value_size, off); 11816 fdput(f); 11817 return err; 11818 } 11819 11820 aux->map_off = off; 11821 addr += off; 11822 } 11823 11824 insn[0].imm = (u32)addr; 11825 insn[1].imm = addr >> 32; 11826 11827 /* check whether we recorded this map already */ 11828 for (j = 0; j < env->used_map_cnt; j++) { 11829 if (env->used_maps[j] == map) { 11830 aux->map_index = j; 11831 fdput(f); 11832 goto next_insn; 11833 } 11834 } 11835 11836 if (env->used_map_cnt >= MAX_USED_MAPS) { 11837 fdput(f); 11838 return -E2BIG; 11839 } 11840 11841 /* hold the map. If the program is rejected by verifier, 11842 * the map will be released by release_maps() or it 11843 * will be used by the valid program until it's unloaded 11844 * and all maps are released in free_used_maps() 11845 */ 11846 bpf_map_inc(map); 11847 11848 aux->map_index = env->used_map_cnt; 11849 env->used_maps[env->used_map_cnt++] = map; 11850 11851 if (bpf_map_is_cgroup_storage(map) && 11852 bpf_cgroup_storage_assign(env->prog->aux, map)) { 11853 verbose(env, "only one cgroup storage of each type is allowed\n"); 11854 fdput(f); 11855 return -EBUSY; 11856 } 11857 11858 fdput(f); 11859 next_insn: 11860 insn++; 11861 i++; 11862 continue; 11863 } 11864 11865 /* Basic sanity check before we invest more work here. */ 11866 if (!bpf_opcode_in_insntable(insn->code)) { 11867 verbose(env, "unknown opcode %02x\n", insn->code); 11868 return -EINVAL; 11869 } 11870 } 11871 11872 /* now all pseudo BPF_LD_IMM64 instructions load valid 11873 * 'struct bpf_map *' into a register instead of user map_fd. 11874 * These pointers will be used later by verifier to validate map access. 11875 */ 11876 return 0; 11877 } 11878 11879 /* drop refcnt of maps used by the rejected program */ 11880 static void release_maps(struct bpf_verifier_env *env) 11881 { 11882 __bpf_free_used_maps(env->prog->aux, env->used_maps, 11883 env->used_map_cnt); 11884 } 11885 11886 /* drop refcnt of maps used by the rejected program */ 11887 static void release_btfs(struct bpf_verifier_env *env) 11888 { 11889 __bpf_free_used_btfs(env->prog->aux, env->used_btfs, 11890 env->used_btf_cnt); 11891 } 11892 11893 /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ 11894 static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) 11895 { 11896 struct bpf_insn *insn = env->prog->insnsi; 11897 int insn_cnt = env->prog->len; 11898 int i; 11899 11900 for (i = 0; i < insn_cnt; i++, insn++) { 11901 if (insn->code != (BPF_LD | BPF_IMM | BPF_DW)) 11902 continue; 11903 if (insn->src_reg == BPF_PSEUDO_FUNC) 11904 continue; 11905 insn->src_reg = 0; 11906 } 11907 } 11908 11909 /* single env->prog->insni[off] instruction was replaced with the range 11910 * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying 11911 * [0, off) and [off, end) to new locations, so the patched range stays zero 11912 */ 11913 static void adjust_insn_aux_data(struct bpf_verifier_env *env, 11914 struct bpf_insn_aux_data *new_data, 11915 struct bpf_prog *new_prog, u32 off, u32 cnt) 11916 { 11917 struct bpf_insn_aux_data *old_data = env->insn_aux_data; 11918 struct bpf_insn *insn = new_prog->insnsi; 11919 u32 old_seen = old_data[off].seen; 11920 u32 prog_len; 11921 int i; 11922 11923 /* aux info at OFF always needs adjustment, no matter fast path 11924 * (cnt == 1) is taken or not. There is no guarantee INSN at OFF is the 11925 * original insn at old prog. 11926 */ 11927 old_data[off].zext_dst = insn_has_def32(env, insn + off + cnt - 1); 11928 11929 if (cnt == 1) 11930 return; 11931 prog_len = new_prog->len; 11932 11933 memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); 11934 memcpy(new_data + off + cnt - 1, old_data + off, 11935 sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); 11936 for (i = off; i < off + cnt - 1; i++) { 11937 /* Expand insni[off]'s seen count to the patched range. */ 11938 new_data[i].seen = old_seen; 11939 new_data[i].zext_dst = insn_has_def32(env, insn + i); 11940 } 11941 env->insn_aux_data = new_data; 11942 vfree(old_data); 11943 } 11944 11945 static void adjust_subprog_starts(struct bpf_verifier_env *env, u32 off, u32 len) 11946 { 11947 int i; 11948 11949 if (len == 1) 11950 return; 11951 /* NOTE: fake 'exit' subprog should be updated as well. */ 11952 for (i = 0; i <= env->subprog_cnt; i++) { 11953 if (env->subprog_info[i].start <= off) 11954 continue; 11955 env->subprog_info[i].start += len - 1; 11956 } 11957 } 11958 11959 static void adjust_poke_descs(struct bpf_prog *prog, u32 off, u32 len) 11960 { 11961 struct bpf_jit_poke_descriptor *tab = prog->aux->poke_tab; 11962 int i, sz = prog->aux->size_poke_tab; 11963 struct bpf_jit_poke_descriptor *desc; 11964 11965 for (i = 0; i < sz; i++) { 11966 desc = &tab[i]; 11967 if (desc->insn_idx <= off) 11968 continue; 11969 desc->insn_idx += len - 1; 11970 } 11971 } 11972 11973 static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, 11974 const struct bpf_insn *patch, u32 len) 11975 { 11976 struct bpf_prog *new_prog; 11977 struct bpf_insn_aux_data *new_data = NULL; 11978 11979 if (len > 1) { 11980 new_data = vzalloc(array_size(env->prog->len + len - 1, 11981 sizeof(struct bpf_insn_aux_data))); 11982 if (!new_data) 11983 return NULL; 11984 } 11985 11986 new_prog = bpf_patch_insn_single(env->prog, off, patch, len); 11987 if (IS_ERR(new_prog)) { 11988 if (PTR_ERR(new_prog) == -ERANGE) 11989 verbose(env, 11990 "insn %d cannot be patched due to 16-bit range\n", 11991 env->insn_aux_data[off].orig_idx); 11992 vfree(new_data); 11993 return NULL; 11994 } 11995 adjust_insn_aux_data(env, new_data, new_prog, off, len); 11996 adjust_subprog_starts(env, off, len); 11997 adjust_poke_descs(new_prog, off, len); 11998 return new_prog; 11999 } 12000 12001 static int adjust_subprog_starts_after_remove(struct bpf_verifier_env *env, 12002 u32 off, u32 cnt) 12003 { 12004 int i, j; 12005 12006 /* find first prog starting at or after off (first to remove) */ 12007 for (i = 0; i < env->subprog_cnt; i++) 12008 if (env->subprog_info[i].start >= off) 12009 break; 12010 /* find first prog starting at or after off + cnt (first to stay) */ 12011 for (j = i; j < env->subprog_cnt; j++) 12012 if (env->subprog_info[j].start >= off + cnt) 12013 break; 12014 /* if j doesn't start exactly at off + cnt, we are just removing 12015 * the front of previous prog 12016 */ 12017 if (env->subprog_info[j].start != off + cnt) 12018 j--; 12019 12020 if (j > i) { 12021 struct bpf_prog_aux *aux = env->prog->aux; 12022 int move; 12023 12024 /* move fake 'exit' subprog as well */ 12025 move = env->subprog_cnt + 1 - j; 12026 12027 memmove(env->subprog_info + i, 12028 env->subprog_info + j, 12029 sizeof(*env->subprog_info) * move); 12030 env->subprog_cnt -= j - i; 12031 12032 /* remove func_info */ 12033 if (aux->func_info) { 12034 move = aux->func_info_cnt - j; 12035 12036 memmove(aux->func_info + i, 12037 aux->func_info + j, 12038 sizeof(*aux->func_info) * move); 12039 aux->func_info_cnt -= j - i; 12040 /* func_info->insn_off is set after all code rewrites, 12041 * in adjust_btf_func() - no need to adjust 12042 */ 12043 } 12044 } else { 12045 /* convert i from "first prog to remove" to "first to adjust" */ 12046 if (env->subprog_info[i].start == off) 12047 i++; 12048 } 12049 12050 /* update fake 'exit' subprog as well */ 12051 for (; i <= env->subprog_cnt; i++) 12052 env->subprog_info[i].start -= cnt; 12053 12054 return 0; 12055 } 12056 12057 static int bpf_adj_linfo_after_remove(struct bpf_verifier_env *env, u32 off, 12058 u32 cnt) 12059 { 12060 struct bpf_prog *prog = env->prog; 12061 u32 i, l_off, l_cnt, nr_linfo; 12062 struct bpf_line_info *linfo; 12063 12064 nr_linfo = prog->aux->nr_linfo; 12065 if (!nr_linfo) 12066 return 0; 12067 12068 linfo = prog->aux->linfo; 12069 12070 /* find first line info to remove, count lines to be removed */ 12071 for (i = 0; i < nr_linfo; i++) 12072 if (linfo[i].insn_off >= off) 12073 break; 12074 12075 l_off = i; 12076 l_cnt = 0; 12077 for (; i < nr_linfo; i++) 12078 if (linfo[i].insn_off < off + cnt) 12079 l_cnt++; 12080 else 12081 break; 12082 12083 /* First live insn doesn't match first live linfo, it needs to "inherit" 12084 * last removed linfo. prog is already modified, so prog->len == off 12085 * means no live instructions after (tail of the program was removed). 12086 */ 12087 if (prog->len != off && l_cnt && 12088 (i == nr_linfo || linfo[i].insn_off != off + cnt)) { 12089 l_cnt--; 12090 linfo[--i].insn_off = off + cnt; 12091 } 12092 12093 /* remove the line info which refer to the removed instructions */ 12094 if (l_cnt) { 12095 memmove(linfo + l_off, linfo + i, 12096 sizeof(*linfo) * (nr_linfo - i)); 12097 12098 prog->aux->nr_linfo -= l_cnt; 12099 nr_linfo = prog->aux->nr_linfo; 12100 } 12101 12102 /* pull all linfo[i].insn_off >= off + cnt in by cnt */ 12103 for (i = l_off; i < nr_linfo; i++) 12104 linfo[i].insn_off -= cnt; 12105 12106 /* fix up all subprogs (incl. 'exit') which start >= off */ 12107 for (i = 0; i <= env->subprog_cnt; i++) 12108 if (env->subprog_info[i].linfo_idx > l_off) { 12109 /* program may have started in the removed region but 12110 * may not be fully removed 12111 */ 12112 if (env->subprog_info[i].linfo_idx >= l_off + l_cnt) 12113 env->subprog_info[i].linfo_idx -= l_cnt; 12114 else 12115 env->subprog_info[i].linfo_idx = l_off; 12116 } 12117 12118 return 0; 12119 } 12120 12121 static int verifier_remove_insns(struct bpf_verifier_env *env, u32 off, u32 cnt) 12122 { 12123 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 12124 unsigned int orig_prog_len = env->prog->len; 12125 int err; 12126 12127 if (bpf_prog_is_dev_bound(env->prog->aux)) 12128 bpf_prog_offload_remove_insns(env, off, cnt); 12129 12130 err = bpf_remove_insns(env->prog, off, cnt); 12131 if (err) 12132 return err; 12133 12134 err = adjust_subprog_starts_after_remove(env, off, cnt); 12135 if (err) 12136 return err; 12137 12138 err = bpf_adj_linfo_after_remove(env, off, cnt); 12139 if (err) 12140 return err; 12141 12142 memmove(aux_data + off, aux_data + off + cnt, 12143 sizeof(*aux_data) * (orig_prog_len - off - cnt)); 12144 12145 return 0; 12146 } 12147 12148 /* The verifier does more data flow analysis than llvm and will not 12149 * explore branches that are dead at run time. Malicious programs can 12150 * have dead code too. Therefore replace all dead at-run-time code 12151 * with 'ja -1'. 12152 * 12153 * Just nops are not optimal, e.g. if they would sit at the end of the 12154 * program and through another bug we would manage to jump there, then 12155 * we'd execute beyond program memory otherwise. Returning exception 12156 * code also wouldn't work since we can have subprogs where the dead 12157 * code could be located. 12158 */ 12159 static void sanitize_dead_code(struct bpf_verifier_env *env) 12160 { 12161 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 12162 struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1); 12163 struct bpf_insn *insn = env->prog->insnsi; 12164 const int insn_cnt = env->prog->len; 12165 int i; 12166 12167 for (i = 0; i < insn_cnt; i++) { 12168 if (aux_data[i].seen) 12169 continue; 12170 memcpy(insn + i, &trap, sizeof(trap)); 12171 aux_data[i].zext_dst = false; 12172 } 12173 } 12174 12175 static bool insn_is_cond_jump(u8 code) 12176 { 12177 u8 op; 12178 12179 if (BPF_CLASS(code) == BPF_JMP32) 12180 return true; 12181 12182 if (BPF_CLASS(code) != BPF_JMP) 12183 return false; 12184 12185 op = BPF_OP(code); 12186 return op != BPF_JA && op != BPF_EXIT && op != BPF_CALL; 12187 } 12188 12189 static void opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env) 12190 { 12191 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 12192 struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 12193 struct bpf_insn *insn = env->prog->insnsi; 12194 const int insn_cnt = env->prog->len; 12195 int i; 12196 12197 for (i = 0; i < insn_cnt; i++, insn++) { 12198 if (!insn_is_cond_jump(insn->code)) 12199 continue; 12200 12201 if (!aux_data[i + 1].seen) 12202 ja.off = insn->off; 12203 else if (!aux_data[i + 1 + insn->off].seen) 12204 ja.off = 0; 12205 else 12206 continue; 12207 12208 if (bpf_prog_is_dev_bound(env->prog->aux)) 12209 bpf_prog_offload_replace_insn(env, i, &ja); 12210 12211 memcpy(insn, &ja, sizeof(ja)); 12212 } 12213 } 12214 12215 static int opt_remove_dead_code(struct bpf_verifier_env *env) 12216 { 12217 struct bpf_insn_aux_data *aux_data = env->insn_aux_data; 12218 int insn_cnt = env->prog->len; 12219 int i, err; 12220 12221 for (i = 0; i < insn_cnt; i++) { 12222 int j; 12223 12224 j = 0; 12225 while (i + j < insn_cnt && !aux_data[i + j].seen) 12226 j++; 12227 if (!j) 12228 continue; 12229 12230 err = verifier_remove_insns(env, i, j); 12231 if (err) 12232 return err; 12233 insn_cnt = env->prog->len; 12234 } 12235 12236 return 0; 12237 } 12238 12239 static int opt_remove_nops(struct bpf_verifier_env *env) 12240 { 12241 const struct bpf_insn ja = BPF_JMP_IMM(BPF_JA, 0, 0, 0); 12242 struct bpf_insn *insn = env->prog->insnsi; 12243 int insn_cnt = env->prog->len; 12244 int i, err; 12245 12246 for (i = 0; i < insn_cnt; i++) { 12247 if (memcmp(&insn[i], &ja, sizeof(ja))) 12248 continue; 12249 12250 err = verifier_remove_insns(env, i, 1); 12251 if (err) 12252 return err; 12253 insn_cnt--; 12254 i--; 12255 } 12256 12257 return 0; 12258 } 12259 12260 static int opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env, 12261 const union bpf_attr *attr) 12262 { 12263 struct bpf_insn *patch, zext_patch[2], rnd_hi32_patch[4]; 12264 struct bpf_insn_aux_data *aux = env->insn_aux_data; 12265 int i, patch_len, delta = 0, len = env->prog->len; 12266 struct bpf_insn *insns = env->prog->insnsi; 12267 struct bpf_prog *new_prog; 12268 bool rnd_hi32; 12269 12270 rnd_hi32 = attr->prog_flags & BPF_F_TEST_RND_HI32; 12271 zext_patch[1] = BPF_ZEXT_REG(0); 12272 rnd_hi32_patch[1] = BPF_ALU64_IMM(BPF_MOV, BPF_REG_AX, 0); 12273 rnd_hi32_patch[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_AX, 32); 12274 rnd_hi32_patch[3] = BPF_ALU64_REG(BPF_OR, 0, BPF_REG_AX); 12275 for (i = 0; i < len; i++) { 12276 int adj_idx = i + delta; 12277 struct bpf_insn insn; 12278 int load_reg; 12279 12280 insn = insns[adj_idx]; 12281 load_reg = insn_def_regno(&insn); 12282 if (!aux[adj_idx].zext_dst) { 12283 u8 code, class; 12284 u32 imm_rnd; 12285 12286 if (!rnd_hi32) 12287 continue; 12288 12289 code = insn.code; 12290 class = BPF_CLASS(code); 12291 if (load_reg == -1) 12292 continue; 12293 12294 /* NOTE: arg "reg" (the fourth one) is only used for 12295 * BPF_STX + SRC_OP, so it is safe to pass NULL 12296 * here. 12297 */ 12298 if (is_reg64(env, &insn, load_reg, NULL, DST_OP)) { 12299 if (class == BPF_LD && 12300 BPF_MODE(code) == BPF_IMM) 12301 i++; 12302 continue; 12303 } 12304 12305 /* ctx load could be transformed into wider load. */ 12306 if (class == BPF_LDX && 12307 aux[adj_idx].ptr_type == PTR_TO_CTX) 12308 continue; 12309 12310 imm_rnd = get_random_int(); 12311 rnd_hi32_patch[0] = insn; 12312 rnd_hi32_patch[1].imm = imm_rnd; 12313 rnd_hi32_patch[3].dst_reg = load_reg; 12314 patch = rnd_hi32_patch; 12315 patch_len = 4; 12316 goto apply_patch_buffer; 12317 } 12318 12319 /* Add in an zero-extend instruction if a) the JIT has requested 12320 * it or b) it's a CMPXCHG. 12321 * 12322 * The latter is because: BPF_CMPXCHG always loads a value into 12323 * R0, therefore always zero-extends. However some archs' 12324 * equivalent instruction only does this load when the 12325 * comparison is successful. This detail of CMPXCHG is 12326 * orthogonal to the general zero-extension behaviour of the 12327 * CPU, so it's treated independently of bpf_jit_needs_zext. 12328 */ 12329 if (!bpf_jit_needs_zext() && !is_cmpxchg_insn(&insn)) 12330 continue; 12331 12332 if (WARN_ON(load_reg == -1)) { 12333 verbose(env, "verifier bug. zext_dst is set, but no reg is defined\n"); 12334 return -EFAULT; 12335 } 12336 12337 zext_patch[0] = insn; 12338 zext_patch[1].dst_reg = load_reg; 12339 zext_patch[1].src_reg = load_reg; 12340 patch = zext_patch; 12341 patch_len = 2; 12342 apply_patch_buffer: 12343 new_prog = bpf_patch_insn_data(env, adj_idx, patch, patch_len); 12344 if (!new_prog) 12345 return -ENOMEM; 12346 env->prog = new_prog; 12347 insns = new_prog->insnsi; 12348 aux = env->insn_aux_data; 12349 delta += patch_len - 1; 12350 } 12351 12352 return 0; 12353 } 12354 12355 /* convert load instructions that access fields of a context type into a 12356 * sequence of instructions that access fields of the underlying structure: 12357 * struct __sk_buff -> struct sk_buff 12358 * struct bpf_sock_ops -> struct sock 12359 */ 12360 static int convert_ctx_accesses(struct bpf_verifier_env *env) 12361 { 12362 const struct bpf_verifier_ops *ops = env->ops; 12363 int i, cnt, size, ctx_field_size, delta = 0; 12364 const int insn_cnt = env->prog->len; 12365 struct bpf_insn insn_buf[16], *insn; 12366 u32 target_size, size_default, off; 12367 struct bpf_prog *new_prog; 12368 enum bpf_access_type type; 12369 bool is_narrower_load; 12370 12371 if (ops->gen_prologue || env->seen_direct_write) { 12372 if (!ops->gen_prologue) { 12373 verbose(env, "bpf verifier is misconfigured\n"); 12374 return -EINVAL; 12375 } 12376 cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, 12377 env->prog); 12378 if (cnt >= ARRAY_SIZE(insn_buf)) { 12379 verbose(env, "bpf verifier is misconfigured\n"); 12380 return -EINVAL; 12381 } else if (cnt) { 12382 new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); 12383 if (!new_prog) 12384 return -ENOMEM; 12385 12386 env->prog = new_prog; 12387 delta += cnt - 1; 12388 } 12389 } 12390 12391 if (bpf_prog_is_dev_bound(env->prog->aux)) 12392 return 0; 12393 12394 insn = env->prog->insnsi + delta; 12395 12396 for (i = 0; i < insn_cnt; i++, insn++) { 12397 bpf_convert_ctx_access_t convert_ctx_access; 12398 bool ctx_access; 12399 12400 if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || 12401 insn->code == (BPF_LDX | BPF_MEM | BPF_H) || 12402 insn->code == (BPF_LDX | BPF_MEM | BPF_W) || 12403 insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) { 12404 type = BPF_READ; 12405 ctx_access = true; 12406 } else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || 12407 insn->code == (BPF_STX | BPF_MEM | BPF_H) || 12408 insn->code == (BPF_STX | BPF_MEM | BPF_W) || 12409 insn->code == (BPF_STX | BPF_MEM | BPF_DW) || 12410 insn->code == (BPF_ST | BPF_MEM | BPF_B) || 12411 insn->code == (BPF_ST | BPF_MEM | BPF_H) || 12412 insn->code == (BPF_ST | BPF_MEM | BPF_W) || 12413 insn->code == (BPF_ST | BPF_MEM | BPF_DW)) { 12414 type = BPF_WRITE; 12415 ctx_access = BPF_CLASS(insn->code) == BPF_STX; 12416 } else { 12417 continue; 12418 } 12419 12420 if (type == BPF_WRITE && 12421 env->insn_aux_data[i + delta].sanitize_stack_spill) { 12422 struct bpf_insn patch[] = { 12423 *insn, 12424 BPF_ST_NOSPEC(), 12425 }; 12426 12427 cnt = ARRAY_SIZE(patch); 12428 new_prog = bpf_patch_insn_data(env, i + delta, patch, cnt); 12429 if (!new_prog) 12430 return -ENOMEM; 12431 12432 delta += cnt - 1; 12433 env->prog = new_prog; 12434 insn = new_prog->insnsi + i + delta; 12435 continue; 12436 } 12437 12438 if (!ctx_access) 12439 continue; 12440 12441 switch (env->insn_aux_data[i + delta].ptr_type) { 12442 case PTR_TO_CTX: 12443 if (!ops->convert_ctx_access) 12444 continue; 12445 convert_ctx_access = ops->convert_ctx_access; 12446 break; 12447 case PTR_TO_SOCKET: 12448 case PTR_TO_SOCK_COMMON: 12449 convert_ctx_access = bpf_sock_convert_ctx_access; 12450 break; 12451 case PTR_TO_TCP_SOCK: 12452 convert_ctx_access = bpf_tcp_sock_convert_ctx_access; 12453 break; 12454 case PTR_TO_XDP_SOCK: 12455 convert_ctx_access = bpf_xdp_sock_convert_ctx_access; 12456 break; 12457 case PTR_TO_BTF_ID: 12458 if (type == BPF_READ) { 12459 insn->code = BPF_LDX | BPF_PROBE_MEM | 12460 BPF_SIZE((insn)->code); 12461 env->prog->aux->num_exentries++; 12462 } else if (resolve_prog_type(env->prog) != BPF_PROG_TYPE_STRUCT_OPS) { 12463 verbose(env, "Writes through BTF pointers are not allowed\n"); 12464 return -EINVAL; 12465 } 12466 continue; 12467 default: 12468 continue; 12469 } 12470 12471 ctx_field_size = env->insn_aux_data[i + delta].ctx_field_size; 12472 size = BPF_LDST_BYTES(insn); 12473 12474 /* If the read access is a narrower load of the field, 12475 * convert to a 4/8-byte load, to minimum program type specific 12476 * convert_ctx_access changes. If conversion is successful, 12477 * we will apply proper mask to the result. 12478 */ 12479 is_narrower_load = size < ctx_field_size; 12480 size_default = bpf_ctx_off_adjust_machine(ctx_field_size); 12481 off = insn->off; 12482 if (is_narrower_load) { 12483 u8 size_code; 12484 12485 if (type == BPF_WRITE) { 12486 verbose(env, "bpf verifier narrow ctx access misconfigured\n"); 12487 return -EINVAL; 12488 } 12489 12490 size_code = BPF_H; 12491 if (ctx_field_size == 4) 12492 size_code = BPF_W; 12493 else if (ctx_field_size == 8) 12494 size_code = BPF_DW; 12495 12496 insn->off = off & ~(size_default - 1); 12497 insn->code = BPF_LDX | BPF_MEM | size_code; 12498 } 12499 12500 target_size = 0; 12501 cnt = convert_ctx_access(type, insn, insn_buf, env->prog, 12502 &target_size); 12503 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf) || 12504 (ctx_field_size && !target_size)) { 12505 verbose(env, "bpf verifier is misconfigured\n"); 12506 return -EINVAL; 12507 } 12508 12509 if (is_narrower_load && size < target_size) { 12510 u8 shift = bpf_ctx_narrow_access_offset( 12511 off, size, size_default) * 8; 12512 if (shift && cnt + 1 >= ARRAY_SIZE(insn_buf)) { 12513 verbose(env, "bpf verifier narrow ctx load misconfigured\n"); 12514 return -EINVAL; 12515 } 12516 if (ctx_field_size <= 4) { 12517 if (shift) 12518 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_RSH, 12519 insn->dst_reg, 12520 shift); 12521 insn_buf[cnt++] = BPF_ALU32_IMM(BPF_AND, insn->dst_reg, 12522 (1 << size * 8) - 1); 12523 } else { 12524 if (shift) 12525 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_RSH, 12526 insn->dst_reg, 12527 shift); 12528 insn_buf[cnt++] = BPF_ALU64_IMM(BPF_AND, insn->dst_reg, 12529 (1ULL << size * 8) - 1); 12530 } 12531 } 12532 12533 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12534 if (!new_prog) 12535 return -ENOMEM; 12536 12537 delta += cnt - 1; 12538 12539 /* keep walking new program and skip insns we just inserted */ 12540 env->prog = new_prog; 12541 insn = new_prog->insnsi + i + delta; 12542 } 12543 12544 return 0; 12545 } 12546 12547 static int jit_subprogs(struct bpf_verifier_env *env) 12548 { 12549 struct bpf_prog *prog = env->prog, **func, *tmp; 12550 int i, j, subprog_start, subprog_end = 0, len, subprog; 12551 struct bpf_map *map_ptr; 12552 struct bpf_insn *insn; 12553 void *old_bpf_func; 12554 int err, num_exentries; 12555 12556 if (env->subprog_cnt <= 1) 12557 return 0; 12558 12559 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 12560 if (bpf_pseudo_func(insn)) { 12561 env->insn_aux_data[i].call_imm = insn->imm; 12562 /* subprog is encoded in insn[1].imm */ 12563 continue; 12564 } 12565 12566 if (!bpf_pseudo_call(insn)) 12567 continue; 12568 /* Upon error here we cannot fall back to interpreter but 12569 * need a hard reject of the program. Thus -EFAULT is 12570 * propagated in any case. 12571 */ 12572 subprog = find_subprog(env, i + insn->imm + 1); 12573 if (subprog < 0) { 12574 WARN_ONCE(1, "verifier bug. No program starts at insn %d\n", 12575 i + insn->imm + 1); 12576 return -EFAULT; 12577 } 12578 /* temporarily remember subprog id inside insn instead of 12579 * aux_data, since next loop will split up all insns into funcs 12580 */ 12581 insn->off = subprog; 12582 /* remember original imm in case JIT fails and fallback 12583 * to interpreter will be needed 12584 */ 12585 env->insn_aux_data[i].call_imm = insn->imm; 12586 /* point imm to __bpf_call_base+1 from JITs point of view */ 12587 insn->imm = 1; 12588 } 12589 12590 err = bpf_prog_alloc_jited_linfo(prog); 12591 if (err) 12592 goto out_undo_insn; 12593 12594 err = -ENOMEM; 12595 func = kcalloc(env->subprog_cnt, sizeof(prog), GFP_KERNEL); 12596 if (!func) 12597 goto out_undo_insn; 12598 12599 for (i = 0; i < env->subprog_cnt; i++) { 12600 subprog_start = subprog_end; 12601 subprog_end = env->subprog_info[i + 1].start; 12602 12603 len = subprog_end - subprog_start; 12604 /* bpf_prog_run() doesn't call subprogs directly, 12605 * hence main prog stats include the runtime of subprogs. 12606 * subprogs don't have IDs and not reachable via prog_get_next_id 12607 * func[i]->stats will never be accessed and stays NULL 12608 */ 12609 func[i] = bpf_prog_alloc_no_stats(bpf_prog_size(len), GFP_USER); 12610 if (!func[i]) 12611 goto out_free; 12612 memcpy(func[i]->insnsi, &prog->insnsi[subprog_start], 12613 len * sizeof(struct bpf_insn)); 12614 func[i]->type = prog->type; 12615 func[i]->len = len; 12616 if (bpf_prog_calc_tag(func[i])) 12617 goto out_free; 12618 func[i]->is_func = 1; 12619 func[i]->aux->func_idx = i; 12620 /* Below members will be freed only at prog->aux */ 12621 func[i]->aux->btf = prog->aux->btf; 12622 func[i]->aux->func_info = prog->aux->func_info; 12623 func[i]->aux->poke_tab = prog->aux->poke_tab; 12624 func[i]->aux->size_poke_tab = prog->aux->size_poke_tab; 12625 12626 for (j = 0; j < prog->aux->size_poke_tab; j++) { 12627 struct bpf_jit_poke_descriptor *poke; 12628 12629 poke = &prog->aux->poke_tab[j]; 12630 if (poke->insn_idx < subprog_end && 12631 poke->insn_idx >= subprog_start) 12632 poke->aux = func[i]->aux; 12633 } 12634 12635 /* Use bpf_prog_F_tag to indicate functions in stack traces. 12636 * Long term would need debug info to populate names 12637 */ 12638 func[i]->aux->name[0] = 'F'; 12639 func[i]->aux->stack_depth = env->subprog_info[i].stack_depth; 12640 func[i]->jit_requested = 1; 12641 func[i]->aux->kfunc_tab = prog->aux->kfunc_tab; 12642 func[i]->aux->kfunc_btf_tab = prog->aux->kfunc_btf_tab; 12643 func[i]->aux->linfo = prog->aux->linfo; 12644 func[i]->aux->nr_linfo = prog->aux->nr_linfo; 12645 func[i]->aux->jited_linfo = prog->aux->jited_linfo; 12646 func[i]->aux->linfo_idx = env->subprog_info[i].linfo_idx; 12647 num_exentries = 0; 12648 insn = func[i]->insnsi; 12649 for (j = 0; j < func[i]->len; j++, insn++) { 12650 if (BPF_CLASS(insn->code) == BPF_LDX && 12651 BPF_MODE(insn->code) == BPF_PROBE_MEM) 12652 num_exentries++; 12653 } 12654 func[i]->aux->num_exentries = num_exentries; 12655 func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable; 12656 func[i] = bpf_int_jit_compile(func[i]); 12657 if (!func[i]->jited) { 12658 err = -ENOTSUPP; 12659 goto out_free; 12660 } 12661 cond_resched(); 12662 } 12663 12664 /* at this point all bpf functions were successfully JITed 12665 * now populate all bpf_calls with correct addresses and 12666 * run last pass of JIT 12667 */ 12668 for (i = 0; i < env->subprog_cnt; i++) { 12669 insn = func[i]->insnsi; 12670 for (j = 0; j < func[i]->len; j++, insn++) { 12671 if (bpf_pseudo_func(insn)) { 12672 subprog = insn[1].imm; 12673 insn[0].imm = (u32)(long)func[subprog]->bpf_func; 12674 insn[1].imm = ((u64)(long)func[subprog]->bpf_func) >> 32; 12675 continue; 12676 } 12677 if (!bpf_pseudo_call(insn)) 12678 continue; 12679 subprog = insn->off; 12680 insn->imm = BPF_CALL_IMM(func[subprog]->bpf_func); 12681 } 12682 12683 /* we use the aux data to keep a list of the start addresses 12684 * of the JITed images for each function in the program 12685 * 12686 * for some architectures, such as powerpc64, the imm field 12687 * might not be large enough to hold the offset of the start 12688 * address of the callee's JITed image from __bpf_call_base 12689 * 12690 * in such cases, we can lookup the start address of a callee 12691 * by using its subprog id, available from the off field of 12692 * the call instruction, as an index for this list 12693 */ 12694 func[i]->aux->func = func; 12695 func[i]->aux->func_cnt = env->subprog_cnt; 12696 } 12697 for (i = 0; i < env->subprog_cnt; i++) { 12698 old_bpf_func = func[i]->bpf_func; 12699 tmp = bpf_int_jit_compile(func[i]); 12700 if (tmp != func[i] || func[i]->bpf_func != old_bpf_func) { 12701 verbose(env, "JIT doesn't support bpf-to-bpf calls\n"); 12702 err = -ENOTSUPP; 12703 goto out_free; 12704 } 12705 cond_resched(); 12706 } 12707 12708 /* finally lock prog and jit images for all functions and 12709 * populate kallsysm 12710 */ 12711 for (i = 0; i < env->subprog_cnt; i++) { 12712 bpf_prog_lock_ro(func[i]); 12713 bpf_prog_kallsyms_add(func[i]); 12714 } 12715 12716 /* Last step: make now unused interpreter insns from main 12717 * prog consistent for later dump requests, so they can 12718 * later look the same as if they were interpreted only. 12719 */ 12720 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 12721 if (bpf_pseudo_func(insn)) { 12722 insn[0].imm = env->insn_aux_data[i].call_imm; 12723 insn[1].imm = find_subprog(env, i + insn[0].imm + 1); 12724 continue; 12725 } 12726 if (!bpf_pseudo_call(insn)) 12727 continue; 12728 insn->off = env->insn_aux_data[i].call_imm; 12729 subprog = find_subprog(env, i + insn->off + 1); 12730 insn->imm = subprog; 12731 } 12732 12733 prog->jited = 1; 12734 prog->bpf_func = func[0]->bpf_func; 12735 prog->aux->func = func; 12736 prog->aux->func_cnt = env->subprog_cnt; 12737 bpf_prog_jit_attempt_done(prog); 12738 return 0; 12739 out_free: 12740 /* We failed JIT'ing, so at this point we need to unregister poke 12741 * descriptors from subprogs, so that kernel is not attempting to 12742 * patch it anymore as we're freeing the subprog JIT memory. 12743 */ 12744 for (i = 0; i < prog->aux->size_poke_tab; i++) { 12745 map_ptr = prog->aux->poke_tab[i].tail_call.map; 12746 map_ptr->ops->map_poke_untrack(map_ptr, prog->aux); 12747 } 12748 /* At this point we're guaranteed that poke descriptors are not 12749 * live anymore. We can just unlink its descriptor table as it's 12750 * released with the main prog. 12751 */ 12752 for (i = 0; i < env->subprog_cnt; i++) { 12753 if (!func[i]) 12754 continue; 12755 func[i]->aux->poke_tab = NULL; 12756 bpf_jit_free(func[i]); 12757 } 12758 kfree(func); 12759 out_undo_insn: 12760 /* cleanup main prog to be interpreted */ 12761 prog->jit_requested = 0; 12762 for (i = 0, insn = prog->insnsi; i < prog->len; i++, insn++) { 12763 if (!bpf_pseudo_call(insn)) 12764 continue; 12765 insn->off = 0; 12766 insn->imm = env->insn_aux_data[i].call_imm; 12767 } 12768 bpf_prog_jit_attempt_done(prog); 12769 return err; 12770 } 12771 12772 static int fixup_call_args(struct bpf_verifier_env *env) 12773 { 12774 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 12775 struct bpf_prog *prog = env->prog; 12776 struct bpf_insn *insn = prog->insnsi; 12777 bool has_kfunc_call = bpf_prog_has_kfunc_call(prog); 12778 int i, depth; 12779 #endif 12780 int err = 0; 12781 12782 if (env->prog->jit_requested && 12783 !bpf_prog_is_dev_bound(env->prog->aux)) { 12784 err = jit_subprogs(env); 12785 if (err == 0) 12786 return 0; 12787 if (err == -EFAULT) 12788 return err; 12789 } 12790 #ifndef CONFIG_BPF_JIT_ALWAYS_ON 12791 if (has_kfunc_call) { 12792 verbose(env, "calling kernel functions are not allowed in non-JITed programs\n"); 12793 return -EINVAL; 12794 } 12795 if (env->subprog_cnt > 1 && env->prog->aux->tail_call_reachable) { 12796 /* When JIT fails the progs with bpf2bpf calls and tail_calls 12797 * have to be rejected, since interpreter doesn't support them yet. 12798 */ 12799 verbose(env, "tail_calls are not allowed in non-JITed programs with bpf-to-bpf calls\n"); 12800 return -EINVAL; 12801 } 12802 for (i = 0; i < prog->len; i++, insn++) { 12803 if (bpf_pseudo_func(insn)) { 12804 /* When JIT fails the progs with callback calls 12805 * have to be rejected, since interpreter doesn't support them yet. 12806 */ 12807 verbose(env, "callbacks are not allowed in non-JITed programs\n"); 12808 return -EINVAL; 12809 } 12810 12811 if (!bpf_pseudo_call(insn)) 12812 continue; 12813 depth = get_callee_stack_depth(env, insn, i); 12814 if (depth < 0) 12815 return depth; 12816 bpf_patch_call_args(insn, depth); 12817 } 12818 err = 0; 12819 #endif 12820 return err; 12821 } 12822 12823 static int fixup_kfunc_call(struct bpf_verifier_env *env, 12824 struct bpf_insn *insn) 12825 { 12826 const struct bpf_kfunc_desc *desc; 12827 12828 if (!insn->imm) { 12829 verbose(env, "invalid kernel function call not eliminated in verifier pass\n"); 12830 return -EINVAL; 12831 } 12832 12833 /* insn->imm has the btf func_id. Replace it with 12834 * an address (relative to __bpf_base_call). 12835 */ 12836 desc = find_kfunc_desc(env->prog, insn->imm, insn->off); 12837 if (!desc) { 12838 verbose(env, "verifier internal error: kernel function descriptor not found for func_id %u\n", 12839 insn->imm); 12840 return -EFAULT; 12841 } 12842 12843 insn->imm = desc->imm; 12844 12845 return 0; 12846 } 12847 12848 /* Do various post-verification rewrites in a single program pass. 12849 * These rewrites simplify JIT and interpreter implementations. 12850 */ 12851 static int do_misc_fixups(struct bpf_verifier_env *env) 12852 { 12853 struct bpf_prog *prog = env->prog; 12854 bool expect_blinding = bpf_jit_blinding_enabled(prog); 12855 enum bpf_prog_type prog_type = resolve_prog_type(prog); 12856 struct bpf_insn *insn = prog->insnsi; 12857 const struct bpf_func_proto *fn; 12858 const int insn_cnt = prog->len; 12859 const struct bpf_map_ops *ops; 12860 struct bpf_insn_aux_data *aux; 12861 struct bpf_insn insn_buf[16]; 12862 struct bpf_prog *new_prog; 12863 struct bpf_map *map_ptr; 12864 int i, ret, cnt, delta = 0; 12865 12866 for (i = 0; i < insn_cnt; i++, insn++) { 12867 /* Make divide-by-zero exceptions impossible. */ 12868 if (insn->code == (BPF_ALU64 | BPF_MOD | BPF_X) || 12869 insn->code == (BPF_ALU64 | BPF_DIV | BPF_X) || 12870 insn->code == (BPF_ALU | BPF_MOD | BPF_X) || 12871 insn->code == (BPF_ALU | BPF_DIV | BPF_X)) { 12872 bool is64 = BPF_CLASS(insn->code) == BPF_ALU64; 12873 bool isdiv = BPF_OP(insn->code) == BPF_DIV; 12874 struct bpf_insn *patchlet; 12875 struct bpf_insn chk_and_div[] = { 12876 /* [R,W]x div 0 -> 0 */ 12877 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 12878 BPF_JNE | BPF_K, insn->src_reg, 12879 0, 2, 0), 12880 BPF_ALU32_REG(BPF_XOR, insn->dst_reg, insn->dst_reg), 12881 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 12882 *insn, 12883 }; 12884 struct bpf_insn chk_and_mod[] = { 12885 /* [R,W]x mod 0 -> [R,W]x */ 12886 BPF_RAW_INSN((is64 ? BPF_JMP : BPF_JMP32) | 12887 BPF_JEQ | BPF_K, insn->src_reg, 12888 0, 1 + (is64 ? 0 : 1), 0), 12889 *insn, 12890 BPF_JMP_IMM(BPF_JA, 0, 0, 1), 12891 BPF_MOV32_REG(insn->dst_reg, insn->dst_reg), 12892 }; 12893 12894 patchlet = isdiv ? chk_and_div : chk_and_mod; 12895 cnt = isdiv ? ARRAY_SIZE(chk_and_div) : 12896 ARRAY_SIZE(chk_and_mod) - (is64 ? 2 : 0); 12897 12898 new_prog = bpf_patch_insn_data(env, i + delta, patchlet, cnt); 12899 if (!new_prog) 12900 return -ENOMEM; 12901 12902 delta += cnt - 1; 12903 env->prog = prog = new_prog; 12904 insn = new_prog->insnsi + i + delta; 12905 continue; 12906 } 12907 12908 /* Implement LD_ABS and LD_IND with a rewrite, if supported by the program type. */ 12909 if (BPF_CLASS(insn->code) == BPF_LD && 12910 (BPF_MODE(insn->code) == BPF_ABS || 12911 BPF_MODE(insn->code) == BPF_IND)) { 12912 cnt = env->ops->gen_ld_abs(insn, insn_buf); 12913 if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { 12914 verbose(env, "bpf verifier is misconfigured\n"); 12915 return -EINVAL; 12916 } 12917 12918 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12919 if (!new_prog) 12920 return -ENOMEM; 12921 12922 delta += cnt - 1; 12923 env->prog = prog = new_prog; 12924 insn = new_prog->insnsi + i + delta; 12925 continue; 12926 } 12927 12928 /* Rewrite pointer arithmetic to mitigate speculation attacks. */ 12929 if (insn->code == (BPF_ALU64 | BPF_ADD | BPF_X) || 12930 insn->code == (BPF_ALU64 | BPF_SUB | BPF_X)) { 12931 const u8 code_add = BPF_ALU64 | BPF_ADD | BPF_X; 12932 const u8 code_sub = BPF_ALU64 | BPF_SUB | BPF_X; 12933 struct bpf_insn *patch = &insn_buf[0]; 12934 bool issrc, isneg, isimm; 12935 u32 off_reg; 12936 12937 aux = &env->insn_aux_data[i + delta]; 12938 if (!aux->alu_state || 12939 aux->alu_state == BPF_ALU_NON_POINTER) 12940 continue; 12941 12942 isneg = aux->alu_state & BPF_ALU_NEG_VALUE; 12943 issrc = (aux->alu_state & BPF_ALU_SANITIZE) == 12944 BPF_ALU_SANITIZE_SRC; 12945 isimm = aux->alu_state & BPF_ALU_IMMEDIATE; 12946 12947 off_reg = issrc ? insn->src_reg : insn->dst_reg; 12948 if (isimm) { 12949 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 12950 } else { 12951 if (isneg) 12952 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 12953 *patch++ = BPF_MOV32_IMM(BPF_REG_AX, aux->alu_limit); 12954 *patch++ = BPF_ALU64_REG(BPF_SUB, BPF_REG_AX, off_reg); 12955 *patch++ = BPF_ALU64_REG(BPF_OR, BPF_REG_AX, off_reg); 12956 *patch++ = BPF_ALU64_IMM(BPF_NEG, BPF_REG_AX, 0); 12957 *patch++ = BPF_ALU64_IMM(BPF_ARSH, BPF_REG_AX, 63); 12958 *patch++ = BPF_ALU64_REG(BPF_AND, BPF_REG_AX, off_reg); 12959 } 12960 if (!issrc) 12961 *patch++ = BPF_MOV64_REG(insn->dst_reg, insn->src_reg); 12962 insn->src_reg = BPF_REG_AX; 12963 if (isneg) 12964 insn->code = insn->code == code_add ? 12965 code_sub : code_add; 12966 *patch++ = *insn; 12967 if (issrc && isneg && !isimm) 12968 *patch++ = BPF_ALU64_IMM(BPF_MUL, off_reg, -1); 12969 cnt = patch - insn_buf; 12970 12971 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 12972 if (!new_prog) 12973 return -ENOMEM; 12974 12975 delta += cnt - 1; 12976 env->prog = prog = new_prog; 12977 insn = new_prog->insnsi + i + delta; 12978 continue; 12979 } 12980 12981 if (insn->code != (BPF_JMP | BPF_CALL)) 12982 continue; 12983 if (insn->src_reg == BPF_PSEUDO_CALL) 12984 continue; 12985 if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) { 12986 ret = fixup_kfunc_call(env, insn); 12987 if (ret) 12988 return ret; 12989 continue; 12990 } 12991 12992 if (insn->imm == BPF_FUNC_get_route_realm) 12993 prog->dst_needed = 1; 12994 if (insn->imm == BPF_FUNC_get_prandom_u32) 12995 bpf_user_rnd_init_once(); 12996 if (insn->imm == BPF_FUNC_override_return) 12997 prog->kprobe_override = 1; 12998 if (insn->imm == BPF_FUNC_tail_call) { 12999 /* If we tail call into other programs, we 13000 * cannot make any assumptions since they can 13001 * be replaced dynamically during runtime in 13002 * the program array. 13003 */ 13004 prog->cb_access = 1; 13005 if (!allow_tail_call_in_subprogs(env)) 13006 prog->aux->stack_depth = MAX_BPF_STACK; 13007 prog->aux->max_pkt_offset = MAX_PACKET_OFF; 13008 13009 /* mark bpf_tail_call as different opcode to avoid 13010 * conditional branch in the interpreter for every normal 13011 * call and to prevent accidental JITing by JIT compiler 13012 * that doesn't support bpf_tail_call yet 13013 */ 13014 insn->imm = 0; 13015 insn->code = BPF_JMP | BPF_TAIL_CALL; 13016 13017 aux = &env->insn_aux_data[i + delta]; 13018 if (env->bpf_capable && !expect_blinding && 13019 prog->jit_requested && 13020 !bpf_map_key_poisoned(aux) && 13021 !bpf_map_ptr_poisoned(aux) && 13022 !bpf_map_ptr_unpriv(aux)) { 13023 struct bpf_jit_poke_descriptor desc = { 13024 .reason = BPF_POKE_REASON_TAIL_CALL, 13025 .tail_call.map = BPF_MAP_PTR(aux->map_ptr_state), 13026 .tail_call.key = bpf_map_key_immediate(aux), 13027 .insn_idx = i + delta, 13028 }; 13029 13030 ret = bpf_jit_add_poke_descriptor(prog, &desc); 13031 if (ret < 0) { 13032 verbose(env, "adding tail call poke descriptor failed\n"); 13033 return ret; 13034 } 13035 13036 insn->imm = ret + 1; 13037 continue; 13038 } 13039 13040 if (!bpf_map_ptr_unpriv(aux)) 13041 continue; 13042 13043 /* instead of changing every JIT dealing with tail_call 13044 * emit two extra insns: 13045 * if (index >= max_entries) goto out; 13046 * index &= array->index_mask; 13047 * to avoid out-of-bounds cpu speculation 13048 */ 13049 if (bpf_map_ptr_poisoned(aux)) { 13050 verbose(env, "tail_call abusing map_ptr\n"); 13051 return -EINVAL; 13052 } 13053 13054 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 13055 insn_buf[0] = BPF_JMP_IMM(BPF_JGE, BPF_REG_3, 13056 map_ptr->max_entries, 2); 13057 insn_buf[1] = BPF_ALU32_IMM(BPF_AND, BPF_REG_3, 13058 container_of(map_ptr, 13059 struct bpf_array, 13060 map)->index_mask); 13061 insn_buf[2] = *insn; 13062 cnt = 3; 13063 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 13064 if (!new_prog) 13065 return -ENOMEM; 13066 13067 delta += cnt - 1; 13068 env->prog = prog = new_prog; 13069 insn = new_prog->insnsi + i + delta; 13070 continue; 13071 } 13072 13073 if (insn->imm == BPF_FUNC_timer_set_callback) { 13074 /* The verifier will process callback_fn as many times as necessary 13075 * with different maps and the register states prepared by 13076 * set_timer_callback_state will be accurate. 13077 * 13078 * The following use case is valid: 13079 * map1 is shared by prog1, prog2, prog3. 13080 * prog1 calls bpf_timer_init for some map1 elements 13081 * prog2 calls bpf_timer_set_callback for some map1 elements. 13082 * Those that were not bpf_timer_init-ed will return -EINVAL. 13083 * prog3 calls bpf_timer_start for some map1 elements. 13084 * Those that were not both bpf_timer_init-ed and 13085 * bpf_timer_set_callback-ed will return -EINVAL. 13086 */ 13087 struct bpf_insn ld_addrs[2] = { 13088 BPF_LD_IMM64(BPF_REG_3, (long)prog->aux), 13089 }; 13090 13091 insn_buf[0] = ld_addrs[0]; 13092 insn_buf[1] = ld_addrs[1]; 13093 insn_buf[2] = *insn; 13094 cnt = 3; 13095 13096 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); 13097 if (!new_prog) 13098 return -ENOMEM; 13099 13100 delta += cnt - 1; 13101 env->prog = prog = new_prog; 13102 insn = new_prog->insnsi + i + delta; 13103 goto patch_call_imm; 13104 } 13105 13106 /* BPF_EMIT_CALL() assumptions in some of the map_gen_lookup 13107 * and other inlining handlers are currently limited to 64 bit 13108 * only. 13109 */ 13110 if (prog->jit_requested && BITS_PER_LONG == 64 && 13111 (insn->imm == BPF_FUNC_map_lookup_elem || 13112 insn->imm == BPF_FUNC_map_update_elem || 13113 insn->imm == BPF_FUNC_map_delete_elem || 13114 insn->imm == BPF_FUNC_map_push_elem || 13115 insn->imm == BPF_FUNC_map_pop_elem || 13116 insn->imm == BPF_FUNC_map_peek_elem || 13117 insn->imm == BPF_FUNC_redirect_map || 13118 insn->imm == BPF_FUNC_for_each_map_elem)) { 13119 aux = &env->insn_aux_data[i + delta]; 13120 if (bpf_map_ptr_poisoned(aux)) 13121 goto patch_call_imm; 13122 13123 map_ptr = BPF_MAP_PTR(aux->map_ptr_state); 13124 ops = map_ptr->ops; 13125 if (insn->imm == BPF_FUNC_map_lookup_elem && 13126 ops->map_gen_lookup) { 13127 cnt = ops->map_gen_lookup(map_ptr, insn_buf); 13128 if (cnt == -EOPNOTSUPP) 13129 goto patch_map_ops_generic; 13130 if (cnt <= 0 || cnt >= ARRAY_SIZE(insn_buf)) { 13131 verbose(env, "bpf verifier is misconfigured\n"); 13132 return -EINVAL; 13133 } 13134 13135 new_prog = bpf_patch_insn_data(env, i + delta, 13136 insn_buf, cnt); 13137 if (!new_prog) 13138 return -ENOMEM; 13139 13140 delta += cnt - 1; 13141 env->prog = prog = new_prog; 13142 insn = new_prog->insnsi + i + delta; 13143 continue; 13144 } 13145 13146 BUILD_BUG_ON(!__same_type(ops->map_lookup_elem, 13147 (void *(*)(struct bpf_map *map, void *key))NULL)); 13148 BUILD_BUG_ON(!__same_type(ops->map_delete_elem, 13149 (int (*)(struct bpf_map *map, void *key))NULL)); 13150 BUILD_BUG_ON(!__same_type(ops->map_update_elem, 13151 (int (*)(struct bpf_map *map, void *key, void *value, 13152 u64 flags))NULL)); 13153 BUILD_BUG_ON(!__same_type(ops->map_push_elem, 13154 (int (*)(struct bpf_map *map, void *value, 13155 u64 flags))NULL)); 13156 BUILD_BUG_ON(!__same_type(ops->map_pop_elem, 13157 (int (*)(struct bpf_map *map, void *value))NULL)); 13158 BUILD_BUG_ON(!__same_type(ops->map_peek_elem, 13159 (int (*)(struct bpf_map *map, void *value))NULL)); 13160 BUILD_BUG_ON(!__same_type(ops->map_redirect, 13161 (int (*)(struct bpf_map *map, u32 ifindex, u64 flags))NULL)); 13162 BUILD_BUG_ON(!__same_type(ops->map_for_each_callback, 13163 (int (*)(struct bpf_map *map, 13164 bpf_callback_t callback_fn, 13165 void *callback_ctx, 13166 u64 flags))NULL)); 13167 13168 patch_map_ops_generic: 13169 switch (insn->imm) { 13170 case BPF_FUNC_map_lookup_elem: 13171 insn->imm = BPF_CALL_IMM(ops->map_lookup_elem); 13172 continue; 13173 case BPF_FUNC_map_update_elem: 13174 insn->imm = BPF_CALL_IMM(ops->map_update_elem); 13175 continue; 13176 case BPF_FUNC_map_delete_elem: 13177 insn->imm = BPF_CALL_IMM(ops->map_delete_elem); 13178 continue; 13179 case BPF_FUNC_map_push_elem: 13180 insn->imm = BPF_CALL_IMM(ops->map_push_elem); 13181 continue; 13182 case BPF_FUNC_map_pop_elem: 13183 insn->imm = BPF_CALL_IMM(ops->map_pop_elem); 13184 continue; 13185 case BPF_FUNC_map_peek_elem: 13186 insn->imm = BPF_CALL_IMM(ops->map_peek_elem); 13187 continue; 13188 case BPF_FUNC_redirect_map: 13189 insn->imm = BPF_CALL_IMM(ops->map_redirect); 13190 continue; 13191 case BPF_FUNC_for_each_map_elem: 13192 insn->imm = BPF_CALL_IMM(ops->map_for_each_callback); 13193 continue; 13194 } 13195 13196 goto patch_call_imm; 13197 } 13198 13199 /* Implement bpf_jiffies64 inline. */ 13200 if (prog->jit_requested && BITS_PER_LONG == 64 && 13201 insn->imm == BPF_FUNC_jiffies64) { 13202 struct bpf_insn ld_jiffies_addr[2] = { 13203 BPF_LD_IMM64(BPF_REG_0, 13204 (unsigned long)&jiffies), 13205 }; 13206 13207 insn_buf[0] = ld_jiffies_addr[0]; 13208 insn_buf[1] = ld_jiffies_addr[1]; 13209 insn_buf[2] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 13210 BPF_REG_0, 0); 13211 cnt = 3; 13212 13213 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 13214 cnt); 13215 if (!new_prog) 13216 return -ENOMEM; 13217 13218 delta += cnt - 1; 13219 env->prog = prog = new_prog; 13220 insn = new_prog->insnsi + i + delta; 13221 continue; 13222 } 13223 13224 /* Implement bpf_get_func_ip inline. */ 13225 if (prog_type == BPF_PROG_TYPE_TRACING && 13226 insn->imm == BPF_FUNC_get_func_ip) { 13227 /* Load IP address from ctx - 8 */ 13228 insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8); 13229 13230 new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, 1); 13231 if (!new_prog) 13232 return -ENOMEM; 13233 13234 env->prog = prog = new_prog; 13235 insn = new_prog->insnsi + i + delta; 13236 continue; 13237 } 13238 13239 patch_call_imm: 13240 fn = env->ops->get_func_proto(insn->imm, env->prog); 13241 /* all functions that have prototype and verifier allowed 13242 * programs to call them, must be real in-kernel functions 13243 */ 13244 if (!fn->func) { 13245 verbose(env, 13246 "kernel subsystem misconfigured func %s#%d\n", 13247 func_id_name(insn->imm), insn->imm); 13248 return -EFAULT; 13249 } 13250 insn->imm = fn->func - __bpf_call_base; 13251 } 13252 13253 /* Since poke tab is now finalized, publish aux to tracker. */ 13254 for (i = 0; i < prog->aux->size_poke_tab; i++) { 13255 map_ptr = prog->aux->poke_tab[i].tail_call.map; 13256 if (!map_ptr->ops->map_poke_track || 13257 !map_ptr->ops->map_poke_untrack || 13258 !map_ptr->ops->map_poke_run) { 13259 verbose(env, "bpf verifier is misconfigured\n"); 13260 return -EINVAL; 13261 } 13262 13263 ret = map_ptr->ops->map_poke_track(map_ptr, prog->aux); 13264 if (ret < 0) { 13265 verbose(env, "tracking tail call prog failed\n"); 13266 return ret; 13267 } 13268 } 13269 13270 sort_kfunc_descs_by_imm(env->prog); 13271 13272 return 0; 13273 } 13274 13275 static void free_states(struct bpf_verifier_env *env) 13276 { 13277 struct bpf_verifier_state_list *sl, *sln; 13278 int i; 13279 13280 sl = env->free_list; 13281 while (sl) { 13282 sln = sl->next; 13283 free_verifier_state(&sl->state, false); 13284 kfree(sl); 13285 sl = sln; 13286 } 13287 env->free_list = NULL; 13288 13289 if (!env->explored_states) 13290 return; 13291 13292 for (i = 0; i < state_htab_size(env); i++) { 13293 sl = env->explored_states[i]; 13294 13295 while (sl) { 13296 sln = sl->next; 13297 free_verifier_state(&sl->state, false); 13298 kfree(sl); 13299 sl = sln; 13300 } 13301 env->explored_states[i] = NULL; 13302 } 13303 } 13304 13305 static int do_check_common(struct bpf_verifier_env *env, int subprog) 13306 { 13307 bool pop_log = !(env->log.level & BPF_LOG_LEVEL2); 13308 struct bpf_verifier_state *state; 13309 struct bpf_reg_state *regs; 13310 int ret, i; 13311 13312 env->prev_linfo = NULL; 13313 env->pass_cnt++; 13314 13315 state = kzalloc(sizeof(struct bpf_verifier_state), GFP_KERNEL); 13316 if (!state) 13317 return -ENOMEM; 13318 state->curframe = 0; 13319 state->speculative = false; 13320 state->branches = 1; 13321 state->frame[0] = kzalloc(sizeof(struct bpf_func_state), GFP_KERNEL); 13322 if (!state->frame[0]) { 13323 kfree(state); 13324 return -ENOMEM; 13325 } 13326 env->cur_state = state; 13327 init_func_state(env, state->frame[0], 13328 BPF_MAIN_FUNC /* callsite */, 13329 0 /* frameno */, 13330 subprog); 13331 13332 regs = state->frame[state->curframe]->regs; 13333 if (subprog || env->prog->type == BPF_PROG_TYPE_EXT) { 13334 ret = btf_prepare_func_args(env, subprog, regs); 13335 if (ret) 13336 goto out; 13337 for (i = BPF_REG_1; i <= BPF_REG_5; i++) { 13338 if (regs[i].type == PTR_TO_CTX) 13339 mark_reg_known_zero(env, regs, i); 13340 else if (regs[i].type == SCALAR_VALUE) 13341 mark_reg_unknown(env, regs, i); 13342 else if (regs[i].type == PTR_TO_MEM_OR_NULL) { 13343 const u32 mem_size = regs[i].mem_size; 13344 13345 mark_reg_known_zero(env, regs, i); 13346 regs[i].mem_size = mem_size; 13347 regs[i].id = ++env->id_gen; 13348 } 13349 } 13350 } else { 13351 /* 1st arg to a function */ 13352 regs[BPF_REG_1].type = PTR_TO_CTX; 13353 mark_reg_known_zero(env, regs, BPF_REG_1); 13354 ret = btf_check_subprog_arg_match(env, subprog, regs); 13355 if (ret == -EFAULT) 13356 /* unlikely verifier bug. abort. 13357 * ret == 0 and ret < 0 are sadly acceptable for 13358 * main() function due to backward compatibility. 13359 * Like socket filter program may be written as: 13360 * int bpf_prog(struct pt_regs *ctx) 13361 * and never dereference that ctx in the program. 13362 * 'struct pt_regs' is a type mismatch for socket 13363 * filter that should be using 'struct __sk_buff'. 13364 */ 13365 goto out; 13366 } 13367 13368 ret = do_check(env); 13369 out: 13370 /* check for NULL is necessary, since cur_state can be freed inside 13371 * do_check() under memory pressure. 13372 */ 13373 if (env->cur_state) { 13374 free_verifier_state(env->cur_state, true); 13375 env->cur_state = NULL; 13376 } 13377 while (!pop_stack(env, NULL, NULL, false)); 13378 if (!ret && pop_log) 13379 bpf_vlog_reset(&env->log, 0); 13380 free_states(env); 13381 return ret; 13382 } 13383 13384 /* Verify all global functions in a BPF program one by one based on their BTF. 13385 * All global functions must pass verification. Otherwise the whole program is rejected. 13386 * Consider: 13387 * int bar(int); 13388 * int foo(int f) 13389 * { 13390 * return bar(f); 13391 * } 13392 * int bar(int b) 13393 * { 13394 * ... 13395 * } 13396 * foo() will be verified first for R1=any_scalar_value. During verification it 13397 * will be assumed that bar() already verified successfully and call to bar() 13398 * from foo() will be checked for type match only. Later bar() will be verified 13399 * independently to check that it's safe for R1=any_scalar_value. 13400 */ 13401 static int do_check_subprogs(struct bpf_verifier_env *env) 13402 { 13403 struct bpf_prog_aux *aux = env->prog->aux; 13404 int i, ret; 13405 13406 if (!aux->func_info) 13407 return 0; 13408 13409 for (i = 1; i < env->subprog_cnt; i++) { 13410 if (aux->func_info_aux[i].linkage != BTF_FUNC_GLOBAL) 13411 continue; 13412 env->insn_idx = env->subprog_info[i].start; 13413 WARN_ON_ONCE(env->insn_idx == 0); 13414 ret = do_check_common(env, i); 13415 if (ret) { 13416 return ret; 13417 } else if (env->log.level & BPF_LOG_LEVEL) { 13418 verbose(env, 13419 "Func#%d is safe for any args that match its prototype\n", 13420 i); 13421 } 13422 } 13423 return 0; 13424 } 13425 13426 static int do_check_main(struct bpf_verifier_env *env) 13427 { 13428 int ret; 13429 13430 env->insn_idx = 0; 13431 ret = do_check_common(env, 0); 13432 if (!ret) 13433 env->prog->aux->stack_depth = env->subprog_info[0].stack_depth; 13434 return ret; 13435 } 13436 13437 13438 static void print_verification_stats(struct bpf_verifier_env *env) 13439 { 13440 int i; 13441 13442 if (env->log.level & BPF_LOG_STATS) { 13443 verbose(env, "verification time %lld usec\n", 13444 div_u64(env->verification_time, 1000)); 13445 verbose(env, "stack depth "); 13446 for (i = 0; i < env->subprog_cnt; i++) { 13447 u32 depth = env->subprog_info[i].stack_depth; 13448 13449 verbose(env, "%d", depth); 13450 if (i + 1 < env->subprog_cnt) 13451 verbose(env, "+"); 13452 } 13453 verbose(env, "\n"); 13454 } 13455 verbose(env, "processed %d insns (limit %d) max_states_per_insn %d " 13456 "total_states %d peak_states %d mark_read %d\n", 13457 env->insn_processed, BPF_COMPLEXITY_LIMIT_INSNS, 13458 env->max_states_per_insn, env->total_states, 13459 env->peak_states, env->longest_mark_read_walk); 13460 } 13461 13462 static int check_struct_ops_btf_id(struct bpf_verifier_env *env) 13463 { 13464 const struct btf_type *t, *func_proto; 13465 const struct bpf_struct_ops *st_ops; 13466 const struct btf_member *member; 13467 struct bpf_prog *prog = env->prog; 13468 u32 btf_id, member_idx; 13469 const char *mname; 13470 13471 if (!prog->gpl_compatible) { 13472 verbose(env, "struct ops programs must have a GPL compatible license\n"); 13473 return -EINVAL; 13474 } 13475 13476 btf_id = prog->aux->attach_btf_id; 13477 st_ops = bpf_struct_ops_find(btf_id); 13478 if (!st_ops) { 13479 verbose(env, "attach_btf_id %u is not a supported struct\n", 13480 btf_id); 13481 return -ENOTSUPP; 13482 } 13483 13484 t = st_ops->type; 13485 member_idx = prog->expected_attach_type; 13486 if (member_idx >= btf_type_vlen(t)) { 13487 verbose(env, "attach to invalid member idx %u of struct %s\n", 13488 member_idx, st_ops->name); 13489 return -EINVAL; 13490 } 13491 13492 member = &btf_type_member(t)[member_idx]; 13493 mname = btf_name_by_offset(btf_vmlinux, member->name_off); 13494 func_proto = btf_type_resolve_func_ptr(btf_vmlinux, member->type, 13495 NULL); 13496 if (!func_proto) { 13497 verbose(env, "attach to invalid member %s(@idx %u) of struct %s\n", 13498 mname, member_idx, st_ops->name); 13499 return -EINVAL; 13500 } 13501 13502 if (st_ops->check_member) { 13503 int err = st_ops->check_member(t, member); 13504 13505 if (err) { 13506 verbose(env, "attach to unsupported member %s of struct %s\n", 13507 mname, st_ops->name); 13508 return err; 13509 } 13510 } 13511 13512 prog->aux->attach_func_proto = func_proto; 13513 prog->aux->attach_func_name = mname; 13514 env->ops = st_ops->verifier_ops; 13515 13516 return 0; 13517 } 13518 #define SECURITY_PREFIX "security_" 13519 13520 static int check_attach_modify_return(unsigned long addr, const char *func_name) 13521 { 13522 if (within_error_injection_list(addr) || 13523 !strncmp(SECURITY_PREFIX, func_name, sizeof(SECURITY_PREFIX) - 1)) 13524 return 0; 13525 13526 return -EINVAL; 13527 } 13528 13529 /* list of non-sleepable functions that are otherwise on 13530 * ALLOW_ERROR_INJECTION list 13531 */ 13532 BTF_SET_START(btf_non_sleepable_error_inject) 13533 /* Three functions below can be called from sleepable and non-sleepable context. 13534 * Assume non-sleepable from bpf safety point of view. 13535 */ 13536 BTF_ID(func, __filemap_add_folio) 13537 BTF_ID(func, should_fail_alloc_page) 13538 BTF_ID(func, should_failslab) 13539 BTF_SET_END(btf_non_sleepable_error_inject) 13540 13541 static int check_non_sleepable_error_inject(u32 btf_id) 13542 { 13543 return btf_id_set_contains(&btf_non_sleepable_error_inject, btf_id); 13544 } 13545 13546 int bpf_check_attach_target(struct bpf_verifier_log *log, 13547 const struct bpf_prog *prog, 13548 const struct bpf_prog *tgt_prog, 13549 u32 btf_id, 13550 struct bpf_attach_target_info *tgt_info) 13551 { 13552 bool prog_extension = prog->type == BPF_PROG_TYPE_EXT; 13553 const char prefix[] = "btf_trace_"; 13554 int ret = 0, subprog = -1, i; 13555 const struct btf_type *t; 13556 bool conservative = true; 13557 const char *tname; 13558 struct btf *btf; 13559 long addr = 0; 13560 13561 if (!btf_id) { 13562 bpf_log(log, "Tracing programs must provide btf_id\n"); 13563 return -EINVAL; 13564 } 13565 btf = tgt_prog ? tgt_prog->aux->btf : prog->aux->attach_btf; 13566 if (!btf) { 13567 bpf_log(log, 13568 "FENTRY/FEXIT program can only be attached to another program annotated with BTF\n"); 13569 return -EINVAL; 13570 } 13571 t = btf_type_by_id(btf, btf_id); 13572 if (!t) { 13573 bpf_log(log, "attach_btf_id %u is invalid\n", btf_id); 13574 return -EINVAL; 13575 } 13576 tname = btf_name_by_offset(btf, t->name_off); 13577 if (!tname) { 13578 bpf_log(log, "attach_btf_id %u doesn't have a name\n", btf_id); 13579 return -EINVAL; 13580 } 13581 if (tgt_prog) { 13582 struct bpf_prog_aux *aux = tgt_prog->aux; 13583 13584 for (i = 0; i < aux->func_info_cnt; i++) 13585 if (aux->func_info[i].type_id == btf_id) { 13586 subprog = i; 13587 break; 13588 } 13589 if (subprog == -1) { 13590 bpf_log(log, "Subprog %s doesn't exist\n", tname); 13591 return -EINVAL; 13592 } 13593 conservative = aux->func_info_aux[subprog].unreliable; 13594 if (prog_extension) { 13595 if (conservative) { 13596 bpf_log(log, 13597 "Cannot replace static functions\n"); 13598 return -EINVAL; 13599 } 13600 if (!prog->jit_requested) { 13601 bpf_log(log, 13602 "Extension programs should be JITed\n"); 13603 return -EINVAL; 13604 } 13605 } 13606 if (!tgt_prog->jited) { 13607 bpf_log(log, "Can attach to only JITed progs\n"); 13608 return -EINVAL; 13609 } 13610 if (tgt_prog->type == prog->type) { 13611 /* Cannot fentry/fexit another fentry/fexit program. 13612 * Cannot attach program extension to another extension. 13613 * It's ok to attach fentry/fexit to extension program. 13614 */ 13615 bpf_log(log, "Cannot recursively attach\n"); 13616 return -EINVAL; 13617 } 13618 if (tgt_prog->type == BPF_PROG_TYPE_TRACING && 13619 prog_extension && 13620 (tgt_prog->expected_attach_type == BPF_TRACE_FENTRY || 13621 tgt_prog->expected_attach_type == BPF_TRACE_FEXIT)) { 13622 /* Program extensions can extend all program types 13623 * except fentry/fexit. The reason is the following. 13624 * The fentry/fexit programs are used for performance 13625 * analysis, stats and can be attached to any program 13626 * type except themselves. When extension program is 13627 * replacing XDP function it is necessary to allow 13628 * performance analysis of all functions. Both original 13629 * XDP program and its program extension. Hence 13630 * attaching fentry/fexit to BPF_PROG_TYPE_EXT is 13631 * allowed. If extending of fentry/fexit was allowed it 13632 * would be possible to create long call chain 13633 * fentry->extension->fentry->extension beyond 13634 * reasonable stack size. Hence extending fentry is not 13635 * allowed. 13636 */ 13637 bpf_log(log, "Cannot extend fentry/fexit\n"); 13638 return -EINVAL; 13639 } 13640 } else { 13641 if (prog_extension) { 13642 bpf_log(log, "Cannot replace kernel functions\n"); 13643 return -EINVAL; 13644 } 13645 } 13646 13647 switch (prog->expected_attach_type) { 13648 case BPF_TRACE_RAW_TP: 13649 if (tgt_prog) { 13650 bpf_log(log, 13651 "Only FENTRY/FEXIT progs are attachable to another BPF prog\n"); 13652 return -EINVAL; 13653 } 13654 if (!btf_type_is_typedef(t)) { 13655 bpf_log(log, "attach_btf_id %u is not a typedef\n", 13656 btf_id); 13657 return -EINVAL; 13658 } 13659 if (strncmp(prefix, tname, sizeof(prefix) - 1)) { 13660 bpf_log(log, "attach_btf_id %u points to wrong type name %s\n", 13661 btf_id, tname); 13662 return -EINVAL; 13663 } 13664 tname += sizeof(prefix) - 1; 13665 t = btf_type_by_id(btf, t->type); 13666 if (!btf_type_is_ptr(t)) 13667 /* should never happen in valid vmlinux build */ 13668 return -EINVAL; 13669 t = btf_type_by_id(btf, t->type); 13670 if (!btf_type_is_func_proto(t)) 13671 /* should never happen in valid vmlinux build */ 13672 return -EINVAL; 13673 13674 break; 13675 case BPF_TRACE_ITER: 13676 if (!btf_type_is_func(t)) { 13677 bpf_log(log, "attach_btf_id %u is not a function\n", 13678 btf_id); 13679 return -EINVAL; 13680 } 13681 t = btf_type_by_id(btf, t->type); 13682 if (!btf_type_is_func_proto(t)) 13683 return -EINVAL; 13684 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 13685 if (ret) 13686 return ret; 13687 break; 13688 default: 13689 if (!prog_extension) 13690 return -EINVAL; 13691 fallthrough; 13692 case BPF_MODIFY_RETURN: 13693 case BPF_LSM_MAC: 13694 case BPF_TRACE_FENTRY: 13695 case BPF_TRACE_FEXIT: 13696 if (!btf_type_is_func(t)) { 13697 bpf_log(log, "attach_btf_id %u is not a function\n", 13698 btf_id); 13699 return -EINVAL; 13700 } 13701 if (prog_extension && 13702 btf_check_type_match(log, prog, btf, t)) 13703 return -EINVAL; 13704 t = btf_type_by_id(btf, t->type); 13705 if (!btf_type_is_func_proto(t)) 13706 return -EINVAL; 13707 13708 if ((prog->aux->saved_dst_prog_type || prog->aux->saved_dst_attach_type) && 13709 (!tgt_prog || prog->aux->saved_dst_prog_type != tgt_prog->type || 13710 prog->aux->saved_dst_attach_type != tgt_prog->expected_attach_type)) 13711 return -EINVAL; 13712 13713 if (tgt_prog && conservative) 13714 t = NULL; 13715 13716 ret = btf_distill_func_proto(log, btf, t, tname, &tgt_info->fmodel); 13717 if (ret < 0) 13718 return ret; 13719 13720 if (tgt_prog) { 13721 if (subprog == 0) 13722 addr = (long) tgt_prog->bpf_func; 13723 else 13724 addr = (long) tgt_prog->aux->func[subprog]->bpf_func; 13725 } else { 13726 addr = kallsyms_lookup_name(tname); 13727 if (!addr) { 13728 bpf_log(log, 13729 "The address of function %s cannot be found\n", 13730 tname); 13731 return -ENOENT; 13732 } 13733 } 13734 13735 if (prog->aux->sleepable) { 13736 ret = -EINVAL; 13737 switch (prog->type) { 13738 case BPF_PROG_TYPE_TRACING: 13739 /* fentry/fexit/fmod_ret progs can be sleepable only if they are 13740 * attached to ALLOW_ERROR_INJECTION and are not in denylist. 13741 */ 13742 if (!check_non_sleepable_error_inject(btf_id) && 13743 within_error_injection_list(addr)) 13744 ret = 0; 13745 break; 13746 case BPF_PROG_TYPE_LSM: 13747 /* LSM progs check that they are attached to bpf_lsm_*() funcs. 13748 * Only some of them are sleepable. 13749 */ 13750 if (bpf_lsm_is_sleepable_hook(btf_id)) 13751 ret = 0; 13752 break; 13753 default: 13754 break; 13755 } 13756 if (ret) { 13757 bpf_log(log, "%s is not sleepable\n", tname); 13758 return ret; 13759 } 13760 } else if (prog->expected_attach_type == BPF_MODIFY_RETURN) { 13761 if (tgt_prog) { 13762 bpf_log(log, "can't modify return codes of BPF programs\n"); 13763 return -EINVAL; 13764 } 13765 ret = check_attach_modify_return(addr, tname); 13766 if (ret) { 13767 bpf_log(log, "%s() is not modifiable\n", tname); 13768 return ret; 13769 } 13770 } 13771 13772 break; 13773 } 13774 tgt_info->tgt_addr = addr; 13775 tgt_info->tgt_name = tname; 13776 tgt_info->tgt_type = t; 13777 return 0; 13778 } 13779 13780 BTF_SET_START(btf_id_deny) 13781 BTF_ID_UNUSED 13782 #ifdef CONFIG_SMP 13783 BTF_ID(func, migrate_disable) 13784 BTF_ID(func, migrate_enable) 13785 #endif 13786 #if !defined CONFIG_PREEMPT_RCU && !defined CONFIG_TINY_RCU 13787 BTF_ID(func, rcu_read_unlock_strict) 13788 #endif 13789 BTF_SET_END(btf_id_deny) 13790 13791 static int check_attach_btf_id(struct bpf_verifier_env *env) 13792 { 13793 struct bpf_prog *prog = env->prog; 13794 struct bpf_prog *tgt_prog = prog->aux->dst_prog; 13795 struct bpf_attach_target_info tgt_info = {}; 13796 u32 btf_id = prog->aux->attach_btf_id; 13797 struct bpf_trampoline *tr; 13798 int ret; 13799 u64 key; 13800 13801 if (prog->type == BPF_PROG_TYPE_SYSCALL) { 13802 if (prog->aux->sleepable) 13803 /* attach_btf_id checked to be zero already */ 13804 return 0; 13805 verbose(env, "Syscall programs can only be sleepable\n"); 13806 return -EINVAL; 13807 } 13808 13809 if (prog->aux->sleepable && prog->type != BPF_PROG_TYPE_TRACING && 13810 prog->type != BPF_PROG_TYPE_LSM) { 13811 verbose(env, "Only fentry/fexit/fmod_ret and lsm programs can be sleepable\n"); 13812 return -EINVAL; 13813 } 13814 13815 if (prog->type == BPF_PROG_TYPE_STRUCT_OPS) 13816 return check_struct_ops_btf_id(env); 13817 13818 if (prog->type != BPF_PROG_TYPE_TRACING && 13819 prog->type != BPF_PROG_TYPE_LSM && 13820 prog->type != BPF_PROG_TYPE_EXT) 13821 return 0; 13822 13823 ret = bpf_check_attach_target(&env->log, prog, tgt_prog, btf_id, &tgt_info); 13824 if (ret) 13825 return ret; 13826 13827 if (tgt_prog && prog->type == BPF_PROG_TYPE_EXT) { 13828 /* to make freplace equivalent to their targets, they need to 13829 * inherit env->ops and expected_attach_type for the rest of the 13830 * verification 13831 */ 13832 env->ops = bpf_verifier_ops[tgt_prog->type]; 13833 prog->expected_attach_type = tgt_prog->expected_attach_type; 13834 } 13835 13836 /* store info about the attachment target that will be used later */ 13837 prog->aux->attach_func_proto = tgt_info.tgt_type; 13838 prog->aux->attach_func_name = tgt_info.tgt_name; 13839 13840 if (tgt_prog) { 13841 prog->aux->saved_dst_prog_type = tgt_prog->type; 13842 prog->aux->saved_dst_attach_type = tgt_prog->expected_attach_type; 13843 } 13844 13845 if (prog->expected_attach_type == BPF_TRACE_RAW_TP) { 13846 prog->aux->attach_btf_trace = true; 13847 return 0; 13848 } else if (prog->expected_attach_type == BPF_TRACE_ITER) { 13849 if (!bpf_iter_prog_supported(prog)) 13850 return -EINVAL; 13851 return 0; 13852 } 13853 13854 if (prog->type == BPF_PROG_TYPE_LSM) { 13855 ret = bpf_lsm_verify_prog(&env->log, prog); 13856 if (ret < 0) 13857 return ret; 13858 } else if (prog->type == BPF_PROG_TYPE_TRACING && 13859 btf_id_set_contains(&btf_id_deny, btf_id)) { 13860 return -EINVAL; 13861 } 13862 13863 key = bpf_trampoline_compute_key(tgt_prog, prog->aux->attach_btf, btf_id); 13864 tr = bpf_trampoline_get(key, &tgt_info); 13865 if (!tr) 13866 return -ENOMEM; 13867 13868 prog->aux->dst_trampoline = tr; 13869 return 0; 13870 } 13871 13872 struct btf *bpf_get_btf_vmlinux(void) 13873 { 13874 if (!btf_vmlinux && IS_ENABLED(CONFIG_DEBUG_INFO_BTF)) { 13875 mutex_lock(&bpf_verifier_lock); 13876 if (!btf_vmlinux) 13877 btf_vmlinux = btf_parse_vmlinux(); 13878 mutex_unlock(&bpf_verifier_lock); 13879 } 13880 return btf_vmlinux; 13881 } 13882 13883 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr) 13884 { 13885 u64 start_time = ktime_get_ns(); 13886 struct bpf_verifier_env *env; 13887 struct bpf_verifier_log *log; 13888 int i, len, ret = -EINVAL; 13889 bool is_priv; 13890 13891 /* no program is valid */ 13892 if (ARRAY_SIZE(bpf_verifier_ops) == 0) 13893 return -EINVAL; 13894 13895 /* 'struct bpf_verifier_env' can be global, but since it's not small, 13896 * allocate/free it every time bpf_check() is called 13897 */ 13898 env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); 13899 if (!env) 13900 return -ENOMEM; 13901 log = &env->log; 13902 13903 len = (*prog)->len; 13904 env->insn_aux_data = 13905 vzalloc(array_size(sizeof(struct bpf_insn_aux_data), len)); 13906 ret = -ENOMEM; 13907 if (!env->insn_aux_data) 13908 goto err_free_env; 13909 for (i = 0; i < len; i++) 13910 env->insn_aux_data[i].orig_idx = i; 13911 env->prog = *prog; 13912 env->ops = bpf_verifier_ops[env->prog->type]; 13913 env->fd_array = make_bpfptr(attr->fd_array, uattr.is_kernel); 13914 is_priv = bpf_capable(); 13915 13916 bpf_get_btf_vmlinux(); 13917 13918 /* grab the mutex to protect few globals used by verifier */ 13919 if (!is_priv) 13920 mutex_lock(&bpf_verifier_lock); 13921 13922 if (attr->log_level || attr->log_buf || attr->log_size) { 13923 /* user requested verbose verifier output 13924 * and supplied buffer to store the verification trace 13925 */ 13926 log->level = attr->log_level; 13927 log->ubuf = (char __user *) (unsigned long) attr->log_buf; 13928 log->len_total = attr->log_size; 13929 13930 ret = -EINVAL; 13931 /* log attributes have to be sane */ 13932 if (log->len_total < 128 || log->len_total > UINT_MAX >> 2 || 13933 !log->level || !log->ubuf || log->level & ~BPF_LOG_MASK) 13934 goto err_unlock; 13935 } 13936 13937 if (IS_ERR(btf_vmlinux)) { 13938 /* Either gcc or pahole or kernel are broken. */ 13939 verbose(env, "in-kernel BTF is malformed\n"); 13940 ret = PTR_ERR(btf_vmlinux); 13941 goto skip_full_check; 13942 } 13943 13944 env->strict_alignment = !!(attr->prog_flags & BPF_F_STRICT_ALIGNMENT); 13945 if (!IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS)) 13946 env->strict_alignment = true; 13947 if (attr->prog_flags & BPF_F_ANY_ALIGNMENT) 13948 env->strict_alignment = false; 13949 13950 env->allow_ptr_leaks = bpf_allow_ptr_leaks(); 13951 env->allow_uninit_stack = bpf_allow_uninit_stack(); 13952 env->allow_ptr_to_map_access = bpf_allow_ptr_to_map_access(); 13953 env->bypass_spec_v1 = bpf_bypass_spec_v1(); 13954 env->bypass_spec_v4 = bpf_bypass_spec_v4(); 13955 env->bpf_capable = bpf_capable(); 13956 13957 if (is_priv) 13958 env->test_state_freq = attr->prog_flags & BPF_F_TEST_STATE_FREQ; 13959 13960 env->explored_states = kvcalloc(state_htab_size(env), 13961 sizeof(struct bpf_verifier_state_list *), 13962 GFP_USER); 13963 ret = -ENOMEM; 13964 if (!env->explored_states) 13965 goto skip_full_check; 13966 13967 ret = add_subprog_and_kfunc(env); 13968 if (ret < 0) 13969 goto skip_full_check; 13970 13971 ret = check_subprogs(env); 13972 if (ret < 0) 13973 goto skip_full_check; 13974 13975 ret = check_btf_info(env, attr, uattr); 13976 if (ret < 0) 13977 goto skip_full_check; 13978 13979 ret = check_attach_btf_id(env); 13980 if (ret) 13981 goto skip_full_check; 13982 13983 ret = resolve_pseudo_ldimm64(env); 13984 if (ret < 0) 13985 goto skip_full_check; 13986 13987 if (bpf_prog_is_dev_bound(env->prog->aux)) { 13988 ret = bpf_prog_offload_verifier_prep(env->prog); 13989 if (ret) 13990 goto skip_full_check; 13991 } 13992 13993 ret = check_cfg(env); 13994 if (ret < 0) 13995 goto skip_full_check; 13996 13997 ret = do_check_subprogs(env); 13998 ret = ret ?: do_check_main(env); 13999 14000 if (ret == 0 && bpf_prog_is_dev_bound(env->prog->aux)) 14001 ret = bpf_prog_offload_finalize(env); 14002 14003 skip_full_check: 14004 kvfree(env->explored_states); 14005 14006 if (ret == 0) 14007 ret = check_max_stack_depth(env); 14008 14009 /* instruction rewrites happen after this point */ 14010 if (is_priv) { 14011 if (ret == 0) 14012 opt_hard_wire_dead_code_branches(env); 14013 if (ret == 0) 14014 ret = opt_remove_dead_code(env); 14015 if (ret == 0) 14016 ret = opt_remove_nops(env); 14017 } else { 14018 if (ret == 0) 14019 sanitize_dead_code(env); 14020 } 14021 14022 if (ret == 0) 14023 /* program is valid, convert *(u32*)(ctx + off) accesses */ 14024 ret = convert_ctx_accesses(env); 14025 14026 if (ret == 0) 14027 ret = do_misc_fixups(env); 14028 14029 /* do 32-bit optimization after insn patching has done so those patched 14030 * insns could be handled correctly. 14031 */ 14032 if (ret == 0 && !bpf_prog_is_dev_bound(env->prog->aux)) { 14033 ret = opt_subreg_zext_lo32_rnd_hi32(env, attr); 14034 env->prog->aux->verifier_zext = bpf_jit_needs_zext() ? !ret 14035 : false; 14036 } 14037 14038 if (ret == 0) 14039 ret = fixup_call_args(env); 14040 14041 env->verification_time = ktime_get_ns() - start_time; 14042 print_verification_stats(env); 14043 env->prog->aux->verified_insns = env->insn_processed; 14044 14045 if (log->level && bpf_verifier_log_full(log)) 14046 ret = -ENOSPC; 14047 if (log->level && !log->ubuf) { 14048 ret = -EFAULT; 14049 goto err_release_maps; 14050 } 14051 14052 if (ret) 14053 goto err_release_maps; 14054 14055 if (env->used_map_cnt) { 14056 /* if program passed verifier, update used_maps in bpf_prog_info */ 14057 env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, 14058 sizeof(env->used_maps[0]), 14059 GFP_KERNEL); 14060 14061 if (!env->prog->aux->used_maps) { 14062 ret = -ENOMEM; 14063 goto err_release_maps; 14064 } 14065 14066 memcpy(env->prog->aux->used_maps, env->used_maps, 14067 sizeof(env->used_maps[0]) * env->used_map_cnt); 14068 env->prog->aux->used_map_cnt = env->used_map_cnt; 14069 } 14070 if (env->used_btf_cnt) { 14071 /* if program passed verifier, update used_btfs in bpf_prog_aux */ 14072 env->prog->aux->used_btfs = kmalloc_array(env->used_btf_cnt, 14073 sizeof(env->used_btfs[0]), 14074 GFP_KERNEL); 14075 if (!env->prog->aux->used_btfs) { 14076 ret = -ENOMEM; 14077 goto err_release_maps; 14078 } 14079 14080 memcpy(env->prog->aux->used_btfs, env->used_btfs, 14081 sizeof(env->used_btfs[0]) * env->used_btf_cnt); 14082 env->prog->aux->used_btf_cnt = env->used_btf_cnt; 14083 } 14084 if (env->used_map_cnt || env->used_btf_cnt) { 14085 /* program is valid. Convert pseudo bpf_ld_imm64 into generic 14086 * bpf_ld_imm64 instructions 14087 */ 14088 convert_pseudo_ld_imm64(env); 14089 } 14090 14091 adjust_btf_func(env); 14092 14093 err_release_maps: 14094 if (!env->prog->aux->used_maps) 14095 /* if we didn't copy map pointers into bpf_prog_info, release 14096 * them now. Otherwise free_used_maps() will release them. 14097 */ 14098 release_maps(env); 14099 if (!env->prog->aux->used_btfs) 14100 release_btfs(env); 14101 14102 /* extension progs temporarily inherit the attach_type of their targets 14103 for verification purposes, so set it back to zero before returning 14104 */ 14105 if (env->prog->type == BPF_PROG_TYPE_EXT) 14106 env->prog->expected_attach_type = 0; 14107 14108 *prog = env->prog; 14109 err_unlock: 14110 if (!is_priv) 14111 mutex_unlock(&bpf_verifier_lock); 14112 vfree(env->insn_aux_data); 14113 err_free_env: 14114 kfree(env); 14115 return ret; 14116 } 14117